{"version":3,"sources":["../src/is-object.ts","../src/shallow-copy.ts","../src/basic-lens.ts","../src/lens-focus.ts","../src/breaker.ts","../src/suspended-closure.ts","../src/connection.ts","../src/key-path-to-string.ts","../src/react.ts","../src/proxy-value.ts","../src/should-update.ts","../src/react-devtools.ts","../src/awaitable.ts","../src/subscription-graph.ts","../src/store.ts","../src/proxy-lens.ts","../src/create-lens.ts"],"sourcesContent":["export const isObject = (obj: any): obj is object => Object.prototype.toString.call(obj) === \"[object Object]\";\n","import { isObject } from \"./is-object\";\n\nconst DO_NOT_SHALLOW_COPY = Symbol();\n\nexport const doNotShallowCopy = <T extends {}>(obj: T): T => {\n  Object.defineProperty(obj, DO_NOT_SHALLOW_COPY, {\n    configurable: true,\n    enumerable: false,\n    writable: false,\n    value: true,\n  });\n\n  return obj;\n};\n\nexport const shallowCopy = <T extends {}>(obj: T): T => {\n  if (Reflect.has(obj, DO_NOT_SHALLOW_COPY)) {\n    return obj;\n  }\n\n  /**\n   * Need to do this check to ensure that referential\n   * equality will only break a single key in the object/array.\n   * We can't blanket use `{ ...obj }` on everything because\n   * that would transform an array into a plain object.\n   */\n  if (isObject(obj)) {\n    return { ...obj };\n  } else if (Array.isArray(obj)) {\n    return [...obj] as any as T;\n  } else {\n    /**\n     * This function should only ever be called with a plain object or array.\n     * Other data types either can't be copied or can only be mutated, so\n     * just throw.\n     */\n    throw new Error(\"shallowCopy expected a plain object or array\");\n  }\n};\n","import { shallowCopy } from \"./shallow-copy\";\n\nexport type BasicLens<S, A> = {\n  get(s: S): A;\n  set(s: S, a: A): S;\n};\n\nconst identity: BasicLens<any, any> = Object.freeze({\n  get(s) {\n    return s;\n  },\n  set(s, a) {\n    return a;\n  },\n});\n\nexport const basicLens = <S>(): BasicLens<S, S> => identity;\n\nconst refine = <S extends {}, A, B>(\n  lens: BasicLens<S, A>,\n  get: (a: A) => B,\n  set: (a: A, b: B) => A\n): BasicLens<S, B> => {\n  return {\n    get(s) {\n      const a = lens.get(s);\n      return get(a);\n    },\n\n    set(s, b) {\n      const a = lens.get(s);\n      return lens.set(s, set(a, b));\n    },\n  };\n};\n\nexport const prop = <S extends {}, A extends {}, K extends keyof A>(\n  lens: BasicLens<S, A>,\n  key: K\n): BasicLens<S, A[K]> => {\n  return refine(\n    lens,\n    (s) => s[key],\n    (a, ak) => {\n      const copy = shallowCopy(a);\n      copy[key] = ak;\n\n      return copy;\n    }\n  );\n};\n","import { basicLens, BasicLens, prop } from \"./basic-lens\";\nimport { Key } from \"./types\";\n\nexport type LensFocus<S, A> = {\n  keyPath: Key[];\n  lens: BasicLens<S, A>;\n};\n\nexport function refineLensFocus<S, A, K1 extends keyof A>(focus: LensFocus<S, A>, keys: [K1]): LensFocus<S, A[K1]>;\n\nexport function refineLensFocus<S, A, K1 extends keyof A, K2 extends keyof A[K1]>(\n  focus: LensFocus<S, A>,\n  keys: [K1, K2]\n): LensFocus<S, A[K1][K2]>;\n\nexport function refineLensFocus<S, A, K1 extends keyof A, K2 extends keyof A[K1], K3 extends keyof A[K1][K2]>(\n  focus: LensFocus<S, A>,\n  keys: [K1, K2, K3]\n): LensFocus<S, A[K1][K2][K3]>;\n\nexport function refineLensFocus(focus: LensFocus<any, any>, keys: Key[]): LensFocus<any, any> {\n  const keyPath = [...focus.keyPath, ...keys];\n  let lens = focus.lens;\n\n  for (const key of keys) {\n    lens = prop(lens, key);\n  }\n\n  return { keyPath, lens };\n}\n\nexport const rootLensFocus = <S>(): LensFocus<S, S> => {\n  return {\n    keyPath: [],\n    lens: basicLens(),\n  };\n};\n","import { Unsubscribe } from \"./types\";\n\ntype State = { connected: false } | { connected: true; unsubscribe: Unsubscribe };\n\nexport interface Breakable {\n  connect(): void;\n  disconnect(): void;\n}\n\nexport class Breaker implements Breakable {\n  static noop() {\n    return new Breaker(() => () => {});\n  }\n\n  private state: State = { connected: false };\n\n  constructor(private subscribe: () => Unsubscribe) {}\n\n  get connected() {\n    return this.state.connected;\n  }\n\n  connect() {\n    if (this.state.connected) {\n      return;\n    }\n\n    const unsubscribe = this.subscribe.call(null);\n\n    this.state = {\n      connected: true,\n      unsubscribe,\n    };\n  }\n\n  disconnect() {\n    if (!this.state.connected) {\n      return;\n    }\n\n    this.state.unsubscribe();\n\n    this.state = {\n      connected: false,\n    };\n  }\n}\n","import { Breakable, Breaker } from \"./breaker\";\nimport { Unsubscribe } from \"./types\";\n\ntype Resolution<A> = { status: \"unresolved\" } | { status: \"loading\" } | { status: \"resolved\"; value: A };\n\nexport class SuspendedClosure<A> implements Breakable {\n  private resolution: Resolution<A> = { status: \"unresolved\" };\n  private breaker = Breaker.noop();\n  private onReady: Promise<unknown>;\n  private ready: () => void;\n\n  constructor() {\n    let ready = () => {};\n\n    this.onReady = new Promise<void>((resolve) => {\n      ready = resolve;\n    });\n\n    this.ready = () => ready();\n  }\n\n  getSnapshot(): A {\n    if (this.resolution.status !== \"resolved\") {\n      throw this.onReady;\n    }\n\n    return this.resolution.value;\n  }\n\n  setSnapshot(value: A) {\n    switch (this.resolution.status) {\n      case \"unresolved\": {\n        return;\n      }\n\n      case \"loading\": {\n        this.resolution = { status: \"resolved\", value };\n        this.ready();\n        return;\n      }\n\n      case \"resolved\": {\n        this.resolution.value = value;\n        return;\n      }\n    }\n  }\n\n  /**\n   * Connect the entry to the store by passing a subscribe function. Only\n   * allow this in transitioning from unresolved to resolved.\n   */\n  load(subscribe: () => Unsubscribe) {\n    if (this.resolution.status !== \"unresolved\") {\n      return;\n    }\n\n    this.resolution = { status: \"loading\" };\n\n    /**\n     * If the entry was previously unresolved, but connected—via subscribe—then\n     * we need to actually call the `connect()` function because we've now been given the\n     * real subscribe function.\n     */\n    const isAlreadyConnected = this.breaker.connected;\n\n    this.breaker = new Breaker(subscribe);\n\n    if (isAlreadyConnected) {\n      this.breaker.connect();\n    }\n  }\n\n  connect() {\n    this.breaker.connect();\n  }\n\n  disconnect() {\n    this.breaker.disconnect();\n  }\n}\n","import { isObject } from \"./is-object\";\nimport { LensFocus, refineLensFocus } from \"./lens-focus\";\nimport { doNotShallowCopy } from \"./shallow-copy\";\nimport { Store } from \"./store\";\nimport { SuspendedClosure } from \"./suspended-closure\";\nimport { Unsubscribe } from \"./types\";\n\ntype ConnectionCache<A> = {\n  [cacheKey: string]: SuspendedClosure<A>;\n};\n\ntype ValueCache<A> = {\n  [cacheKey: string]: A;\n};\n\ntype InsertConnection<A, I> = (store: Store<A>, input: I, cacheKey: string) => SuspendedClosure<A>;\n\nconst INSERT = Symbol();\nconst CACHE = Symbol();\n\nexport type Connection<A, I = void> = {\n  [INSERT]: InsertConnection<A, I>;\n  [CACHE]: ValueCache<A>;\n};\n\nexport const connection = <A, I = void>(\n  create: (store: Store<A>, input: I) => Unsubscribe | void\n): Connection<A, I> => {\n  const connectionCache: ConnectionCache<A> = {};\n  const stub = doNotShallowCopy({} as ValueCache<A>);\n  /**\n   * Wrap the real cache to handle suspense.\n   */\n  const cache = new Proxy(stub, {\n    get(_target, _key): A {\n      let key = _key as keyof ConnectionCache<A>;\n\n      /**\n       * If the value is not in the cache then create an unresolved entry for it.\n       * This can happen if we call `getSnapshot()` before the connection has even\n       * had a chance to insert an entry for the cache yet.\n       */\n      let cached = (connectionCache[key] ??= new SuspendedClosure<A>());\n\n      return cached.getSnapshot();\n    },\n\n    set(_target, _key, value) {\n      let key = _key as keyof ConnectionCache<A>;\n      let conn = connectionCache[key];\n\n      if (conn === undefined) {\n        return false;\n      }\n\n      conn.setSnapshot(value);\n      return true;\n    },\n  });\n\n  const insert: InsertConnection<A, I> = (store, input, cacheKey) => {\n    /**\n     * It can be that the cache entry was previously created by trying to\n     * access the cache because the code had been loaded.\n     */\n    let conn = (connectionCache[cacheKey] ??= new SuspendedClosure<A>());\n\n    conn.load(() => create(store, input) ?? (() => {}));\n\n    return conn;\n  };\n\n  const conn = doNotShallowCopy({} as Connection<A, I>);\n\n  Object.defineProperties(conn, {\n    [INSERT]: {\n      configurable: true,\n      enumerable: false,\n      writable: false,\n      value: insert,\n    },\n    [CACHE]: {\n      configurable: true,\n      enumerable: false,\n      writable: true,\n      value: cache,\n    },\n  });\n\n  return conn;\n};\n\nexport const focusToCache = <S, A, I>(focus: LensFocus<S, Connection<A, I>>, cacheKey: string): LensFocus<S, A> =>\n  refineLensFocus(focus, [CACHE, cacheKey]);\n\nexport const insert = <A, I>(conn: Connection<A, I>, store: Store<A>, input: I, cacheKey: string) => {\n  return conn[INSERT](store, input, cacheKey);\n};\n\nexport const isConnection = <A, I>(conn: any): conn is Connection<A, I> => {\n  return isObject(conn) && Reflect.has(conn, INSERT) && Reflect.has(conn, CACHE);\n};\n","import { Key } from \"./types\";\n\nconst cache = new WeakMap<Key[], string>();\nconst IS_NUMBER_STRING = /^\\d+$/;\n\nexport const keyPathToString = (keyPath: Key[]) => {\n  let cached = cache.get(keyPath);\n\n  if (!cached) {\n    cached = \"root\";\n\n    for (let key of keyPath) {\n      if (typeof key === \"symbol\" || typeof key === \"number\" || key.match(IS_NUMBER_STRING)) {\n        cached += `[${String(key)}]`;\n      } else {\n        cached += `.${key}`;\n      }\n    }\n\n    cache.set(keyPath, cached);\n  }\n\n  return cached;\n};\n","/// <reference types=\"react/next\" />\n\nimport React from \"react\";\nimport { createLens } from \"./create-lens\";\nimport { ProxyLens } from \"./proxy-lens\";\nimport { proxyValue, ProxyValue } from \"./proxy-value\";\nimport { ShouldUpdate, shouldUpdateToFunction } from \"./should-update\";\nimport { Listener, Update, Updater } from \"./types\";\n\ntype Nothing = typeof NOTHING;\n\nconst NOTHING = Symbol();\nconst SHOULD_ALWAYS_RETURN_NEXT = () => true;\n\nexport const createUseLens = <A>(proxy: ProxyLens<A>) =>\n  function useLens(shouldUpdate: ShouldUpdate<A> = SHOULD_ALWAYS_RETURN_NEXT): [ProxyValue<A>, Update<A>] {\n    React.useDebugValue(proxy.$key);\n\n    /**\n     * Memoize store from proxy. Proxy should never change, so this should be static.\n     */\n    const store = React.useMemo(() => proxy.getStore(), [proxy]);\n\n    /**\n     * Memoize shouldUpdate into a function.\n     */\n    const shouldUpdateFn = React.useMemo(() => shouldUpdateToFunction(shouldUpdate), [shouldUpdate]);\n\n    /**\n     * Track the previously resolved state, starting with `Nothing`.\n     */\n    const prevStateRef = React.useRef<A | Nothing>(NOTHING);\n\n    const getSnapshot = () => {\n      const prev = prevStateRef.current;\n      const next = store.getSnapshot();\n\n      /**\n       * If `prev` _is_ `next` then we should bail because nothing changed.\n       */\n      if (Object.is(prev, next)) {\n        return prev as A;\n      }\n\n      /**\n       * If the `prev` is `Nothing` then this is the first render,\n       * so just take `next.\n       */\n      if (prev === NOTHING) {\n        return next;\n      }\n\n      /**\n       * If we should update then return the `next`, else return `prev`\n       */\n      if (shouldUpdateFn(prev, next)) {\n        return next;\n      } else {\n        return prev;\n      }\n    };\n\n    /**\n     * Have to do this because the first thing `useSyncExternalStore` does is\n     * call `getSnapshot`; however, it is necessary to call subscribe first so that\n     * the connection is loaded.\n     */\n    const subscribe = React.useMemo(() => {\n      let listeners: Listener[] = [];\n\n      const unsubscribe = store.subscribe(() => {\n        listeners.forEach((fn) => fn());\n      });\n\n      return (listener: Listener) => {\n        listeners.push(listener);\n\n        return () => {\n          unsubscribe();\n          listeners = [];\n        };\n      };\n    }, [store]);\n\n    const state = React.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n    const update = React.useCallback(\n      (updater: Updater<A>) => {\n        const prev = store.getSnapshot();\n        const next = updater(prev);\n\n        /**\n         * If the next value is the previous one, then do nothing.\n         */\n        if (Object.is(prev, next)) {\n          return;\n        }\n\n        store.setSnapshot(next);\n      },\n      [store]\n    );\n\n    /**\n     * Assign the current state to the previous state so that when `getSnapshot`\n     * is called again it will reference it.\n     */\n    prevStateRef.current = state;\n\n    /**\n     * Wrap the state in a proxy value so that it can be transformed back into a lens.\n     */\n    const value = React.useMemo(() => proxyValue(state, proxy), [state, proxy]);\n\n    return [value, update];\n  };\n\nexport function useCreateLens<S>(initialState: S | (() => S)) {\n  return React.useMemo(() => {\n    if (typeof initialState === \"function\") {\n      return createLens((initialState as () => S)());\n    } else {\n      return createLens(initialState);\n    }\n  }, []);\n}\n","import { isObject } from \"./is-object\";\nimport { ProxyLens } from \"./proxy-lens\";\nimport { AnyArray, AnyObject, AnyPrimitive, Key } from \"./types\";\n\ntype Proxyable = AnyArray | AnyObject;\n\ntype BaseProxyValue<A> = {\n  toJSON(): A;\n  toLens(): ProxyLens<A>;\n};\n\ntype ArrayProxyValue<A extends AnyArray> = BaseProxyValue<A> & Array<ProxyValue<A[number]>>;\ntype ObjectProxyValue<A extends AnyObject> = BaseProxyValue<A> & { [K in keyof A]: ProxyValue<A[K]> };\n\n// prettier-ignore\nexport type ProxyValue<A> =\n  A extends AnyArray ? ArrayProxyValue<A> :\n  A extends AnyObject ? ObjectProxyValue<A> :\n  A extends AnyPrimitive ? A :\n  never;\n\ntype Target<A> = { data: A; lens: ProxyLens<A>; toJSON?(): A; toLens?(): ProxyLens<A> };\n\nconst isProxyable = (obj: any): obj is Proxyable => Array.isArray(obj) || isObject(obj);\n\nconst proxyHandler: ProxyHandler<Target<{}>> = {\n  get(target, key) {\n    if (key === \"toJSON\") {\n      target.toJSON ??= () => target.data;\n      return target.toJSON;\n    }\n\n    if (key === \"toLens\") {\n      target.toLens ??= () => target.lens;\n      return target.toLens;\n    }\n\n    const nextData = target.data[key as keyof typeof target.data];\n    const nextLens = (target.lens as any)[key as keyof typeof target.lens];\n\n    return proxyValue<{}>(nextData, nextLens);\n  },\n\n  ownKeys(target) {\n    return Reflect.ownKeys(target.data).concat([\"toLens\", \"toJSON\"]);\n  },\n\n  getOwnPropertyDescriptor(target, key) {\n    /**\n     * If the key is one of the special ProxyValue keys,\n     * set the property descriptor to a custom value.\n     */\n    if (key === \"toLens\" || key === \"toJSON\") {\n      return {\n        configurable: true,\n        enumerable: true,\n        writable: false,\n        value: target[key],\n      };\n    }\n\n    const desc = Object.getOwnPropertyDescriptor(target.data, key);\n\n    /**\n     * Now bail if the descriptor is `undefined`. This could only\n     * occur if the key is not `keyof A`.\n     */\n    if (desc === undefined) {\n      return;\n    }\n\n    return {\n      writable: desc.writable,\n      enumerable: desc.enumerable,\n      configurable: desc.configurable,\n      value: target.data[key as keyof typeof target.data],\n    };\n  },\n  has(target, key) {\n    return key in target.data;\n  },\n  getPrototypeOf() {\n    return null;\n  },\n  preventExtensions() {\n    return true;\n  },\n  isExtensible() {\n    return false;\n  },\n  set() {\n    throw new Error(\"Cannot set property on ProxyValue\");\n  },\n  deleteProperty() {\n    throw new Error(\"Cannot delete property on ProxyValue\");\n  },\n};\n\nconst valueCache = new WeakMap<{}, ProxyValue<{}>>();\n\nexport const proxyValue = <A>(data: A, lens: ProxyLens<A>): ProxyValue<A> => {\n  if (!isProxyable(data)) {\n    return data as ProxyValue<A>;\n  }\n\n  let cached = valueCache.get(data) as ProxyValue<A>;\n\n  if (!cached) {\n    cached = new Proxy({ data, lens } as any, proxyHandler);\n    valueCache.set(data, cached as any);\n  }\n\n  return cached;\n};\n","type ShouldUpdateBoolean = boolean;\ntype ShouldUpdateArray<A> = (keyof A)[];\ntype ShouldUpdateObject<A> = { [K in keyof A]?: A[K] extends any[] ? ShouldUpdate<A[K][number]> : ShouldUpdate<A[K]> };\nexport type ShouldUpdateFunction<A> = (prev: A, next: A) => boolean;\nexport type ShouldUpdate<A> =\n  | ShouldUpdateBoolean\n  | ShouldUpdateFunction<A>\n  | ShouldUpdateArray<A>\n  | ShouldUpdateObject<A>;\n\nexport const shouldUpdateToFunction = <A>(shouldUpdate: ShouldUpdate<A>): ShouldUpdateFunction<A> => {\n  if (typeof shouldUpdate === \"boolean\") {\n    return (prev, next) => (shouldUpdate ? prev !== next : false);\n  }\n\n  if (typeof shouldUpdate === \"function\") {\n    return shouldUpdate as ShouldUpdateFunction<A>;\n  }\n\n  if (Array.isArray(shouldUpdate)) {\n    const obj = Object.fromEntries(shouldUpdate.map((key) => [key, true])) as { [K in keyof A]: boolean };\n    return shouldUpdateToFunction(obj);\n  }\n\n  return (prev, next) => {\n    let prevIsArr = false;\n    let nextIsArr = false;\n\n    let prevArr: (A & any[]) | A[];\n    let nextArr: (A & any[]) | A[];\n\n    /**\n     * If the prev or next values are arrays then keep\n     * track of it, but noop. If they are not arrays then\n     * wrap in an array to make the rest of the function\n     * easy to walk.\n     */\n    if (Array.isArray(prev)) {\n      prevIsArr = true;\n      prevArr = prev;\n    } else {\n      prevArr = [prev];\n    }\n\n    if (Array.isArray(next)) {\n      nextIsArr = true;\n      nextArr = next;\n    } else {\n      nextArr = [next];\n    }\n\n    /**\n     * If one value was is an array but the other isn't\n     * then stop and just return true... and fix your data.\n     */\n    if (nextIsArr !== prevIsArr) {\n      return true;\n    }\n\n    /**\n     * This is implicitly required to be able to traverse\n     * array keys. Therefore using `[]` or `{}` as the value\n     * for a key will automatically compare the length of an array.\n     * If both prev and next were not arrays then we will not return here.\n     */\n    if (prevArr.length !== nextArr.length) {\n      return true;\n    }\n\n    /**\n     * Iterate through each entry in the array and short circuit `true` at\n     * the first check to return `true`.\n     */\n    for (let i = 0; i < prevArr.length; i++) {\n      const prevValue = prevArr[i];\n      const nextValue = nextArr[i];\n\n      for (const key in shouldUpdate) {\n        const func = shouldUpdateToFunction(shouldUpdate[key] as ShouldUpdate<A[keyof A]>);\n\n        if (func(prevValue[key], nextValue[key])) {\n          return true;\n        }\n      }\n    }\n\n    /**\n     * No checks returns true so we won't update.\n     */\n    return false;\n  };\n};\n","export const ReactDevtools = {\n  /**\n   * A shitty hack to check whether the current function call is occurring\n   * inside React Devtools.\n   */\n  isCalledInsideReactDevtools: () => {\n    const err = new Error();\n    return err.stack?.includes(\"react_devtools_backend\");\n  },\n};\n","import { isObject } from \"./is-object\";\n\nexport type Awaitable<T> = T | PromiseLike<T>;\n\nconst isPromiseLike = <T>(obj: any): obj is PromiseLike<T> => {\n  return isObject(obj) && Reflect.has(obj, \"then\");\n};\n\n/**\n * Wraps a callback that returns an `Awaitable`. This is benefitial over async/await in\n * some cases because it can be made to be synchronous when the callback does not return\n * a promise and therefore calling `.then()` will yield immediately instead of waiting\n * like a typical promise does. If the callback does return a promise then the consumer\n * will wait.\n */\nexport const awaitable =\n  <T>(get: () => Awaitable<T>) =>\n  (): PromiseLike<T> => {\n    return {\n      then(onfulfilled) {\n        const value = get();\n        onfulfilled ??= null;\n\n        if (onfulfilled === null) {\n          throw new Error(\"Unexpected error. Do not use awaitable(value).then()\");\n        }\n\n        if (isPromiseLike(value)) {\n          return value.then(onfulfilled);\n        }\n\n        const result = onfulfilled(value);\n\n        if (isPromiseLike(result)) {\n          return result;\n        }\n\n        return awaitable(() => result)();\n      },\n    };\n  };\n","import { keyPathToString } from \"./key-path-to-string\";\nimport { Key, Listener, Unsubscribe } from \"./types\";\n\ntype NodeId = string;\ntype SubscriptionNodeAncestor = { none: true } | { none: false; keyPath: Key[] };\n\nconst id = keyPathToString;\n\nclass SubscriptionNode {\n  private listeners = new Set<Listener>();\n  public readonly id: string;\n  public readonly ancestor: SubscriptionNodeAncestor;\n\n  constructor(private readonly keyPath: Key[]) {\n    this.id = id(keyPath);\n\n    if (keyPath.length === 0) {\n      this.ancestor = { none: true };\n    } else {\n      this.ancestor = { none: false, keyPath: this.keyPath.slice(0, -1) };\n    }\n  }\n\n  public subscribe(listener: Listener): Unsubscribe {\n    this.listeners.add(listener);\n    return () => this.listeners.delete(listener);\n  }\n\n  public notify(): void {\n    this.listeners.forEach((fn) => fn());\n  }\n\n  public get size(): number {\n    return this.listeners.size;\n  }\n}\n\n/**\n * A graph to keep track of depedencies between keyPaths\n * so that notifications do not need to cascade to all listeners.\n */\nexport class SubscriptionGraph {\n  private nodes = new Map<NodeId, SubscriptionNode>();\n  private parents = new Map<NodeId, SubscriptionNode>();\n  private children = new Map<NodeId, Set<SubscriptionNode>>();\n\n  /**\n   * Notifies all ancestors and then all children of the node.\n   */\n  public notify(keyPath: Key[]) {\n    const nodeId = id(keyPath);\n    const node = this.nodes.get(nodeId);\n\n    /**\n     * If this node exists, then we need to notify. There is an assumption\n     * that we will only ever notify from a node that exists, i.e. a `keyPath`\n     * where there is currently a subscription.\n     */\n    if (node) {\n      /**\n       * Notify the ancestors first because they made notifications to children unnecessary.\n       */\n      this.notifyAncestors(node);\n      this.notifySelfAndChildren(node);\n    }\n  }\n\n  public subscribe(keyPath: Key[], listener: Listener): Unsubscribe {\n    const node = this.addNode(keyPath);\n    const unsubscribe = node.subscribe(listener);\n\n    return () => {\n      unsubscribe();\n      this.clean(node);\n    };\n  }\n\n  public get size() {\n    return this.nodes.size;\n  }\n\n  /**\n   * Recursively inserts nodes until there is a pathway\n   * between the `keyPath` and the root (keyPath === []).\n   */\n  private addNode(keyPath: Key[]): SubscriptionNode {\n    /**\n     * Derive a `nodeId` key based on the `keyPath`.\n     */\n    const nodeId: NodeId = id(keyPath);\n    let node = this.nodes.get(nodeId);\n\n    /**\n     * If the node already exists then just return it.\n     */\n    if (node) {\n      return node;\n    }\n\n    /**\n     * Otherwise, create a new node with the `nodeId`\n     * and insert it into the nodes map.\n     */\n    node = new SubscriptionNode(keyPath);\n    this.nodes.set(node.id, node);\n    this.children.set(node.id, new Set());\n\n    /**\n     * If the node does not have an ancestor, then we can\n     * exit here because we don't need to create any parent/child\n     * relationship.\n     */\n    if (node.ancestor.none) {\n      return node;\n    }\n\n    /**\n     * Upsert the parent node. It will recursively create\n     * the parent if it does not exist yet. An example of how this\n     * could happen might be calling subscribe with `['a', 'b', 'c']`\n     * before calling it with `['a']` or `['a', 'b']`. See tests.\n     */\n    const parent = this.addNode(node.ancestor.keyPath);\n\n    /**\n     * Keep track of the node's parent.\n     */\n    this.parents.set(node.id, parent);\n\n    /**\n     * Add this node to the set of children for the parent.\n     */\n    const siblings = this.children.get(parent.id);\n\n    if (siblings === undefined) {\n      // impossible?\n      throw new Error(\"Unexpected Error\");\n    }\n\n    siblings.add(node);\n\n    return node;\n  }\n\n  /**\n   * Recursively notifies the parent node until there is no parent left.\n   */\n  private notifyAncestors(node: SubscriptionNode) {\n    const ancestor = this.parents.get(node.id);\n\n    if (ancestor) {\n      /**\n       * Make sure the root node is the first one to receive the notification\n       * by recursively calling up the graph before notifying self.\n       */\n      this.notifyAncestors(ancestor);\n\n      ancestor.notify();\n    }\n  }\n\n  /**\n   * Recursively notifies children until there are no children left.\n   */\n  private notifySelfAndChildren(node: SubscriptionNode) {\n    /**\n     * Notify self before recursively going down the graph to notify children.\n     */\n    node.notify();\n\n    const children = this.children.get(node.id) ?? new Set();\n\n    for (const child of children) {\n      this.notifySelfAndChildren(child);\n    }\n  }\n\n  /**\n   * Check whether a node no longer has listeners or children.\n   * If so, then it should be cleaned up to avoid memory leaks.\n   */\n  private clean(node: SubscriptionNode) {\n    const children = this.children.get(node.id) ?? new Set();\n\n    /**\n     * If the node has any dependents (children or listeners),\n     * then we should not clean this up, so bail.\n     */\n    if (children.size > 0 || node.size > 0) {\n      return;\n    }\n\n    /**\n     * Remove this node from the list of nodes.\n     */\n    this.nodes.delete(node.id);\n    this.children.delete(node.id);\n\n    /**\n     * Get the parent node. If there is no parent, we\n     * are at the root node so there is nothing left to do.\n     */\n    const parent = this.parents.get(node.id);\n\n    if (parent) {\n      /**\n       * Delete the current node parents map.\n       */\n      this.parents.delete(node.id);\n\n      /**\n       * Remove the node from the parent's list of children. It's a `Set`\n       * so no need to re-insert into `this.children`.\n       */\n      const siblings = this.children.get(parent.id) ?? new Set();\n      siblings.delete(node);\n\n      /**\n       * Now recurse and see whether the parent node should also be removed.\n       * This could occur if you only had one listener for `['a', 'b', 'c', 'd']`\n       * and it is removed. In this case, we would want to go up the chain and\n       * remove all of them.\n       */\n      this.clean(parent);\n    }\n  }\n}\n","import { Awaitable, awaitable } from \"./awaitable\";\nimport { Breakable, Breaker } from \"./breaker\";\nimport { Connection, focusToCache, insert, isConnection } from \"./connection\";\nimport { isObject } from \"./is-object\";\nimport { keyPathToString } from \"./key-path-to-string\";\nimport { LensFocus, rootLensFocus } from \"./lens-focus\";\nimport { SubscriptionGraph } from \"./subscription-graph\";\nimport { Key, Listener, Unsubscribe } from \"./types\";\n\nexport type StoreFactory<S> = <A>(focus: LensFocus<S, A>) => Store<A>;\n\nexport type Store<A> = {\n  getSnapshot(): A;\n  setSnapshot(next: A): boolean;\n  subscribe(onStoreChange?: Listener): Unsubscribe;\n};\n\nconst noop: Listener = () => {};\n\nexport const createRootStoreFactory = <S extends {}>(initialState: S): [StoreFactory<S>, LensFocus<S, S>] => {\n  const graph = new SubscriptionGraph();\n  const focus = rootLensFocus<S>();\n  let snapshot = initialState;\n\n  const factory: StoreFactory<S> = ({ keyPath, lens }) => {\n    return {\n      getSnapshot() {\n        return lens.get(snapshot);\n      },\n      subscribe(listener = noop) {\n        return graph.subscribe(keyPath, listener);\n      },\n      setSnapshot(next) {\n        snapshot = lens.set(snapshot, next);\n        graph.notify(keyPath);\n        return true;\n      },\n    };\n  };\n\n  return [factory, focus];\n};\n\nlet noopBreakable: Breakable = { connect() {}, disconnect() {} };\n\nexport const createConnectionStoreFactory = <S, A, I>(\n  storeFactory: StoreFactory<S>,\n  connFocus: LensFocus<S, Connection<A, I>>,\n  input: I\n): [StoreFactory<S>, LensFocus<S, A>] => {\n  const cacheKey = `connection([${keyPathToString(connFocus.keyPath)}], ${JSON.stringify(input ?? {})})`;\n  const cacheKeyFocus = focusToCache(connFocus, cacheKey);\n\n  const rootStore = storeFactory(connFocus);\n  const cacheEntryStore = storeFactory(cacheKeyFocus);\n\n  const getBreakable = awaitable<Breakable>((): Awaitable<Breakable> => {\n    try {\n      const conn = rootStore.getSnapshot();\n\n      if (isConnection<A, I>(conn)) {\n        return insert(conn, cacheEntryStore, input, cacheKey);\n      } else {\n        return noopBreakable;\n      }\n    } catch (err) {\n      if (err instanceof Promise) {\n        return err.then(getBreakable);\n      }\n\n      throw err;\n    }\n  });\n\n  const breaker = new Breaker(() => {\n    let connected = true;\n    let prevConn = noopBreakable;\n\n    getBreakable().then((conn) => {\n      /**\n       * In the case that the breaker\n       * is disconnected before `getBreakable`\n       * is resolved.\n       */\n      if (connected) {\n        conn.connect();\n      }\n\n      prevConn = conn;\n    });\n\n    const unsubscribe = rootStore.subscribe(() => {\n      getBreakable().then((nextConn) => {\n        /**\n         * If the root state is updated and the connection\n         * changes, then disconnect the old previous and\n         * connect the next.\n         */\n        if (nextConn !== prevConn) {\n          prevConn.disconnect();\n          prevConn = nextConn;\n\n          /**\n           * In the case that the breaker\n           * is disconnected before `getBreakable`\n           * is resolved.\n           */\n          if (connected) {\n            nextConn.connect();\n          }\n        }\n      });\n    });\n\n    return () => {\n      connected = false;\n\n      prevConn.disconnect();\n      unsubscribe();\n    };\n  });\n\n  /**\n   * Here we wrap the parent store factory in order to keep track of\n   * the number of subscribers in order to enable/disable the above breaker.\n   * This will be done at every \"level\" that a connection exists in the state\n   * hierarchy.\n   */\n  let currentSubscribers = 0;\n\n  const connectionStoreFactory: StoreFactory<S> = (refinedFocus) => {\n    const store = storeFactory(refinedFocus);\n\n    return {\n      ...store,\n      subscribe(listener) {\n        const unsubscribe = store.subscribe(listener);\n\n        currentSubscribers += 1;\n        breaker.connect();\n\n        return () => {\n          unsubscribe();\n\n          currentSubscribers = Math.max(currentSubscribers - 1, 0);\n\n          if (currentSubscribers <= 0) {\n            breaker.disconnect();\n          }\n        };\n      },\n    };\n  };\n\n  return [connectionStoreFactory, cacheKeyFocus];\n};\n","import { Connection } from \"./connection\";\nimport { keyPathToString } from \"./key-path-to-string\";\nimport { LensFocus, refineLensFocus } from \"./lens-focus\";\nimport { ProxyValue } from \"./proxy-value\";\nimport { createUseLens } from \"./react\";\nimport { ReactDevtools } from \"./react-devtools\";\nimport { ShouldUpdate } from \"./should-update\";\nimport { createConnectionStoreFactory, Store } from \"./store\";\nimport { AnyArray, AnyConnection, AnyObject, AnyPrimitive, Update } from \"./types\";\n\ntype StoreFactory<S> = <A>(focus: LensFocus<S, A>) => Store<A>;\n\ntype BaseProxyLens<A> = {\n  /**\n   * Fetches the store for current focus.\n   */\n  getStore(): Store<A>;\n\n  /**\n   * Collapses the lens into a React hook.\n   */\n  use(shouldUpdate?: ShouldUpdate<A>): [ProxyValue<A>, Update<A>];\n  /**\n   * A unique key for cases when you need a key. e.g. A React list.\n   *\n   * @example\n   * const [list] = useLens(state);\n   *\n   * list.map(value => {\n   *   const lens = value.toLens();\n   *\n   *   return <ListItem key={lens.$key} state={lens} />;\n   * });\n   */\n  $key: string;\n};\n\ntype ConnectionProxyLens<A> = BaseProxyLens<A> &\n  (A extends Connection<infer B, infer I> ? (input: I) => ProxyLens<B> : {});\n\ntype ArrayProxyLens<A extends AnyArray> = BaseProxyLens<A> & { [K in number]: ProxyLens<A[K]> };\ntype ObjectProxyLens<A extends AnyObject> = BaseProxyLens<A> & { [K in keyof A]: ProxyLens<A[K]> };\ntype PrimitiveProxyLens<A extends AnyPrimitive> = BaseProxyLens<A>;\n\n// prettier-ignore\nexport type ProxyLens<A> =\n  A extends AnyConnection ? ConnectionProxyLens<A> :\n  A extends AnyObject ? ObjectProxyLens<A> :\n  A extends AnyArray ? ArrayProxyLens<A> :\n  A extends AnyPrimitive ? PrimitiveProxyLens<A> :\n  never;\n\nconst THROW_ON_COPY = Symbol();\nconst specialKeys: (keyof BaseProxyLens<{}>)[] = [\"use\", \"getStore\", \"$key\"];\nconst functionTrapKeys = [\"arguments\", \"caller\", \"prototype\"];\n\nexport const proxyLens = <S, A>(storeFactory: StoreFactory<S>, focus: LensFocus<S, A>): ProxyLens<A> => {\n  type KeyCache = { [K in keyof A]?: ProxyLens<A[K]> };\n  type ConnectionCache = { [cacheKey: string]: A extends Connection<infer B, any> ? ProxyLens<B> : never };\n  type Target = Partial<BaseProxyLens<A>>;\n\n  let keyCache: KeyCache;\n  let connectionCache: ConnectionCache;\n  let $key: string;\n  let use: (shouldUpdate?: ShouldUpdate<A>) => [ProxyValue<A>, Update<A>];\n  let getStore: () => Store<A>;\n\n  /**\n   * Use a function here so that we can trick the Proxy into allowing us to use `apply`\n   * for connections. This won't really impact performance for property access because `ProxyLens`\n   * never actually accesses target properties. Further, constructing a function is slightly\n   * slower than constructing an object, but it is only done once and then cached forever.\n   */\n  const proxy = new Proxy(function () {} as Target, {\n    apply(_target, _thisArg, argsArray) {\n      const connCache = (connectionCache ??= {});\n      const [input] = argsArray;\n      const cacheKey = JSON.stringify(input);\n      let next = connCache[cacheKey];\n\n      if (!next) {\n        const [nextFactory, nextFocus] = createConnectionStoreFactory(storeFactory, focus as any, input);\n        next = connCache[cacheKey] = proxyLens(nextFactory, nextFocus) as any;\n      }\n\n      return next;\n    },\n\n    get(_target, key) {\n      /**\n       * Block React introspection as it will otherwise produce an infinite chain of\n       * ProxyLens values in React Devtools.\n       */\n      if (key === \"$$typeof\") {\n        return undefined;\n      }\n\n      if (key === \"$key\") {\n        $key ??= keyPathToString(focus.keyPath);\n        return $key;\n      }\n\n      if (key === \"use\") {\n        use ??= createUseLens(proxy);\n        return use;\n      }\n\n      if (key === \"getStore\") {\n        getStore ??= () => storeFactory(focus);\n        return getStore;\n      }\n\n      keyCache ??= {};\n\n      if (keyCache[key as keyof A] === undefined) {\n        const nextFocus = refineLensFocus(focus, [key as keyof A]);\n        const nextProxy = proxyLens(storeFactory, nextFocus);\n        keyCache[key as keyof A] = nextProxy;\n      }\n\n      return keyCache[key as keyof A];\n    },\n\n    ownKeys(_target) {\n      return [...specialKeys, ...functionTrapKeys, THROW_ON_COPY];\n    },\n\n    has(_target, key) {\n      return specialKeys.includes(key as keyof BaseProxyLens<{}>);\n    },\n\n    getOwnPropertyDescriptor(target, key) {\n      if (specialKeys.includes(key as keyof BaseProxyLens<{}>)) {\n        return {\n          configurable: true,\n          enumerable: true,\n          writable: false,\n          value: proxy[key as keyof Partial<BaseProxyLens<A>>],\n        };\n      }\n\n      if (functionTrapKeys.includes(key as keyof Target)) {\n        return Reflect.getOwnPropertyDescriptor(target, key);\n      }\n\n      /**\n       * This is a hack to ensure that when React Devtools is\n       * reading all of the props with `getOwnPropertyDescriptors`\n       * it does not throw an error.\n       */\n      if (ReactDevtools.isCalledInsideReactDevtools()) {\n        return {\n          configurable: true,\n          enumerable: false,\n          value: undefined,\n        };\n      }\n\n      /**\n       * We otherwise do not want the lens to be introspected with `Object.getOwnPropertyDescriptors`\n       * which will happen internally with `{ ...lens }` or `Object.assign({}, lens)`.\n       * Both of those operations will create a new plain object from the properties that it can retrieve\n       * off of the lens; however, the lens is a shell around nothing and relies _heavily_ on TypeScript\n       * telling the developer which attributes are available. Therefore, copying the lens will leave you\n       * with an object that only has `$key` and `use`. Accessing `lens.user`, for example, will be\n       * `undefined` and will not be caught by TypeScript because the Proxy is typed as `A & { $key, use }`.\n       *\n       * If we've reached here, we are trying to access the property descriptor for `THROW_ON_COPY`,\n       * which is not a real property on the lens, so just throw.\n       */\n      throw new Error(\n        \"ProxyLens threw because you tried to access all property descriptors—probably through \" +\n          \"`{ ...lens }` or `Object.assign({}, lens)`. Doing this will break the type safety offered by \" +\n          \"this library so it is forbidden. Sorry, buddy pal.\"\n      );\n    },\n\n    getPrototypeOf() {\n      return null;\n    },\n    preventExtensions() {\n      return true;\n    },\n    isExtensible() {\n      return false;\n    },\n    set() {\n      throw new Error(\"Cannot set property on ProxyLens\");\n    },\n    deleteProperty() {\n      throw new Error(\"Cannot delete property on ProxyLens\");\n    },\n  }) as ProxyLens<A>;\n\n  return proxy;\n};\n","import { ProxyLens, proxyLens } from \"./proxy-lens\";\nimport { createRootStoreFactory } from \"./store\";\n\nexport const createLens = <S>(initialState: S): ProxyLens<S> => {\n  const [factory, focus] = createRootStoreFactory(initialState);\n  return proxyLens(factory, focus);\n};\n"],"mappings":";;;;;;;;;AAAO,IAAM,WAAW,wBAAC,QAA4B,OAAO,UAAU,SAAS,KAAK,SAAS,mBAArE;;;ACExB,IAAM,sBAAsB;AAErB,IAAM,mBAAmB,wBAAe,QAAc;AAC3D,SAAO,eAAe,KAAK,qBAAqB;AAAA,IAC9C,cAAc;AAAA,IACd,YAAY;AAAA,IACZ,UAAU;AAAA,IACV,OAAO;AAAA;AAGT,SAAO;AAAA,GARuB;AAWzB,IAAM,cAAc,wBAAe,QAAc;AACtD,MAAI,QA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