\r\n >(): AppDispatch {\r\n const store = useStore()\r\n // @ts-ignore\r\n return store.dispatch\r\n }\r\n}\r\n\r\n/**\r\n * A hook to access the redux `dispatch` function.\r\n *\r\n * @returns {any|function} redux store's `dispatch` function\r\n *\r\n * @example\r\n *\r\n * import React, { useCallback } from 'react'\r\n * import { useDispatch } from 'react-redux'\r\n *\r\n * export const CounterComponent = ({ value }) => {\r\n * const dispatch = useDispatch()\r\n * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])\r\n * return (\r\n * \r\n * {value}\r\n * \r\n *
\r\n * )\r\n * }\r\n */\r\nexport const useDispatch = /*#__PURE__*/ createDispatchHook()\r\n","// The primary entry point assumes we are working with React 18, and thus have\r\n// useSyncExternalStore available. We can import that directly from React itself.\r\n// The useSyncExternalStoreWithSelector has to be imported, but we can use the\r\n// non-shim version. This shaves off the byte size of the shim.\r\n\r\nimport * as React from 'react'\r\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector.js'\r\n\r\nimport { initializeUseSelector } from './hooks/useSelector'\r\nimport { initializeConnect } from './components/connect'\r\n\r\ninitializeUseSelector(useSyncExternalStoreWithSelector)\r\ninitializeConnect(React.useSyncExternalStore)\r\n\r\nexport * from './exports'\r\n","/* eslint-disable valid-jsdoc, @typescript-eslint/no-unused-vars */\r\nimport type { ComponentType } from 'react'\r\nimport { React } from '../utils/react'\r\nimport { isValidElementType, isContextConsumer } from '../utils/react-is'\r\n\r\nimport type { Store } from 'redux'\r\n\r\nimport type {\r\n ConnectedComponent,\r\n InferableComponentEnhancer,\r\n InferableComponentEnhancerWithProps,\r\n ResolveThunks,\r\n DispatchProp,\r\n ConnectPropsMaybeWithoutContext,\r\n} from '../types'\r\n\r\nimport type {\r\n MapStateToPropsParam,\r\n MapDispatchToPropsParam,\r\n MergeProps,\r\n MapDispatchToPropsNonObject,\r\n SelectorFactoryOptions,\r\n} from '../connect/selectorFactory'\r\nimport defaultSelectorFactory from '../connect/selectorFactory'\r\nimport { mapDispatchToPropsFactory } from '../connect/mapDispatchToProps'\r\nimport { mapStateToPropsFactory } from '../connect/mapStateToProps'\r\nimport { mergePropsFactory } from '../connect/mergeProps'\r\n\r\nimport type { Subscription } from '../utils/Subscription'\r\nimport { createSubscription } from '../utils/Subscription'\r\nimport { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect'\r\nimport shallowEqual from '../utils/shallowEqual'\r\nimport hoistStatics from '../utils/hoistStatics'\r\nimport warning from '../utils/warning'\r\n\r\nimport type {\r\n ReactReduxContextValue,\r\n ReactReduxContextInstance,\r\n} from './Context'\r\nimport { ReactReduxContext } from './Context'\r\n\r\nimport type { uSES } from '../utils/useSyncExternalStore'\r\nimport { notInitialized } from '../utils/useSyncExternalStore'\r\n\r\nlet useSyncExternalStore = notInitialized as uSES\r\nexport const initializeConnect = (fn: uSES) => {\r\n useSyncExternalStore = fn\r\n}\r\n\r\n// Define some constant arrays just to avoid re-creating these\r\nconst EMPTY_ARRAY: [unknown, number] = [null, 0]\r\nconst NO_SUBSCRIPTION_ARRAY = [null, null]\r\n\r\n// Attempts to stringify whatever not-really-a-component value we were given\r\n// for logging in an error message\r\nconst stringifyComponent = (Comp: unknown) => {\r\n try {\r\n return JSON.stringify(Comp)\r\n } catch (err) {\r\n return String(Comp)\r\n }\r\n}\r\n\r\ntype EffectFunc = (...args: any[]) => void | ReturnType\r\n\r\n// This is \"just\" a `useLayoutEffect`, but with two modifications:\r\n// - we need to fall back to `useEffect` in SSR to avoid annoying warnings\r\n// - we extract this to a separate function to avoid closing over values\r\n// and causing memory leaks\r\nfunction useIsomorphicLayoutEffectWithArgs(\r\n effectFunc: EffectFunc,\r\n effectArgs: any[],\r\n dependencies?: React.DependencyList\r\n) {\r\n useIsomorphicLayoutEffect(() => effectFunc(...effectArgs), dependencies)\r\n}\r\n\r\n// Effect callback, extracted: assign the latest props values to refs for later usage\r\nfunction captureWrapperProps(\r\n lastWrapperProps: React.MutableRefObject,\r\n lastChildProps: React.MutableRefObject,\r\n renderIsScheduled: React.MutableRefObject,\r\n wrapperProps: unknown,\r\n // actualChildProps: unknown,\r\n childPropsFromStoreUpdate: React.MutableRefObject,\r\n notifyNestedSubs: () => void\r\n) {\r\n // We want to capture the wrapper props and child props we used for later comparisons\r\n lastWrapperProps.current = wrapperProps\r\n renderIsScheduled.current = false\r\n\r\n // If the render was from a store update, clear out that reference and cascade the subscriber update\r\n if (childPropsFromStoreUpdate.current) {\r\n childPropsFromStoreUpdate.current = null\r\n notifyNestedSubs()\r\n }\r\n}\r\n\r\n// Effect callback, extracted: subscribe to the Redux store or nearest connected ancestor,\r\n// check for updates after dispatched actions, and trigger re-renders.\r\nfunction subscribeUpdates(\r\n shouldHandleStateChanges: boolean,\r\n store: Store,\r\n subscription: Subscription,\r\n childPropsSelector: (state: unknown, props: unknown) => unknown,\r\n lastWrapperProps: React.MutableRefObject,\r\n lastChildProps: React.MutableRefObject,\r\n renderIsScheduled: React.MutableRefObject,\r\n isMounted: React.MutableRefObject,\r\n childPropsFromStoreUpdate: React.MutableRefObject,\r\n notifyNestedSubs: () => void,\r\n // forceComponentUpdateDispatch: React.Dispatch,\r\n additionalSubscribeListener: () => void\r\n) {\r\n // If we're not subscribed to the store, nothing to do here\r\n if (!shouldHandleStateChanges) return () => {}\r\n\r\n // Capture values for checking if and when this component unmounts\r\n let didUnsubscribe = false\r\n let lastThrownError: Error | null = null\r\n\r\n // We'll run this callback every time a store subscription update propagates to this component\r\n const checkForUpdates = () => {\r\n if (didUnsubscribe || !isMounted.current) {\r\n // Don't run stale listeners.\r\n // Redux doesn't guarantee unsubscriptions happen until next dispatch.\r\n return\r\n }\r\n\r\n // TODO We're currently calling getState ourselves here, rather than letting `uSES` do it\r\n const latestStoreState = store.getState()\r\n\r\n let newChildProps, error\r\n try {\r\n // Actually run the selector with the most recent store state and wrapper props\r\n // to determine what the child props should be\r\n newChildProps = childPropsSelector(\r\n latestStoreState,\r\n lastWrapperProps.current\r\n )\r\n } catch (e) {\r\n error = e\r\n lastThrownError = e as Error | null\r\n }\r\n\r\n if (!error) {\r\n lastThrownError = null\r\n }\r\n\r\n // If the child props haven't changed, nothing to do here - cascade the subscription update\r\n if (newChildProps === lastChildProps.current) {\r\n if (!renderIsScheduled.current) {\r\n notifyNestedSubs()\r\n }\r\n } else {\r\n // Save references to the new child props. Note that we track the \"child props from store update\"\r\n // as a ref instead of a useState/useReducer because we need a way to determine if that value has\r\n // been processed. If this went into useState/useReducer, we couldn't clear out the value without\r\n // forcing another re-render, which we don't want.\r\n lastChildProps.current = newChildProps\r\n childPropsFromStoreUpdate.current = newChildProps\r\n renderIsScheduled.current = true\r\n\r\n // TODO This is hacky and not how `uSES` is meant to be used\r\n // Trigger the React `useSyncExternalStore` subscriber\r\n additionalSubscribeListener()\r\n }\r\n }\r\n\r\n // Actually subscribe to the nearest connected ancestor (or store)\r\n subscription.onStateChange = checkForUpdates\r\n subscription.trySubscribe()\r\n\r\n // Pull data from the store after first render in case the store has\r\n // changed since we began.\r\n checkForUpdates()\r\n\r\n const unsubscribeWrapper = () => {\r\n didUnsubscribe = true\r\n subscription.tryUnsubscribe()\r\n subscription.onStateChange = null\r\n\r\n if (lastThrownError) {\r\n // It's possible that we caught an error due to a bad mapState function, but the\r\n // parent re-rendered without this component and we're about to unmount.\r\n // This shouldn't happen as long as we do top-down subscriptions correctly, but\r\n // if we ever do those wrong, this throw will surface the error in our tests.\r\n // In that case, throw the error from here so it doesn't get lost.\r\n throw lastThrownError\r\n }\r\n }\r\n\r\n return unsubscribeWrapper\r\n}\r\n\r\n// Reducer initial state creation for our update reducer\r\nconst initStateUpdates = () => EMPTY_ARRAY\r\n\r\nexport interface ConnectProps {\r\n /** A custom Context instance that the component can use to access the store from an alternate Provider using that same Context instance */\r\n context?: ReactReduxContextInstance\r\n /** A Redux store instance to be used for subscriptions instead of the store from a Provider */\r\n store?: Store\r\n}\r\n\r\ninterface InternalConnectProps extends ConnectProps {\r\n reactReduxForwardedRef?: React.ForwardedRef\r\n}\r\n\r\nfunction strictEqual(a: unknown, b: unknown) {\r\n return a === b\r\n}\r\n\r\n/**\r\n * Infers the type of props that a connector will inject into a component.\r\n */\r\nexport type ConnectedProps =\r\n TConnector extends InferableComponentEnhancerWithProps<\r\n infer TInjectedProps,\r\n any\r\n >\r\n ? unknown extends TInjectedProps\r\n ? TConnector extends InferableComponentEnhancer\r\n ? TInjectedProps\r\n : never\r\n : TInjectedProps\r\n : never\r\n\r\nexport interface ConnectOptions<\r\n State = unknown,\r\n TStateProps = {},\r\n TOwnProps = {},\r\n TMergedProps = {}\r\n> {\r\n forwardRef?: boolean\r\n context?: typeof ReactReduxContext\r\n areStatesEqual?: (\r\n nextState: State,\r\n prevState: State,\r\n nextOwnProps: TOwnProps,\r\n prevOwnProps: TOwnProps\r\n ) => boolean\r\n\r\n areOwnPropsEqual?: (\r\n nextOwnProps: TOwnProps,\r\n prevOwnProps: TOwnProps\r\n ) => boolean\r\n\r\n areStatePropsEqual?: (\r\n nextStateProps: TStateProps,\r\n prevStateProps: TStateProps\r\n ) => boolean\r\n areMergedPropsEqual?: (\r\n nextMergedProps: TMergedProps,\r\n prevMergedProps: TMergedProps\r\n ) => boolean\r\n}\r\n\r\n/**\r\n * Connects a React component to a Redux store.\r\n *\r\n * - Without arguments, just wraps the component, without changing the behavior / props\r\n *\r\n * - If 2 params are passed (3rd param, mergeProps, is skipped), default behavior\r\n * is to override ownProps (as stated in the docs), so what remains is everything that's\r\n * not a state or dispatch prop\r\n *\r\n * - When 3rd param is passed, we don't know if ownProps propagate and whether they\r\n * should be valid component props, because it depends on mergeProps implementation.\r\n * As such, it is the user's responsibility to extend ownProps interface from state or\r\n * dispatch props or both when applicable\r\n *\r\n * @param mapStateToProps\r\n * @param mapDispatchToProps\r\n * @param mergeProps\r\n * @param options\r\n */\r\nexport interface Connect {\r\n // tslint:disable:no-unnecessary-generics\r\n (): InferableComponentEnhancer\r\n\r\n /** mapState only */\r\n (\r\n mapStateToProps: MapStateToPropsParam\r\n ): InferableComponentEnhancerWithProps\r\n\r\n /** mapDispatch only (as a function) */\r\n (\r\n mapStateToProps: null | undefined,\r\n mapDispatchToProps: MapDispatchToPropsNonObject\r\n ): InferableComponentEnhancerWithProps\r\n\r\n /** mapDispatch only (as an object) */\r\n (\r\n mapStateToProps: null | undefined,\r\n mapDispatchToProps: MapDispatchToPropsParam\r\n ): InferableComponentEnhancerWithProps<\r\n ResolveThunks,\r\n TOwnProps\r\n >\r\n\r\n /** mapState and mapDispatch (as a function)*/\r\n (\r\n mapStateToProps: MapStateToPropsParam,\r\n mapDispatchToProps: MapDispatchToPropsNonObject\r\n ): InferableComponentEnhancerWithProps<\r\n TStateProps & TDispatchProps,\r\n TOwnProps\r\n >\r\n\r\n /** mapState and mapDispatch (nullish) */\r\n (\r\n mapStateToProps: MapStateToPropsParam,\r\n mapDispatchToProps: null | undefined\r\n ): InferableComponentEnhancerWithProps\r\n\r\n /** mapState and mapDispatch (as an object) */\r\n (\r\n mapStateToProps: MapStateToPropsParam,\r\n mapDispatchToProps: MapDispatchToPropsParam\r\n ): InferableComponentEnhancerWithProps<\r\n TStateProps & ResolveThunks,\r\n TOwnProps\r\n >\r\n\r\n /** mergeProps only */\r\n (\r\n mapStateToProps: null | undefined,\r\n mapDispatchToProps: null | undefined,\r\n mergeProps: MergeProps\r\n ): InferableComponentEnhancerWithProps\r\n\r\n /** mapState and mergeProps */\r\n <\r\n TStateProps = {},\r\n no_dispatch = {},\r\n TOwnProps = {},\r\n TMergedProps = {},\r\n State = DefaultState\r\n >(\r\n mapStateToProps: MapStateToPropsParam,\r\n mapDispatchToProps: null | undefined,\r\n mergeProps: MergeProps\r\n ): InferableComponentEnhancerWithProps\r\n\r\n /** mapDispatch (as a object) and mergeProps */\r\n (\r\n mapStateToProps: null | undefined,\r\n mapDispatchToProps: MapDispatchToPropsParam,\r\n mergeProps: MergeProps\r\n ): InferableComponentEnhancerWithProps\r\n\r\n /** mapState and options */\r\n (\r\n mapStateToProps: MapStateToPropsParam,\r\n mapDispatchToProps: null | undefined,\r\n mergeProps: null | undefined,\r\n options: ConnectOptions\r\n ): InferableComponentEnhancerWithProps\r\n\r\n /** mapDispatch (as a function) and options */\r\n (\r\n mapStateToProps: null | undefined,\r\n mapDispatchToProps: MapDispatchToPropsNonObject,\r\n mergeProps: null | undefined,\r\n options: ConnectOptions<{}, TStateProps, TOwnProps>\r\n ): InferableComponentEnhancerWithProps\r\n\r\n /** mapDispatch (as an object) and options*/\r\n (\r\n mapStateToProps: null | undefined,\r\n mapDispatchToProps: MapDispatchToPropsParam,\r\n mergeProps: null | undefined,\r\n options: ConnectOptions<{}, TStateProps, TOwnProps>\r\n ): InferableComponentEnhancerWithProps<\r\n ResolveThunks,\r\n TOwnProps\r\n >\r\n\r\n /** mapState, mapDispatch (as a function), and options */\r\n (\r\n mapStateToProps: MapStateToPropsParam,\r\n mapDispatchToProps: MapDispatchToPropsNonObject,\r\n mergeProps: null | undefined,\r\n options: ConnectOptions\r\n ): InferableComponentEnhancerWithProps<\r\n TStateProps & TDispatchProps,\r\n TOwnProps\r\n >\r\n\r\n /** mapState, mapDispatch (as an object), and options */\r\n (\r\n mapStateToProps: MapStateToPropsParam,\r\n mapDispatchToProps: MapDispatchToPropsParam,\r\n mergeProps: null | undefined,\r\n options: ConnectOptions\r\n ): InferableComponentEnhancerWithProps<\r\n TStateProps & ResolveThunks,\r\n TOwnProps\r\n >\r\n\r\n /** mapState, mapDispatch, mergeProps, and options */\r\n <\r\n TStateProps = {},\r\n TDispatchProps = {},\r\n TOwnProps = {},\r\n TMergedProps = {},\r\n State = DefaultState\r\n >(\r\n mapStateToProps: MapStateToPropsParam,\r\n mapDispatchToProps: MapDispatchToPropsParam,\r\n mergeProps: MergeProps<\r\n TStateProps,\r\n TDispatchProps,\r\n TOwnProps,\r\n TMergedProps\r\n >,\r\n options?: ConnectOptions\r\n ): InferableComponentEnhancerWithProps\r\n // tslint:enable:no-unnecessary-generics\r\n}\r\n\r\nlet hasWarnedAboutDeprecatedPureOption = false\r\n\r\n/**\r\n * Connects a React component to a Redux store.\r\n *\r\n * - Without arguments, just wraps the component, without changing the behavior / props\r\n *\r\n * - If 2 params are passed (3rd param, mergeProps, is skipped), default behavior\r\n * is to override ownProps (as stated in the docs), so what remains is everything that's\r\n * not a state or dispatch prop\r\n *\r\n * - When 3rd param is passed, we don't know if ownProps propagate and whether they\r\n * should be valid component props, because it depends on mergeProps implementation.\r\n * As such, it is the user's responsibility to extend ownProps interface from state or\r\n * dispatch props or both when applicable\r\n *\r\n * @param mapStateToProps A function that extracts values from state\r\n * @param mapDispatchToProps Setup for dispatching actions\r\n * @param mergeProps Optional callback to merge state and dispatch props together\r\n * @param options Options for configuring the connection\r\n *\r\n */\r\nfunction connect<\r\n TStateProps = {},\r\n TDispatchProps = {},\r\n TOwnProps = {},\r\n TMergedProps = {},\r\n State = unknown\r\n>(\r\n mapStateToProps?: MapStateToPropsParam,\r\n mapDispatchToProps?: MapDispatchToPropsParam,\r\n mergeProps?: MergeProps,\r\n {\r\n // The `pure` option has been removed, so TS doesn't like us destructuring this to check its existence.\r\n // @ts-ignore\r\n pure,\r\n areStatesEqual = strictEqual,\r\n areOwnPropsEqual = shallowEqual,\r\n areStatePropsEqual = shallowEqual,\r\n areMergedPropsEqual = shallowEqual,\r\n\r\n // use React's forwardRef to expose a ref of the wrapped component\r\n forwardRef = false,\r\n\r\n // the context consumer to use\r\n context = ReactReduxContext,\r\n }: ConnectOptions = {}\r\n): unknown {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (pure !== undefined && !hasWarnedAboutDeprecatedPureOption) {\r\n hasWarnedAboutDeprecatedPureOption = true\r\n warning(\r\n 'The `pure` option has been removed. `connect` is now always a \"pure/memoized\" component'\r\n )\r\n }\r\n }\r\n\r\n const Context = context\r\n\r\n const initMapStateToProps = mapStateToPropsFactory(mapStateToProps)\r\n const initMapDispatchToProps = mapDispatchToPropsFactory(mapDispatchToProps)\r\n const initMergeProps = mergePropsFactory(mergeProps)\r\n\r\n const shouldHandleStateChanges = Boolean(mapStateToProps)\r\n\r\n const wrapWithConnect = (\r\n WrappedComponent: ComponentType\r\n ) => {\r\n type WrappedComponentProps = TProps &\r\n ConnectPropsMaybeWithoutContext\r\n\r\n if (process.env.NODE_ENV !== 'production') {\r\n const isValid = /*#__PURE__*/ isValidElementType(WrappedComponent)\r\n if (!isValid)\r\n throw new Error(\r\n `You must pass a component to the function returned by connect. Instead received ${stringifyComponent(\r\n WrappedComponent\r\n )}`\r\n )\r\n }\r\n\r\n const wrappedComponentName =\r\n WrappedComponent.displayName || WrappedComponent.name || 'Component'\r\n\r\n const displayName = `Connect(${wrappedComponentName})`\r\n\r\n const selectorFactoryOptions: SelectorFactoryOptions<\r\n any,\r\n any,\r\n any,\r\n any,\r\n State\r\n > = {\r\n shouldHandleStateChanges,\r\n displayName,\r\n wrappedComponentName,\r\n WrappedComponent,\r\n // @ts-ignore\r\n initMapStateToProps,\r\n // @ts-ignore\r\n initMapDispatchToProps,\r\n initMergeProps,\r\n areStatesEqual,\r\n areStatePropsEqual,\r\n areOwnPropsEqual,\r\n areMergedPropsEqual,\r\n }\r\n\r\n function ConnectFunction(\r\n props: InternalConnectProps & TOwnProps\r\n ) {\r\n const [propsContext, reactReduxForwardedRef, wrapperProps] =\r\n React.useMemo(() => {\r\n // Distinguish between actual \"data\" props that were passed to the wrapper component,\r\n // and values needed to control behavior (forwarded refs, alternate context instances).\r\n // To maintain the wrapperProps object reference, memoize this destructuring.\r\n const { reactReduxForwardedRef, ...wrapperProps } = props\r\n return [props.context, reactReduxForwardedRef, wrapperProps]\r\n }, [props])\r\n\r\n const ContextToUse: ReactReduxContextInstance = React.useMemo(() => {\r\n // Users may optionally pass in a custom context instance to use instead of our ReactReduxContext.\r\n // Memoize the check that determines which context instance we should use.\r\n let ResultContext = Context\r\n if (propsContext?.Consumer) {\r\n if (process.env.NODE_ENV !== 'production') {\r\n const isValid = /*#__PURE__*/ isContextConsumer(\r\n // @ts-ignore\r\n \r\n )\r\n if (!isValid) {\r\n throw new Error(\r\n 'You must pass a valid React context consumer as `props.context`'\r\n )\r\n }\r\n ResultContext = propsContext\r\n }\r\n }\r\n return ResultContext\r\n }, [propsContext, Context])\r\n\r\n // Retrieve the store and ancestor subscription via context, if available\r\n const contextValue = React.useContext(ContextToUse)\r\n\r\n // The store _must_ exist as either a prop or in context.\r\n // We'll check to see if it _looks_ like a Redux store first.\r\n // This allows us to pass through a `store` prop that is just a plain value.\r\n const didStoreComeFromProps =\r\n Boolean(props.store) &&\r\n Boolean(props.store!.getState) &&\r\n Boolean(props.store!.dispatch)\r\n const didStoreComeFromContext =\r\n Boolean(contextValue) && Boolean(contextValue!.store)\r\n\r\n if (\r\n process.env.NODE_ENV !== 'production' &&\r\n !didStoreComeFromProps &&\r\n !didStoreComeFromContext\r\n ) {\r\n throw new Error(\r\n `Could not find \"store\" in the context of ` +\r\n `\"${displayName}\". Either wrap the root component in a , ` +\r\n `or pass a custom React context provider to and the corresponding ` +\r\n `React context consumer to ${displayName} in connect options.`\r\n )\r\n }\r\n\r\n // Based on the previous check, one of these must be true\r\n const store: Store = didStoreComeFromProps\r\n ? props.store!\r\n : contextValue!.store\r\n\r\n const getServerState = didStoreComeFromContext\r\n ? contextValue!.getServerState\r\n : store.getState\r\n\r\n const childPropsSelector = React.useMemo(() => {\r\n // The child props selector needs the store reference as an input.\r\n // Re-create this selector whenever the store changes.\r\n return defaultSelectorFactory(store.dispatch, selectorFactoryOptions)\r\n }, [store])\r\n\r\n const [subscription, notifyNestedSubs] = React.useMemo(() => {\r\n if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY\r\n\r\n // This Subscription's source should match where store came from: props vs. context. A component\r\n // connected to the store via props shouldn't use subscription from context, or vice versa.\r\n const subscription = createSubscription(\r\n store,\r\n didStoreComeFromProps ? undefined : contextValue!.subscription\r\n )\r\n\r\n // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in\r\n // the middle of the notification loop, where `subscription` will then be null. This can\r\n // probably be avoided if Subscription's listeners logic is changed to not call listeners\r\n // that have been unsubscribed in the middle of the notification loop.\r\n const notifyNestedSubs =\r\n subscription.notifyNestedSubs.bind(subscription)\r\n\r\n return [subscription, notifyNestedSubs]\r\n }, [store, didStoreComeFromProps, contextValue])\r\n\r\n // Determine what {store, subscription} value should be put into nested context, if necessary,\r\n // and memoize that value to avoid unnecessary context updates.\r\n const overriddenContextValue = React.useMemo(() => {\r\n if (didStoreComeFromProps) {\r\n // This component is directly subscribed to a store from props.\r\n // We don't want descendants reading from this store - pass down whatever\r\n // the existing context value is from the nearest connected ancestor.\r\n return contextValue!\r\n }\r\n\r\n // Otherwise, put this component's subscription instance into context, so that\r\n // connected descendants won't update until after this component is done\r\n return {\r\n ...contextValue,\r\n subscription,\r\n } as ReactReduxContextValue\r\n }, [didStoreComeFromProps, contextValue, subscription])\r\n\r\n // Set up refs to coordinate values between the subscription effect and the render logic\r\n const lastChildProps = React.useRef()\r\n const lastWrapperProps = React.useRef(wrapperProps)\r\n const childPropsFromStoreUpdate = React.useRef()\r\n const renderIsScheduled = React.useRef(false)\r\n const isProcessingDispatch = React.useRef(false)\r\n const isMounted = React.useRef(false)\r\n\r\n const latestSubscriptionCallbackError = React.useRef()\r\n\r\n useIsomorphicLayoutEffect(() => {\r\n isMounted.current = true\r\n return () => {\r\n isMounted.current = false\r\n }\r\n }, [])\r\n\r\n const actualChildPropsSelector = React.useMemo(() => {\r\n const selector = () => {\r\n // Tricky logic here:\r\n // - This render may have been triggered by a Redux store update that produced new child props\r\n // - However, we may have gotten new wrapper props after that\r\n // If we have new child props, and the same wrapper props, we know we should use the new child props as-is.\r\n // But, if we have new wrapper props, those might change the child props, so we have to recalculate things.\r\n // So, we'll use the child props from store update only if the wrapper props are the same as last time.\r\n if (\r\n childPropsFromStoreUpdate.current &&\r\n wrapperProps === lastWrapperProps.current\r\n ) {\r\n return childPropsFromStoreUpdate.current\r\n }\r\n\r\n // TODO We're reading the store directly in render() here. Bad idea?\r\n // This will likely cause Bad Things (TM) to happen in Concurrent Mode.\r\n // Note that we do this because on renders _not_ caused by store updates, we need the latest store state\r\n // to determine what the child props should be.\r\n return childPropsSelector(store.getState(), wrapperProps)\r\n }\r\n return selector\r\n }, [store, wrapperProps])\r\n\r\n // We need this to execute synchronously every time we re-render. However, React warns\r\n // about useLayoutEffect in SSR, so we try to detect environment and fall back to\r\n // just useEffect instead to avoid the warning, since neither will run anyway.\r\n\r\n const subscribeForReact = React.useMemo(() => {\r\n const subscribe = (reactListener: () => void) => {\r\n if (!subscription) {\r\n return () => {}\r\n }\r\n\r\n return subscribeUpdates(\r\n shouldHandleStateChanges,\r\n store,\r\n subscription,\r\n // @ts-ignore\r\n childPropsSelector,\r\n lastWrapperProps,\r\n lastChildProps,\r\n renderIsScheduled,\r\n isMounted,\r\n childPropsFromStoreUpdate,\r\n notifyNestedSubs,\r\n reactListener\r\n )\r\n }\r\n\r\n return subscribe\r\n }, [subscription])\r\n\r\n useIsomorphicLayoutEffectWithArgs(captureWrapperProps, [\r\n lastWrapperProps,\r\n lastChildProps,\r\n renderIsScheduled,\r\n wrapperProps,\r\n childPropsFromStoreUpdate,\r\n notifyNestedSubs,\r\n ])\r\n\r\n let actualChildProps: Record\r\n\r\n try {\r\n actualChildProps = useSyncExternalStore(\r\n // TODO We're passing through a big wrapper that does a bunch of extra side effects besides subscribing\r\n subscribeForReact,\r\n // TODO This is incredibly hacky. We've already processed the store update and calculated new child props,\r\n // TODO and we're just passing that through so it triggers a re-render for us rather than relying on `uSES`.\r\n actualChildPropsSelector,\r\n getServerState\r\n ? () => childPropsSelector(getServerState(), wrapperProps)\r\n : actualChildPropsSelector\r\n )\r\n } catch (err) {\r\n if (latestSubscriptionCallbackError.current) {\r\n ;(\r\n err as Error\r\n ).message += `\\nThe error may be correlated with this previous error:\\n${latestSubscriptionCallbackError.current.stack}\\n\\n`\r\n }\r\n\r\n throw err\r\n }\r\n\r\n useIsomorphicLayoutEffect(() => {\r\n latestSubscriptionCallbackError.current = undefined\r\n childPropsFromStoreUpdate.current = undefined\r\n lastChildProps.current = actualChildProps\r\n })\r\n\r\n // Now that all that's done, we can finally try to actually render the child component.\r\n // We memoize the elements for the rendered child component as an optimization.\r\n const renderedWrappedComponent = React.useMemo(() => {\r\n return (\r\n // @ts-ignore\r\n \r\n )\r\n }, [reactReduxForwardedRef, WrappedComponent, actualChildProps])\r\n\r\n // If React sees the exact same element reference as last time, it bails out of re-rendering\r\n // that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate.\r\n const renderedChild = React.useMemo(() => {\r\n if (shouldHandleStateChanges) {\r\n // If this component is subscribed to store updates, we need to pass its own\r\n // subscription instance down to our descendants. That means rendering the same\r\n // Context instance, and putting a different value into the context.\r\n return (\r\n \r\n {renderedWrappedComponent}\r\n \r\n )\r\n }\r\n\r\n return renderedWrappedComponent\r\n }, [ContextToUse, renderedWrappedComponent, overriddenContextValue])\r\n\r\n return renderedChild\r\n }\r\n\r\n const _Connect = React.memo(ConnectFunction)\r\n\r\n type ConnectedWrapperComponent = typeof _Connect & {\r\n WrappedComponent: typeof WrappedComponent\r\n }\r\n\r\n // Add a hacky cast to get the right output type\r\n const Connect = _Connect as unknown as ConnectedComponent<\r\n typeof WrappedComponent,\r\n WrappedComponentProps\r\n >\r\n Connect.WrappedComponent = WrappedComponent\r\n Connect.displayName = ConnectFunction.displayName = displayName\r\n\r\n if (forwardRef) {\r\n const _forwarded = React.forwardRef(function forwardConnectRef(\r\n props,\r\n ref\r\n ) {\r\n // @ts-ignore\r\n return \r\n })\r\n\r\n const forwarded = _forwarded as ConnectedWrapperComponent\r\n forwarded.displayName = displayName\r\n forwarded.WrappedComponent = WrappedComponent\r\n return /*#__PURE__*/ hoistStatics(forwarded, WrappedComponent)\r\n }\r\n\r\n return /*#__PURE__*/ hoistStatics(Connect, WrappedComponent)\r\n }\r\n\r\n return wrapWithConnect\r\n}\r\n\r\nexport default connect as Connect\r\n","export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = !0,\n o = !1;\n try {\n if (i = (t = t.call(r)).next, 0 === l) {\n if (Object(t) !== t) return;\n f = !1;\n } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = !0, n = r;\n } finally {\n try {\n if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","import defineProperty from \"./defineProperty.js\";\nfunction ownKeys(e, r) {\n var t = Object.keys(e);\n if (Object.getOwnPropertySymbols) {\n var o = Object.getOwnPropertySymbols(e);\n r && (o = o.filter(function (r) {\n return Object.getOwnPropertyDescriptor(e, r).enumerable;\n })), t.push.apply(t, o);\n }\n return t;\n}\nexport default function _objectSpread2(e) {\n for (var r = 1; r < arguments.length; r++) {\n var t = null != arguments[r] ? arguments[r] : {};\n r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {\n defineProperty(e, r, t[r]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n });\n }\n return e;\n}","import objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose.js\";\nexport default function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n return target;\n}","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}","import arrayWithoutHoles from \"./arrayWithoutHoles.js\";\nimport iterableToArray from \"./iterableToArray.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableSpread from \"./nonIterableSpread.js\";\nexport default function _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return arrayLikeToArray(arr);\n}","export default function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}","export default function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e))for(t=0;t= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n },\n e: function e(_e) {\n throw _e;\n },\n f: F\n };\n }\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n var normalCompletion = true,\n didErr = false,\n err;\n return {\n s: function s() {\n it = it.call(o);\n },\n n: function n() {\n var step = it.next();\n normalCompletion = step.done;\n return step;\n },\n e: function e(_e2) {\n didErr = true;\n err = _e2;\n },\n f: function f() {\n try {\n if (!normalCompletion && it[\"return\"] != null) it[\"return\"]();\n } finally {\n if (didErr) throw err;\n }\n }\n };\n}","// Should be no imports here!\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: unique symbol = Symbol.for(\"immer-nothing\")\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = Symbol.for(\"immer-draftable\")\n\nexport const DRAFT_STATE: unique symbol = Symbol.for(\"immer-state\")\n","export const errors =\n\tprocess.env.NODE_ENV !== \"production\"\n\t\t? [\n\t\t\t\t// All error codes, starting by 0:\n\t\t\t\tfunction(plugin: string) {\n\t\t\t\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t\t\t\t},\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t\t\t\t},\n\t\t\t\t\"This object has been frozen and should not be mutated\",\n\t\t\t\tfunction(data: any) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\t\t\t\tdata\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\t\"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t\t\t\t\"Immer forbids circular references\",\n\t\t\t\t\"The first or second argument to `produce` must be a function\",\n\t\t\t\t\"The third argument to `produce` must be a function or undefined\",\n\t\t\t\t\"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t\t\t\t\"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'current' expects a draft, got: ${thing}`\n\t\t\t\t},\n\t\t\t\t\"Object.defineProperty() cannot be used on an Immer draft\",\n\t\t\t\t\"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t\t\t\t\"Immer only supports deleting array indices\",\n\t\t\t\t\"Immer only supports setting array indices and the 'length' property\",\n\t\t\t\tfunction(thing: string) {\n\t\t\t\t\treturn `'original' expects a draft, got: ${thing}`\n\t\t\t\t}\n\t\t\t\t// Note: if more errors are added, the errorOffset in Patches.ts should be increased\n\t\t\t\t// See Patches.ts for additional errors\n\t\t ]\n\t\t: []\n\nexport function die(error: number, ...args: any[]): never {\n\tif (process.env.NODE_ENV !== \"production\") {\n\t\tconst e = errors[error]\n\t\tconst msg = typeof e === \"function\" ? e.apply(null, args as any) : e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n","import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\tArchType,\n\tdie\n} from \"../internal\"\n\nexport const getPrototypeOf = Object.getPrototypeOf\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport function isDraft(value: any): boolean {\n\treturn !!value && !!value[DRAFT_STATE]\n}\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tArray.isArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value.constructor?.[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = Object.prototype.constructor.toString()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || typeof value !== \"object\") return false\n\tconst proto = getPrototypeOf(value)\n\tif (proto === null) {\n\t\treturn true\n\t}\n\tconst Ctor =\n\t\tObject.hasOwnProperty.call(proto, \"constructor\") && proto.constructor\n\n\tif (Ctor === Object) return true\n\n\treturn (\n\t\ttypeof Ctor == \"function\" &&\n\t\tFunction.toString.call(Ctor) === objectCtorString\n\t)\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original(value: T): T | undefined\nexport function original(value: Drafted): any {\n\tif (!isDraft(value)) die(15, value)\n\treturn value[DRAFT_STATE].base_\n}\n\nexport function each(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tenumerableOnly?: boolean\n): void\nexport function each(obj: any, iter: any) {\n\tif (getArchtype(obj) === ArchType.Object) {\n\t\tObject.entries(obj).forEach(([key, value]) => {\n\t\t\titer(key, value, obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): ArchType {\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_\n\t\t: Array.isArray(thing)\n\t\t? ArchType.Array\n\t\t: isMap(thing)\n\t\t? ArchType.Map\n\t\t: isSet(thing)\n\t\t? ArchType.Set\n\t\t: ArchType.Object\n}\n\n/*#__PURE__*/\nexport function has(thing: any, prop: PropertyKey): boolean {\n\treturn getArchtype(thing) === ArchType.Map\n\t\t? thing.has(prop)\n\t\t: Object.prototype.hasOwnProperty.call(thing, prop)\n}\n\n/*#__PURE__*/\nexport function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {\n\t// @ts-ignore\n\treturn getArchtype(thing) === ArchType.Map ? thing.get(prop) : thing[prop]\n}\n\n/*#__PURE__*/\nexport function set(thing: any, propOrOldValue: PropertyKey, value: any) {\n\tconst t = getArchtype(thing)\n\tif (t === ArchType.Map) thing.set(propOrOldValue, value)\n\telse if (t === ArchType.Set) {\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\n/*#__PURE__*/\nexport function isMap(target: any): target is AnyMap {\n\treturn target instanceof Map\n}\n\n/*#__PURE__*/\nexport function isSet(target: any): target is AnySet {\n\treturn target instanceof Set\n}\n/*#__PURE__*/\nexport function latest(state: ImmerState): any {\n\treturn state.copy_ || state.base_\n}\n\n/*#__PURE__*/\nexport function shallowCopy(base: any, strict: boolean) {\n\tif (isMap(base)) {\n\t\treturn new Map(base)\n\t}\n\tif (isSet(base)) {\n\t\treturn new Set(base)\n\t}\n\tif (Array.isArray(base)) return Array.prototype.slice.call(base)\n\n\tif (!strict && isPlainObject(base)) {\n\t\tif (!getPrototypeOf(base)) {\n\t\t\tconst obj = Object.create(null)\n\t\t\treturn Object.assign(obj, base)\n\t\t}\n\t\treturn {...base}\n\t}\n\n\tconst descriptors = Object.getOwnPropertyDescriptors(base)\n\tdelete descriptors[DRAFT_STATE as any]\n\tlet keys = Reflect.ownKeys(descriptors)\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tconst key: any = keys[i]\n\t\tconst desc = descriptors[key]\n\t\tif (desc.writable === false) {\n\t\t\tdesc.writable = true\n\t\t\tdesc.configurable = true\n\t\t}\n\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t// with libraries that trap values, like mobx or vue\n\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\tif (desc.get || desc.set)\n\t\t\tdescriptors[key] = {\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true, // could live with !!desc.set as well here...\n\t\t\t\tenumerable: desc.enumerable,\n\t\t\t\tvalue: base[key]\n\t\t\t}\n\t}\n\treturn Object.create(getPrototypeOf(base), descriptors)\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze(obj: T, deep?: boolean): T\nexport function freeze(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tobj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any\n\t}\n\tObject.freeze(obj)\n\tif (deep) each(obj, (_key, value) => freeze(value, true), true)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nexport function isFrozen(obj: any): boolean {\n\treturn Object.isFrozen(obj)\n}\n","import {\n\tImmerState,\n\tPatch,\n\tDrafted,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tArchType,\n\tdie\n} from \"../internal\"\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: {\n\t\tgeneratePatches_(\n\t\t\tstate: ImmerState,\n\t\t\tbasePath: PatchPath,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tgenerateReplacementPatches_(\n\t\t\tbase: any,\n\t\t\treplacement: any,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tapplyPatches_(draft: T, patches: Patch[]): T\n\t}\n\tMapSet?: {\n\t\tproxyMap_(target: T, parent?: ImmerState): T\n\t\tproxySet_(target: T, parent?: ImmerState): T\n\t}\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin(\n\tpluginKey: K\n): Exclude {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(0, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport function loadPlugin(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ArchType.Map\n\tcopy_: AnyMap | undefined\n\tassigned_: Map | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ArchType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n","import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tArchType,\n\tgetPlugin\n} from \"../internal\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport function getCurrentScope() {\n\treturn currentScope!\n}\n\nfunction createScope(\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope {\n\treturn {\n\t\tdrafts_: [],\n\t\tparent_,\n\t\timmer_,\n\t\t// Whenever the modified draft contains a draft from another scope, we\n\t\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\t\tcanAutoFreeze_: true,\n\t\tunfinalizedDrafts_: 0\n\t}\n}\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tgetPlugin(\"Patches\") // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport function enterScope(immer: Immer) {\n\treturn (currentScope = createScope(currentScope, immer))\n}\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (state.type_ === ArchType.Object || state.type_ === ArchType.Array)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n","import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\thas,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tArchType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t\tif (!scope.parent_) maybeFreeze(scope, result)\n\t\t}\n\t\tif (scope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE].base_,\n\t\t\t\tresult,\n\t\t\t\tscope.patches_,\n\t\t\t\tscope.inversePatches_!\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft, [])\n\t}\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\t// A plain object, might need freezing, might contain drafts\n\tif (!state) {\n\t\teach(\n\t\t\tvalue,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, value, key, childValue, path),\n\t\t\ttrue // See #590, don't recurse into non-enumerable of non drafted objects\n\t\t)\n\t\treturn value\n\t}\n\t// Never finalize drafts owned by another scope.\n\tif (state.scope_ !== rootScope) return value\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\tmaybeFreeze(rootScope, state.base_, true)\n\t\treturn state.base_\n\t}\n\t// Not finalized yet, let's do that now\n\tif (!state.finalized_) {\n\t\tstate.finalized_ = true\n\t\tstate.scope_.unfinalizedDrafts_--\n\t\tconst result = state.copy_\n\t\t// Finalize all children of the copy\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// To preserve insertion order in all cases we then clear the set\n\t\t// And we let finalizeProperty know it needs to re-add non-draft children back to the target\n\t\tlet resultEach = result\n\t\tlet isSet = false\n\t\tif (state.type_ === ArchType.Set) {\n\t\t\tresultEach = new Set(result)\n\t\t\tresult.clear()\n\t\t\tisSet = true\n\t\t}\n\t\teach(resultEach, (key, childValue) =>\n\t\t\tfinalizeProperty(rootScope, state, result, key, childValue, path, isSet)\n\t\t)\n\t\t// everything inside is frozen, we can freeze here\n\t\tmaybeFreeze(rootScope, result, false)\n\t\t// first time finalizing, let's create those patches\n\t\tif (path && rootScope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generatePatches_(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\trootScope.patches_,\n\t\t\t\trootScope.inversePatches_!\n\t\t\t)\n\t\t}\n\t}\n\treturn state.copy_\n}\n\nfunction finalizeProperty(\n\trootScope: ImmerScope,\n\tparentState: undefined | ImmerState,\n\ttargetObject: any,\n\tprop: string | number,\n\tchildValue: any,\n\trootPath?: PatchPath,\n\ttargetIsSet?: boolean\n) {\n\tif (process.env.NODE_ENV !== \"production\" && childValue === targetObject)\n\t\tdie(5)\n\tif (isDraft(childValue)) {\n\t\tconst path =\n\t\t\trootPath &&\n\t\t\tparentState &&\n\t\t\tparentState!.type_ !== ArchType.Set && // Set objects are atomic since they have no keys.\n\t\t\t!has((parentState as Exclude).assigned_!, prop) // Skip deep patches for assigned keys.\n\t\t\t\t? rootPath!.concat(prop)\n\t\t\t\t: undefined\n\t\t// Drafts owned by `scope` are finalized here.\n\t\tconst res = finalize(rootScope, childValue, path)\n\t\tset(targetObject, prop, res)\n\t\t// Drafts from another scope must prevented to be frozen\n\t\t// if we got a draft back from finalize, we're in a nested produce and shouldn't freeze\n\t\tif (isDraft(res)) {\n\t\t\trootScope.canAutoFreeze_ = false\n\t\t} else return\n\t} else if (targetIsSet) {\n\t\ttargetObject.add(childValue)\n\t}\n\t// Search new objects for unfinalized drafts. Frozen objects should never contain drafts.\n\tif (isDraftable(childValue) && !isFrozen(childValue)) {\n\t\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t\t// This benefits especially adding large data tree's without further processing.\n\t\t\t// See add-data.js perf test\n\t\t\treturn\n\t\t}\n\t\tfinalize(rootScope, childValue)\n\t\t// immer deep freezes plain objects, so if there is no parent state, we freeze as well\n\t\tif (!parentState || !parentState.scope_.parent_)\n\t\t\tmaybeFreeze(rootScope, childValue)\n\t}\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\t// we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects\n\tif (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n","import {\n\teach,\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tgetPrototypeOf,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tArchType,\n\tImmerScope\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tassigned_: {\n\t\t[property: string]: boolean\n\t}\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ArchType.Object\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ArchType.Array\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy(\n\tbase: T,\n\tparent?: ImmerState\n): Drafted {\n\tconst isArray = Array.isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: isArray ? ArchType.Array : (ArchType.Object as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\tassigned_: {},\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler