{"version":3,"file":"yorkie-js-react.cjs","sources":["../src/YorkieProvider.tsx","../src/createStore.ts","../src/createDocumentStore.ts","../src/useSelector.ts","../src/shallowEqual.ts","../src/DocumentProvider.tsx","../src/useYorkieDoc.ts","../src/createChannelStore.ts","../src/ChannelProvider.tsx","../src/usePeekChannel.ts"],"sourcesContent":["/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  createContext,\n  PropsWithChildren,\n  useContext,\n  useEffect,\n  useMemo,\n  useState,\n} from 'react';\nimport { Client, ClientOptions } from '@yorkie-js/sdk';\nimport pkg from '../package.json';\n\ntype YorkieContextType = {\n  client: Client | undefined;\n  loading: boolean;\n  error: Error | undefined;\n};\n\nconst YorkieContext = createContext<YorkieContextType>({\n  client: undefined,\n  loading: true,\n  error: undefined,\n});\n\n/**\n * `useYorkieClient` is a custom hook that initializes a Yorkie client.\n *\n * When `activate` is true (default) the client is activated against the\n * server on mount and deactivated on unmount — required for Document use\n * cases. Set `activate` to false for channel-only apps: the SDK now\n * lazy-attaches the client on the first RefreshChannel heartbeat, so\n * skipping the explicit activate/deactivate round trips removes two\n * unused RPCs per page load.\n */\nexport function useYorkieClient(opts: ClientOptions, activate: boolean = true) {\n  const [client, setClient] = useState<Client | undefined>(undefined);\n  const [loading, setLoading] = useState<boolean>(true);\n  const [error, setError] = useState<Error | undefined>(undefined);\n  const [didMount, setDidMount] = useState(false);\n\n  // NOTE(hackerwins): In StrictMode, the component will call twice\n  // useEffect in development mode. To prevent creating a new client\n  // twice, create a client after the mounting.\n  useEffect(() => {\n    setDidMount(true);\n  }, []);\n\n  useEffect(() => {\n    setLoading(true);\n    setError(undefined);\n\n    /**\n     * `activateClient` activates the Yorkie client.\n     */\n    async function activateClient() {\n      if (!didMount) {\n        return;\n      }\n\n      try {\n        const newClient = new Client(opts);\n        if (activate) {\n          await newClient.activate();\n        }\n        setClient(newClient);\n      } catch (e) {\n        setError(\n          e instanceof Error ? e : new Error('Failed to activate client'),\n        );\n      } finally {\n        setLoading(false);\n      }\n    }\n    activateClient();\n\n    return () => {\n      if (activate && client?.isActive() && opts.deactivateOnUnload !== false) {\n        client.deactivate({ keepalive: true });\n      }\n    };\n  }, [opts.apiKey, opts.rpcAddr, opts.key, didMount, activate]);\n\n  return { client, loading, error };\n}\n\n/**\n * `YorkieProviderProps` extends `ClientOptions` with provider-level options.\n *\n * - `activate` (default `true`): whether to call `client.activate()` on mount\n *   and `client.deactivate()` on unmount. Set to `false` for apps that only\n *   use Channels — under the RefreshChannel-only lifecycle the SDK\n *   lazy-attaches the client on the first heartbeat, so explicit activate\n *   round trips become unnecessary. Document use cases (`useDocument`,\n *   `useYorkieDoc`) still require activation, so leave this `true` if any\n *   descendant attaches a document.\n */\nexport type YorkieProviderProps = Omit<ClientOptions, 'key'> & {\n  activate?: boolean;\n\n  /**\n   * The client key, as `ClientOptions.key`.\n   *\n   * It is spelled differently here because `key` is reserved by React: React\n   * strips it at element creation — as a JSX attribute and through a spread\n   * alike — so a `key` prop never reaches this component and could never reach\n   * the `Client` constructor. `ClientOptions.key` is therefore unreachable\n   * through the provider without an alias, which matters for offline\n   * persistence: the SDK's store is keyed by `apiKey/clientKey/docKey`, so a\n   * client whose key is random per session resumes nothing.\n   *\n   * Changing it builds a new client, since the key is what the client carries.\n   */\n  clientKey?: string;\n};\n\n/**\n * `YorkieProvider` is a component that provides the Yorkie client to its children.\n * It initializes the Yorkie client with the given API key and RPC address.\n */\nexport const YorkieProvider: React.FC<\n  PropsWithChildren<YorkieProviderProps>\n> = ({ children, activate = true, clientKey, ...opts }) => {\n  // NOTE(hackerwins): useMemo is used to prevent re-creating the client\n  // when the component re-renders. If the apiKey, rpcAddr or clientKey\n  // changes, the client will be re-created.\n  const clientOpts = useMemo(() => {\n    return {\n      userAgent: pkg.name + '/' + pkg.version,\n      ...opts,\n      // Only when given, so a provider that passes none leaves the SDK to mint\n      // its own rather than receiving an explicit `undefined`.\n      ...(clientKey !== undefined ? { key: clientKey } : {}),\n    };\n  }, [opts.apiKey, opts.rpcAddr, clientKey]);\n  const { client, loading, error } = useYorkieClient(clientOpts, activate);\n\n  return (\n    <YorkieContext.Provider value={{ client, loading, error }}>\n      {children}\n    </YorkieContext.Provider>\n  );\n};\n\n/**\n * `useYorkie` is a custom hook that returns the Yorkie client and its loading state.\n * @returns\n */\nexport const useYorkie = () => {\n  const context = useContext(YorkieContext);\n  if (!context) {\n    throw new Error('useYorkie must be used under YorkieProvider');\n  }\n\n  return {\n    client: context.client,\n    loading: context.loading,\n    error: context.error,\n  };\n};\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\ntype Subscriber<T> = (state: T) => void;\n\ntype Updater<T> = T | ((prevState: T) => T);\n\nexport type Store<T> = {\n  subscribe: (callback: Subscriber<T>) => () => void;\n  getSnapshot: () => T;\n  setState: (newState: Updater<T>) => void;\n  destroy: () => void;\n};\n\n/**\n * `createStore` creates a simple state management store.\n */\nexport function createStore<T>(initialState: T): Store<T> {\n  type InternalSubscriber = Subscriber<T>;\n\n  const subscribers = new Set<InternalSubscriber>();\n  let currentState: T = initialState;\n\n  const notify = () => {\n    subscribers.forEach((callback) => callback(currentState));\n  };\n\n  const setState = (newState: Updater<T>) => {\n    const prevState = currentState;\n    currentState =\n      typeof newState === 'function'\n        ? (newState as (prevState: T) => T)(prevState)\n        : newState;\n\n    if (prevState !== currentState) {\n      notify();\n    }\n  };\n\n  const subscribe = (callback: InternalSubscriber) => {\n    subscribers.add(callback);\n    return () => subscribers.delete(callback);\n  };\n\n  const getSnapshot = () => currentState;\n\n  const destroy = () => {\n    subscribers.clear();\n  };\n\n  return {\n    subscribe,\n    getSnapshot,\n    setState,\n    destroy,\n  };\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Indexable } from '@yorkie-js/sdk';\nimport { createStore } from './createStore';\nimport { DocumentContextType } from './DocumentProvider';\n\nexport const createDocumentStore = <R, P extends Indexable = Indexable>(\n  initialState: DocumentContextType<R, P>,\n) => {\n  return createStore<DocumentContextType<R, P>>(initialState);\n};\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useRef, useSyncExternalStore } from 'react';\nimport { Store } from './createStore';\n\n/**\n * `useSelector` is a custom hook that allows\n * users to select a slice of state from the store.\n * Only renders when the selected slice changes.\n */\nexport function useSelector<T, R = T>(\n  store: Store<T>,\n  selector?: (state: T) => R,\n  equalityFn: (a: R, b: R) => boolean = Object.is,\n): R {\n  const selectorRef = useRef(selector);\n  const equalityFnRef = useRef(equalityFn);\n  const currentSliceRef = useRef<R | undefined>(undefined);\n\n  selectorRef.current = selector;\n  equalityFnRef.current = equalityFn;\n\n  const getSelection = (): R => {\n    const state = store.getSnapshot();\n    const nextSlice = selectorRef.current\n      ? selectorRef.current(state)\n      : (state as unknown as R);\n\n    if (\n      currentSliceRef.current !== undefined &&\n      equalityFnRef.current(currentSliceRef.current, nextSlice)\n    ) {\n      return currentSliceRef.current;\n    }\n\n    currentSliceRef.current = nextSlice;\n    return nextSlice;\n  };\n\n  return useSyncExternalStore(store.subscribe, getSelection, getSelection);\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * incorporates code from Zustand - https://github.com/pmndrs/zustand\n */\n\n/**\n * `isIterable` checks if the given object is iterable.\n */\nfunction isIterable(obj: any): obj is Iterable<unknown> {\n  return obj != null && typeof obj[Symbol.iterator] === 'function';\n}\n\n/**\n * `hasIterableEntries` checks if the given iterable has an `entries` method.\n */\nfunction hasIterableEntries(\n  value: Iterable<unknown>,\n): value is Iterable<unknown> & { entries(): Iterable<[unknown, unknown]> } {\n  return 'entries' in value && typeof (value as any).entries === 'function';\n}\n\n/**\n * `compareEntries` compares two iterables with `entries` methods for shallow equality.\n */\nfunction compareEntries(\n  valueA: { entries(): Iterable<[unknown, unknown]> },\n  valueB: { entries(): Iterable<[unknown, unknown]> },\n): boolean {\n  const mapA = valueA instanceof Map ? valueA : new Map(valueA.entries());\n  const mapB = valueB instanceof Map ? valueB : new Map(valueB.entries());\n\n  if (mapA.size !== mapB.size) {\n    return false;\n  }\n\n  for (const [key, value] of mapA) {\n    if (!mapB.has(key) || !Object.is(value, mapB.get(key))) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n/**\n * `compareIterables` compares two general iterables for shallow equality.\n */\nfunction compareIterables(\n  valueA: Iterable<unknown>,\n  valueB: Iterable<unknown>,\n): boolean {\n  const iteratorA = valueA[Symbol.iterator]();\n  const iteratorB = valueB[Symbol.iterator]();\n\n  let nextA = iteratorA.next();\n  let nextB = iteratorB.next();\n\n  while (!nextA.done && !nextB.done) {\n    if (!Object.is(nextA.value, nextB.value)) {\n      return false;\n    }\n    nextA = iteratorA.next();\n    nextB = iteratorB.next();\n  }\n\n  return nextA.done === nextB.done;\n}\n\n/**\n * `comparePlainObjects` compares two plain objects for shallow equality.\n */\nfunction comparePlainObjects(\n  valueA: Record<string, unknown>,\n  valueB: Record<string, unknown>,\n): boolean {\n  const keysA = Object.keys(valueA);\n  const keysB = Object.keys(valueB);\n\n  if (keysA.length !== keysB.length) {\n    return false;\n  }\n\n  for (const key of keysA) {\n    if (\n      !Object.prototype.hasOwnProperty.call(valueB, key) ||\n      !Object.is(valueA[key], valueB[key])\n    ) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n/**\n * Performs a shallow equality check between two values.\n */\nexport function shallowEqual<T>(valueA: T, valueB: T): boolean {\n  if (Object.is(valueA, valueB)) {\n    return true;\n  }\n\n  if (\n    typeof valueA !== 'object' ||\n    valueA === null ||\n    typeof valueB !== 'object' ||\n    valueB === null\n  ) {\n    return false;\n  }\n\n  if (Object.getPrototypeOf(valueA) !== Object.getPrototypeOf(valueB)) {\n    return false;\n  }\n\n  const isIterableA = isIterable(valueA);\n  const isIterableB = isIterable(valueB);\n\n  if (isIterableA !== isIterableB) {\n    return false;\n  }\n\n  if (isIterableA && isIterableB) {\n    if (hasIterableEntries(valueA) && hasIterableEntries(valueB)) {\n      return compareEntries(valueA, valueB);\n    }\n\n    return compareIterables(valueA, valueB);\n  }\n\n  return comparePlainObjects(\n    valueA as Record<string, unknown>,\n    valueB as Record<string, unknown>,\n  );\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React, {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useRef,\n  useState,\n} from 'react';\nimport {\n  Document,\n  Presence,\n  Indexable,\n  StreamConnectionStatus,\n  Client,\n  RevisionSummary,\n  SyncMode,\n  teardownDevtools,\n} from '@yorkie-js/sdk';\nimport { useYorkie } from './YorkieProvider';\nimport { createDocumentStore } from './createDocumentStore';\nimport { useSelector } from './useSelector';\nimport { Store } from './createStore';\nimport { shallowEqual } from './shallowEqual';\n\n/**\n * `useYorkieDocument` is a custom hook that initializes a Yorkie document.\n * @param client\n * @param clientLoading\n * @param clientError\n * @param docKey\n * @param initialRoot\n * @param initialPresence\n * @param docStore\n * @param docOpts\n * @returns\n */\nexport function useYorkieDocument<R, P extends Indexable = Indexable>(\n  client: Client | undefined,\n  clientLoading: boolean,\n  clientError: Error | undefined,\n  docKey: string,\n  initialRoot: R,\n  initialPresence: P,\n  enableDevtools: boolean,\n  syncMode: SyncMode | undefined,\n  documentPollInterval: number | undefined,\n  disableGC: boolean | undefined,\n  disablePresence: boolean | undefined,\n  docStore: Store<DocumentContextType<R, P>>,\n) {\n  const initialRootRef = useRef(initialRoot);\n  const initialPresenceRef = useRef(initialPresence);\n  const [didMount, setDidMount] = useState(false);\n\n  // NOTE(hackerwins): In StrictMode, the component will call twice\n  // useEffect in development mode. To prevent attaching a document\n  // twice, attach a document after the mounting.\n  useEffect(() => {\n    setDidMount(true);\n  }, []);\n\n  useEffect(() => {\n    if (clientError) {\n      docStore.setState((state) => ({\n        ...state,\n        loading: false,\n        error: clientError,\n      }));\n      return;\n    }\n\n    if (!client || clientLoading || !didMount) {\n      docStore.setState((state) => ({\n        ...state,\n        loading: true,\n      }));\n      return;\n    }\n\n    docStore.setState((state) => ({\n      ...state,\n      loading: true,\n      error: undefined,\n    }));\n\n    const newDoc = new Document<R, P>(docKey, {\n      enableDevtools,\n      disablePresence,\n    });\n    const unsubs: Array<() => void> = [];\n\n    unsubs.push(\n      newDoc.subscribe(() => {\n        docStore.setState((state) => ({\n          ...state,\n          root: newDoc.getRoot(),\n        }));\n      }),\n    );\n\n    unsubs.push(\n      newDoc.subscribe('presence', () => {\n        docStore.setState((state) => ({\n          ...state,\n          presences: newDoc.getPresences(),\n        }));\n      }),\n    );\n\n    unsubs.push(\n      newDoc.subscribe('connection', (event) => {\n        docStore.setState((state) => ({\n          ...state,\n          connection: event.value,\n        }));\n      }),\n    );\n\n    /**\n     * `attachDocument` attaches a new document to the client.\n     */\n    async function attachDocument() {\n      try {\n        await client?.attach(newDoc, {\n          initialRoot: initialRootRef.current,\n          initialPresence: initialPresenceRef.current,\n          syncMode,\n          documentPollInterval,\n          disableGC,\n          disablePresence,\n        });\n\n        const update = (callback: (root: R, presence: Presence<P>) => void) => {\n          try {\n            newDoc.update(callback);\n          } catch (err) {\n            docStore.setState((state) => ({\n              ...state,\n              error:\n                err instanceof Error\n                  ? err\n                  : new Error('Failed to update document'),\n            }));\n          }\n        };\n\n        docStore.setState((state) => ({\n          ...state,\n          doc: newDoc,\n          root: newDoc.getRoot(),\n          presences: newDoc.getPresences(),\n          update,\n        }));\n      } catch (err) {\n        docStore.setState((state) => ({\n          ...state,\n          error:\n            err instanceof Error ? err : new Error('Failed to attach document'),\n        }));\n      } finally {\n        docStore.setState((state) => ({\n          ...state,\n          loading: false,\n        }));\n      }\n    }\n\n    attachDocument();\n\n    return () => {\n      if (client && client.has(docKey)) {\n        // `detach` can fail, and an unmount cleanup has nowhere to put the\n        // failure: the component is already going away, and an exception\n        // thrown here aborts the rest of this cleanup (the subscriptions and\n        // the devtools teardown below). It can also fail *synchronously* —\n        // before the detach RPC is ever enqueued — when the client is no\n        // longer activated or the document is mid-recovery, so both sides of\n        // the call are covered.\n        try {\n          void Promise.resolve(client.detach(newDoc)).catch(() => {});\n        } catch {\n          // The detach could not even be started. Nothing a cleanup can do.\n        }\n      }\n\n      for (const unsub of unsubs) {\n        unsub();\n      }\n\n      // NOTE(chacha912): This effect builds a new Document every time it\n      // re-runs — StrictMode's double render, a remount, a `syncMode` change —\n      // and the one it leaves behind is unreachable from here on. The devtools\n      // bridge holds a window listener, a subscription and a growing recording\n      // per Document, none of them reachable from the Document itself, so they\n      // are given back here instead of accumulating once per re-run.\n      teardownDevtools(newDoc);\n    };\n  }, [\n    client,\n    clientLoading,\n    clientError,\n    docKey,\n    docStore,\n    didMount,\n    syncMode,\n    documentPollInterval,\n    disableGC,\n    disablePresence,\n  ]);\n}\n\nexport type DocumentContextType<R, P extends Indexable = Indexable> = {\n  doc: Document<R, P> | undefined;\n  root: R;\n  presences: Array<{ clientID: string; presence: P }>;\n  connection: StreamConnectionStatus;\n  update: (callback: (root: R, presence: Presence<P>) => void) => void;\n  loading: boolean;\n  error: Error | undefined;\n};\n\nconst DocumentContext = createContext<\n  Store<DocumentContextType<any, any>> | undefined\n>(undefined);\n\n/**\n * `DocumentProvider` is a component that provides a document to its children.\n * This component must be under a `YorkieProvider` component to initialize the\n * Yorkie client properly.\n */\nexport const DocumentProvider = <R, P extends Indexable = Indexable>({\n  docKey,\n  initialRoot = {} as R,\n  initialPresence = {} as P,\n  enableDevtools = false,\n  syncMode,\n  documentPollInterval,\n  disableGC,\n  disablePresence,\n  children,\n}: {\n  docKey: string;\n  initialRoot?: R;\n  initialPresence?: P;\n  enableDevtools?: boolean;\n  /**\n   * `syncMode` defines the synchronization mode of the document.\n   * Defaults to `SyncMode.Realtime`.\n   */\n  syncMode?: SyncMode;\n  /**\n   * `documentPollInterval` (ms) — only used when `syncMode` is `Polling`.\n   * Default: 3000. Applied at attach time.\n   */\n  documentPollInterval?: number;\n  /**\n   * `disableGC` declares that this attachment will not produce or consume\n   * tombstones. Use only with Counter or primitive workloads; misuse on a\n   * document that uses Tree, Text, or Array deletions leads to undefined\n   * GC behavior on this client.\n   */\n  disableGC?: boolean;\n  /**\n   * `disablePresence` declares that this document does not use presence.\n   * Forwarded to both `new Document(...)` and `client.attach(...)`. The\n   * server fixates the value on first attach — subsequent attaches\n   * inherit the server's value regardless of what this prop carries.\n   * Useful for counter-only documents where the per-client presence\n   * map would otherwise leak memory.\n   */\n  disablePresence?: boolean;\n  children?: React.ReactNode;\n}) => {\n  const { client, loading: clientLoading, error: clientError } = useYorkie();\n\n  /**\n   * Initialize the document store only once per component instance.\n   * It prevents creating a new store on every render without using `useMemo`.\n   */\n  const documentStoreRef = useRef<\n    ReturnType<typeof createDocumentStore<R, P>> | undefined\n  >(undefined);\n\n  if (!documentStoreRef.current) {\n    documentStoreRef.current = createDocumentStore<R, P>({\n      doc: undefined,\n      root: initialRoot,\n      presences: [],\n      connection: StreamConnectionStatus.Disconnected,\n      update: () => {},\n      loading: true,\n      error: undefined,\n    });\n  }\n\n  const documentStore = documentStoreRef.current;\n\n  useYorkieDocument<R, P>(\n    client,\n    clientLoading,\n    clientError,\n    docKey,\n    initialRoot,\n    initialPresence,\n    enableDevtools,\n    syncMode,\n    documentPollInterval,\n    disableGC,\n    disablePresence,\n    documentStore,\n  );\n\n  return (\n    <DocumentContext.Provider value={documentStore}>\n      {children}\n    </DocumentContext.Provider>\n  );\n};\n\n/**\n * `useDocument` is a custom hook that returns the complete document context.\n * This hook must be used within a `DocumentProvider`.\n * @returns The complete document context.\n */\nexport function useDocument<\n  R,\n  P extends Indexable = Indexable,\n>(): DocumentContextType<R, P> {\n  const documentStore = useContext(DocumentContext);\n  if (!documentStore) {\n    throw new Error('useDocument must be used within a DocumentProvider');\n  }\n\n  return useSelector(documentStore);\n}\n\n/**\n * `createDocumentSelector` is a factory function that provides a selector-based `useDocument` hook.\n * By currying this function, type T can be inferred from the selector function.\n */\nexport const createDocumentSelector = <\n  R,\n  P extends Indexable = Indexable,\n>() => {\n  return <T = DocumentContextType<R, P>,>(\n    selector: (state: DocumentContextType<R, P>) => T,\n    equalityFn: (a: T, b: T) => boolean = shallowEqual,\n  ): T => {\n    const documentStore = useContext(DocumentContext);\n    if (!documentStore) {\n      throw new Error('useDocument must be used within a DocumentProvider');\n    }\n\n    return useSelector(documentStore, selector, equalityFn);\n  };\n};\n\n/**\n * `useRoot` is a custom hook that returns the root object of the document.\n * This hook must be used within a `DocumentProvider`.\n */\nexport const useRoot = <R,>() => {\n  const documentStore = useDocumentStore('useRoot');\n  const root = useSelector(documentStore, (store) => store.root);\n  return { root: root as R };\n};\n\n/**\n * `usePresences` is a custom hook that returns the presences of the document.\n */\nexport const usePresences = <P extends Indexable = Indexable>() => {\n  const documentStore = useDocumentStore('usePresences');\n  return useSelector(documentStore, (store) => store.presences) as Array<{\n    clientID: string;\n    presence: P;\n  }>;\n};\n\n/**\n * `useConnection` is a custom hook that returns the connection status of the document.\n */\nexport const useConnection = () => {\n  const documentStore = useDocumentStore('useConnection');\n  return useSelector(documentStore, (store) => store.connection);\n};\n\n/**\n * `useRevisions` is a custom hook that provides revision management methods\n * for the current document. It wraps the client's revision API methods\n * and automatically binds the current client and document.\n * This hook must be used within a `DocumentProvider`.\n */\nexport const useRevisions = <R, P extends Indexable = Indexable>() => {\n  const { client } = useYorkie();\n  const documentStore = useDocumentStore('useRevisions');\n  const doc = useSelector(documentStore, (store) => store.doc) as\n    | Document<R, P>\n    | undefined;\n\n  const createRevision = useCallback(\n    async (label: string, description?: string): Promise<RevisionSummary> => {\n      if (!client || !doc) {\n        throw new Error('Client or document is not ready');\n      }\n      return client.createRevision(doc, label, description);\n    },\n    [client, doc],\n  );\n\n  const listRevisions = useCallback(\n    async (options?: {\n      pageSize?: number;\n      offset?: number;\n      isForward?: boolean;\n    }): Promise<Array<RevisionSummary>> => {\n      if (!client || !doc) {\n        throw new Error('Client or document is not ready');\n      }\n      return client.listRevisions(doc, options);\n    },\n    [client, doc],\n  );\n\n  const getRevision = useCallback(\n    async (revisionID: string): Promise<RevisionSummary> => {\n      if (!client || !doc) {\n        throw new Error('Client or document is not ready');\n      }\n      return client.getRevision(doc, revisionID);\n    },\n    [client, doc],\n  );\n\n  const restoreRevision = useCallback(\n    async (revisionID: string): Promise<void> => {\n      if (!client || !doc) {\n        throw new Error('Client or document is not ready');\n      }\n      return client.restoreRevision(doc, revisionID);\n    },\n    [client, doc],\n  );\n\n  return { createRevision, listRevisions, getRevision, restoreRevision };\n};\n\n/**\n * `useRemoveDocument` returns a function that removes the current document\n * from the server via `client.remove` (as opposed to `client.detach`).\n * After it resolves the document is gone for every client and the key can\n * be reattached as a fresh document. The returned function rejects until\n * the document is attached, and the removal error is propagated to the\n * caller. This hook must be used within a `DocumentProvider`.\n */\nexport const useRemoveDocument = <R, P extends Indexable = Indexable>() => {\n  const { client } = useYorkie();\n  const documentStore = useDocumentStore('useRemoveDocument');\n  const doc = useSelector(documentStore, (store) => store.doc) as\n    | Document<R, P>\n    | undefined;\n\n  return useCallback(async (): Promise<void> => {\n    if (!client || !doc) {\n      throw new Error('Client or document is not ready');\n    }\n    await client.remove(doc);\n  }, [client, doc]);\n};\n\n/**\n * `useDocumentStore` is a custom hook that returns the document store.\n * It also ensures that the hook is used within a `DocumentProvider`.\n */\nconst useDocumentStore = (hookName: string) => {\n  const documentStore = useContext(DocumentContext);\n  if (!documentStore) {\n    throw new Error(`${hookName} must be used within a DocumentProvider`);\n  }\n  return documentStore;\n};\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  ClientOptions,\n  Indexable,\n  Presence,\n  StreamConnectionStatus,\n  SyncMode,\n} from '@yorkie-js/sdk';\nimport pkg from '../package.json';\nimport { useYorkieClient } from './YorkieProvider';\nimport { useYorkieDocument } from './DocumentProvider';\nimport { useMemo, useRef } from 'react';\nimport { createDocumentStore } from './createDocumentStore';\nimport { useSelector } from './useSelector';\n\n/**\n * `useYorkieDoc` is a custom hook that initializes a Yorkie Client and a\n * document in a single hook.\n */\nexport function useYorkieDoc<R, P extends Indexable = Indexable>(\n  apiKey: string,\n  docKey: string,\n  opts?: Omit<ClientOptions, 'apiKey'> & {\n    initialRoot?: R;\n    initialPresence?: P;\n    enableDevtools?: boolean;\n    syncMode?: SyncMode;\n    documentPollInterval?: number;\n    /**\n     * `disableGC` declares that this attachment will not produce or consume\n     * tombstones. Use only with Counter or primitive workloads; misuse on a\n     * document that uses Tree, Text, or Array deletions leads to undefined\n     * GC behavior on this client.\n     */\n    disableGC?: boolean;\n    /**\n     * `disablePresence` declares that this document does not use presence.\n     * Forwarded to both `new Document(...)` and `client.attach(...)`. The\n     * server fixates the value on first attach — subsequent attaches\n     * inherit the server's value regardless of what this option carries.\n     */\n    disablePresence?: boolean;\n  },\n): {\n  root: R;\n  presences: Array<{ clientID: string; presence: P }>;\n  connection: StreamConnectionStatus;\n  update: (callback: (root: R, presence: Presence<P>) => void) => void;\n  loading: boolean;\n  error: Error | undefined;\n} {\n  const documentStoreRef = useRef<\n    ReturnType<typeof createDocumentStore<R, P>> | undefined\n  >(undefined);\n\n  if (!documentStoreRef.current) {\n    documentStoreRef.current = createDocumentStore<R, P>({\n      doc: undefined,\n      root: opts?.initialRoot ?? ({} as R),\n      presences: [] as Array<{ clientID: string; presence: P }>,\n      connection: StreamConnectionStatus.Disconnected,\n      update: () => {},\n      loading: true,\n      error: undefined,\n    });\n  }\n\n  const documentStore = documentStoreRef.current;\n\n  // NOTE(hackerwins): useMemo is used to prevent creating a new client\n  // every time the component re-renders. If the apiKey or docKey\n  // changes, a new client will be created.\n  const clientOpts = useMemo(() => {\n    return {\n      apiKey,\n      userAgent: pkg.name + '/' + pkg.version,\n      ...opts,\n    };\n  }, [apiKey, opts]);\n\n  const {\n    client,\n    loading: clientLoading,\n    error: clientError,\n  } = useYorkieClient(clientOpts);\n\n  useYorkieDocument<R, P>(\n    client,\n    clientLoading,\n    clientError,\n    docKey,\n    opts?.initialRoot ?? ({} as R),\n    opts?.initialPresence ?? ({} as P),\n    opts?.enableDevtools ?? false,\n    opts?.syncMode,\n    opts?.documentPollInterval,\n    opts?.disableGC,\n    opts?.disablePresence,\n    documentStore,\n  );\n\n  const documentState = useSelector(documentStore);\n\n  return {\n    root: documentState.root,\n    presences: documentState.presences,\n    connection: documentState.connection,\n    update: documentState.update,\n    loading: documentState.loading,\n    error: documentState.error,\n  };\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Channel } from '@yorkie-js/sdk';\nimport { createStore, Store } from './createStore';\n\n/**\n * `ChannelContextType` represents the state of the Channel context.\n */\nexport type ChannelContextType = {\n  /**\n   * `channel` is the Channel instance.\n   */\n  channel: Channel | undefined;\n\n  /**\n   * `sessionCount` is the current online session count.\n   * NOTE: This is session-based (e.g., multiple tabs can increase the count).\n   */\n  sessionCount: number;\n\n  /**\n   * `loading` indicates whether the channel is being initialized.\n   */\n  loading: boolean;\n\n  /**\n   * `error` contains any error that occurred during initialization.\n   */\n  error: Error | undefined;\n\n  /**\n   * `detach` tears the channel down on demand — useful when a consumer\n   * decides that the channel should be permanently stopped (e.g. after\n   * observing `error` from `useChannel()`). Idempotent: a second call,\n   * or a call after `ChannelProvider` has already unmounted and cleaned\n   * up, resolves silently instead of throwing.\n   */\n  detach: () => Promise<void>;\n};\n\n/**\n * `createChannelStore` creates a store for managing Channel state.\n * @param initialState - Initial state for the channel store\n * @returns Store instance for channel state management\n */\nexport function createChannelStore(\n  initialState: ChannelContextType,\n): Store<ChannelContextType> {\n  return createStore<ChannelContextType>(initialState);\n}\n","/*\n * Copyright 2025 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  createContext,\n  PropsWithChildren,\n  useContext,\n  useEffect,\n  useRef,\n  useState,\n} from 'react';\nimport { Client, Channel, ChannelEventType, SyncMode } from '@yorkie-js/sdk';\nimport { Store } from './createStore';\nimport {\n  createChannelStore as createChannelStore,\n  ChannelContextType as ChannelContextType,\n} from './createChannelStore';\nimport { useSelector } from './useSelector';\nimport { useYorkie } from './YorkieProvider';\n\n/**\n * `ChannelContext` is a context for sharing Channel store across components.\n */\nconst ChannelContext = createContext<Store<ChannelContextType> | undefined>(\n  undefined,\n);\n\n/**\n * `useYorkieChannel` is a custom hook that initializes and manages a Yorkie Channel.\n */\nexport function useYorkieChannel(\n  client: Client | undefined,\n  clientLoading: boolean,\n  clientError: Error | undefined,\n  channelKey: string,\n  syncMode: SyncMode,\n  channelHeartbeatInterval: number | undefined,\n  channelStore: Store<ChannelContextType>,\n) {\n  const channelRef = useRef<Channel | undefined>(undefined);\n  const [didMount, setDidMount] = useState(false);\n\n  // NOTE(hackerwins): In StrictMode, the component will call twice\n  // useEffect in development mode. To prevent attaching a channel\n  // twice, attach a channel after the mounting.\n  useEffect(() => {\n    setDidMount(true);\n  }, []);\n\n  useEffect(() => {\n    if (!didMount || clientLoading || clientError || !client) {\n      if (clientError) {\n        channelStore.setState((state) => ({\n          ...state,\n          error: clientError,\n          loading: false,\n        }));\n      }\n      return;\n    }\n\n    let unsubscribe: (() => void) | undefined;\n\n    /**\n     * `attachChannel` attaches the channel to the client.\n     */\n    async function attachChannel() {\n      // No `isActive()` gate: channels can attach on inactive clients under\n      // the RefreshChannel-only lifecycle. The first heartbeat lazy-attaches\n      // the client (and the channel) to the server.\n      if (!client) {\n        return;\n      }\n\n      channelStore.setState((state) => ({\n        ...state,\n        loading: true,\n        error: undefined,\n      }));\n\n      try {\n        const newChannel = new Channel(channelKey);\n        await client.attach(newChannel, {\n          syncMode,\n          channelHeartbeatInterval,\n        });\n\n        channelRef.current = newChannel;\n\n        // Subscribe to channel events. `client.attach(channel)` now returns\n        // before the first RefreshChannel heartbeat, so `sessionCount` and\n        // the Attached status only become valid after the server's first\n        // response. Keep `loading: true` until that happens, then flip it\n        // along with the populated sessionCount on the same event so the\n        // UI never sees a transient `loading: false, sessionCount: 0`.\n        //\n        // SyncError / AuthError events from the SDK populate `error` so\n        // consumers can render an error state via the same hook return.\n        // Server-confirmed events (PresenceChanged / Initialized / remote\n        // Broadcast) clear `error` because they prove the channel is\n        // healthy again. LocalBroadcast is purely local and does not\n        // imply recovery — exclude it explicitly.\n        unsubscribe = newChannel.subscribe((event) => {\n          if (\n            event.type === ChannelEventType.SyncError ||\n            event.type === ChannelEventType.AuthError\n          ) {\n            const nextError =\n              event.type === ChannelEventType.SyncError\n                ? event.error instanceof Error\n                  ? event.error\n                  : new Error(String(event.error))\n                : new Error(\n                    `auth error during ${event.method}: ${event.reason}`,\n                  );\n            channelStore.setState((state) => ({\n              ...state,\n              loading: false,\n              error: nextError,\n            }));\n            return;\n          }\n\n          const recovers =\n            event.type === ChannelEventType.PresenceChanged ||\n            event.type === ChannelEventType.Initialized ||\n            event.type === ChannelEventType.Broadcast;\n          const ready = newChannel.isAttached() && !!newChannel.getSessionID();\n          channelStore.setState((state) => ({\n            ...state,\n            sessionCount: newChannel.getSessionCount(),\n            ...(recovers && state.error ? { error: undefined } : {}),\n            ...(ready && state.loading ? { loading: false } : {}),\n          }));\n        });\n\n        // Expose an idempotent detach so consumers can permanently stop a\n        // channel from inside the tree (e.g. on `error`) without unmounting\n        // the surrounding `<ChannelProvider>`. Calling `isAttached()` here\n        // would be wrong — `client.attach(channel)` is local-only under the\n        // RefreshChannel-only lifecycle, so the status stays `Detached`\n        // until the first heartbeat lands; an `isAttached()` gate would\n        // skip the call and leak the attachment entry. Instead, dispatch\n        // unconditionally and swallow `ErrNotAttached` from duplicate /\n        // post-unmount calls.\n        const detach = async () => {\n          if (!client) return;\n          try {\n            await client.detach(newChannel);\n          } catch (err) {\n            if (err instanceof Error && /not attached/i.test(err.message)) {\n              return;\n            }\n            throw err;\n          }\n        };\n\n        channelStore.setState((state) => ({\n          ...state,\n          channel: newChannel,\n          error: undefined,\n          detach,\n        }));\n      } catch (e) {\n        channelStore.setState((state) => ({\n          ...state,\n          loading: false,\n          error: e instanceof Error ? e : new Error('Failed to attach channel'),\n        }));\n      }\n    }\n\n    attachChannel();\n\n    return () => {\n      if (unsubscribe) {\n        unsubscribe();\n      }\n\n      /**\n       * `detachChannel` detaches the channel from the client. Channels can\n       * be detached on inactive clients — detach is local cleanup only and\n       * the server reclaims the session via TTL.\n       *\n       * Idempotent against the consumer-facing `detach` exposed via\n       * `useChannel()`: if the consumer detached first, `client.detach`\n       * throws `ErrNotAttached`, which we swallow as a normal cleanup race.\n       */\n      async function detachChannel() {\n        if (channelRef.current && client) {\n          try {\n            await client.detach(channelRef.current);\n          } catch (e) {\n            if (e instanceof Error && /not attached/i.test(e.message)) {\n              return;\n            }\n            console.error('Failed to detach channel:', e);\n          }\n        }\n      }\n      detachChannel();\n    };\n  }, [\n    client,\n    clientLoading,\n    clientError,\n    channelKey,\n    syncMode,\n    channelHeartbeatInterval,\n    didMount,\n  ]);\n}\n\n/**\n * `ChannelProviderProps` represents the props for ChannelProvider.\n */\nexport type ChannelProviderProps = PropsWithChildren<{\n  /**\n   * `channelKey` is the key for the channel.\n   */\n  channelKey: string;\n\n  /**\n   * `syncMode` selects how the channel keeps presence in sync with the server.\n   * - `SyncMode.Realtime` (default): open a watch stream and run the\n   *   heartbeat. Required to receive broadcast events.\n   * - `SyncMode.Polling`: heartbeat-only. No watch stream is opened.\n   *   Recommended for large channels where broadcast is not needed.\n   * - `SyncMode.Manual`: no automatic activity.\n   *\n   * If `isRealtime` is also set, `syncMode` wins.\n   */\n  syncMode?: SyncMode;\n\n  /**\n   * `isRealtime` is a convenience prop covering only Realtime/Manual.\n   * - `true`: equivalent to `syncMode={SyncMode.Realtime}`.\n   * - `false`: equivalent to `syncMode={SyncMode.Manual}`.\n   *\n   * Use `syncMode` directly when you want `SyncMode.Polling`, which this\n   * boolean prop cannot express. When neither prop is set, the channel\n   * falls back to `SyncMode.Realtime`.\n   */\n  isRealtime?: boolean;\n\n  /**\n   * `channelHeartbeatInterval` overrides the heartbeat interval (ms).\n   * Applied at attach time. Defaults: Polling=3000, Realtime=30000.\n   */\n  channelHeartbeatInterval?: number;\n}>;\n\n/**\n * `ChannelProvider` is a component that provides Channel context to its children.\n * It must be used within a YorkieProvider to access the client.\n *\n * @example\n * ```tsx\n * import { ChannelProvider, SyncMode } from '@yorkie-js/react';\n *\n * <YorkieProvider apiKey=\"...\" rpcAddr=\"...\">\n *   <ChannelProvider channelKey=\"room-123\" syncMode={SyncMode.Realtime}>\n *     <ChatRoom />\n *   </ChannelProvider>\n * </YorkieProvider>\n * ```\n *\n * The boolean `isRealtime` prop is also accepted as a shortcut for\n * the Realtime/Manual choice (`true` → Realtime, `false` → Manual).\n */\nexport const ChannelProvider: React.FC<ChannelProviderProps> = ({\n  children,\n  channelKey,\n  syncMode,\n  isRealtime,\n  channelHeartbeatInterval,\n}) => {\n  const { client, loading: clientLoading, error: clientError } = useYorkie();\n\n  const channelStoreRef = useRef<Store<ChannelContextType> | undefined>(\n    undefined,\n  );\n\n  if (!channelStoreRef.current) {\n    channelStoreRef.current = createChannelStore({\n      channel: undefined,\n      sessionCount: 0,\n      loading: true,\n      error: undefined,\n      // Placeholder until `useYorkieChannel` wires up the real detach.\n      // Pre-attach calls are a no-op rather than a throw.\n      detach: async () => {},\n    });\n  }\n\n  const channelStore = channelStoreRef.current;\n\n  // Resolve syncMode: explicit syncMode wins, then isRealtime, else Realtime.\n  const resolvedSyncMode: SyncMode =\n    syncMode ?? (isRealtime === false ? SyncMode.Manual : SyncMode.Realtime);\n\n  useYorkieChannel(\n    client,\n    clientLoading,\n    clientError,\n    channelKey,\n    resolvedSyncMode,\n    channelHeartbeatInterval,\n    channelStore,\n  );\n\n  return (\n    <ChannelContext.Provider value={channelStore}>\n      {children}\n    </ChannelContext.Provider>\n  );\n};\n\n/**\n * `useChannelStore` returns the Channel store from context.\n * It ensures that the hook is used within a ChannelProvider.\n *\n * @param hookName - Name of the hook calling this function (for error messages)\n * @returns The channel store\n * @throws Error if used outside of ChannelProvider\n */\nexport const useChannelStore = (hookName: string) => {\n  const channelStore = useContext(ChannelContext);\n  if (!channelStore) {\n    throw new Error(`${hookName} must be used within ChannelProvider`);\n  }\n  return channelStore;\n};\n\n/**\n * `useChannel` is a custom hook that returns the channel state.\n * It must be used within a ChannelProvider.\n *\n * @returns An object containing sessionCount, loading, error state and\n *          a `detach` function for permanently stopping the channel.\n *\n * @example\n * ```tsx\n * function ChatRoom() {\n *   const { sessionCount, loading, error } = useChannel();\n *\n *   if (loading) return <div>Loading...</div>;\n *   if (error) return <div>Error: {error.message}</div>;\n *\n *   return <div>{sessionCount} online</div>;\n * }\n * ```\n */\nexport const useChannel = () => {\n  const channelStore = useChannelStore('useChannel');\n  const sessionCount = useSelector(channelStore, (state) => state.sessionCount);\n  const loading = useSelector(channelStore, (state) => state.loading);\n  const error = useSelector(channelStore, (state) => state.error);\n  const detach = useSelector(channelStore, (state) => state.detach);\n\n  return { sessionCount, loading, error, detach };\n};\n\n/**\n * `useChannelSessionCount` is a custom hook that returns only the session count value.\n * It must be used within a ChannelProvider.\n * This is a convenience hook for when you only need the session count.\n *\n * @returns The current online session count\n *\n * @example\n * ```tsx\n * function UserCounter() {\n *   const count = useChannelSessionCount();\n *   return <span>{count} online</span>;\n * }\n * ```\n */\nexport const useChannelSessionCount = (): number => {\n  const channelStore = useChannelStore('useChannelSessionCount');\n  return useSelector(channelStore, (state) => state.sessionCount);\n};\n","/*\n * Copyright 2026 The Yorkie Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useYorkie } from './YorkieProvider';\n\n/**\n * `UsePeekChannelOptions` are user-settable options for `usePeekChannel`.\n */\nexport interface UsePeekChannelOptions {\n  /**\n   * `pollInterval` opts the hook into continuous polling at the given\n   * cadence (ms). When unset, the hook fetches once on mount and stops —\n   * this matches the common \"snapshot at entry\" pattern. Use polling only\n   * when the UI genuinely needs a live-updating count.\n   */\n  pollInterval?: number;\n\n  /**\n   * `enabled` toggles execution. When false, the hook does not fetch and\n   * holds the last value. Default: true.\n   */\n  enabled?: boolean;\n}\n\n/**\n * `UsePeekChannelResult` is the state exposed by `usePeekChannel`.\n */\nexport interface UsePeekChannelResult {\n  /**\n   * `sessionCount` is the most recently fetched count. Starts at 0 before\n   * the first successful fetch; gate display on `loading` if 0-vs-unfetched\n   * matters in your UI.\n   */\n  sessionCount: number;\n\n  /**\n   * `loading` is true before the first successful fetch (or while a\n   * `refetch()` is in flight). Becomes false on success or error.\n   */\n  loading: boolean;\n\n  /**\n   * `error` holds the last error from a fetch, if any.\n   */\n  error?: Error;\n\n  /**\n   * `refetch` issues a peek immediately, ignoring `pollInterval`. Useful on\n   * button clicks or after user actions that may have changed the count.\n   */\n  refetch: () => Promise<void>;\n}\n\n/**\n * `usePeekChannel` reads a channel's current session count without joining\n * the channel. By default it fetches once on mount; pass `pollInterval` to\n * opt into continuous polling. The caller does not create a Session on the\n * server, does not receive broadcasts, and does not contribute to the\n * channel's count.\n *\n * Prefer this over `<ChannelProvider readOnly>` when many viewers need to\n * display a count and only a few become real participants — e.g. a global\n * \"N people writing\" badge shown on every surrounding page.\n *\n * @example One-shot (snapshot at entry)\n * ```tsx\n * function WritersBadge() {\n *   const { sessionCount, loading } = usePeekChannel('post-writers');\n *   if (loading) return null;\n *   return <span>{sessionCount} writing</span>;\n * }\n * ```\n *\n * @example Continuous polling\n * ```tsx\n * function LiveCounter() {\n *   const { sessionCount } = usePeekChannel('post-writers', {\n *     pollInterval: 3000,\n *   });\n *   return <span>{sessionCount} writing</span>;\n * }\n * ```\n *\n * @example Imperative refetch\n * ```tsx\n * function WithRefresh() {\n *   const { sessionCount, refetch } = usePeekChannel('post-writers');\n *   return (\n *     <button onClick={() => refetch()}>{sessionCount} (refresh)</button>\n *   );\n * }\n * ```\n */\nexport function usePeekChannel(\n  channelKey: string,\n  opts: UsePeekChannelOptions = {},\n): UsePeekChannelResult {\n  const { client, loading: clientLoading, error: clientError } = useYorkie();\n  const { pollInterval, enabled = true } = opts;\n\n  const [sessionCount, setSessionCount] = useState(0);\n  const [loading, setLoading] = useState(true);\n  const [error, setError] = useState<Error | undefined>(clientError);\n\n  // Latest channelKey captured for refetch. Avoids closing over stale prop.\n  const channelKeyRef = useRef(channelKey);\n  channelKeyRef.current = channelKey;\n\n  // Track mount state so imperative refetch() does not setState after unmount.\n  const mountedRef = useRef(true);\n  useEffect(() => {\n    mountedRef.current = true;\n    return () => {\n      mountedRef.current = false;\n    };\n  }, []);\n\n  const peekOnce = useCallback(async () => {\n    // No `isActive()` gate: peekChannel is stateless on the server and does\n    // not require `client.activate()`. Channel-only apps that opt out of\n    // activation via `<YorkieProvider activate={false}>` should still peek.\n    if (!client) return;\n    if (mountedRef.current) setLoading(true);\n    try {\n      const count = await client.peekChannel(channelKeyRef.current);\n      if (!mountedRef.current) return;\n      setSessionCount(count);\n      setError(undefined);\n    } catch (e) {\n      if (!mountedRef.current) return;\n      setError(e instanceof Error ? e : new Error(String(e)));\n    } finally {\n      if (mountedRef.current) setLoading(false);\n    }\n  }, [client]);\n\n  useEffect(() => {\n    if (clientError) {\n      setError(clientError);\n      setLoading(false);\n      return;\n    }\n    // Mark loading before the early-return guards so a stale sessionCount\n    // from a previous channelKey is not shown while the client is still\n    // initializing; the !enabled branch resets it below.\n    setLoading(true);\n    if (!enabled) {\n      setLoading(false);\n      return;\n    }\n    if (clientLoading || !client) return;\n\n    let cancelled = false;\n    let timer: ReturnType<typeof setTimeout> | undefined;\n\n    const run = async () => {\n      if (cancelled) return;\n      try {\n        const count = await client.peekChannel(channelKey);\n        if (cancelled) return;\n        setSessionCount(count);\n        setError(undefined);\n      } catch (e) {\n        if (cancelled) return;\n        setError(e instanceof Error ? e : new Error(String(e)));\n      } finally {\n        if (!cancelled) setLoading(false);\n      }\n      if (!cancelled && pollInterval !== undefined && pollInterval > 0) {\n        timer = setTimeout(run, pollInterval);\n      }\n    };\n\n    run();\n\n    return () => {\n      cancelled = true;\n      if (timer) clearTimeout(timer);\n    };\n  }, [client, clientLoading, clientError, channelKey, pollInterval, enabled]);\n\n  return { sessionCount, loading, error, refetch: peekOnce };\n}\n"],"names":["createContext","useState","useEffect","Client","useMemo","jsx","useContext","useRef","useSyncExternalStore","Document","teardownDevtools","StreamConnectionStatus","useCallback","Channel","ChannelEventType","SyncMode"],"mappings":";;;;;;;;;;;AAiCA,MAAM,gBAAgBA,MAAAA,cAAiC;AAAA,EACrD,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,OAAO;AACT,CAAC;AAYM,SAAS,gBAAgB,MAAqB,WAAoB,MAAM;AAC7E,QAAM,CAAC,QAAQ,SAAS,IAAIC,MAAAA,SAA6B,MAAS;AAClE,QAAM,CAAC,SAAS,UAAU,IAAIA,MAAAA,SAAkB,IAAI;AACpD,QAAM,CAAC,OAAO,QAAQ,IAAIA,MAAAA,SAA4B,MAAS;AAC/D,QAAM,CAAC,UAAU,WAAW,IAAIA,MAAAA,SAAS,KAAK;AAK9CC,QAAAA,UAAU,MAAM;AACd,gBAAY,IAAI;AAAA,EAClB,GAAG,CAAA,CAAE;AAELA,QAAAA,UAAU,MAAM;AACd,eAAW,IAAI;AACf,aAAS,MAAS;AAKlB,mBAAe,iBAAiB;AAC9B,UAAI,CAAC,UAAU;AACb;AAAA,MACF;AAEA,UAAI;AACF,cAAM,YAAY,IAAIC,IAAAA,OAAO,IAAI;AACjC,YAAI,UAAU;AACZ,gBAAM,UAAU,SAAA;AAAA,QAClB;AACA,kBAAU,SAAS;AAAA,MACrB,SAAS,GAAG;AACV;AAAA,UACE,aAAa,QAAQ,IAAI,IAAI,MAAM,2BAA2B;AAAA,QAAA;AAAA,MAElE,UAAA;AACE,mBAAW,KAAK;AAAA,MAClB;AAAA,IACF;AACA,mBAAA;AAEA,WAAO,MAAM;AACX,UAAI,YAAY,QAAQ,SAAA,KAAc,KAAK,uBAAuB,OAAO;AACvE,eAAO,WAAW,EAAE,WAAW,KAAA,CAAM;AAAA,MACvC;AAAA,IACF;AAAA,EACF,GAAG,CAAC,KAAK,QAAQ,KAAK,SAAS,KAAK,KAAK,UAAU,QAAQ,CAAC;AAE5D,SAAO,EAA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