vite-plugin-react-pages
Version:
<p> <a href="https://www.npmjs.com/package/vite-plugin-react-pages" target="_blank" rel="noopener"><img src="https://img.shields.io/npm/v/vite-plugin-react-pages.svg" alt="npm package" /></a> </p>
1 lines • 99.2 kB
Source Map (JSON)
{"version":3,"file":"csr.mjs","sources":["../../../src/client/ctx.tsx","../../../src/client/entries/ClientAppWrapper.tsx","../../../../../node_modules/.pnpm/jotai@2.6.2_@types+react@18.2.48_react@18.2.0/node_modules/jotai/esm/vanilla.mjs","../../../../../node_modules/.pnpm/jotai@2.6.2_@types+react@18.2.48_react@18.2.0/node_modules/jotai/esm/react.mjs","../../../../../node_modules/.pnpm/jotai@2.6.2_@types+react@18.2.48_react@18.2.0/node_modules/jotai/esm/vanilla/utils.mjs","../../../src/client/state.ts","../../../src/client/utils.ts","../../../src/client/useAppState.tsx","../../../src/client/PageLoader.tsx","../../../src/client/App.tsx","../../../src/client/entries/csr.tsx"],"sourcesContent":["import { createContext } from 'react'\nimport type { PagesLoaded } from '../../clientTypes'\n\n/**\n * During ssr hydration, we pass all the data needed by App\n * with this ctx\n * so the App can render the page data directly\n * instead of render the loading state\n */\nexport const dataCacheCtx = createContext<PagesLoaded>({})\nexport const setDataCacheCtx = createContext<\n React.Dispatch<React.SetStateAction<PagesLoaded>>\n>(() => {\n throw new Error(`setDataCacheCtx not found`)\n})\n","/// <reference types=\"vite/client\" />\n\n/**\n * This is a common wrapper component for csr.tsx and ssg-client.tsx\n */\n\nimport React, { useState } from 'react'\nimport { HashRouter, BrowserRouter } from 'react-router-dom'\nimport { dataCacheCtx, setDataCacheCtx } from '../ctx'\nimport type { PageLoaded } from '../../../clientTypes'\n\n// @ts-expect-error\nconst Router = __HASH_ROUTER__ ? HashRouter : BrowserRouter\n// @ts-expect-error\nconst basename = __HASH_ROUTER__\n ? undefined\n : import.meta.env.BASE_URL?.replace(/\\/$/, '')\n\ninterface Props {\n readonly initCache?: PageLoaded\n readonly children: React.ReactNode\n}\n\nconst ClientAppWrapper: React.FC<React.PropsWithChildren<Props>> = ({\n initCache,\n children,\n}) => {\n const [dataCache, setDataCache] = useState<PageLoaded>(initCache ?? {})\n return (\n <Router basename={basename}>\n <dataCacheCtx.Provider value={dataCache}>\n <setDataCacheCtx.Provider value={setDataCache}>\n {children}\n </setDataCacheCtx.Provider>\n </dataCacheCtx.Provider>\n </Router>\n )\n}\n\nexport default ClientAppWrapper\n","let keyCount = 0;\nfunction atom(read, write) {\n const key = `atom${++keyCount}`;\n const config = {\n toString: () => key\n };\n if (typeof read === \"function\") {\n config.read = read;\n } else {\n config.init = read;\n config.read = function(get) {\n return get(this);\n };\n config.write = function(get, set, arg) {\n return set(\n this,\n typeof arg === \"function\" ? arg(get(this)) : arg\n );\n };\n }\n if (write) {\n config.write = write;\n }\n return config;\n}\n\nconst hasInitialValue = (atom) => \"init\" in atom;\nconst isActuallyWritableAtom = (atom) => !!atom.write;\nconst cancelPromiseMap = /* @__PURE__ */ new WeakMap();\nconst registerCancelPromise = (promise, cancel) => {\n cancelPromiseMap.set(promise, cancel);\n promise.catch(() => {\n }).finally(() => cancelPromiseMap.delete(promise));\n};\nconst cancelPromise = (promise, next) => {\n const cancel = cancelPromiseMap.get(promise);\n if (cancel) {\n cancelPromiseMap.delete(promise);\n cancel(next);\n }\n};\nconst resolvePromise = (promise, value) => {\n promise.status = \"fulfilled\";\n promise.value = value;\n};\nconst rejectPromise = (promise, e) => {\n promise.status = \"rejected\";\n promise.reason = e;\n};\nconst isPromiseLike = (x) => typeof (x == null ? void 0 : x.then) === \"function\";\nconst isEqualAtomValue = (a, b) => !!a && \"v\" in a && \"v\" in b && Object.is(a.v, b.v);\nconst isEqualAtomError = (a, b) => !!a && \"e\" in a && \"e\" in b && Object.is(a.e, b.e);\nconst hasPromiseAtomValue = (a) => !!a && \"v\" in a && a.v instanceof Promise;\nconst isEqualPromiseAtomValue = (a, b) => \"v\" in a && \"v\" in b && a.v.orig && a.v.orig === b.v.orig;\nconst returnAtomValue = (atomState) => {\n if (\"e\" in atomState) {\n throw atomState.e;\n }\n return atomState.v;\n};\nconst createStore = () => {\n const atomStateMap = /* @__PURE__ */ new WeakMap();\n const mountedMap = /* @__PURE__ */ new WeakMap();\n const pendingMap = /* @__PURE__ */ new Map();\n let storeListenersRev2;\n let mountedAtoms;\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n storeListenersRev2 = /* @__PURE__ */ new Set();\n mountedAtoms = /* @__PURE__ */ new Set();\n }\n const getAtomState = (atom) => atomStateMap.get(atom);\n const setAtomState = (atom, atomState) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n Object.freeze(atomState);\n }\n const prevAtomState = atomStateMap.get(atom);\n atomStateMap.set(atom, atomState);\n if (!pendingMap.has(atom)) {\n pendingMap.set(atom, prevAtomState);\n }\n if (hasPromiseAtomValue(prevAtomState)) {\n const next = \"v\" in atomState ? atomState.v instanceof Promise ? atomState.v : Promise.resolve(atomState.v) : Promise.reject(atomState.e);\n if (prevAtomState.v !== next) {\n cancelPromise(prevAtomState.v, next);\n }\n }\n };\n const updateDependencies = (atom, nextAtomState, nextDependencies) => {\n const dependencies = /* @__PURE__ */ new Map();\n let changed = false;\n nextDependencies.forEach((aState, a) => {\n if (!aState && a === atom) {\n aState = nextAtomState;\n }\n if (aState) {\n dependencies.set(a, aState);\n if (nextAtomState.d.get(a) !== aState) {\n changed = true;\n }\n } else if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n console.warn(\"[Bug] atom state not found\");\n }\n });\n if (changed || nextAtomState.d.size !== dependencies.size) {\n nextAtomState.d = dependencies;\n }\n };\n const setAtomValue = (atom, value, nextDependencies) => {\n const prevAtomState = getAtomState(atom);\n const nextAtomState = {\n d: (prevAtomState == null ? void 0 : prevAtomState.d) || /* @__PURE__ */ new Map(),\n v: value\n };\n if (nextDependencies) {\n updateDependencies(atom, nextAtomState, nextDependencies);\n }\n if (isEqualAtomValue(prevAtomState, nextAtomState) && prevAtomState.d === nextAtomState.d) {\n return prevAtomState;\n }\n if (hasPromiseAtomValue(prevAtomState) && hasPromiseAtomValue(nextAtomState) && isEqualPromiseAtomValue(prevAtomState, nextAtomState)) {\n if (prevAtomState.d === nextAtomState.d) {\n return prevAtomState;\n } else {\n nextAtomState.v = prevAtomState.v;\n }\n }\n setAtomState(atom, nextAtomState);\n return nextAtomState;\n };\n const setAtomValueOrPromise = (atom, valueOrPromise, nextDependencies, abortPromise) => {\n if (isPromiseLike(valueOrPromise)) {\n let continuePromise;\n const updatePromiseDependencies = () => {\n const prevAtomState = getAtomState(atom);\n if (!hasPromiseAtomValue(prevAtomState) || prevAtomState.v !== promise) {\n return;\n }\n const nextAtomState = setAtomValue(\n atom,\n promise,\n nextDependencies\n );\n if (mountedMap.has(atom) && prevAtomState.d !== nextAtomState.d) {\n mountDependencies(atom, nextAtomState, prevAtomState.d);\n }\n };\n const promise = new Promise((resolve, reject) => {\n let settled = false;\n valueOrPromise.then(\n (v) => {\n if (!settled) {\n settled = true;\n resolvePromise(promise, v);\n resolve(v);\n updatePromiseDependencies();\n }\n },\n (e) => {\n if (!settled) {\n settled = true;\n rejectPromise(promise, e);\n reject(e);\n updatePromiseDependencies();\n }\n }\n );\n continuePromise = (next) => {\n if (!settled) {\n settled = true;\n next.then(\n (v) => resolvePromise(promise, v),\n (e) => rejectPromise(promise, e)\n );\n resolve(next);\n }\n };\n });\n promise.orig = valueOrPromise;\n promise.status = \"pending\";\n registerCancelPromise(promise, (next) => {\n if (next) {\n continuePromise(next);\n }\n abortPromise == null ? void 0 : abortPromise();\n });\n return setAtomValue(atom, promise, nextDependencies);\n }\n return setAtomValue(atom, valueOrPromise, nextDependencies);\n };\n const setAtomError = (atom, error, nextDependencies) => {\n const prevAtomState = getAtomState(atom);\n const nextAtomState = {\n d: (prevAtomState == null ? void 0 : prevAtomState.d) || /* @__PURE__ */ new Map(),\n e: error\n };\n if (nextDependencies) {\n updateDependencies(atom, nextAtomState, nextDependencies);\n }\n if (isEqualAtomError(prevAtomState, nextAtomState) && prevAtomState.d === nextAtomState.d) {\n return prevAtomState;\n }\n setAtomState(atom, nextAtomState);\n return nextAtomState;\n };\n const readAtomState = (atom, force) => {\n const atomState = getAtomState(atom);\n if (!force && atomState) {\n if (mountedMap.has(atom)) {\n return atomState;\n }\n if (Array.from(atomState.d).every(([a, s]) => {\n if (a === atom) {\n return true;\n }\n const aState = readAtomState(a);\n return aState === s || isEqualAtomValue(aState, s);\n })) {\n return atomState;\n }\n }\n const nextDependencies = /* @__PURE__ */ new Map();\n let isSync = true;\n const getter = (a) => {\n if (a === atom) {\n const aState2 = getAtomState(a);\n if (aState2) {\n nextDependencies.set(a, aState2);\n return returnAtomValue(aState2);\n }\n if (hasInitialValue(a)) {\n nextDependencies.set(a, void 0);\n return a.init;\n }\n throw new Error(\"no atom init\");\n }\n const aState = readAtomState(a);\n nextDependencies.set(a, aState);\n return returnAtomValue(aState);\n };\n let controller;\n let setSelf;\n const options = {\n get signal() {\n if (!controller) {\n controller = new AbortController();\n }\n return controller.signal;\n },\n get setSelf() {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && !isActuallyWritableAtom(atom)) {\n console.warn(\"setSelf function cannot be used with read-only atom\");\n }\n if (!setSelf && isActuallyWritableAtom(atom)) {\n setSelf = (...args) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && isSync) {\n console.warn(\"setSelf function cannot be called in sync\");\n }\n if (!isSync) {\n return writeAtom(atom, ...args);\n }\n };\n }\n return setSelf;\n }\n };\n try {\n const valueOrPromise = atom.read(getter, options);\n return setAtomValueOrPromise(\n atom,\n valueOrPromise,\n nextDependencies,\n () => controller == null ? void 0 : controller.abort()\n );\n } catch (error) {\n return setAtomError(atom, error, nextDependencies);\n } finally {\n isSync = false;\n }\n };\n const readAtom = (atom) => returnAtomValue(readAtomState(atom));\n const addAtom = (atom) => {\n let mounted = mountedMap.get(atom);\n if (!mounted) {\n mounted = mountAtom(atom);\n }\n return mounted;\n };\n const canUnmountAtom = (atom, mounted) => !mounted.l.size && (!mounted.t.size || mounted.t.size === 1 && mounted.t.has(atom));\n const delAtom = (atom) => {\n const mounted = mountedMap.get(atom);\n if (mounted && canUnmountAtom(atom, mounted)) {\n unmountAtom(atom);\n }\n };\n const recomputeDependents = (atom) => {\n const dependencyMap = /* @__PURE__ */ new Map();\n const dirtyMap = /* @__PURE__ */ new WeakMap();\n const getDependents = (a) => {\n var _a;\n const dependents = new Set((_a = mountedMap.get(a)) == null ? void 0 : _a.t);\n pendingMap.forEach((_, pendingAtom) => {\n var _a2;\n if ((_a2 = getAtomState(pendingAtom)) == null ? void 0 : _a2.d.has(a)) {\n dependents.add(pendingAtom);\n }\n });\n return dependents;\n };\n const loop1 = (a) => {\n getDependents(a).forEach((dependent) => {\n if (dependent !== a) {\n dependencyMap.set(\n dependent,\n (dependencyMap.get(dependent) || /* @__PURE__ */ new Set()).add(a)\n );\n dirtyMap.set(dependent, (dirtyMap.get(dependent) || 0) + 1);\n loop1(dependent);\n }\n });\n };\n loop1(atom);\n const loop2 = (a) => {\n getDependents(a).forEach((dependent) => {\n var _a;\n if (dependent !== a) {\n let dirtyCount = dirtyMap.get(dependent);\n if (dirtyCount) {\n dirtyMap.set(dependent, --dirtyCount);\n }\n if (!dirtyCount) {\n let isChanged = !!((_a = dependencyMap.get(dependent)) == null ? void 0 : _a.size);\n if (isChanged) {\n const prevAtomState = getAtomState(dependent);\n const nextAtomState = readAtomState(dependent, true);\n isChanged = !isEqualAtomValue(prevAtomState, nextAtomState);\n }\n if (!isChanged) {\n dependencyMap.forEach((s) => s.delete(dependent));\n }\n }\n loop2(dependent);\n }\n });\n };\n loop2(atom);\n };\n const writeAtomState = (atom, ...args) => {\n let isSync = true;\n const getter = (a) => returnAtomValue(readAtomState(a));\n const setter = (a, ...args2) => {\n let r;\n if (a === atom) {\n if (!hasInitialValue(a)) {\n throw new Error(\"atom not writable\");\n }\n const prevAtomState = getAtomState(a);\n const nextAtomState = setAtomValueOrPromise(a, args2[0]);\n if (!isEqualAtomValue(prevAtomState, nextAtomState)) {\n recomputeDependents(a);\n }\n } else {\n r = writeAtomState(a, ...args2);\n }\n if (!isSync) {\n const flushed = flushPending();\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n storeListenersRev2.forEach(\n (l) => l({ type: \"async-write\", flushed })\n );\n }\n }\n return r;\n };\n const result = atom.write(getter, setter, ...args);\n isSync = false;\n return result;\n };\n const writeAtom = (atom, ...args) => {\n const result = writeAtomState(atom, ...args);\n const flushed = flushPending();\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n storeListenersRev2.forEach(\n (l) => l({ type: \"write\", flushed })\n );\n }\n return result;\n };\n const mountAtom = (atom, initialDependent, onMountQueue) => {\n var _a;\n const queue = onMountQueue || [];\n (_a = getAtomState(atom)) == null ? void 0 : _a.d.forEach((_, a) => {\n const aMounted = mountedMap.get(a);\n if (aMounted) {\n aMounted.t.add(atom);\n } else {\n if (a !== atom) {\n mountAtom(a, atom, queue);\n }\n }\n });\n readAtomState(atom);\n const mounted = {\n t: new Set(initialDependent && [initialDependent]),\n l: /* @__PURE__ */ new Set()\n };\n mountedMap.set(atom, mounted);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n mountedAtoms.add(atom);\n }\n if (isActuallyWritableAtom(atom) && atom.onMount) {\n const { onMount } = atom;\n queue.push(() => {\n const onUnmount = onMount((...args) => writeAtom(atom, ...args));\n if (onUnmount) {\n mounted.u = onUnmount;\n }\n });\n }\n if (!onMountQueue) {\n queue.forEach((f) => f());\n }\n return mounted;\n };\n const unmountAtom = (atom) => {\n var _a;\n const onUnmount = (_a = mountedMap.get(atom)) == null ? void 0 : _a.u;\n if (onUnmount) {\n onUnmount();\n }\n mountedMap.delete(atom);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n mountedAtoms.delete(atom);\n }\n const atomState = getAtomState(atom);\n if (atomState) {\n if (hasPromiseAtomValue(atomState)) {\n cancelPromise(atomState.v);\n }\n atomState.d.forEach((_, a) => {\n if (a !== atom) {\n const mounted = mountedMap.get(a);\n if (mounted) {\n mounted.t.delete(atom);\n if (canUnmountAtom(a, mounted)) {\n unmountAtom(a);\n }\n }\n }\n });\n } else if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n console.warn(\"[Bug] could not find atom state to unmount\", atom);\n }\n };\n const mountDependencies = (atom, atomState, prevDependencies) => {\n const depSet = new Set(atomState.d.keys());\n const maybeUnmountAtomSet = /* @__PURE__ */ new Set();\n prevDependencies == null ? void 0 : prevDependencies.forEach((_, a) => {\n if (depSet.has(a)) {\n depSet.delete(a);\n return;\n }\n maybeUnmountAtomSet.add(a);\n const mounted = mountedMap.get(a);\n if (mounted) {\n mounted.t.delete(atom);\n }\n });\n depSet.forEach((a) => {\n const mounted = mountedMap.get(a);\n if (mounted) {\n mounted.t.add(atom);\n } else if (mountedMap.has(atom)) {\n mountAtom(a, atom);\n }\n });\n maybeUnmountAtomSet.forEach((a) => {\n const mounted = mountedMap.get(a);\n if (mounted && canUnmountAtom(a, mounted)) {\n unmountAtom(a);\n }\n });\n };\n const flushPending = () => {\n let flushed;\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n flushed = /* @__PURE__ */ new Set();\n }\n while (pendingMap.size) {\n const pending = Array.from(pendingMap);\n pendingMap.clear();\n pending.forEach(([atom, prevAtomState]) => {\n const atomState = getAtomState(atom);\n if (atomState) {\n const mounted = mountedMap.get(atom);\n if (mounted && atomState.d !== (prevAtomState == null ? void 0 : prevAtomState.d)) {\n mountDependencies(atom, atomState, prevAtomState == null ? void 0 : prevAtomState.d);\n }\n if (mounted && !// TODO This seems pretty hacky. Hope to fix it.\n // Maybe we could `mountDependencies` in `setAtomState`?\n (!hasPromiseAtomValue(prevAtomState) && (isEqualAtomValue(prevAtomState, atomState) || isEqualAtomError(prevAtomState, atomState)))) {\n mounted.l.forEach((listener) => listener());\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n flushed.add(atom);\n }\n }\n } else if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n console.warn(\"[Bug] no atom state to flush\");\n }\n });\n }\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n return flushed;\n }\n };\n const subscribeAtom = (atom, listener) => {\n const mounted = addAtom(atom);\n const flushed = flushPending();\n const listeners = mounted.l;\n listeners.add(listener);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n storeListenersRev2.forEach(\n (l) => l({ type: \"sub\", flushed })\n );\n }\n return () => {\n listeners.delete(listener);\n delAtom(atom);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n storeListenersRev2.forEach((l) => l({ type: \"unsub\" }));\n }\n };\n };\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n return {\n get: readAtom,\n set: writeAtom,\n sub: subscribeAtom,\n // store dev methods (these are tentative and subject to change without notice)\n dev_subscribe_store: (l, rev) => {\n if (rev !== 2) {\n throw new Error(\"The current StoreListener revision is 2.\");\n }\n storeListenersRev2.add(l);\n return () => {\n storeListenersRev2.delete(l);\n };\n },\n dev_get_mounted_atoms: () => mountedAtoms.values(),\n dev_get_atom_state: (a) => atomStateMap.get(a),\n dev_get_mounted: (a) => mountedMap.get(a),\n dev_restore_atoms: (values) => {\n for (const [atom, valueOrPromise] of values) {\n if (hasInitialValue(atom)) {\n setAtomValueOrPromise(atom, valueOrPromise);\n recomputeDependents(atom);\n }\n }\n const flushed = flushPending();\n storeListenersRev2.forEach(\n (l) => l({ type: \"restore\", flushed })\n );\n }\n };\n }\n return {\n get: readAtom,\n set: writeAtom,\n sub: subscribeAtom\n };\n};\nlet defaultStore;\nif ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n if (typeof globalThis.__NUMBER_OF_JOTAI_INSTANCES__ === \"number\") {\n ++globalThis.__NUMBER_OF_JOTAI_INSTANCES__;\n } else {\n globalThis.__NUMBER_OF_JOTAI_INSTANCES__ = 1;\n }\n}\nconst getDefaultStore = () => {\n if (!defaultStore) {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && globalThis.__NUMBER_OF_JOTAI_INSTANCES__ !== 1) {\n console.warn(\n \"Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044\"\n );\n }\n defaultStore = createStore();\n }\n return defaultStore;\n};\n\nexport { atom, createStore, getDefaultStore };\n","'use client';\nimport ReactExports, { createContext, useContext, useRef, createElement, useReducer, useEffect, useDebugValue, useCallback } from 'react';\nimport { getDefaultStore, createStore } from 'jotai/vanilla';\n\nconst StoreContext = createContext(void 0);\nconst useStore = (options) => {\n const store = useContext(StoreContext);\n return (options == null ? void 0 : options.store) || store || getDefaultStore();\n};\nconst Provider = ({\n children,\n store\n}) => {\n const storeRef = useRef();\n if (!store && !storeRef.current) {\n storeRef.current = createStore();\n }\n return createElement(\n StoreContext.Provider,\n {\n value: store || storeRef.current\n },\n children\n );\n};\n\nconst isPromiseLike = (x) => typeof (x == null ? void 0 : x.then) === \"function\";\nconst use = ReactExports.use || ((promise) => {\n if (promise.status === \"pending\") {\n throw promise;\n } else if (promise.status === \"fulfilled\") {\n return promise.value;\n } else if (promise.status === \"rejected\") {\n throw promise.reason;\n } else {\n promise.status = \"pending\";\n promise.then(\n (v) => {\n promise.status = \"fulfilled\";\n promise.value = v;\n },\n (e) => {\n promise.status = \"rejected\";\n promise.reason = e;\n }\n );\n throw promise;\n }\n});\nfunction useAtomValue(atom, options) {\n const store = useStore(options);\n const [[valueFromReducer, storeFromReducer, atomFromReducer], rerender] = useReducer(\n (prev) => {\n const nextValue = store.get(atom);\n if (Object.is(prev[0], nextValue) && prev[1] === store && prev[2] === atom) {\n return prev;\n }\n return [nextValue, store, atom];\n },\n void 0,\n () => [store.get(atom), store, atom]\n );\n let value = valueFromReducer;\n if (storeFromReducer !== store || atomFromReducer !== atom) {\n rerender();\n value = store.get(atom);\n }\n const delay = options == null ? void 0 : options.delay;\n useEffect(() => {\n const unsub = store.sub(atom, () => {\n if (typeof delay === \"number\") {\n setTimeout(rerender, delay);\n return;\n }\n rerender();\n });\n rerender();\n return unsub;\n }, [store, atom, delay]);\n useDebugValue(value);\n return isPromiseLike(value) ? use(value) : value;\n}\n\nfunction useSetAtom(atom, options) {\n const store = useStore(options);\n const setAtom = useCallback(\n (...args) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && !(\"write\" in atom)) {\n throw new Error(\"not writable atom\");\n }\n return store.set(atom, ...args);\n },\n [store, atom]\n );\n return setAtom;\n}\n\nfunction useAtom(atom, options) {\n return [\n useAtomValue(atom, options),\n // We do wrong type assertion here, which results in throwing an error.\n useSetAtom(atom, options)\n ];\n}\n\nexport { Provider, useAtom, useAtomValue, useSetAtom, useStore };\n","import { atom } from 'jotai/vanilla';\n\nconst RESET = Symbol(\n (import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" ? \"RESET\" : \"\"\n);\n\nfunction atomWithReset(initialValue) {\n const anAtom = atom(\n initialValue,\n (get, set, update) => {\n const nextValue = typeof update === \"function\" ? update(get(anAtom)) : update;\n set(anAtom, nextValue === RESET ? initialValue : nextValue);\n }\n );\n return anAtom;\n}\n\nfunction atomWithReducer(initialValue, reducer) {\n const anAtom = atom(\n initialValue,\n (get, set, action) => set(anAtom, reducer(get(anAtom), action))\n );\n return anAtom;\n}\n\nfunction atomFamily(initializeAtom, areEqual) {\n let shouldRemove = null;\n const atoms = /* @__PURE__ */ new Map();\n const createAtom = (param) => {\n let item;\n if (areEqual === void 0) {\n item = atoms.get(param);\n } else {\n for (const [key, value] of atoms) {\n if (areEqual(key, param)) {\n item = value;\n break;\n }\n }\n }\n if (item !== void 0) {\n if (shouldRemove == null ? void 0 : shouldRemove(item[1], param)) {\n createAtom.remove(param);\n } else {\n return item[0];\n }\n }\n const newAtom = initializeAtom(param);\n atoms.set(param, [newAtom, Date.now()]);\n return newAtom;\n };\n createAtom.remove = (param) => {\n if (areEqual === void 0) {\n atoms.delete(param);\n } else {\n for (const [key] of atoms) {\n if (areEqual(key, param)) {\n atoms.delete(key);\n break;\n }\n }\n }\n };\n createAtom.setShouldRemove = (fn) => {\n shouldRemove = fn;\n if (!shouldRemove)\n return;\n for (const [key, value] of atoms) {\n if (shouldRemove(value[1], key)) {\n atoms.delete(key);\n }\n }\n };\n return createAtom;\n}\n\nconst getCached$2 = (c, m, k) => (m.has(k) ? m : m.set(k, c())).get(k);\nconst cache1$4 = /* @__PURE__ */ new WeakMap();\nconst memo3 = (create, dep1, dep2, dep3) => {\n const cache2 = getCached$2(() => /* @__PURE__ */ new WeakMap(), cache1$4, dep1);\n const cache3 = getCached$2(() => /* @__PURE__ */ new WeakMap(), cache2, dep2);\n return getCached$2(create, cache3, dep3);\n};\nfunction selectAtom(anAtom, selector, equalityFn = Object.is) {\n return memo3(\n () => {\n const EMPTY = Symbol();\n const selectValue = ([value, prevSlice]) => {\n if (prevSlice === EMPTY) {\n return selector(value);\n }\n const slice = selector(value, prevSlice);\n return equalityFn(prevSlice, slice) ? prevSlice : slice;\n };\n const derivedAtom = atom((get) => {\n const prev = get(derivedAtom);\n const value = get(anAtom);\n if (value instanceof Promise || prev instanceof Promise) {\n return Promise.all([value, prev]).then(selectValue);\n }\n return selectValue([value, prev]);\n });\n derivedAtom.init = EMPTY;\n return derivedAtom;\n },\n anAtom,\n selector,\n equalityFn\n );\n}\n\nconst cache1$3 = /* @__PURE__ */ new WeakMap();\nconst memo1$1 = (create, dep1) => (cache1$3.has(dep1) ? cache1$3 : cache1$3.set(dep1, create())).get(dep1);\nconst deepFreeze = (obj) => {\n if (typeof obj !== \"object\" || obj === null)\n return;\n Object.freeze(obj);\n const propNames = Object.getOwnPropertyNames(obj);\n for (const name of propNames) {\n const value = obj[name];\n deepFreeze(value);\n }\n return obj;\n};\nfunction freezeAtom(anAtom) {\n return memo1$1(() => {\n const frozenAtom = atom(\n (get) => deepFreeze(get(anAtom)),\n (_get, set, arg) => set(anAtom, arg)\n );\n return frozenAtom;\n }, anAtom);\n}\nfunction freezeAtomCreator(createAtom) {\n return (...params) => {\n const anAtom = createAtom(...params);\n const origRead = anAtom.read;\n anAtom.read = function(get, options) {\n return deepFreeze(origRead.call(this, get, options));\n };\n return anAtom;\n };\n}\n\nconst getCached$1 = (c, m, k) => (m.has(k) ? m : m.set(k, c())).get(k);\nconst cache1$2 = /* @__PURE__ */ new WeakMap();\nconst memo2$1 = (create, dep1, dep2) => {\n const cache2 = getCached$1(() => /* @__PURE__ */ new WeakMap(), cache1$2, dep1);\n return getCached$1(create, cache2, dep2);\n};\nconst cacheKeyForEmptyKeyExtractor = {};\nconst isWritable = (atom2) => !!atom2.write;\nconst isFunction = (x) => typeof x === \"function\";\nfunction splitAtom(arrAtom, keyExtractor) {\n return memo2$1(\n () => {\n const mappingCache = /* @__PURE__ */ new WeakMap();\n const getMapping = (arr, prev) => {\n let mapping = mappingCache.get(arr);\n if (mapping) {\n return mapping;\n }\n const prevMapping = prev && mappingCache.get(prev);\n const atomList = [];\n const keyList = [];\n arr.forEach((item, index) => {\n const key = keyExtractor ? keyExtractor(item) : index;\n keyList[index] = key;\n const cachedAtom = prevMapping && prevMapping.atomList[prevMapping.keyList.indexOf(key)];\n if (cachedAtom) {\n atomList[index] = cachedAtom;\n return;\n }\n const read = (get) => {\n const prev2 = get(mappingAtom);\n const currArr = get(arrAtom);\n const mapping2 = getMapping(currArr, prev2 == null ? void 0 : prev2.arr);\n const index2 = mapping2.keyList.indexOf(key);\n if (index2 < 0 || index2 >= currArr.length) {\n const prevItem = arr[getMapping(arr).keyList.indexOf(key)];\n if (prevItem) {\n return prevItem;\n }\n throw new Error(\"splitAtom: index out of bounds for read\");\n }\n return currArr[index2];\n };\n const write = (get, set, update) => {\n const prev2 = get(mappingAtom);\n const arr2 = get(arrAtom);\n const mapping2 = getMapping(arr2, prev2 == null ? void 0 : prev2.arr);\n const index2 = mapping2.keyList.indexOf(key);\n if (index2 < 0 || index2 >= arr2.length) {\n throw new Error(\"splitAtom: index out of bounds for write\");\n }\n const nextItem = isFunction(update) ? update(arr2[index2]) : update;\n if (!Object.is(arr2[index2], nextItem)) {\n set(arrAtom, [\n ...arr2.slice(0, index2),\n nextItem,\n ...arr2.slice(index2 + 1)\n ]);\n }\n };\n atomList[index] = isWritable(arrAtom) ? atom(read, write) : atom(read);\n });\n if (prevMapping && prevMapping.keyList.length === keyList.length && prevMapping.keyList.every((x, i) => x === keyList[i])) {\n mapping = prevMapping;\n } else {\n mapping = { arr, atomList, keyList };\n }\n mappingCache.set(arr, mapping);\n return mapping;\n };\n const mappingAtom = atom((get) => {\n const prev = get(mappingAtom);\n const arr = get(arrAtom);\n const mapping = getMapping(arr, prev == null ? void 0 : prev.arr);\n return mapping;\n });\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n mappingAtom.debugPrivate = true;\n }\n mappingAtom.init = void 0;\n const splittedAtom = isWritable(arrAtom) ? atom(\n (get) => get(mappingAtom).atomList,\n (get, set, action) => {\n switch (action.type) {\n case \"remove\": {\n const index = get(splittedAtom).indexOf(action.atom);\n if (index >= 0) {\n const arr = get(arrAtom);\n set(arrAtom, [\n ...arr.slice(0, index),\n ...arr.slice(index + 1)\n ]);\n }\n break;\n }\n case \"insert\": {\n const index = action.before ? get(splittedAtom).indexOf(action.before) : get(splittedAtom).length;\n if (index >= 0) {\n const arr = get(arrAtom);\n set(arrAtom, [\n ...arr.slice(0, index),\n action.value,\n ...arr.slice(index)\n ]);\n }\n break;\n }\n case \"move\": {\n const index1 = get(splittedAtom).indexOf(action.atom);\n const index2 = action.before ? get(splittedAtom).indexOf(action.before) : get(splittedAtom).length;\n if (index1 >= 0 && index2 >= 0) {\n const arr = get(arrAtom);\n if (index1 < index2) {\n set(arrAtom, [\n ...arr.slice(0, index1),\n ...arr.slice(index1 + 1, index2),\n arr[index1],\n ...arr.slice(index2)\n ]);\n } else {\n set(arrAtom, [\n ...arr.slice(0, index2),\n arr[index1],\n ...arr.slice(index2, index1),\n ...arr.slice(index1 + 1)\n ]);\n }\n }\n break;\n }\n }\n }\n ) : atom((get) => get(mappingAtom).atomList);\n return splittedAtom;\n },\n arrAtom,\n keyExtractor || cacheKeyForEmptyKeyExtractor\n );\n}\n\nfunction atomWithDefault(getDefault) {\n const EMPTY = Symbol();\n const overwrittenAtom = atom(EMPTY);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n overwrittenAtom.debugPrivate = true;\n }\n const anAtom = atom(\n (get, options) => {\n const overwritten = get(overwrittenAtom);\n if (overwritten !== EMPTY) {\n return overwritten;\n }\n return getDefault(get, options);\n },\n (get, set, update) => {\n if (update === RESET) {\n set(overwrittenAtom, EMPTY);\n } else if (typeof update === \"function\") {\n const prevValue = get(anAtom);\n set(overwrittenAtom, update(prevValue));\n } else {\n set(overwrittenAtom, update);\n }\n }\n );\n return anAtom;\n}\n\nconst isPromiseLike = (x) => typeof (x == null ? void 0 : x.then) === \"function\";\nfunction withStorageValidator(validator) {\n return (unknownStorage) => {\n const storage = {\n ...unknownStorage,\n getItem: (key, initialValue) => {\n const validate = (value2) => {\n if (!validator(value2)) {\n return initialValue;\n }\n return value2;\n };\n const value = unknownStorage.getItem(key, initialValue);\n if (isPromiseLike(value)) {\n return value.then(validate);\n }\n return validate(value);\n }\n };\n return storage;\n };\n}\nfunction createJSONStorage(getStringStorage = () => typeof window !== \"undefined\" ? window.localStorage : void 0, options) {\n let lastStr;\n let lastValue;\n const storage = {\n getItem: (key, initialValue) => {\n var _a, _b;\n const parse = (str2) => {\n str2 = str2 || \"\";\n if (lastStr !== str2) {\n try {\n lastValue = JSON.parse(str2, options == null ? void 0 : options.reviver);\n } catch {\n return initialValue;\n }\n lastStr = str2;\n }\n return lastValue;\n };\n const str = (_b = (_a = getStringStorage()) == null ? void 0 : _a.getItem(key)) != null ? _b : null;\n if (isPromiseLike(str)) {\n return str.then(parse);\n }\n return parse(str);\n },\n setItem: (key, newValue) => {\n var _a;\n return (_a = getStringStorage()) == null ? void 0 : _a.setItem(\n key,\n JSON.stringify(newValue, options == null ? void 0 : options.replacer)\n );\n },\n removeItem: (key) => {\n var _a;\n return (_a = getStringStorage()) == null ? void 0 : _a.removeItem(key);\n }\n };\n if (typeof window !== \"undefined\" && typeof window.addEventListener === \"function\" && window.Storage) {\n storage.subscribe = (key, callback, initialValue) => {\n if (!(getStringStorage() instanceof window.Storage)) {\n return () => {\n };\n }\n const storageEventCallback = (e) => {\n if (e.storageArea === getStringStorage() && e.key === key) {\n let newValue;\n try {\n newValue = JSON.parse(e.newValue || \"\");\n } catch {\n newValue = initialValue;\n }\n callback(newValue);\n }\n };\n window.addEventListener(\"storage\", storageEventCallback);\n return () => {\n window.removeEventListener(\"storage\", storageEventCallback);\n };\n };\n }\n return storage;\n}\nconst defaultStorage = createJSONStorage();\nfunction atomWithStorage(key, initialValue, storage = defaultStorage, options) {\n const getOnInit = options == null ? void 0 : options.getOnInit;\n const baseAtom = atom(\n getOnInit ? storage.getItem(key, initialValue) : initialValue\n );\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n baseAtom.debugPrivate = true;\n }\n baseAtom.onMount = (setAtom) => {\n if (!getOnInit) {\n setAtom(storage.getItem(key, initialValue));\n }\n let unsub;\n if (storage.subscribe) {\n unsub = storage.subscribe(key, setAtom, initialValue);\n }\n return unsub;\n };\n const anAtom = atom(\n (get) => get(baseAtom),\n (get, set, update) => {\n const nextValue = typeof update === \"function\" ? update(get(baseAtom)) : update;\n if (nextValue === RESET) {\n set(baseAtom, initialValue);\n return storage.removeItem(key);\n }\n if (nextValue instanceof Promise) {\n return nextValue.then((resolvedValue) => {\n set(baseAtom, resolvedValue);\n return storage.setItem(key, resolvedValue);\n });\n }\n set(baseAtom, nextValue);\n return storage.setItem(key, nextValue);\n }\n );\n return anAtom;\n}\n\nfunction atomWithObservable(getObservable, options) {\n const returnResultData = (result) => {\n if (\"e\" in result) {\n throw result.e;\n }\n return result.d;\n };\n const observableResultAtom = atom((get) => {\n var _a;\n let observable = getObservable(get);\n const itself = (_a = observable[Symbol.observable]) == null ? void 0 : _a.call(observable);\n if (itself) {\n observable = itself;\n }\n let resolve;\n const makePending = () => new Promise((r) => {\n resolve = r;\n });\n const initialResult = options && \"initialValue\" in options ? {\n d: typeof options.initialValue === \"function\" ? options.initialValue() : options.initialValue\n } : makePending();\n let setResult;\n let lastResult;\n const listener = (result) => {\n lastResult = result;\n resolve == null ? void 0 : resolve(result);\n setResult == null ? void 0 : setResult(result);\n };\n let subscription;\n let timer;\n const isNotMounted = () => !setResult;\n const start = () => {\n if (subscription) {\n clearTimeout(timer);\n subscription.unsubscribe();\n }\n subscription = observable.subscribe({\n next: (d) => listener({ d }),\n error: (e) => listener({ e }),\n complete: () => {\n }\n });\n if (isNotMounted() && (options == null ? void 0 : options.unstable_timeout)) {\n timer = setTimeout(() => {\n if (subscription) {\n subscription.unsubscribe();\n subscription = void 0;\n }\n }, options.unstable_timeout);\n }\n };\n start();\n const resultAtom = atom(lastResult || initialResult);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n resultAtom.debugPrivate = true;\n }\n resultAtom.onMount = (update) => {\n setResult = update;\n if (lastResult) {\n update(lastResult);\n }\n if (subscription) {\n clearTimeout(timer);\n } else {\n start();\n }\n return () => {\n setResult = void 0;\n if (subscription) {\n subscription.unsubscribe();\n subscription = void 0;\n }\n };\n };\n return [resultAtom, observable, makePending, start, isNotMounted];\n });\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n observableResultAtom.debugPrivate = true;\n }\n const observableAtom = atom(\n (get) => {\n const [resultAtom] = get(observableResultAtom);\n const result = get(resultAtom);\n if (result instanceof Promise) {\n return result.then(returnResultData);\n }\n return returnResultData(result);\n },\n (get, set, data) => {\n const [resultAtom, observable, makePending, start, isNotMounted] = get(observableResultAtom);\n if (\"next\" in observable) {\n if (isNotMounted()) {\n set(resultAtom, makePending());\n start();\n }\n observable.next(data);\n } else {\n throw new Error(\"observable is not subject\");\n }\n }\n );\n return observableAtom;\n}\n\nconst cache1$1 = /* @__PURE__ */ new WeakMap();\nconst memo1 = (create, dep1) => (cache1$1.has(dep1) ? cache1$1 : cache1$1.set(dep1, create())).get(dep1);\nconst LOADING = { state: \"loading\" };\nfunction loadable(anAtom) {\n return memo1(() => {\n const loadableCache = /* @__PURE__ */ new WeakMap();\n const refreshAtom = atom(0);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n refreshAtom.debugPrivate = true;\n }\n const derivedAtom = atom(\n (get, { setSelf }) => {\n get(refreshAtom);\n let value;\n try {\n value = get(anAtom);\n } catch (error) {\n return { state: \"hasError\", error };\n }\n if (!(value instanceof Promise)) {\n return { state: \"hasData\", data: value };\n }\n const promise = value;\n const cached = loadableCache.get(promise);\n if (cached) {\n return cached;\n }\n loadableCache.set(promise, LOADING);\n promise.then(\n (data) => {\n loadableCache.set(promise, { state: \"hasData\", data });\n },\n (error) => {\n loadableCache.set(promise, { state: \"hasError\", error });\n }\n ).finally(setSelf);\n return LOADING;\n },\n (_get, set) => {\n set(refreshAtom, (c) => c + 1);\n }\n );\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n derivedAtom.debugPrivate = true;\n }\n return atom((get) => get(derivedAtom));\n }, anAtom);\n}\n\nconst getCached = (c, m, k) => (m.has(k) ? m : m.set(k, c())).get(k);\nconst cache1 = /* @__PURE__ */ new WeakMap();\nconst memo2 = (create, dep1, dep2) => {\n const cache2 = getCached(() => /* @__PURE__ */ new WeakMap(), cache1, dep1);\n return getCached(create, cache2, dep2);\n};\nconst defaultFallback = () => void 0;\nfunction unwrap(anAtom, fallback = defaultFallback) {\n return memo2(\n () => {\n const promiseErrorCache = /* @__PURE__ */ new WeakMap();\n const promiseResultCache = /* @__PURE__ */ new WeakMap();\n const refreshAtom = atom(0);\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n refreshAtom.debugPrivate = true;\n }\n const promiseAndValueAtom = atom(\n (get, { setSelf }) => {\n get(refreshAtom);\n const prev = get(promiseAndValueAtom);\n const promise = get(anAtom);\n if (!(promise instanceof Promise)) {\n return { v: promise };\n }\n if (promise === (prev == null ? void 0 : prev.p)) {\n if (promiseErrorCache.has(promise)) {\n throw promiseErrorCache.get(promise);\n }\n if (promiseResultCache.has(promise)) {\n return {\n p: promise,\n v: promiseResultCache.get(promise)\n };\n }\n }\n if (promise !== (prev == null ? void 0 : prev.p)) {\n promise.then(\n (v) => promiseResultCache.set(promise, v),\n (e) => promiseErrorCache.set(promise, e)\n ).finally(setSelf);\n }\n if (prev && \"v\" in prev) {\n return { p: promise, f: fallback(prev.v), v: prev.v };\n }\n return { p: promise, f: fallback() };\n },\n (_get, set) => {\n set(refreshAtom, (c) => c + 1);\n }\n );\n promiseAndValueAtom.init = void 0;\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") {\n promiseAndValueAtom.debugPrivate = true;\n }\n return atom(\n (get) => {\n const state = get(promiseAndValueAtom);\n if (\"f\" in state) {\n return state.f;\n }\n return state.v;\n },\n (_get, set, ...args) => set(anAtom, ...args)\n );\n },\n anAtom,\n fallback\n );\n}\n\nexport { RESET, atomFamily, atomWithDefault, atomWithObservable, atomWithReducer, atomWithReset, atomWithStorage, createJSONStorage, freezeAtom, freezeAtomCreator, loadable, selectAtom, splitAtom, withStorageValidator as unstable_withStorageValidator, unwrap };\n","import { useMemo, useEffect, useState } from 'react'\nimport { dequal } from 'dequal'\nimport { atom, useAtom, useAtomValue, useSetAtom } from 'jotai'\nimport { atomFamily } from 'jotai/utils'\nimport type {\n PageLoaded,\n UseStaticData,\n Theme,\n UseAllPagesOutlines,\n} from '../../clientTypes'\n\nexport let useTheme: () => Theme\nexport let usePagePaths: () => string[]\nexport let usePageModule: (path: string) => Promise<PageModule> | undefined\nexport let useStaticData: UseStaticData\nexport let useAllPagesOutlines: UseAllPagesOutlines\n\ninterface PageModule {\n ['default']: PageLoaded\n}\ntype SetAtom<Args extends any[], Result> = (...args: Args) => Result\n\nimport initialPages from '/@react-pages/pages'\nimport initialTheme from '/@react-pages/theme'\n\n// TODO: simplify this\n// there is no easy way to handle the hmr of module such as `/@react-pages/pages/page1` so stop trying it\n// https://github.com/vitejs/vite-plugin-react-pages/pull/19#discussion_r604251258\n\nconst initialPagePaths = Object.keys(initialPages)\n\n// This HMR code assumes that our Jotai atoms are always managed\n// by the same Provider. It also mutates during render, which is\n// generally discouraged, but in this case it's okay.\nif (import.meta.hot) {\n let setTheme: SetAtom<[{ Theme: Theme }], void> | undefined\n import.meta.hot!.accept('/@react-pages/theme', (module) => {\n // console.log('@@hot update /@react-pages/theme', module)\n if (!module) {\n console.error('unexpected hot module', module)\n return\n }\n setTheme?.({ Theme: module.default })\n })\n\n const themeAtom = atom({ Theme: initialTheme })\n useTheme = () => {\n const [{ Theme }, set] = useAtom(themeAtom)\n setTheme = set\n return Theme\n }\n\n let setPages: SetAtom<any, void> | undefined\n import.meta.hot!.accept('/@react-pages/pages', (module) => {\n // console.log('@@hot update /@react-pages/pages', module)\n if (!module) {\n console.error('unexpected hot module', module)\n return\n }\n setPages?.(module.default)\n })\n\n // let setAllPagesOutlines: SetAtom<any, void> | undefined\n // import.meta.hot!.accept('/@react-pages/allPagesOutlines', (module) => {\n // // console.log('@@hot update /@react-pages/allPagesOutlines', module)\n // if (!module) {\n // console.error('unexpected hot module', module)\n // return\n // }\n // setAllPagesOutlines?.(module)\n // })\n\n const pagesAtom = atom(initialPages)\n const pagePathsAtom = atom(initialPagePaths.sort())\n const staticDataAtom = atom(toStaticData(initialPages))\n const allPagesOutlinesAtom = atom(initialPages)\n\n const setPagesAtom = atom(null, (get, set, newPages: any) => {\n let newStaticData: Record<string, any> | undefined\n\n const pages = get(pagesAtom)\n for (const path in newPages) {\n const newPage = newPages[path]\n const p