@rekayasa/erica-bubble 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["#setup","#cleanup","#focused","#providerCalled","#provider","#setup","#cleanup","#online","#gcTimeout","#abortSignalConsumed","#defaultOptions","#client","#cache","#initialState","getDefaultState","#retryer","#dispatch","#isInitialPausedFetch","#revertState","#client","#selectError","#currentThenable","#currentQuery","#executeFetch","#updateTimers","#clearStaleTimeout","#clearRefetchInterval","#updateQuery","#updateStaleTimeout","#computeRefetchInterval","#currentRefetchInterval","#updateRefetchInterval","#currentResult","#currentResultOptions","#currentResultState","#trackedProps","#staleTimeoutId","#refetchIntervalId","#currentQueryInitialState","#lastQueryWithDefinedData","#selectFn","#selectResult","#notify","#client","#mutationCache","#observers","#retryer","#dispatch","#mutations","#scopes","#mutationId","#queries","#queryCache","#mutationCache","#defaultOptions","#queryDefaults","#mutationDefaults","#mountCount","#unsubscribeFocus","#unsubscribeOnline","__iconNode","__iconNode","__iconNode","__iconNode"],"sources":["../node_modules/@tanstack/query-core/build/modern/subscribable.js","../node_modules/@tanstack/query-core/build/modern/focusManager.js","../node_modules/@tanstack/query-core/build/modern/timeoutManager.js","../node_modules/@tanstack/query-core/build/modern/utils.js","../node_modules/@tanstack/query-core/build/modern/environmentManager.js","../node_modules/@tanstack/query-core/build/modern/thenable.js","../node_modules/@tanstack/query-core/build/modern/notifyManager.js","../node_modules/@tanstack/query-core/build/modern/onlineManager.js","../node_modules/@tanstack/query-core/build/modern/retryer.js","../node_modules/@tanstack/query-core/build/modern/removable.js","../node_modules/@tanstack/query-core/build/modern/query.js","../node_modules/@tanstack/query-core/build/modern/queryObserver.js","../node_modules/@tanstack/query-core/build/modern/infiniteQueryBehavior.js","../node_modules/@tanstack/query-core/build/modern/mutation.js","../node_modules/@tanstack/query-core/build/modern/mutationCache.js","../node_modules/@tanstack/query-core/build/modern/queryCache.js","../node_modules/@tanstack/query-core/build/modern/queryClient.js","../node_modules/@tanstack/react-query/build/modern/QueryClientProvider.js","../node_modules/@tanstack/react-query/build/modern/IsRestoringProvider.js","../node_modules/@tanstack/react-query/build/modern/QueryErrorResetBoundary.js","../node_modules/@tanstack/react-query/build/modern/errorBoundaryUtils.js","../node_modules/@tanstack/react-query/build/modern/suspense.js","../node_modules/@tanstack/react-query/build/modern/useBaseQuery.js","../node_modules/@tanstack/react-query/build/modern/useQuery.js","../node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.js","../node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.js","../node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.js","../node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.js","../node_modules/lucide-react/dist/esm/defaultAttributes.js","../node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.js","../node_modules/lucide-react/dist/esm/context.js","../node_modules/lucide-react/dist/esm/Icon.js","../node_modules/lucide-react/dist/esm/createLucideIcon.js","../node_modules/lucide-react/dist/esm/icons/chevron-down.js","../node_modules/lucide-react/dist/esm/icons/download.js","../node_modules/lucide-react/dist/esm/icons/paperclip.js","../node_modules/lucide-react/dist/esm/icons/square-pen.js","../node_modules/lucide-react/dist/esm/icons/x.js","../src/shared/api/v1/core/bodySerializer.gen.ts","../src/shared/api/v1/core/params.gen.ts","../src/shared/api/v1/core/serverSentEvents.gen.ts","../src/shared/api/v1/core/pathSerializer.gen.ts","../src/shared/api/v1/core/utils.gen.ts","../src/shared/api/v1/core/auth.gen.ts","../src/shared/api/v1/client/utils.gen.ts","../src/shared/api/v1/client/client.gen.ts","../src/shared/api/v1/client.gen.ts","../src/shared/api/setup.ts","../src/shared/api/v1/sdk.gen.ts","../src/lib/attachment-api.ts","../src/components/EricaChatInput.tsx","../src/lib/thread-api.ts","../src/hooks/use-threads.ts","../src/components/EricaChatHeader.tsx","../src/components/EricaChat.tsx"],"sourcesContent":["// src/subscribable.ts\nvar Subscribable = class {\n constructor() {\n this.listeners = /* @__PURE__ */ new Set();\n this.subscribe = this.subscribe.bind(this);\n }\n subscribe(listener) {\n this.listeners.add(listener);\n this.onSubscribe();\n return () => {\n this.listeners.delete(listener);\n this.onUnsubscribe();\n };\n }\n hasListeners() {\n return this.listeners.size > 0;\n }\n onSubscribe() {\n }\n onUnsubscribe() {\n }\n};\nexport {\n Subscribable\n};\n//# sourceMappingURL=subscribable.js.map","// src/focusManager.ts\nimport { Subscribable } from \"./subscribable.js\";\nvar FocusManager = class extends Subscribable {\n #focused;\n #cleanup;\n #setup;\n constructor() {\n super();\n this.#setup = (onFocus) => {\n if (typeof window !== \"undefined\" && window.addEventListener) {\n const listener = () => onFocus();\n window.addEventListener(\"visibilitychange\", listener, false);\n return () => {\n window.removeEventListener(\"visibilitychange\", listener);\n };\n }\n return;\n };\n }\n onSubscribe() {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup);\n }\n }\n onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.();\n this.#cleanup = void 0;\n }\n }\n setEventListener(setup) {\n this.#setup = setup;\n this.#cleanup?.();\n this.#cleanup = setup((focused) => {\n if (typeof focused === \"boolean\") {\n this.setFocused(focused);\n } else {\n this.onFocus();\n }\n });\n }\n setFocused(focused) {\n const changed = this.#focused !== focused;\n if (changed) {\n this.#focused = focused;\n this.onFocus();\n }\n }\n onFocus() {\n const isFocused = this.isFocused();\n this.listeners.forEach((listener) => {\n listener(isFocused);\n });\n }\n isFocused() {\n if (typeof this.#focused === \"boolean\") {\n return this.#focused;\n }\n return globalThis.document?.visibilityState !== \"hidden\";\n }\n};\nvar focusManager = new FocusManager();\nexport {\n FocusManager,\n focusManager\n};\n//# sourceMappingURL=focusManager.js.map","// src/timeoutManager.ts\nvar defaultTimeoutProvider = {\n // We need the wrapper function syntax below instead of direct references to\n // global setTimeout etc.\n //\n // BAD: `setTimeout: setTimeout`\n // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`\n //\n // If we use direct references here, then anything that wants to spy on or\n // replace the global setTimeout (like tests) won't work since we'll already\n // have a hard reference to the original implementation at the time when this\n // file was imported.\n setTimeout: (callback, delay) => setTimeout(callback, delay),\n clearTimeout: (timeoutId) => clearTimeout(timeoutId),\n setInterval: (callback, delay) => setInterval(callback, delay),\n clearInterval: (intervalId) => clearInterval(intervalId)\n};\nvar TimeoutManager = class {\n // We cannot have TimeoutManager<T> as we must instantiate it with a concrete\n // type at app boot; and if we leave that type, then any new timer provider\n // would need to support the default provider's concrete timer ID, which is\n // infeasible across environments.\n //\n // We settle for type safety for the TimeoutProvider type, and accept that\n // this class is unsafe internally to allow for extension.\n #provider = defaultTimeoutProvider;\n #providerCalled = false;\n setTimeoutProvider(provider) {\n if (process.env.NODE_ENV !== \"production\") {\n if (this.#providerCalled && provider !== this.#provider) {\n console.error(\n `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,\n { previous: this.#provider, provider }\n );\n }\n }\n this.#provider = provider;\n if (process.env.NODE_ENV !== \"production\") {\n this.#providerCalled = false;\n }\n }\n setTimeout(callback, delay) {\n if (process.env.NODE_ENV !== \"production\") {\n this.#providerCalled = true;\n }\n return this.#provider.setTimeout(callback, delay);\n }\n clearTimeout(timeoutId) {\n this.#provider.clearTimeout(timeoutId);\n }\n setInterval(callback, delay) {\n if (process.env.NODE_ENV !== \"production\") {\n this.#providerCalled = true;\n }\n return this.#provider.setInterval(callback, delay);\n }\n clearInterval(intervalId) {\n this.#provider.clearInterval(intervalId);\n }\n};\nvar timeoutManager = new TimeoutManager();\nfunction systemSetTimeoutZero(callback) {\n setTimeout(callback, 0);\n}\nexport {\n TimeoutManager,\n defaultTimeoutProvider,\n systemSetTimeoutZero,\n timeoutManager\n};\n//# sourceMappingURL=timeoutManager.js.map","// src/utils.ts\nimport { timeoutManager } from \"./timeoutManager.js\";\nvar isServer = typeof window === \"undefined\" || \"Deno\" in globalThis;\nfunction noop() {\n}\nfunction functionalUpdate(updater, input) {\n return typeof updater === \"function\" ? updater(input) : updater;\n}\nfunction isValidTimeout(value) {\n return typeof value === \"number\" && value >= 0 && value !== Infinity;\n}\nfunction timeUntilStale(updatedAt, staleTime) {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);\n}\nfunction resolveStaleTime(staleTime, query) {\n return typeof staleTime === \"function\" ? staleTime(query) : staleTime;\n}\nfunction resolveEnabled(enabled, query) {\n return typeof enabled === \"function\" ? enabled(query) : enabled;\n}\nfunction matchQuery(filters, query) {\n const {\n type = \"all\",\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale\n } = filters;\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false;\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false;\n }\n }\n if (type !== \"all\") {\n const isActive = query.isActive();\n if (type === \"active\" && !isActive) {\n return false;\n }\n if (type === \"inactive\" && isActive) {\n return false;\n }\n }\n if (typeof stale === \"boolean\" && query.isStale() !== stale) {\n return false;\n }\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false;\n }\n if (predicate && !predicate(query)) {\n return false;\n }\n return true;\n}\nfunction matchMutation(filters, mutation) {\n const { exact, status, predicate, mutationKey } = filters;\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false;\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false;\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false;\n }\n }\n if (status && mutation.state.status !== status) {\n return false;\n }\n if (predicate && !predicate(mutation)) {\n return false;\n }\n return true;\n}\nfunction hashQueryKeyByOptions(queryKey, options) {\n const hashFn = options?.queryKeyHashFn || hashKey;\n return hashFn(queryKey);\n}\nfunction hashKey(queryKey) {\n return JSON.stringify(\n queryKey,\n (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {\n result[key] = val[key];\n return result;\n }, {}) : val\n );\n}\nfunction partialMatchKey(a, b) {\n if (a === b) {\n return true;\n }\n if (typeof a !== typeof b) {\n return false;\n }\n if (a && b && typeof a === \"object\" && typeof b === \"object\") {\n return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]));\n }\n return false;\n}\nvar hasOwn = Object.prototype.hasOwnProperty;\nfunction replaceEqualDeep(a, b, depth = 0) {\n if (a === b) {\n return a;\n }\n if (depth > 500) return b;\n const array = isPlainArray(a) && isPlainArray(b);\n if (!array && !(isPlainObject(a) && isPlainObject(b))) return b;\n const aItems = array ? a : Object.keys(a);\n const aSize = aItems.length;\n const bItems = array ? b : Object.keys(b);\n const bSize = bItems.length;\n const copy = array ? new Array(bSize) : {};\n let equalItems = 0;\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i];\n const aItem = a[key];\n const bItem = b[key];\n if (aItem === bItem) {\n copy[key] = aItem;\n if (array ? i < aSize : hasOwn.call(a, key)) equalItems++;\n continue;\n }\n if (aItem === null || bItem === null || typeof aItem !== \"object\" || typeof bItem !== \"object\") {\n copy[key] = bItem;\n continue;\n }\n const v = replaceEqualDeep(aItem, bItem, depth + 1);\n copy[key] = v;\n if (v === aItem) equalItems++;\n }\n return aSize === bSize && equalItems === aSize ? a : copy;\n}\nfunction shallowEqualObjects(a, b) {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false;\n }\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false;\n }\n }\n return true;\n}\nfunction isPlainArray(value) {\n return Array.isArray(value) && value.length === Object.keys(value).length;\n}\nfunction isPlainObject(o) {\n if (!hasObjectPrototype(o)) {\n return false;\n }\n const ctor = o.constructor;\n if (ctor === void 0) {\n return true;\n }\n const prot = ctor.prototype;\n if (!hasObjectPrototype(prot)) {\n return false;\n }\n if (!prot.hasOwnProperty(\"isPrototypeOf\")) {\n return false;\n }\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false;\n }\n return true;\n}\nfunction hasObjectPrototype(o) {\n return Object.prototype.toString.call(o) === \"[object Object]\";\n}\nfunction sleep(timeout) {\n return new Promise((resolve) => {\n timeoutManager.setTimeout(resolve, timeout);\n });\n}\nfunction replaceData(prevData, data, options) {\n if (typeof options.structuralSharing === \"function\") {\n return options.structuralSharing(prevData, data);\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== \"production\") {\n try {\n return replaceEqualDeep(prevData, data);\n } catch (error) {\n console.error(\n `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`\n );\n throw error;\n }\n }\n return replaceEqualDeep(prevData, data);\n }\n return data;\n}\nfunction keepPreviousData(previousData) {\n return previousData;\n}\nfunction addToEnd(items, item, max = 0) {\n const newItems = [...items, item];\n return max && newItems.length > max ? newItems.slice(1) : newItems;\n}\nfunction addToStart(items, item, max = 0) {\n const newItems = [item, ...items];\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems;\n}\nvar skipToken = /* @__PURE__ */ Symbol();\nfunction ensureQueryFn(options, fetchOptions) {\n if (process.env.NODE_ENV !== \"production\") {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`\n );\n }\n }\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise;\n }\n if (!options.queryFn || options.queryFn === skipToken) {\n return () => Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`));\n }\n return options.queryFn;\n}\nfunction shouldThrowError(throwOnError, params) {\n if (typeof throwOnError === \"function\") {\n return throwOnError(...params);\n }\n return !!throwOnError;\n}\nfunction addConsumeAwareSignal(object, getSignal, onCancelled) {\n let consumed = false;\n let signal;\n Object.defineProperty(object, \"signal\", {\n enumerable: true,\n get: () => {\n signal ??= getSignal();\n if (consumed) {\n return signal;\n }\n consumed = true;\n if (signal.aborted) {\n onCancelled();\n } else {\n signal.addEventListener(\"abort\", onCancelled, { once: true });\n }\n return signal;\n }\n });\n return object;\n}\nexport {\n addConsumeAwareSignal,\n addToEnd,\n addToStart,\n ensureQueryFn,\n functionalUpdate,\n hashKey,\n hashQueryKeyByOptions,\n isPlainArray,\n isPlainObject,\n isServer,\n isValidTimeout,\n keepPreviousData,\n matchMutation,\n matchQuery,\n noop,\n partialMatchKey,\n replaceData,\n replaceEqualDeep,\n resolveEnabled,\n resolveStaleTime,\n shallowEqualObjects,\n shouldThrowError,\n skipToken,\n sleep,\n timeUntilStale\n};\n//# sourceMappingURL=utils.js.map","// src/environmentManager.ts\nimport { isServer } from \"./utils.js\";\nvar environmentManager = /* @__PURE__ */ (() => {\n let isServerFn = () => isServer;\n return {\n /**\n * Returns whether the current runtime should be treated as a server environment.\n */\n isServer() {\n return isServerFn();\n },\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue) {\n isServerFn = isServerValue;\n }\n };\n})();\nexport {\n environmentManager\n};\n//# sourceMappingURL=environmentManager.js.map","// src/thenable.ts\nimport { noop } from \"./utils.js\";\nfunction pendingThenable() {\n let resolve;\n let reject;\n const thenable = new Promise((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n thenable.status = \"pending\";\n thenable.catch(() => {\n });\n function finalize(data) {\n Object.assign(thenable, data);\n delete thenable.resolve;\n delete thenable.reject;\n }\n thenable.resolve = (value) => {\n finalize({\n status: \"fulfilled\",\n value\n });\n resolve(value);\n };\n thenable.reject = (reason) => {\n finalize({\n status: \"rejected\",\n reason\n });\n reject(reason);\n };\n return thenable;\n}\nfunction tryResolveSync(promise) {\n let data;\n promise.then((result) => {\n data = result;\n return result;\n }, noop)?.catch(noop);\n if (data !== void 0) {\n return { data };\n }\n return void 0;\n}\nexport {\n pendingThenable,\n tryResolveSync\n};\n//# sourceMappingURL=thenable.js.map","// src/notifyManager.ts\nimport { systemSetTimeoutZero } from \"./timeoutManager.js\";\nvar defaultScheduler = systemSetTimeoutZero;\nfunction createNotifyManager() {\n let queue = [];\n let transactions = 0;\n let notifyFn = (callback) => {\n callback();\n };\n let batchNotifyFn = (callback) => {\n callback();\n };\n let scheduleFn = defaultScheduler;\n const schedule = (callback) => {\n if (transactions) {\n queue.push(callback);\n } else {\n scheduleFn(() => {\n notifyFn(callback);\n });\n }\n };\n const flush = () => {\n const originalQueue = queue;\n queue = [];\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback);\n });\n });\n });\n }\n };\n return {\n batch: (callback) => {\n let result;\n transactions++;\n try {\n result = callback();\n } finally {\n transactions--;\n if (!transactions) {\n flush();\n }\n }\n return result;\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: (callback) => {\n return (...args) => {\n schedule(() => {\n callback(...args);\n });\n };\n },\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn) => {\n notifyFn = fn;\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn) => {\n batchNotifyFn = fn;\n },\n setScheduler: (fn) => {\n scheduleFn = fn;\n }\n };\n}\nvar notifyManager = createNotifyManager();\nexport {\n createNotifyManager,\n defaultScheduler,\n notifyManager\n};\n//# sourceMappingURL=notifyManager.js.map","// src/onlineManager.ts\nimport { Subscribable } from \"./subscribable.js\";\nvar OnlineManager = class extends Subscribable {\n #online = true;\n #cleanup;\n #setup;\n constructor() {\n super();\n this.#setup = (onOnline) => {\n if (typeof window !== \"undefined\" && window.addEventListener) {\n const onlineListener = () => onOnline(true);\n const offlineListener = () => onOnline(false);\n window.addEventListener(\"online\", onlineListener, false);\n window.addEventListener(\"offline\", offlineListener, false);\n return () => {\n window.removeEventListener(\"online\", onlineListener);\n window.removeEventListener(\"offline\", offlineListener);\n };\n }\n return;\n };\n }\n onSubscribe() {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup);\n }\n }\n onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.();\n this.#cleanup = void 0;\n }\n }\n setEventListener(setup) {\n this.#setup = setup;\n this.#cleanup?.();\n this.#cleanup = setup(this.setOnline.bind(this));\n }\n setOnline(online) {\n const changed = this.#online !== online;\n if (changed) {\n this.#online = online;\n this.listeners.forEach((listener) => {\n listener(online);\n });\n }\n }\n isOnline() {\n return this.#online;\n }\n};\nvar onlineManager = new OnlineManager();\nexport {\n OnlineManager,\n onlineManager\n};\n//# sourceMappingURL=onlineManager.js.map","// src/retryer.ts\nimport { focusManager } from \"./focusManager.js\";\nimport { onlineManager } from \"./onlineManager.js\";\nimport { pendingThenable } from \"./thenable.js\";\nimport { environmentManager } from \"./environmentManager.js\";\nimport { sleep } from \"./utils.js\";\nfunction defaultRetryDelay(failureCount) {\n return Math.min(1e3 * 2 ** failureCount, 3e4);\n}\nfunction canFetch(networkMode) {\n return (networkMode ?? \"online\") === \"online\" ? onlineManager.isOnline() : true;\n}\nvar CancelledError = class extends Error {\n constructor(options) {\n super(\"CancelledError\");\n this.revert = options?.revert;\n this.silent = options?.silent;\n }\n};\nfunction isCancelledError(value) {\n return value instanceof CancelledError;\n}\nfunction createRetryer(config) {\n let isRetryCancelled = false;\n let failureCount = 0;\n let continueFn;\n const thenable = pendingThenable();\n const isResolved = () => thenable.status !== \"pending\";\n const cancel = (cancelOptions) => {\n if (!isResolved()) {\n const error = new CancelledError(cancelOptions);\n reject(error);\n config.onCancel?.(error);\n }\n };\n const cancelRetry = () => {\n isRetryCancelled = true;\n };\n const continueRetry = () => {\n isRetryCancelled = false;\n };\n const canContinue = () => focusManager.isFocused() && (config.networkMode === \"always\" || onlineManager.isOnline()) && config.canRun();\n const canStart = () => canFetch(config.networkMode) && config.canRun();\n const resolve = (value) => {\n if (!isResolved()) {\n continueFn?.();\n thenable.resolve(value);\n }\n };\n const reject = (value) => {\n if (!isResolved()) {\n continueFn?.();\n thenable.reject(value);\n }\n };\n const pause = () => {\n return new Promise((continueResolve) => {\n continueFn = (value) => {\n if (isResolved() || canContinue()) {\n continueResolve(value);\n }\n };\n config.onPause?.();\n }).then(() => {\n continueFn = void 0;\n if (!isResolved()) {\n config.onContinue?.();\n }\n });\n };\n const run = () => {\n if (isResolved()) {\n return;\n }\n let promiseOrValue;\n const initialPromise = failureCount === 0 ? config.initialPromise : void 0;\n try {\n promiseOrValue = initialPromise ?? config.fn();\n } catch (error) {\n promiseOrValue = Promise.reject(error);\n }\n Promise.resolve(promiseOrValue).then(resolve).catch((error) => {\n if (isResolved()) {\n return;\n }\n const retry = config.retry ?? (environmentManager.isServer() ? 0 : 3);\n const retryDelay = config.retryDelay ?? defaultRetryDelay;\n const delay = typeof retryDelay === \"function\" ? retryDelay(failureCount, error) : retryDelay;\n const shouldRetry = retry === true || typeof retry === \"number\" && failureCount < retry || typeof retry === \"function\" && retry(failureCount, error);\n if (isRetryCancelled || !shouldRetry) {\n reject(error);\n return;\n }\n failureCount++;\n config.onFail?.(failureCount, error);\n sleep(delay).then(() => {\n return canContinue() ? void 0 : pause();\n }).then(() => {\n if (isRetryCancelled) {\n reject(error);\n } else {\n run();\n }\n });\n });\n };\n return {\n promise: thenable,\n status: () => thenable.status,\n cancel,\n continue: () => {\n continueFn?.();\n return thenable;\n },\n cancelRetry,\n continueRetry,\n canStart,\n start: () => {\n if (canStart()) {\n run();\n } else {\n pause().then(run);\n }\n return thenable;\n }\n };\n}\nexport {\n CancelledError,\n canFetch,\n createRetryer,\n isCancelledError\n};\n//# sourceMappingURL=retryer.js.map","// src/removable.ts\nimport { timeoutManager } from \"./timeoutManager.js\";\nimport { environmentManager } from \"./environmentManager.js\";\nimport { isValidTimeout } from \"./utils.js\";\nvar Removable = class {\n #gcTimeout;\n destroy() {\n this.clearGcTimeout();\n }\n scheduleGc() {\n this.clearGcTimeout();\n if (isValidTimeout(this.gcTime)) {\n this.#gcTimeout = timeoutManager.setTimeout(() => {\n this.optionalRemove();\n }, this.gcTime);\n }\n }\n updateGcTime(newGcTime) {\n this.gcTime = Math.max(\n this.gcTime || 0,\n newGcTime ?? (environmentManager.isServer() ? Infinity : 5 * 60 * 1e3)\n );\n }\n clearGcTimeout() {\n if (this.#gcTimeout !== void 0) {\n timeoutManager.clearTimeout(this.#gcTimeout);\n this.#gcTimeout = void 0;\n }\n }\n};\nexport {\n Removable\n};\n//# sourceMappingURL=removable.js.map","// src/query.ts\nimport {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n resolveStaleTime,\n skipToken,\n timeUntilStale\n} from \"./utils.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { CancelledError, canFetch, createRetryer } from \"./retryer.js\";\nimport { Removable } from \"./removable.js\";\nvar Query = class extends Removable {\n #initialState;\n #revertState;\n #cache;\n #client;\n #retryer;\n #defaultOptions;\n #abortSignalConsumed;\n constructor(config) {\n super();\n this.#abortSignalConsumed = false;\n this.#defaultOptions = config.defaultOptions;\n this.setOptions(config.options);\n this.observers = [];\n this.#client = config.client;\n this.#cache = this.#client.getQueryCache();\n this.queryKey = config.queryKey;\n this.queryHash = config.queryHash;\n this.#initialState = getDefaultState(this.options);\n this.state = config.state ?? this.#initialState;\n this.scheduleGc();\n }\n get meta() {\n return this.options.meta;\n }\n get promise() {\n return this.#retryer?.promise;\n }\n setOptions(options) {\n this.options = { ...this.#defaultOptions, ...options };\n this.updateGcTime(this.options.gcTime);\n if (this.state && this.state.data === void 0) {\n const defaultState = getDefaultState(this.options);\n if (defaultState.data !== void 0) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt)\n );\n this.#initialState = defaultState;\n }\n }\n }\n optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === \"idle\") {\n this.#cache.remove(this);\n }\n }\n setData(newData, options) {\n const data = replaceData(this.state.data, newData, this.options);\n this.#dispatch({\n data,\n type: \"success\",\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual\n });\n return data;\n }\n setState(state, setStateOptions) {\n this.#dispatch({ type: \"setState\", state, setStateOptions });\n }\n cancel(options) {\n const promise = this.#retryer?.promise;\n this.#retryer?.cancel(options);\n return promise ? promise.then(noop).catch(noop) : Promise.resolve();\n }\n destroy() {\n super.destroy();\n this.cancel({ silent: true });\n }\n get resetState() {\n return this.#initialState;\n }\n reset() {\n this.destroy();\n this.setState(this.resetState);\n }\n isActive() {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false\n );\n }\n isDisabled() {\n if (this.getObserversCount() > 0) {\n return !this.isActive();\n }\n return this.options.queryFn === skipToken || !this.isFetched();\n }\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;\n }\n isStatic() {\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => resolveStaleTime(observer.options.staleTime, this) === \"static\"\n );\n }\n return false;\n }\n isStale() {\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale\n );\n }\n return this.state.data === void 0 || this.state.isInvalidated;\n }\n isStaleByTime(staleTime = 0) {\n if (this.state.data === void 0) {\n return true;\n }\n if (staleTime === \"static\") {\n return false;\n }\n if (this.state.isInvalidated) {\n return true;\n }\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime);\n }\n onFocus() {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());\n observer?.refetch({ cancelRefetch: false });\n this.#retryer?.continue();\n }\n onOnline() {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect());\n observer?.refetch({ cancelRefetch: false });\n this.#retryer?.continue();\n }\n addObserver(observer) {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer);\n this.clearGcTimeout();\n this.#cache.notify({ type: \"observerAdded\", query: this, observer });\n }\n }\n removeObserver(observer) {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer);\n if (!this.observers.length) {\n if (this.#retryer) {\n if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {\n this.#retryer.cancel({ revert: true });\n } else {\n this.#retryer.cancelRetry();\n }\n }\n this.scheduleGc();\n }\n this.#cache.notify({ type: \"observerRemoved\", query: this, observer });\n }\n }\n getObserversCount() {\n return this.observers.length;\n }\n #isInitialPausedFetch() {\n return this.state.fetchStatus === \"paused\" && this.state.status === \"pending\";\n }\n invalidate() {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: \"invalidate\" });\n }\n }\n async fetch(options, fetchOptions) {\n if (this.state.fetchStatus !== \"idle\" && // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== \"rejected\") {\n if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) {\n this.cancel({ silent: true });\n } else if (this.#retryer) {\n this.#retryer.continueRetry();\n return this.#retryer.promise;\n }\n }\n if (options) {\n this.setOptions(options);\n }\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn);\n if (observer) {\n this.setOptions(observer.options);\n }\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`\n );\n }\n }\n const abortController = new AbortController();\n const addSignalProperty = (object) => {\n Object.defineProperty(object, \"signal\", {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true;\n return abortController.signal;\n }\n });\n };\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions);\n const createQueryFnContext = () => {\n const queryFnContext2 = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta\n };\n addSignalProperty(queryFnContext2);\n return queryFnContext2;\n };\n const queryFnContext = createQueryFnContext();\n this.#abortSignalConsumed = false;\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this\n );\n }\n return queryFn(queryFnContext);\n };\n const createFetchContext = () => {\n const context2 = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn\n };\n addSignalProperty(context2);\n return context2;\n };\n const context = createFetchContext();\n this.options.behavior?.onFetch(context, this);\n this.#revertState = this.state;\n if (this.state.fetchStatus === \"idle\" || this.state.fetchMeta !== context.fetchOptions?.meta) {\n this.#dispatch({ type: \"fetch\", meta: context.fetchOptions?.meta });\n }\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise,\n fn: context.fetchFn,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: \"idle\"\n });\n }\n abortController.abort();\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: \"failed\", failureCount, error });\n },\n onPause: () => {\n this.#dispatch({ type: \"pause\" });\n },\n onContinue: () => {\n this.#dispatch({ type: \"continue\" });\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true\n });\n try {\n const data = await this.#retryer.start();\n if (data === void 0) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`\n );\n }\n throw new Error(`${this.queryHash} data is undefined`);\n }\n this.setData(data);\n this.#cache.config.onSuccess?.(data, this);\n this.#cache.config.onSettled?.(\n data,\n this.state.error,\n this\n );\n return data;\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n return this.#retryer.promise;\n } else if (error.revert) {\n if (this.state.data === void 0) {\n throw error;\n }\n return this.state.data;\n }\n }\n this.#dispatch({\n type: \"error\",\n error\n });\n this.#cache.config.onError?.(\n error,\n this\n );\n this.#cache.config.onSettled?.(\n this.state.data,\n error,\n this\n );\n throw error;\n } finally {\n this.scheduleGc();\n }\n }\n #dispatch(action) {\n const reducer = (state) => {\n switch (action.type) {\n case \"failed\":\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error\n };\n case \"pause\":\n return {\n ...state,\n fetchStatus: \"paused\"\n };\n case \"continue\":\n return {\n ...state,\n fetchStatus: \"fetching\"\n };\n case \"fetch\":\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null\n };\n case \"success\":\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...!action.manual && {\n fetchStatus: \"idle\",\n fetchFailureCount: 0,\n fetchFailureReason: null\n }\n };\n this.#revertState = action.manual ? newState : void 0;\n return newState;\n case \"error\":\n const error = action.error;\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: \"idle\",\n status: \"error\",\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true\n };\n case \"invalidate\":\n return {\n ...state,\n isInvalidated: true\n };\n case \"setState\":\n return {\n ...state,\n ...action.state\n };\n }\n };\n this.state = reducer(this.state);\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate();\n });\n this.#cache.notify({ query: this, type: \"updated\", action });\n });\n }\n};\nfunction fetchState(data, options) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? \"fetching\" : \"paused\",\n ...data === void 0 && {\n error: null,\n status: \"pending\"\n }\n };\n}\nfunction successState(data, dataUpdatedAt) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: \"success\"\n };\n}\nfunction getDefaultState(options) {\n const data = typeof options.initialData === \"function\" ? options.initialData() : options.initialData;\n const hasData = data !== void 0;\n const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === \"function\" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? \"success\" : \"pending\",\n fetchStatus: \"idle\"\n };\n}\nexport {\n Query,\n fetchState\n};\n//# sourceMappingURL=query.js.map","// src/queryObserver.ts\nimport { focusManager } from \"./focusManager.js\";\nimport { environmentManager } from \"./environmentManager.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { fetchState } from \"./query.js\";\nimport { Subscribable } from \"./subscribable.js\";\nimport { pendingThenable } from \"./thenable.js\";\nimport {\n isValidTimeout,\n noop,\n replaceData,\n resolveEnabled,\n resolveStaleTime,\n shallowEqualObjects,\n timeUntilStale\n} from \"./utils.js\";\nimport { timeoutManager } from \"./timeoutManager.js\";\nvar QueryObserver = class extends Subscribable {\n constructor(client, options) {\n super();\n this.options = options;\n this.#client = client;\n this.#selectError = null;\n this.#currentThenable = pendingThenable();\n this.bindMethods();\n this.setOptions(options);\n }\n #client;\n #currentQuery = void 0;\n #currentQueryInitialState = void 0;\n #currentResult = void 0;\n #currentResultState;\n #currentResultOptions;\n #currentThenable;\n #selectError;\n #selectFn;\n #selectResult;\n // This property keeps track of the last query with defined data.\n // It will be used to pass the previous data and query to the placeholder function between renders.\n #lastQueryWithDefinedData;\n #staleTimeoutId;\n #refetchIntervalId;\n #currentRefetchInterval;\n #trackedProps = /* @__PURE__ */ new Set();\n bindMethods() {\n this.refetch = this.refetch.bind(this);\n }\n onSubscribe() {\n if (this.listeners.size === 1) {\n this.#currentQuery.addObserver(this);\n if (shouldFetchOnMount(this.#currentQuery, this.options)) {\n this.#executeFetch();\n } else {\n this.updateResult();\n }\n this.#updateTimers();\n }\n }\n onUnsubscribe() {\n if (!this.hasListeners()) {\n this.destroy();\n }\n }\n shouldFetchOnReconnect() {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnReconnect\n );\n }\n shouldFetchOnWindowFocus() {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnWindowFocus\n );\n }\n destroy() {\n this.listeners = /* @__PURE__ */ new Set();\n this.#clearStaleTimeout();\n this.#clearRefetchInterval();\n this.#currentQuery.removeObserver(this);\n }\n setOptions(options) {\n const prevOptions = this.options;\n const prevQuery = this.#currentQuery;\n this.options = this.#client.defaultQueryOptions(options);\n if (this.options.enabled !== void 0 && typeof this.options.enabled !== \"boolean\" && typeof this.options.enabled !== \"function\" && typeof resolveEnabled(this.options.enabled, this.#currentQuery) !== \"boolean\") {\n throw new Error(\n \"Expected enabled to be a boolean or a callback that returns a boolean\"\n );\n }\n this.#updateQuery();\n this.#currentQuery.setOptions(this.options);\n if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getQueryCache().notify({\n type: \"observerOptionsUpdated\",\n query: this.#currentQuery,\n observer: this\n });\n }\n const mounted = this.hasListeners();\n if (mounted && shouldFetchOptionally(\n this.#currentQuery,\n prevQuery,\n this.options,\n prevOptions\n )) {\n this.#executeFetch();\n }\n this.updateResult();\n if (mounted && (this.#currentQuery !== prevQuery || resolveEnabled(this.options.enabled, this.#currentQuery) !== resolveEnabled(prevOptions.enabled, this.#currentQuery) || resolveStaleTime(this.options.staleTime, this.#currentQuery) !== resolveStaleTime(prevOptions.staleTime, this.#currentQuery))) {\n this.#updateStaleTimeout();\n }\n const nextRefetchInterval = this.#computeRefetchInterval();\n if (mounted && (this.#currentQuery !== prevQuery || resolveEnabled(this.options.enabled, this.#currentQuery) !== resolveEnabled(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) {\n this.#updateRefetchInterval(nextRefetchInterval);\n }\n }\n getOptimisticResult(options) {\n const query = this.#client.getQueryCache().build(this.#client, options);\n const result = this.createResult(query, options);\n if (shouldAssignObserverCurrentProperties(this, result)) {\n this.#currentResult = result;\n this.#currentResultOptions = this.options;\n this.#currentResultState = this.#currentQuery.state;\n }\n return result;\n }\n getCurrentResult() {\n return this.#currentResult;\n }\n trackResult(result, onPropTracked) {\n return new Proxy(result, {\n get: (target, key) => {\n this.trackProp(key);\n onPropTracked?.(key);\n if (key === \"promise\") {\n this.trackProp(\"data\");\n if (!this.options.experimental_prefetchInRender && this.#currentThenable.status === \"pending\") {\n this.#currentThenable.reject(\n new Error(\n \"experimental_prefetchInRender feature flag is not enabled\"\n )\n );\n }\n }\n return Reflect.get(target, key);\n }\n });\n }\n trackProp(key) {\n this.#trackedProps.add(key);\n }\n getCurrentQuery() {\n return this.#currentQuery;\n }\n refetch({ ...options } = {}) {\n return this.fetch({\n ...options\n });\n }\n fetchOptimistic(options) {\n const defaultedOptions = this.#client.defaultQueryOptions(options);\n const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);\n return query.fetch().then(() => this.createResult(query, defaultedOptions));\n }\n fetch(fetchOptions) {\n return this.#executeFetch({\n ...fetchOptions,\n cancelRefetch: fetchOptions.cancelRefetch ?? true\n }).then(() => {\n this.updateResult();\n return this.#currentResult;\n });\n }\n #executeFetch(fetchOptions) {\n this.#updateQuery();\n let promise = this.#currentQuery.fetch(\n this.options,\n fetchOptions\n );\n if (!fetchOptions?.throwOnError) {\n promise = promise.catch(noop);\n }\n return promise;\n }\n #updateStaleTimeout() {\n this.#clearStaleTimeout();\n const staleTime = resolveStaleTime(\n this.options.staleTime,\n this.#currentQuery\n );\n if (environmentManager.isServer() || this.#currentResult.isStale || !isValidTimeout(staleTime)) {\n return;\n }\n const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime);\n const timeout = time + 1;\n this.#staleTimeoutId = timeoutManager.setTimeout(() => {\n if (!this.#currentResult.isStale) {\n this.updateResult();\n }\n }, timeout);\n }\n #computeRefetchInterval() {\n return (typeof this.options.refetchInterval === \"function\" ? this.options.refetchInterval(this.#currentQuery) : this.options.refetchInterval) ?? false;\n }\n #updateRefetchInterval(nextInterval) {\n this.#clearRefetchInterval();\n this.#currentRefetchInterval = nextInterval;\n if (environmentManager.isServer() || resolveEnabled(this.options.enabled, this.#currentQuery) === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {\n return;\n }\n this.#refetchIntervalId = timeoutManager.setInterval(() => {\n if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {\n this.#executeFetch();\n }\n }, this.#currentRefetchInterval);\n }\n #updateTimers() {\n this.#updateStaleTimeout();\n this.#updateRefetchInterval(this.#computeRefetchInterval());\n }\n #clearStaleTimeout() {\n if (this.#staleTimeoutId !== void 0) {\n timeoutManager.clearTimeout(this.#staleTimeoutId);\n this.#staleTimeoutId = void 0;\n }\n }\n #clearRefetchInterval() {\n if (this.#refetchIntervalId !== void 0) {\n timeoutManager.clearInterval(this.#refetchIntervalId);\n this.#refetchIntervalId = void 0;\n }\n }\n createResult(query, options) {\n const prevQuery = this.#currentQuery;\n const prevOptions = this.options;\n const prevResult = this.#currentResult;\n const prevResultState = this.#currentResultState;\n const prevResultOptions = this.#currentResultOptions;\n const queryChange = query !== prevQuery;\n const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;\n const { state } = query;\n let newState = { ...state };\n let isPlaceholderData = false;\n let data;\n if (options._optimisticResults) {\n const mounted = this.hasListeners();\n const fetchOnMount = !mounted && shouldFetchOnMount(query, options);\n const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);\n if (fetchOnMount || fetchOptionally) {\n newState = {\n ...newState,\n ...fetchState(state.data, query.options)\n };\n }\n if (options._optimisticResults === \"isRestoring\") {\n newState.fetchStatus = \"idle\";\n }\n }\n let { error, errorUpdatedAt, status } = newState;\n data = newState.data;\n let skipSelect = false;\n if (options.placeholderData !== void 0 && data === void 0 && status === \"pending\") {\n let placeholderData;\n if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {\n placeholderData = prevResult.data;\n skipSelect = true;\n } else {\n placeholderData = typeof options.placeholderData === \"function\" ? options.placeholderData(\n this.#lastQueryWithDefinedData?.state.data,\n this.#lastQueryWithDefinedData\n ) : options.placeholderData;\n }\n if (placeholderData !== void 0) {\n status = \"success\";\n data = replaceData(\n prevResult?.data,\n placeholderData,\n options\n );\n isPlaceholderData = true;\n }\n }\n if (options.select && data !== void 0 && !skipSelect) {\n if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) {\n data = this.#selectResult;\n } else {\n try {\n this.#selectFn = options.select;\n data = options.select(data);\n data = replaceData(prevResult?.data, data, options);\n this.#selectResult = data;\n this.#selectError = null;\n } catch (selectError) {\n this.#selectError = selectError;\n }\n }\n }\n if (this.#selectError) {\n error = this.#selectError;\n data = this.#selectResult;\n errorUpdatedAt = Date.now();\n status = \"error\";\n }\n const isFetching = newState.fetchStatus === \"fetching\";\n const isPending = status === \"pending\";\n const isError = status === \"error\";\n const isLoading = isPending && isFetching;\n const hasData = data !== void 0;\n const result = {\n status,\n fetchStatus: newState.fetchStatus,\n isPending,\n isSuccess: status === \"success\",\n isError,\n isInitialLoading: isLoading,\n isLoading,\n data,\n dataUpdatedAt: newState.dataUpdatedAt,\n error,\n errorUpdatedAt,\n failureCount: newState.fetchFailureCount,\n failureReason: newState.fetchFailureReason,\n errorUpdateCount: newState.errorUpdateCount,\n isFetched: query.isFetched(),\n isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,\n isFetching,\n isRefetching: isFetching && !isPending,\n isLoadingError: isError && !hasData,\n isPaused: newState.fetchStatus === \"paused\",\n isPlaceholderData,\n isRefetchError: isError && hasData,\n isStale: isStale(query, options),\n refetch: this.refetch,\n promise: this.#currentThenable,\n isEnabled: resolveEnabled(options.enabled, query) !== false\n };\n const nextResult = result;\n if (this.options.experimental_prefetchInRender) {\n const hasResultData = nextResult.data !== void 0;\n const isErrorWithoutData = nextResult.status === \"error\" && !hasResultData;\n const finalizeThenableIfPossible = (thenable) => {\n if (isErrorWithoutData) {\n thenable.reject(nextResult.error);\n } else if (hasResultData) {\n thenable.resolve(nextResult.data);\n }\n };\n const recreateThenable = () => {\n const pending = this.#currentThenable = nextResult.promise = pendingThenable();\n finalizeThenableIfPossible(pending);\n };\n const prevThenable = this.#currentThenable;\n switch (prevThenable.status) {\n case \"pending\":\n if (query.queryHash === prevQuery.queryHash) {\n finalizeThenableIfPossible(prevThenable);\n }\n break;\n case \"fulfilled\":\n if (isErrorWithoutData || nextResult.data !== prevThenable.value) {\n recreateThenable();\n }\n break;\n case \"rejected\":\n if (!isErrorWithoutData || nextResult.error !== prevThenable.reason) {\n recreateThenable();\n }\n break;\n }\n }\n return nextResult;\n }\n updateResult() {\n const prevResult = this.#currentResult;\n const nextResult = this.createResult(this.#currentQuery, this.options);\n this.#currentResultState = this.#currentQuery.state;\n this.#currentResultOptions = this.options;\n if (this.#currentResultState.data !== void 0) {\n this.#lastQueryWithDefinedData = this.#currentQuery;\n }\n if (shallowEqualObjects(nextResult, prevResult)) {\n return;\n }\n this.#currentResult = nextResult;\n const shouldNotifyListeners = () => {\n if (!prevResult) {\n return true;\n }\n const { notifyOnChangeProps } = this.options;\n const notifyOnChangePropsValue = typeof notifyOnChangeProps === \"function\" ? notifyOnChangeProps() : notifyOnChangeProps;\n if (notifyOnChangePropsValue === \"all\" || !notifyOnChangePropsValue && !this.#trackedProps.size) {\n return true;\n }\n const includedProps = new Set(\n notifyOnChangePropsValue ?? this.#trackedProps\n );\n if (this.options.throwOnError) {\n includedProps.add(\"error\");\n }\n return Object.keys(this.#currentResult).some((key) => {\n const typedKey = key;\n const changed = this.#currentResult[typedKey] !== prevResult[typedKey];\n return changed && includedProps.has(typedKey);\n });\n };\n this.#notify({ listeners: shouldNotifyListeners() });\n }\n #updateQuery() {\n const query = this.#client.getQueryCache().build(this.#client, this.options);\n if (query === this.#currentQuery) {\n return;\n }\n const prevQuery = this.#currentQuery;\n this.#currentQuery = query;\n this.#currentQueryInitialState = query.state;\n if (this.hasListeners()) {\n prevQuery?.removeObserver(this);\n query.addObserver(this);\n }\n }\n onQueryUpdate() {\n this.updateResult();\n if (this.hasListeners()) {\n this.#updateTimers();\n }\n }\n #notify(notifyOptions) {\n notifyManager.batch(() => {\n if (notifyOptions.listeners) {\n this.listeners.forEach((listener) => {\n listener(this.#currentResult);\n });\n }\n this.#client.getQueryCache().notify({\n query: this.#currentQuery,\n type: \"observerResultsUpdated\"\n });\n });\n }\n};\nfunction shouldLoadOnMount(query, options) {\n return resolveEnabled(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === \"error\" && options.retryOnMount === false);\n}\nfunction shouldFetchOnMount(query, options) {\n return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);\n}\nfunction shouldFetchOn(query, options, field) {\n if (resolveEnabled(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== \"static\") {\n const value = typeof field === \"function\" ? field(query) : field;\n return value === \"always\" || value !== false && isStale(query, options);\n }\n return false;\n}\nfunction shouldFetchOptionally(query, prevQuery, options, prevOptions) {\n return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== \"error\") && isStale(query, options);\n}\nfunction isStale(query, options) {\n return resolveEnabled(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query));\n}\nfunction shouldAssignObserverCurrentProperties(observer, optimisticResult) {\n if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {\n return true;\n }\n return false;\n}\nexport {\n QueryObserver\n};\n//# sourceMappingURL=queryObserver.js.map","// src/infiniteQueryBehavior.ts\nimport {\n addConsumeAwareSignal,\n addToEnd,\n addToStart,\n ensureQueryFn\n} from \"./utils.js\";\nfunction infiniteQueryBehavior(pages) {\n return {\n onFetch: (context, query) => {\n const options = context.options;\n const direction = context.fetchOptions?.meta?.fetchMore?.direction;\n const oldPages = context.state.data?.pages || [];\n const oldPageParams = context.state.data?.pageParams || [];\n let result = { pages: [], pageParams: [] };\n let currentPage = 0;\n const fetchFn = async () => {\n let cancelled = false;\n const addSignalProperty = (object) => {\n addConsumeAwareSignal(\n object,\n () => context.signal,\n () => cancelled = true\n );\n };\n const queryFn = ensureQueryFn(context.options, context.fetchOptions);\n const fetchPage = async (data, param, previous) => {\n if (cancelled) {\n return Promise.reject();\n }\n if (param == null && data.pages.length) {\n return Promise.resolve(data);\n }\n const createQueryFnContext = () => {\n const queryFnContext2 = {\n client: context.client,\n queryKey: context.queryKey,\n pageParam: param,\n direction: previous ? \"backward\" : \"forward\",\n meta: context.options.meta\n };\n addSignalProperty(queryFnContext2);\n return queryFnContext2;\n };\n const queryFnContext = createQueryFnContext();\n const page = await queryFn(queryFnContext);\n const { maxPages } = context.options;\n const addTo = previous ? addToStart : addToEnd;\n return {\n pages: addTo(data.pages, page, maxPages),\n pageParams: addTo(data.pageParams, param, maxPages)\n };\n };\n if (direction && oldPages.length) {\n const previous = direction === \"backward\";\n const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n const oldData = {\n pages: oldPages,\n pageParams: oldPageParams\n };\n const param = pageParamFn(options, oldData);\n result = await fetchPage(oldData, param, previous);\n } else {\n const remainingPages = pages ?? oldPages.length;\n do {\n const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);\n if (currentPage > 0 && param == null) {\n break;\n }\n result = await fetchPage(result, param);\n currentPage++;\n } while (currentPage < remainingPages);\n }\n return result;\n };\n if (context.options.persister) {\n context.fetchFn = () => {\n return context.options.persister?.(\n fetchFn,\n {\n client: context.client,\n queryKey: context.queryKey,\n meta: context.options.meta,\n signal: context.signal\n },\n query\n );\n };\n } else {\n context.fetchFn = fetchFn;\n }\n }\n };\n}\nfunction getNextPageParam(options, { pages, pageParams }) {\n const lastIndex = pages.length - 1;\n return pages.length > 0 ? options.getNextPageParam(\n pages[lastIndex],\n pages,\n pageParams[lastIndex],\n pageParams\n ) : void 0;\n}\nfunction getPreviousPageParam(options, { pages, pageParams }) {\n return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;\n}\nfunction hasNextPage(options, data) {\n if (!data) return false;\n return getNextPageParam(options, data) != null;\n}\nfunction hasPreviousPage(options, data) {\n if (!data || !options.getPreviousPageParam) return false;\n return getPreviousPageParam(options, data) != null;\n}\nexport {\n hasNextPage,\n hasPreviousPage,\n infiniteQueryBehavior\n};\n//# sourceMappingURL=infiniteQueryBehavior.js.map","// src/mutation.ts\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Removable } from \"./removable.js\";\nimport { createRetryer } from \"./retryer.js\";\nvar Mutation = class extends Removable {\n #client;\n #observers;\n #mutationCache;\n #retryer;\n constructor(config) {\n super();\n this.#client = config.client;\n this.mutationId = config.mutationId;\n this.#mutationCache = config.mutationCache;\n this.#observers = [];\n this.state = config.state || getDefaultState();\n this.setOptions(config.options);\n this.scheduleGc();\n }\n setOptions(options) {\n this.options = options;\n this.updateGcTime(this.options.gcTime);\n }\n get meta() {\n return this.options.meta;\n }\n addObserver(observer) {\n if (!this.#observers.includes(observer)) {\n this.#observers.push(observer);\n this.clearGcTimeout();\n this.#mutationCache.notify({\n type: \"observerAdded\",\n mutation: this,\n observer\n });\n }\n }\n removeObserver(observer) {\n this.#observers = this.#observers.filter((x) => x !== observer);\n this.scheduleGc();\n this.#mutationCache.notify({\n type: \"observerRemoved\",\n mutation: this,\n observer\n });\n }\n optionalRemove() {\n if (!this.#observers.length) {\n if (this.state.status === \"pending\") {\n this.scheduleGc();\n } else {\n this.#mutationCache.remove(this);\n }\n }\n }\n continue() {\n return this.#retryer?.continue() ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before\n this.execute(this.state.variables);\n }\n async execute(variables) {\n const onContinue = () => {\n this.#dispatch({ type: \"continue\" });\n };\n const mutationFnContext = {\n client: this.#client,\n meta: this.options.meta,\n mutationKey: this.options.mutationKey\n };\n this.#retryer = createRetryer({\n fn: () => {\n if (!this.options.mutationFn) {\n return Promise.reject(new Error(\"No mutationFn found\"));\n }\n return this.options.mutationFn(variables, mutationFnContext);\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: \"failed\", failureCount, error });\n },\n onPause: () => {\n this.#dispatch({ type: \"pause\" });\n },\n onContinue,\n retry: this.options.retry ?? 0,\n retryDelay: this.options.retryDelay,\n networkMode: this.options.networkMode,\n canRun: () => this.#mutationCache.canRun(this)\n });\n const restored = this.state.status === \"pending\";\n const isPaused = !this.#retryer.canStart();\n try {\n if (restored) {\n onContinue();\n } else {\n this.#dispatch({ type: \"pending\", variables, isPaused });\n if (this.#mutationCache.config.onMutate) {\n await this.#mutationCache.config.onMutate(\n variables,\n this,\n mutationFnContext\n );\n }\n const context = await this.options.onMutate?.(\n variables,\n mutationFnContext\n );\n if (context !== this.state.context) {\n this.#dispatch({\n type: \"pending\",\n context,\n variables,\n isPaused\n });\n }\n }\n const data = await this.#retryer.start();\n await this.#mutationCache.config.onSuccess?.(\n data,\n variables,\n this.state.context,\n this,\n mutationFnContext\n );\n await this.options.onSuccess?.(\n data,\n variables,\n this.state.context,\n mutationFnContext\n );\n await this.#mutationCache.config.onSettled?.(\n data,\n null,\n this.state.variables,\n this.state.context,\n this,\n mutationFnContext\n );\n await this.options.onSettled?.(\n data,\n null,\n variables,\n this.state.context,\n mutationFnContext\n );\n this.#dispatch({ type: \"success\", data });\n return data;\n } catch (error) {\n try {\n await this.#mutationCache.config.onError?.(\n error,\n variables,\n this.state.context,\n this,\n mutationFnContext\n );\n } catch (e) {\n void Promise.reject(e);\n }\n try {\n await this.options.onError?.(\n error,\n variables,\n this.state.context,\n mutationFnContext\n );\n } catch (e) {\n void Promise.reject(e);\n }\n try {\n await this.#mutationCache.config.onSettled?.(\n void 0,\n error,\n this.state.variables,\n this.state.context,\n this,\n mutationFnContext\n );\n } catch (e) {\n void Promise.reject(e);\n }\n try {\n await this.options.onSettled?.(\n void 0,\n error,\n variables,\n this.state.context,\n mutationFnContext\n );\n } catch (e) {\n void Promise.reject(e);\n }\n this.#dispatch({ type: \"error\", error });\n throw error;\n } finally {\n this.#mutationCache.runNext(this);\n }\n }\n #dispatch(action) {\n const reducer = (state) => {\n switch (action.type) {\n case \"failed\":\n return {\n ...state,\n failureCount: action.failureCount,\n failureReason: action.error\n };\n case \"pause\":\n return {\n ...state,\n isPaused: true\n };\n case \"continue\":\n return {\n ...state,\n isPaused: false\n };\n case \"pending\":\n return {\n ...state,\n context: action.context,\n data: void 0,\n failureCount: 0,\n failureReason: null,\n error: null,\n isPaused: action.isPaused,\n status: \"pending\",\n variables: action.variables,\n submittedAt: Date.now()\n };\n case \"success\":\n return {\n ...state,\n data: action.data,\n failureCount: 0,\n failureReason: null,\n error: null,\n status: \"success\",\n isPaused: false\n };\n case \"error\":\n return {\n ...state,\n data: void 0,\n error: action.error,\n failureCount: state.failureCount + 1,\n failureReason: action.error,\n isPaused: false,\n status: \"error\"\n };\n }\n };\n this.state = reducer(this.state);\n notifyManager.batch(() => {\n this.#observers.forEach((observer) => {\n observer.onMutationUpdate(action);\n });\n this.#mutationCache.notify({\n mutation: this,\n type: \"updated\",\n action\n });\n });\n }\n};\nfunction getDefaultState() {\n return {\n context: void 0,\n data: void 0,\n error: null,\n failureCount: 0,\n failureReason: null,\n isPaused: false,\n status: \"idle\",\n variables: void 0,\n submittedAt: 0\n };\n}\nexport {\n Mutation,\n getDefaultState\n};\n//# sourceMappingURL=mutation.js.map","// src/mutationCache.ts\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Mutation } from \"./mutation.js\";\nimport { matchMutation, noop } from \"./utils.js\";\nimport { Subscribable } from \"./subscribable.js\";\nvar MutationCache = class extends Subscribable {\n constructor(config = {}) {\n super();\n this.config = config;\n this.#mutations = /* @__PURE__ */ new Set();\n this.#scopes = /* @__PURE__ */ new Map();\n this.#mutationId = 0;\n }\n #mutations;\n #scopes;\n #mutationId;\n build(client, options, state) {\n const mutation = new Mutation({\n client,\n mutationCache: this,\n mutationId: ++this.#mutationId,\n options: client.defaultMutationOptions(options),\n state\n });\n this.add(mutation);\n return mutation;\n }\n add(mutation) {\n this.#mutations.add(mutation);\n const scope = scopeFor(mutation);\n if (typeof scope === \"string\") {\n const scopedMutations = this.#scopes.get(scope);\n if (scopedMutations) {\n scopedMutations.push(mutation);\n } else {\n this.#scopes.set(scope, [mutation]);\n }\n }\n this.notify({ type: \"added\", mutation });\n }\n remove(mutation) {\n if (this.#mutations.delete(mutation)) {\n const scope = scopeFor(mutation);\n if (typeof scope === \"string\") {\n const scopedMutations = this.#scopes.get(scope);\n if (scopedMutations) {\n if (scopedMutations.length > 1) {\n const index = scopedMutations.indexOf(mutation);\n if (index !== -1) {\n scopedMutations.splice(index, 1);\n }\n } else if (scopedMutations[0] === mutation) {\n this.#scopes.delete(scope);\n }\n }\n }\n }\n this.notify({ type: \"removed\", mutation });\n }\n canRun(mutation) {\n const scope = scopeFor(mutation);\n if (typeof scope === \"string\") {\n const mutationsWithSameScope = this.#scopes.get(scope);\n const firstPendingMutation = mutationsWithSameScope?.find(\n (m) => m.state.status === \"pending\"\n );\n return !firstPendingMutation || firstPendingMutation === mutation;\n } else {\n return true;\n }\n }\n runNext(mutation) {\n const scope = scopeFor(mutation);\n if (typeof scope === \"string\") {\n const foundMutation = this.#scopes.get(scope)?.find((m) => m !== mutation && m.state.isPaused);\n return foundMutation?.continue() ?? Promise.resolve();\n } else {\n return Promise.resolve();\n }\n }\n clear() {\n notifyManager.batch(() => {\n this.#mutations.forEach((mutation) => {\n this.notify({ type: \"removed\", mutation });\n });\n this.#mutations.clear();\n this.#scopes.clear();\n });\n }\n getAll() {\n return Array.from(this.#mutations);\n }\n find(filters) {\n const defaultedFilters = { exact: true, ...filters };\n return this.getAll().find(\n (mutation) => matchMutation(defaultedFilters, mutation)\n );\n }\n findAll(filters = {}) {\n return this.getAll().filter((mutation) => matchMutation(filters, mutation));\n }\n notify(event) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event);\n });\n });\n }\n resumePausedMutations() {\n const pausedMutations = this.getAll().filter((x) => x.state.isPaused);\n return notifyManager.batch(\n () => Promise.all(\n pausedMutations.map((mutation) => mutation.continue().catch(noop))\n )\n );\n }\n};\nfunction scopeFor(mutation) {\n return mutation.options.scope?.id;\n}\nexport {\n MutationCache\n};\n//# sourceMappingURL=mutationCache.js.map","// src/queryCache.ts\nimport { hashQueryKeyByOptions, matchQuery } from \"./utils.js\";\nimport { Query } from \"./query.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Subscribable } from \"./subscribable.js\";\nvar QueryCache = class extends Subscribable {\n constructor(config = {}) {\n super();\n this.config = config;\n this.#queries = /* @__PURE__ */ new Map();\n }\n #queries;\n build(client, options, state) {\n const queryKey = options.queryKey;\n const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);\n let query = this.get(queryHash);\n if (!query) {\n query = new Query({\n client,\n queryKey,\n queryHash,\n options: client.defaultQueryOptions(options),\n state,\n defaultOptions: client.getQueryDefaults(queryKey)\n });\n this.add(query);\n }\n return query;\n }\n add(query) {\n if (!this.#queries.has(query.queryHash)) {\n this.#queries.set(query.queryHash, query);\n this.notify({\n type: \"added\",\n query\n });\n }\n }\n remove(query) {\n const queryInMap = this.#queries.get(query.queryHash);\n if (queryInMap) {\n query.destroy();\n if (queryInMap === query) {\n this.#queries.delete(query.queryHash);\n }\n this.notify({ type: \"removed\", query });\n }\n }\n clear() {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n this.remove(query);\n });\n });\n }\n get(queryHash) {\n return this.#queries.get(queryHash);\n }\n getAll() {\n return [...this.#queries.values()];\n }\n find(filters) {\n const defaultedFilters = { exact: true, ...filters };\n return this.getAll().find(\n (query) => matchQuery(defaultedFilters, query)\n );\n }\n findAll(filters = {}) {\n const queries = this.getAll();\n return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;\n }\n notify(event) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event);\n });\n });\n }\n onFocus() {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onFocus();\n });\n });\n }\n onOnline() {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onOnline();\n });\n });\n }\n};\nexport {\n QueryCache\n};\n//# sourceMappingURL=queryCache.js.map","// src/queryClient.ts\nimport {\n functionalUpdate,\n hashKey,\n hashQueryKeyByOptions,\n noop,\n partialMatchKey,\n resolveStaleTime,\n skipToken\n} from \"./utils.js\";\nimport { QueryCache } from \"./queryCache.js\";\nimport { MutationCache } from \"./mutationCache.js\";\nimport { focusManager } from \"./focusManager.js\";\nimport { onlineManager } from \"./onlineManager.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { infiniteQueryBehavior } from \"./infiniteQueryBehavior.js\";\nvar QueryClient = class {\n #queryCache;\n #mutationCache;\n #defaultOptions;\n #queryDefaults;\n #mutationDefaults;\n #mountCount;\n #unsubscribeFocus;\n #unsubscribeOnline;\n constructor(config = {}) {\n this.#queryCache = config.queryCache || new QueryCache();\n this.#mutationCache = config.mutationCache || new MutationCache();\n this.#defaultOptions = config.defaultOptions || {};\n this.#queryDefaults = /* @__PURE__ */ new Map();\n this.#mutationDefaults = /* @__PURE__ */ new Map();\n this.#mountCount = 0;\n }\n mount() {\n this.#mountCount++;\n if (this.#mountCount !== 1) return;\n this.#unsubscribeFocus = focusManager.subscribe(async (focused) => {\n if (focused) {\n await this.resumePausedMutations();\n this.#queryCache.onFocus();\n }\n });\n this.#unsubscribeOnline = onlineManager.subscribe(async (online) => {\n if (online) {\n await this.resumePausedMutations();\n this.#queryCache.onOnline();\n }\n });\n }\n unmount() {\n this.#mountCount--;\n if (this.#mountCount !== 0) return;\n this.#unsubscribeFocus?.();\n this.#unsubscribeFocus = void 0;\n this.#unsubscribeOnline?.();\n this.#unsubscribeOnline = void 0;\n }\n isFetching(filters) {\n return this.#queryCache.findAll({ ...filters, fetchStatus: \"fetching\" }).length;\n }\n isMutating(filters) {\n return this.#mutationCache.findAll({ ...filters, status: \"pending\" }).length;\n }\n /**\n * Imperative (non-reactive) way to retrieve data for a QueryKey.\n * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.\n *\n * Hint: Do not use this function inside a component, because it won't receive updates.\n * Use `useQuery` to create a `QueryObserver` that subscribes to changes.\n */\n getQueryData(queryKey) {\n const options = this.defaultQueryOptions({ queryKey });\n return this.#queryCache.get(options.queryHash)?.state.data;\n }\n ensureQueryData(options) {\n const defaultedOptions = this.defaultQueryOptions(options);\n const query = this.#queryCache.build(this, defaultedOptions);\n const cachedData = query.state.data;\n if (cachedData === void 0) {\n return this.fetchQuery(options);\n }\n if (options.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) {\n void this.prefetchQuery(defaultedOptions);\n }\n return Promise.resolve(cachedData);\n }\n getQueriesData(filters) {\n return this.#queryCache.findAll(filters).map(({ queryKey, state }) => {\n const data = state.data;\n return [queryKey, data];\n });\n }\n setQueryData(queryKey, updater, options) {\n const defaultedOptions = this.defaultQueryOptions({ queryKey });\n const query = this.#queryCache.get(\n defaultedOptions.queryHash\n );\n const prevData = query?.state.data;\n const data = functionalUpdate(updater, prevData);\n if (data === void 0) {\n return void 0;\n }\n return this.#queryCache.build(this, defaultedOptions).setData(data, { ...options, manual: true });\n }\n setQueriesData(filters, updater, options) {\n return notifyManager.batch(\n () => this.#queryCache.findAll(filters).map(({ queryKey }) => [\n queryKey,\n this.setQueryData(queryKey, updater, options)\n ])\n );\n }\n getQueryState(queryKey) {\n const options = this.defaultQueryOptions({ queryKey });\n return this.#queryCache.get(\n options.queryHash\n )?.state;\n }\n removeQueries(filters) {\n const queryCache = this.#queryCache;\n notifyManager.batch(() => {\n queryCache.findAll(filters).forEach((query) => {\n queryCache.remove(query);\n });\n });\n }\n resetQueries(filters, options) {\n const queryCache = this.#queryCache;\n return notifyManager.batch(() => {\n queryCache.findAll(filters).forEach((query) => {\n query.reset();\n });\n return this.refetchQueries(\n {\n type: \"active\",\n ...filters\n },\n options\n );\n });\n }\n cancelQueries(filters, cancelOptions = {}) {\n const defaultedCancelOptions = { revert: true, ...cancelOptions };\n const promises = notifyManager.batch(\n () => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions))\n );\n return Promise.all(promises).then(noop).catch(noop);\n }\n invalidateQueries(filters, options = {}) {\n return notifyManager.batch(() => {\n this.#queryCache.findAll(filters).forEach((query) => {\n query.invalidate();\n });\n if (filters?.refetchType === \"none\") {\n return Promise.resolve();\n }\n return this.refetchQueries(\n {\n ...filters,\n type: filters?.refetchType ?? filters?.type ?? \"active\"\n },\n options\n );\n });\n }\n refetchQueries(filters, options = {}) {\n const fetchOptions = {\n ...options,\n cancelRefetch: options.cancelRefetch ?? true\n };\n const promises = notifyManager.batch(\n () => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {\n let promise = query.fetch(void 0, fetchOptions);\n if (!fetchOptions.throwOnError) {\n promise = promise.catch(noop);\n }\n return query.state.fetchStatus === \"paused\" ? Promise.resolve() : promise;\n })\n );\n return Promise.all(promises).then(noop);\n }\n fetchQuery(options) {\n const defaultedOptions = this.defaultQueryOptions(options);\n if (defaultedOptions.retry === void 0) {\n defaultedOptions.retry = false;\n }\n const query = this.#queryCache.build(this, defaultedOptions);\n return query.isStaleByTime(\n resolveStaleTime(defaultedOptions.staleTime, query)\n ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);\n }\n prefetchQuery(options) {\n return this.fetchQuery(options).then(noop).catch(noop);\n }\n fetchInfiniteQuery(options) {\n options.behavior = infiniteQueryBehavior(options.pages);\n return this.fetchQuery(options);\n }\n prefetchInfiniteQuery(options) {\n return this.fetchInfiniteQuery(options).then(noop).catch(noop);\n }\n ensureInfiniteQueryData(options) {\n options.behavior = infiniteQueryBehavior(options.pages);\n return this.ensureQueryData(options);\n }\n resumePausedMutations() {\n if (onlineManager.isOnline()) {\n return this.#mutationCache.resumePausedMutations();\n }\n return Promise.resolve();\n }\n getQueryCache() {\n return this.#queryCache;\n }\n getMutationCache() {\n return this.#mutationCache;\n }\n getDefaultOptions() {\n return this.#defaultOptions;\n }\n setDefaultOptions(options) {\n this.#defaultOptions = options;\n }\n setQueryDefaults(queryKey, options) {\n this.#queryDefaults.set(hashKey(queryKey), {\n queryKey,\n defaultOptions: options\n });\n }\n getQueryDefaults(queryKey) {\n const defaults = [...this.#queryDefaults.values()];\n const result = {};\n defaults.forEach((queryDefault) => {\n if (partialMatchKey(queryKey, queryDefault.queryKey)) {\n Object.assign(result, queryDefault.defaultOptions);\n }\n });\n return result;\n }\n setMutationDefaults(mutationKey, options) {\n this.#mutationDefaults.set(hashKey(mutationKey), {\n mutationKey,\n defaultOptions: options\n });\n }\n getMutationDefaults(mutationKey) {\n const defaults = [...this.#mutationDefaults.values()];\n const result = {};\n defaults.forEach((queryDefault) => {\n if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {\n Object.assign(result, queryDefault.defaultOptions);\n }\n });\n return result;\n }\n defaultQueryOptions(options) {\n if (options._defaulted) {\n return options;\n }\n const defaultedOptions = {\n ...this.#defaultOptions.queries,\n ...this.getQueryDefaults(options.queryKey),\n ...options,\n _defaulted: true\n };\n if (!defaultedOptions.queryHash) {\n defaultedOptions.queryHash = hashQueryKeyByOptions(\n defaultedOptions.queryKey,\n defaultedOptions\n );\n }\n if (defaultedOptions.refetchOnReconnect === void 0) {\n defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== \"always\";\n }\n if (defaultedOptions.throwOnError === void 0) {\n defaultedOptions.throwOnError = !!defaultedOptions.suspense;\n }\n if (!defaultedOptions.networkMode && defaultedOptions.persister) {\n defaultedOptions.networkMode = \"offlineFirst\";\n }\n if (defaultedOptions.queryFn === skipToken) {\n defaultedOptions.enabled = false;\n }\n return defaultedOptions;\n }\n defaultMutationOptions(options) {\n if (options?._defaulted) {\n return options;\n }\n return {\n ...this.#defaultOptions.mutations,\n ...options?.mutationKey && this.getMutationDefaults(options.mutationKey),\n ...options,\n _defaulted: true\n };\n }\n clear() {\n this.#queryCache.clear();\n this.#mutationCache.clear();\n }\n};\nexport {\n QueryClient\n};\n//# sourceMappingURL=queryClient.js.map","\"use client\";\n\n// src/QueryClientProvider.tsx\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nvar QueryClientContext = React.createContext(\n void 0\n);\nvar useQueryClient = (queryClient) => {\n const client = React.useContext(QueryClientContext);\n if (queryClient) {\n return queryClient;\n }\n if (!client) {\n throw new Error(\"No QueryClient set, use QueryClientProvider to set one\");\n }\n return client;\n};\nvar QueryClientProvider = ({\n client,\n children\n}) => {\n React.useEffect(() => {\n client.mount();\n return () => {\n client.unmount();\n };\n }, [client]);\n return /* @__PURE__ */ jsx(QueryClientContext.Provider, { value: client, children });\n};\nexport {\n QueryClientContext,\n QueryClientProvider,\n useQueryClient\n};\n//# sourceMappingURL=QueryClientProvider.js.map","\"use client\";\n\n// src/IsRestoringProvider.ts\nimport * as React from \"react\";\nvar IsRestoringContext = React.createContext(false);\nvar useIsRestoring = () => React.useContext(IsRestoringContext);\nvar IsRestoringProvider = IsRestoringContext.Provider;\nexport {\n IsRestoringProvider,\n useIsRestoring\n};\n//# sourceMappingURL=IsRestoringProvider.js.map","\"use client\";\n\n// src/QueryErrorResetBoundary.tsx\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nfunction createValue() {\n let isReset = false;\n return {\n clearReset: () => {\n isReset = false;\n },\n reset: () => {\n isReset = true;\n },\n isReset: () => {\n return isReset;\n }\n };\n}\nvar QueryErrorResetBoundaryContext = React.createContext(createValue());\nvar useQueryErrorResetBoundary = () => React.useContext(QueryErrorResetBoundaryContext);\nvar QueryErrorResetBoundary = ({\n children\n}) => {\n const [value] = React.useState(() => createValue());\n return /* @__PURE__ */ jsx(QueryErrorResetBoundaryContext.Provider, { value, children: typeof children === \"function\" ? children(value) : children });\n};\nexport {\n QueryErrorResetBoundary,\n useQueryErrorResetBoundary\n};\n//# sourceMappingURL=QueryErrorResetBoundary.js.map","\"use client\";\n\n// src/errorBoundaryUtils.ts\nimport * as React from \"react\";\nimport { shouldThrowError } from \"@tanstack/query-core\";\nvar ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {\n const throwOnError = query?.state.error && typeof options.throwOnError === \"function\" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;\n if (options.suspense || options.experimental_prefetchInRender || throwOnError) {\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false;\n }\n }\n};\nvar useClearResetErrorBoundary = (errorResetBoundary) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset();\n }, [errorResetBoundary]);\n};\nvar getHasError = ({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense\n}) => {\n return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));\n};\nexport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary\n};\n//# sourceMappingURL=errorBoundaryUtils.js.map","// src/suspense.ts\nvar defaultThrowOnError = (_error, query) => query.state.data === void 0;\nvar ensureSuspenseTimers = (defaultedOptions) => {\n if (defaultedOptions.suspense) {\n const MIN_SUSPENSE_TIME_MS = 1e3;\n const clamp = (value) => value === \"static\" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);\n const originalStaleTime = defaultedOptions.staleTime;\n defaultedOptions.staleTime = typeof originalStaleTime === \"function\" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);\n if (typeof defaultedOptions.gcTime === \"number\") {\n defaultedOptions.gcTime = Math.max(\n defaultedOptions.gcTime,\n MIN_SUSPENSE_TIME_MS\n );\n }\n }\n};\nvar willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring;\nvar shouldSuspend = (defaultedOptions, result) => defaultedOptions?.suspense && result.isPending;\nvar fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {\n errorResetBoundary.clearReset();\n});\nexport {\n defaultThrowOnError,\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n willFetch\n};\n//# sourceMappingURL=suspense.js.map","\"use client\";\n\n// src/useBaseQuery.ts\nimport * as React from \"react\";\nimport { environmentManager, noop, notifyManager } from \"@tanstack/query-core\";\nimport { useQueryClient } from \"./QueryClientProvider.js\";\nimport { useQueryErrorResetBoundary } from \"./QueryErrorResetBoundary.js\";\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary\n} from \"./errorBoundaryUtils.js\";\nimport { useIsRestoring } from \"./IsRestoringProvider.js\";\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n willFetch\n} from \"./suspense.js\";\nfunction useBaseQuery(options, Observer, queryClient) {\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof options !== \"object\" || Array.isArray(options)) {\n throw new Error(\n 'Bad argument type. Starting with v5, only the \"Object\" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object'\n );\n }\n }\n const isRestoring = useIsRestoring();\n const errorResetBoundary = useQueryErrorResetBoundary();\n const client = useQueryClient(queryClient);\n const defaultedOptions = client.defaultQueryOptions(options);\n client.getDefaultOptions().queries?._experimental_beforeQuery?.(\n defaultedOptions\n );\n const query = client.getQueryCache().get(defaultedOptions.queryHash);\n if (process.env.NODE_ENV !== \"production\") {\n if (!defaultedOptions.queryFn) {\n console.error(\n `[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`\n );\n }\n }\n defaultedOptions._optimisticResults = isRestoring ? \"isRestoring\" : \"optimistic\";\n ensureSuspenseTimers(defaultedOptions);\n ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query);\n useClearResetErrorBoundary(errorResetBoundary);\n const isNewCacheEntry = !client.getQueryCache().get(defaultedOptions.queryHash);\n const [observer] = React.useState(\n () => new Observer(\n client,\n defaultedOptions\n )\n );\n const result = observer.getOptimisticResult(defaultedOptions);\n const shouldSubscribe = !isRestoring && options.subscribed !== false;\n React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) => {\n const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;\n observer.updateResult();\n return unsubscribe;\n },\n [observer, shouldSubscribe]\n ),\n () => observer.getCurrentResult(),\n () => observer.getCurrentResult()\n );\n React.useEffect(() => {\n observer.setOptions(defaultedOptions);\n }, [defaultedOptions, observer]);\n if (shouldSuspend(defaultedOptions, result)) {\n throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);\n }\n if (getHasError({\n result,\n errorResetBoundary,\n throwOnError: defaultedOptions.throwOnError,\n query,\n suspense: defaultedOptions.suspense\n })) {\n throw result.error;\n }\n ;\n client.getDefaultOptions().queries?._experimental_afterQuery?.(\n defaultedOptions,\n result\n );\n if (defaultedOptions.experimental_prefetchInRender && !environmentManager.isServer() && willFetch(result, isRestoring)) {\n const promise = isNewCacheEntry ? (\n // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted\n fetchOptimistic(defaultedOptions, observer, errorResetBoundary)\n ) : (\n // subscribe to the \"cache promise\" so that we can finalize the currentThenable once data comes in\n query?.promise\n );\n promise?.catch(noop).finally(() => {\n observer.updateResult();\n });\n }\n return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;\n}\nexport {\n useBaseQuery\n};\n//# sourceMappingURL=useBaseQuery.js.map","\"use client\";\n\n// src/useQuery.ts\nimport { QueryObserver } from \"@tanstack/query-core\";\nimport { useBaseQuery } from \"./useBaseQuery.js\";\nfunction useQuery(options, queryClient) {\n return useBaseQuery(options, QueryObserver, queryClient);\n}\nexport {\n useQuery\n};\n//# sourceMappingURL=useQuery.js.map","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst mergeClasses = (...classes) => classes.filter((className, index, array) => {\n return Boolean(className) && className.trim() !== \"\" && array.indexOf(className) === index;\n}).join(\" \").trim();\n\nexport { mergeClasses };\n//# sourceMappingURL=mergeClasses.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n\nexport { toKebabCase };\n//# sourceMappingURL=toKebabCase.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst toCamelCase = (string) => string.replace(\n /^([A-Z])|[\\s-_]+(\\w)/g,\n (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()\n);\n\nexport { toCamelCase };\n//# sourceMappingURL=toCamelCase.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { toCamelCase } from './toCamelCase.js';\n\nconst toPascalCase = (string) => {\n const camelCase = toCamelCase(string);\n return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);\n};\n\nexport { toPascalCase };\n//# sourceMappingURL=toPascalCase.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nvar defaultAttributes = {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: 2,\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n};\n\nexport { defaultAttributes as default };\n//# sourceMappingURL=defaultAttributes.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst hasA11yProp = (props) => {\n for (const prop in props) {\n if (prop.startsWith(\"aria-\") || prop === \"role\" || prop === \"title\") {\n return true;\n }\n }\n return false;\n};\n\nexport { hasA11yProp };\n//# sourceMappingURL=hasA11yProp.js.map\n","\"use strict\";\n\"use client\";\n/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { createContext, useContext, useMemo, createElement } from 'react';\n\nconst LucideContext = createContext({});\nfunction LucideProvider({\n children,\n size,\n color,\n strokeWidth,\n absoluteStrokeWidth,\n className\n}) {\n const value = useMemo(\n () => ({\n size,\n color,\n strokeWidth,\n absoluteStrokeWidth,\n className\n }),\n [size, color, strokeWidth, absoluteStrokeWidth, className]\n );\n return createElement(LucideContext.Provider, { value }, children);\n}\nconst useLucideContext = () => useContext(LucideContext);\n\nexport { LucideProvider, useLucideContext };\n//# sourceMappingURL=context.js.map\n","\"use strict\";\n\"use client\";\n/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes.js';\nimport { hasA11yProp } from './shared/src/utils/hasA11yProp.js';\nimport { mergeClasses } from './shared/src/utils/mergeClasses.js';\nimport { useLucideContext } from './context.js';\n\nconst Icon = forwardRef(\n ({ color, size, strokeWidth, absoluteStrokeWidth, className = \"\", children, iconNode, ...rest }, ref) => {\n const {\n size: contextSize = 24,\n strokeWidth: contextStrokeWidth = 2,\n absoluteStrokeWidth: contextAbsoluteStrokeWidth = false,\n color: contextColor = \"currentColor\",\n className: contextClass = \"\"\n } = useLucideContext() ?? {};\n const calculatedStrokeWidth = absoluteStrokeWidth ?? contextAbsoluteStrokeWidth ? Number(strokeWidth ?? contextStrokeWidth) * 24 / Number(size ?? contextSize) : strokeWidth ?? contextStrokeWidth;\n return createElement(\n \"svg\",\n {\n ref,\n ...defaultAttributes,\n width: size ?? contextSize ?? defaultAttributes.width,\n height: size ?? contextSize ?? defaultAttributes.height,\n stroke: color ?? contextColor,\n strokeWidth: calculatedStrokeWidth,\n className: mergeClasses(\"lucide\", contextClass, className),\n ...!children && !hasA11yProp(rest) && { \"aria-hidden\": \"true\" },\n ...rest\n },\n [\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...Array.isArray(children) ? children : [children]\n ]\n );\n }\n);\n\nexport { Icon as default };\n//# sourceMappingURL=Icon.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport { mergeClasses } from './shared/src/utils/mergeClasses.js';\nimport { toKebabCase } from './shared/src/utils/toKebabCase.js';\nimport { toPascalCase } from './shared/src/utils/toPascalCase.js';\nimport Icon from './Icon.js';\n\nconst createLucideIcon = (iconName, iconNode) => {\n const Component = forwardRef(\n ({ className, ...props }, ref) => createElement(Icon, {\n ref,\n iconNode,\n className: mergeClasses(\n `lucide-${toKebabCase(toPascalCase(iconName))}`,\n `lucide-${iconName}`,\n className\n ),\n ...props\n })\n );\n Component.displayName = toPascalCase(iconName);\n return Component;\n};\n\nexport { createLucideIcon as default };\n//# sourceMappingURL=createLucideIcon.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [[\"path\", { d: \"m6 9 6 6 6-6\", key: \"qrunsl\" }]];\nconst ChevronDown = createLucideIcon(\"chevron-down\", __iconNode);\n\nexport { __iconNode, ChevronDown as default };\n//# sourceMappingURL=chevron-down.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M12 15V3\", key: \"m9g1x1\" }],\n [\"path\", { d: \"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\", key: \"ih7n3h\" }],\n [\"path\", { d: \"m7 10 5 5 5-5\", key: \"brsn70\" }]\n];\nconst Download = createLucideIcon(\"download\", __iconNode);\n\nexport { __iconNode, Download as default };\n//# sourceMappingURL=download.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\n \"path\",\n {\n d: \"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551\",\n key: \"1miecu\"\n }\n ]\n];\nconst Paperclip = createLucideIcon(\"paperclip\", __iconNode);\n\nexport { __iconNode, Paperclip as default };\n//# sourceMappingURL=paperclip.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7\", key: \"1m0v6g\" }],\n [\n \"path\",\n {\n d: \"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z\",\n key: \"ohrbg2\"\n }\n ]\n];\nconst SquarePen = createLucideIcon(\"square-pen\", __iconNode);\n\nexport { __iconNode, SquarePen as default };\n//# sourceMappingURL=square-pen.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M18 6 6 18\", key: \"1bl5f8\" }],\n [\"path\", { d: \"m6 6 12 12\", key: \"d8bk6v\" }]\n];\nconst X = createLucideIcon(\"x\", __iconNode);\n\nexport { __iconNode, X as default };\n//# sourceMappingURL=x.js.map\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen';\n\nexport type QuerySerializer = (query: Record<string, unknown>) => string;\n\nexport type BodySerializer = (body: unknown) => unknown;\n\ntype QuerySerializerOptionsObject = {\n allowReserved?: boolean;\n array?: Partial<SerializerOptions<ArrayStyle>>;\n object?: Partial<SerializerOptions<ObjectStyle>>;\n};\n\nexport type QuerySerializerOptions = QuerySerializerOptionsObject & {\n /**\n * Per-parameter serialization overrides. When provided, these settings\n * override the global array/object settings for specific parameter names.\n */\n parameters?: Record<string, QuerySerializerOptionsObject>;\n};\n\nconst serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {\n if (typeof value === 'string' || value instanceof Blob) {\n data.append(key, value);\n } else if (value instanceof Date) {\n data.append(key, value.toISOString());\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nconst serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {\n if (typeof value === 'string') {\n data.append(key, value);\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nexport const formDataBodySerializer = {\n bodySerializer: (body: unknown): FormData => {\n const data = new FormData();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeFormDataPair(data, key, v));\n } else {\n serializeFormDataPair(data, key, value);\n }\n });\n\n return data;\n },\n};\n\nexport const jsonBodySerializer = {\n bodySerializer: (body: unknown): string =>\n JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),\n};\n\nexport const urlSearchParamsBodySerializer = {\n bodySerializer: (body: unknown): string => {\n const data = new URLSearchParams();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));\n } else {\n serializeUrlSearchParamsPair(data, key, value);\n }\n });\n\n return data.toString();\n },\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\ntype Slot = 'body' | 'headers' | 'path' | 'query';\n\nexport type Field =\n | {\n in: Exclude<Slot, 'body'>;\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If omitted, we use the same value as `key`.\n */\n map?: string;\n }\n | {\n in: Extract<Slot, 'body'>;\n /**\n * Key isn't required for bodies.\n */\n key?: string;\n map?: string;\n }\n | {\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If `in` is omitted, `map` aliases `key` to the transport layer.\n */\n map: Slot;\n };\n\nexport interface Fields {\n allowExtra?: Partial<Record<Slot, boolean>>;\n args?: ReadonlyArray<Field>;\n}\n\nexport type FieldsConfig = ReadonlyArray<Field | Fields>;\n\nconst extraPrefixesMap: Record<string, Slot> = {\n $body_: 'body',\n $headers_: 'headers',\n $path_: 'path',\n $query_: 'query',\n};\nconst extraPrefixes = Object.entries(extraPrefixesMap);\n\ntype KeyMap = Map<\n string,\n | {\n in: Slot;\n map?: string;\n }\n | {\n in?: never;\n map: Slot;\n }\n>;\n\nconst buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {\n if (!map) {\n map = new Map();\n }\n\n for (const config of fields) {\n if ('in' in config) {\n if (config.key) {\n map.set(config.key, {\n in: config.in,\n map: config.map,\n });\n }\n } else if ('key' in config) {\n map.set(config.key, {\n map: config.map,\n });\n } else if (config.args) {\n buildKeyMap(config.args, map);\n }\n }\n\n return map;\n};\n\ninterface Params {\n body: unknown;\n headers: Record<string, unknown>;\n path: Record<string, unknown>;\n query: Record<string, unknown>;\n}\n\nconst stripEmptySlots = (params: Params) => {\n for (const [slot, value] of Object.entries(params)) {\n if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {\n delete params[slot as Slot];\n }\n }\n};\n\nexport const buildClientParams = (args: ReadonlyArray<unknown>, fields: FieldsConfig) => {\n const params: Params = {\n body: {},\n headers: {},\n path: {},\n query: {},\n };\n\n const map = buildKeyMap(fields);\n\n let config: FieldsConfig[number] | undefined;\n\n for (const [index, arg] of args.entries()) {\n if (fields[index]) {\n config = fields[index];\n }\n\n if (!config) {\n continue;\n }\n\n if ('in' in config) {\n if (config.key) {\n const field = map.get(config.key)!;\n const name = field.map || config.key;\n if (field.in) {\n (params[field.in] as Record<string, unknown>)[name] = arg;\n }\n } else {\n params.body = arg;\n }\n } else {\n for (const [key, value] of Object.entries(arg ?? {})) {\n const field = map.get(key);\n\n if (field) {\n if (field.in) {\n const name = field.map || key;\n (params[field.in] as Record<string, unknown>)[name] = value;\n } else {\n params[field.map] = value;\n }\n } else {\n const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));\n\n if (extra) {\n const [prefix, slot] = extra;\n (params[slot] as Record<string, unknown>)[key.slice(prefix.length)] = value;\n } else if ('allowExtra' in config && config.allowExtra) {\n for (const [slot, allowed] of Object.entries(config.allowExtra)) {\n if (allowed) {\n (params[slot as Slot] as Record<string, unknown>)[key] = value;\n break;\n }\n }\n }\n }\n }\n }\n }\n\n stripEmptySlots(params);\n\n return params;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { Config } from './types.gen';\n\nexport type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &\n Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {\n /**\n * Fetch API implementation. You can use this option to provide a custom\n * fetch instance.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * Implementing clients can call request interceptors inside this hook.\n */\n onRequest?: (url: string, init: RequestInit) => Promise<Request>;\n /**\n * Callback invoked when a network or parsing error occurs during streaming.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param error The error that occurred.\n */\n onSseError?: (error: unknown) => void;\n /**\n * Callback invoked when an event is streamed from the server.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param event Event streamed from the server.\n * @returns Nothing (void).\n */\n onSseEvent?: (event: StreamEvent<TData>) => void;\n serializedBody?: RequestInit['body'];\n /**\n * Default retry delay in milliseconds.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 3000\n */\n sseDefaultRetryDelay?: number;\n /**\n * Maximum number of retry attempts before giving up.\n */\n sseMaxRetryAttempts?: number;\n /**\n * Maximum retry delay in milliseconds.\n *\n * Applies only when exponential backoff is used.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 30000\n */\n sseMaxRetryDelay?: number;\n /**\n * Optional sleep function for retry backoff.\n *\n * Defaults to using `setTimeout`.\n */\n sseSleepFn?: (ms: number) => Promise<void>;\n url: string;\n };\n\nexport interface StreamEvent<TData = unknown> {\n data: TData;\n event?: string;\n id?: string;\n retry?: number;\n}\n\nexport type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {\n stream: AsyncGenerator<\n TData extends Record<string, unknown> ? TData[keyof TData] : TData,\n TReturn,\n TNext\n >;\n};\n\nexport function createSseClient<TData = unknown>({\n onRequest,\n onSseError,\n onSseEvent,\n responseTransformer,\n responseValidator,\n sseDefaultRetryDelay,\n sseMaxRetryAttempts,\n sseMaxRetryDelay,\n sseSleepFn,\n url,\n ...options\n}: ServerSentEventsOptions): ServerSentEventsResult<TData> {\n let lastEventId: string | undefined;\n\n const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n\n const createStream = async function* () {\n let retryDelay: number = sseDefaultRetryDelay ?? 3000;\n let attempt = 0;\n const signal = options.signal ?? new AbortController().signal;\n\n while (true) {\n if (signal.aborted) break;\n\n attempt++;\n\n const headers =\n options.headers instanceof Headers\n ? options.headers\n : new Headers(options.headers as Record<string, string> | undefined);\n\n if (lastEventId !== undefined) {\n headers.set('Last-Event-ID', lastEventId);\n }\n\n try {\n const requestInit: RequestInit = {\n redirect: 'follow',\n ...options,\n body: options.serializedBody,\n headers,\n signal,\n };\n let request = new Request(url, requestInit);\n if (onRequest) {\n request = await onRequest(url, requestInit);\n }\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = options.fetch ?? globalThis.fetch;\n const response = await _fetch(request);\n\n if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);\n\n if (!response.body) throw new Error('No body in SSE response');\n\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n\n let buffer = '';\n\n const abortHandler = () => {\n try {\n reader.cancel();\n } catch {\n // noop\n }\n };\n\n signal.addEventListener('abort', abortHandler);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += value;\n buffer = buffer.replace(/\\r\\n?/g, '\\n'); // normalize line endings\n\n const chunks = buffer.split('\\n\\n');\n buffer = chunks.pop() ?? '';\n\n for (const chunk of chunks) {\n const lines = chunk.split('\\n');\n const dataLines: Array<string> = [];\n let eventName: string | undefined;\n\n for (const line of lines) {\n if (line.startsWith('data:')) {\n dataLines.push(line.replace(/^data:\\s*/, ''));\n } else if (line.startsWith('event:')) {\n eventName = line.replace(/^event:\\s*/, '');\n } else if (line.startsWith('id:')) {\n lastEventId = line.replace(/^id:\\s*/, '');\n } else if (line.startsWith('retry:')) {\n const parsed = Number.parseInt(line.replace(/^retry:\\s*/, ''), 10);\n if (!Number.isNaN(parsed)) {\n retryDelay = parsed;\n }\n }\n }\n\n let data: unknown;\n let parsedJson = false;\n\n if (dataLines.length) {\n const rawData = dataLines.join('\\n');\n try {\n data = JSON.parse(rawData);\n parsedJson = true;\n } catch {\n data = rawData;\n }\n }\n\n if (parsedJson) {\n if (responseValidator) {\n await responseValidator(data);\n }\n\n if (responseTransformer) {\n data = await responseTransformer(data);\n }\n }\n\n onSseEvent?.({\n data,\n event: eventName,\n id: lastEventId,\n retry: retryDelay,\n });\n\n if (dataLines.length) {\n yield data as any;\n }\n }\n }\n } finally {\n signal.removeEventListener('abort', abortHandler);\n reader.releaseLock();\n }\n\n break; // exit loop on normal completion\n } catch (error) {\n // connection failed or aborted; retry after delay\n onSseError?.(error);\n\n if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {\n break; // stop after firing error\n }\n\n // exponential backoff: double retry each attempt, cap at 30s\n const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);\n await sleep(backoff);\n }\n }\n };\n\n const stream = createStream();\n\n return { stream };\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\ninterface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}\n\ninterface SerializePrimitiveOptions {\n allowReserved?: boolean;\n name: string;\n}\n\nexport interface SerializerOptions<T> {\n /**\n * @default true\n */\n explode: boolean;\n style: T;\n}\n\nexport type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';\nexport type ArraySeparatorStyle = ArrayStyle | MatrixStyle;\ntype MatrixStyle = 'label' | 'matrix' | 'simple';\nexport type ObjectStyle = 'form' | 'deepObject';\ntype ObjectSeparatorStyle = ObjectStyle | MatrixStyle;\n\ninterface SerializePrimitiveParam extends SerializePrimitiveOptions {\n value: string;\n}\n\nexport const separatorArrayExplode = (style: ArraySeparatorStyle) => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {\n switch (style) {\n case 'form':\n return ',';\n case 'pipeDelimited':\n return '|';\n case 'spaceDelimited':\n return '%20';\n default:\n return ',';\n }\n};\n\nexport const separatorObjectExplode = (style: ObjectSeparatorStyle) => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const serializeArrayParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n}: SerializeOptions<ArraySeparatorStyle> & {\n value: unknown[];\n}) => {\n if (!explode) {\n const joinedValues = (\n allowReserved ? value : value.map((v) => encodeURIComponent(v as string))\n ).join(separatorArrayNoExplode(style));\n switch (style) {\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n case 'simple':\n return joinedValues;\n default:\n return `${name}=${joinedValues}`;\n }\n }\n\n const separator = separatorArrayExplode(style);\n const joinedValues = value\n .map((v) => {\n if (style === 'label' || style === 'simple') {\n return allowReserved ? v : encodeURIComponent(v as string);\n }\n\n return serializePrimitiveParam({\n allowReserved,\n name,\n value: v as string,\n });\n })\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n\nexport const serializePrimitiveParam = ({\n allowReserved,\n name,\n value,\n}: SerializePrimitiveParam) => {\n if (value === undefined || value === null) {\n return '';\n }\n\n if (typeof value === 'object') {\n throw new Error(\n 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',\n );\n }\n\n return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;\n};\n\nexport const serializeObjectParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n valueOnly,\n}: SerializeOptions<ObjectSeparatorStyle> & {\n value: Record<string, unknown> | Date;\n valueOnly?: boolean;\n}) => {\n if (value instanceof Date) {\n return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;\n }\n\n if (style !== 'deepObject' && !explode) {\n let values: string[] = [];\n Object.entries(value).forEach(([key, v]) => {\n values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];\n });\n const joinedValues = values.join(',');\n switch (style) {\n case 'form':\n return `${name}=${joinedValues}`;\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n default:\n return joinedValues;\n }\n }\n\n const separator = separatorObjectExplode(style);\n const joinedValues = Object.entries(value)\n .map(([key, v]) =>\n serializePrimitiveParam({\n allowReserved,\n name: style === 'deepObject' ? `${name}[${key}]` : key,\n value: v as string,\n }),\n )\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { BodySerializer, QuerySerializer } from './bodySerializer.gen';\nimport {\n type ArraySeparatorStyle,\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from './pathSerializer.gen';\n\nexport interface PathSerializer {\n path: Record<string, unknown>;\n url: string;\n}\n\nexport const PATH_PARAM_RE = /\\{[^{}]+\\}/g;\n\nexport const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {\n let url = _url;\n const matches = _url.match(PATH_PARAM_RE);\n if (matches) {\n for (const match of matches) {\n let explode = false;\n let name = match.substring(1, match.length - 1);\n let style: ArraySeparatorStyle = 'simple';\n\n if (name.endsWith('*')) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n\n if (name.startsWith('.')) {\n name = name.substring(1);\n style = 'label';\n } else if (name.startsWith(';')) {\n name = name.substring(1);\n style = 'matrix';\n }\n\n const value = path[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n url = url.replace(match, serializeArrayParam({ explode, name, style, value }));\n continue;\n }\n\n if (typeof value === 'object') {\n url = url.replace(\n match,\n serializeObjectParam({\n explode,\n name,\n style,\n value: value as Record<string, unknown>,\n valueOnly: true,\n }),\n );\n continue;\n }\n\n if (style === 'matrix') {\n url = url.replace(\n match,\n `;${serializePrimitiveParam({\n name,\n value: value as string,\n })}`,\n );\n continue;\n }\n\n const replaceValue = encodeURIComponent(\n style === 'label' ? `.${value as string}` : (value as string),\n );\n url = url.replace(match, replaceValue);\n }\n }\n return url;\n};\n\nexport const getUrl = ({\n baseUrl,\n path,\n query,\n querySerializer,\n url: _url,\n}: {\n baseUrl?: string;\n path?: Record<string, unknown>;\n query?: Record<string, unknown>;\n querySerializer: QuerySerializer;\n url: string;\n}) => {\n const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;\n let url = (baseUrl ?? '') + pathUrl;\n if (path) {\n url = defaultPathSerializer({ path, url });\n }\n let search = query ? querySerializer(query) : '';\n if (search.startsWith('?')) {\n search = search.substring(1);\n }\n if (search) {\n url += `?${search}`;\n }\n return url;\n};\n\nexport function getValidRequestBody(options: {\n body?: unknown;\n bodySerializer?: BodySerializer | null;\n serializedBody?: unknown;\n}) {\n const hasBody = options.body !== undefined;\n const isSerializedBody = hasBody && options.bodySerializer;\n\n if (isSerializedBody) {\n if ('serializedBody' in options) {\n const hasSerializedBody =\n options.serializedBody !== undefined && options.serializedBody !== '';\n\n return hasSerializedBody ? options.serializedBody : null;\n }\n\n // not all clients implement a serializedBody property (i.e., client-axios)\n return options.body !== '' ? options.body : null;\n }\n\n // plain/text body\n if (hasBody) {\n return options.body;\n }\n\n // no body was provided\n return undefined;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nexport type AuthToken = string | undefined;\n\nexport interface Auth {\n /**\n * Which part of the request do we use to send the auth?\n *\n * @default 'header'\n */\n in?: 'header' | 'query' | 'cookie';\n /**\n * Header or query parameter name.\n *\n * @default 'Authorization'\n */\n name?: string;\n scheme?: 'basic' | 'bearer';\n type: 'apiKey' | 'http';\n}\n\nexport const getAuthToken = async (\n auth: Auth,\n callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,\n): Promise<string | undefined> => {\n const token = typeof callback === 'function' ? await callback(auth) : callback;\n\n if (!token) {\n return;\n }\n\n if (auth.scheme === 'bearer') {\n return `Bearer ${token}`;\n }\n\n if (auth.scheme === 'basic') {\n return `Basic ${btoa(token)}`;\n }\n\n return token;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { getAuthToken } from '../core/auth.gen';\nimport type { QuerySerializerOptions } from '../core/bodySerializer.gen';\nimport { jsonBodySerializer } from '../core/bodySerializer.gen';\nimport {\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from '../core/pathSerializer.gen';\nimport { getUrl } from '../core/utils.gen';\nimport type { Client, ClientOptions, Config, RequestOptions } from './types.gen';\n\nexport const createQuerySerializer = <T = unknown>({\n parameters = {},\n ...args\n}: QuerySerializerOptions = {}) => {\n const querySerializer = (queryParams: T) => {\n const search: string[] = [];\n if (queryParams && typeof queryParams === 'object') {\n for (const name in queryParams) {\n const value = queryParams[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n const options = parameters[name] || args;\n\n if (Array.isArray(value)) {\n const serializedArray = serializeArrayParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'form',\n value,\n ...options.array,\n });\n if (serializedArray) search.push(serializedArray);\n } else if (typeof value === 'object') {\n const serializedObject = serializeObjectParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'deepObject',\n value: value as Record<string, unknown>,\n ...options.object,\n });\n if (serializedObject) search.push(serializedObject);\n } else {\n const serializedPrimitive = serializePrimitiveParam({\n allowReserved: options.allowReserved,\n name,\n value: value as string,\n });\n if (serializedPrimitive) search.push(serializedPrimitive);\n }\n }\n }\n return search.join('&');\n };\n return querySerializer;\n};\n\n/**\n * Infers parseAs value from provided Content-Type header.\n */\nexport const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {\n if (!contentType) {\n // If no Content-Type header is provided, the best we can do is return the raw response body,\n // which is effectively the same as the 'stream' option.\n return 'stream';\n }\n\n const cleanContent = contentType.split(';')[0]?.trim();\n\n if (!cleanContent) {\n return;\n }\n\n if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {\n return 'json';\n }\n\n if (cleanContent === 'multipart/form-data') {\n return 'formData';\n }\n\n if (\n ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))\n ) {\n return 'blob';\n }\n\n if (cleanContent.startsWith('text/')) {\n return 'text';\n }\n\n return;\n};\n\nconst checkForExistence = (\n options: Pick<RequestOptions, 'auth' | 'query'> & {\n headers: Headers;\n },\n name?: string,\n): boolean => {\n if (!name) {\n return false;\n }\n if (\n options.headers.has(name) ||\n options.query?.[name] ||\n options.headers.get('Cookie')?.includes(`${name}=`)\n ) {\n return true;\n }\n return false;\n};\n\nexport const setAuthParams = async ({\n security,\n ...options\n}: Pick<Required<RequestOptions>, 'security'> &\n Pick<RequestOptions, 'auth' | 'query'> & {\n headers: Headers;\n }) => {\n for (const auth of security) {\n if (checkForExistence(options, auth.name)) {\n continue;\n }\n\n const token = await getAuthToken(auth, options.auth);\n\n if (!token) {\n continue;\n }\n\n const name = auth.name ?? 'Authorization';\n\n switch (auth.in) {\n case 'query':\n if (!options.query) {\n options.query = {};\n }\n options.query[name] = token;\n break;\n case 'cookie':\n options.headers.append('Cookie', `${name}=${token}`);\n break;\n case 'header':\n default:\n options.headers.set(name, token);\n break;\n }\n }\n};\n\nexport const buildUrl: Client['buildUrl'] = (options) =>\n getUrl({\n baseUrl: options.baseUrl as string,\n path: options.path,\n query: options.query,\n querySerializer:\n typeof options.querySerializer === 'function'\n ? options.querySerializer\n : createQuerySerializer(options.querySerializer),\n url: options.url,\n });\n\nexport const mergeConfigs = (a: Config, b: Config): Config => {\n const config = { ...a, ...b };\n if (config.baseUrl?.endsWith('/')) {\n config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);\n }\n config.headers = mergeHeaders(a.headers, b.headers);\n return config;\n};\n\nconst headersEntries = (headers: Headers): Array<[string, string]> => {\n const entries: Array<[string, string]> = [];\n headers.forEach((value, key) => {\n entries.push([key, value]);\n });\n return entries;\n};\n\nexport const mergeHeaders = (\n ...headers: Array<Required<Config>['headers'] | undefined>\n): Headers => {\n const mergedHeaders = new Headers();\n for (const header of headers) {\n if (!header) {\n continue;\n }\n\n const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);\n\n for (const [key, value] of iterator) {\n if (value === null) {\n mergedHeaders.delete(key);\n } else if (Array.isArray(value)) {\n for (const v of value) {\n mergedHeaders.append(key, v as string);\n }\n } else if (value !== undefined) {\n // assume object headers are meant to be JSON stringified, i.e., their\n // content value in OpenAPI specification is 'application/json'\n mergedHeaders.set(\n key,\n typeof value === 'object' ? JSON.stringify(value) : (value as string),\n );\n }\n }\n }\n return mergedHeaders;\n};\n\ntype ErrInterceptor<Err, Res, Req, Options> = (\n error: Err,\n response: Res,\n request: Req,\n options: Options,\n) => Err | Promise<Err>;\n\ntype ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;\n\ntype ResInterceptor<Res, Req, Options> = (\n response: Res,\n request: Req,\n options: Options,\n) => Res | Promise<Res>;\n\nclass Interceptors<Interceptor> {\n fns: Array<Interceptor | null> = [];\n\n clear(): void {\n this.fns = [];\n }\n\n eject(id: number | Interceptor): void {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = null;\n }\n }\n\n exists(id: number | Interceptor): boolean {\n const index = this.getInterceptorIndex(id);\n return Boolean(this.fns[index]);\n }\n\n getInterceptorIndex(id: number | Interceptor): number {\n if (typeof id === 'number') {\n return this.fns[id] ? id : -1;\n }\n return this.fns.indexOf(id);\n }\n\n update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = fn;\n return id;\n }\n return false;\n }\n\n use(fn: Interceptor): number {\n this.fns.push(fn);\n return this.fns.length - 1;\n }\n}\n\nexport interface Middleware<Req, Res, Err, Options> {\n error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;\n request: Interceptors<ReqInterceptor<Req, Options>>;\n response: Interceptors<ResInterceptor<Res, Req, Options>>;\n}\n\nexport const createInterceptors = <Req, Res, Err, Options>(): Middleware<\n Req,\n Res,\n Err,\n Options\n> => ({\n error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),\n request: new Interceptors<ReqInterceptor<Req, Options>>(),\n response: new Interceptors<ResInterceptor<Res, Req, Options>>(),\n});\n\nconst defaultQuerySerializer = createQuerySerializer({\n allowReserved: false,\n array: {\n explode: true,\n style: 'form',\n },\n object: {\n explode: true,\n style: 'deepObject',\n },\n});\n\nconst defaultHeaders = {\n 'Content-Type': 'application/json',\n};\n\nexport const createConfig = <T extends ClientOptions = ClientOptions>(\n override: Config<Omit<ClientOptions, keyof T> & T> = {},\n): Config<Omit<ClientOptions, keyof T> & T> => ({\n ...jsonBodySerializer,\n headers: defaultHeaders,\n parseAs: 'auto',\n querySerializer: defaultQuerySerializer,\n ...override,\n});\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { createSseClient } from '../core/serverSentEvents.gen';\nimport type { HttpMethod } from '../core/types.gen';\nimport { getValidRequestBody } from '../core/utils.gen';\nimport type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen';\nimport {\n buildUrl,\n createConfig,\n createInterceptors,\n getParseAs,\n mergeConfigs,\n mergeHeaders,\n setAuthParams,\n} from './utils.gen';\n\ntype ReqInit = Omit<RequestInit, 'body' | 'headers'> & {\n body?: any;\n headers: ReturnType<typeof mergeHeaders>;\n};\n\nexport const createClient = (config: Config = {}): Client => {\n let _config = mergeConfigs(createConfig(), config);\n\n const getConfig = (): Config => ({ ..._config });\n\n const setConfig = (config: Config): Config => {\n _config = mergeConfigs(_config, config);\n return getConfig();\n };\n\n const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();\n\n const beforeRequest = async <\n TData = unknown,\n TResponseStyle extends 'data' | 'fields' = 'fields',\n ThrowOnError extends boolean = boolean,\n Url extends string = string,\n >(\n options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,\n ) => {\n const opts = {\n ..._config,\n ...options,\n fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,\n headers: mergeHeaders(_config.headers, options.headers),\n serializedBody: undefined as string | undefined,\n };\n\n if (opts.security) {\n await setAuthParams({\n ...opts,\n security: opts.security,\n });\n }\n\n if (opts.requestValidator) {\n await opts.requestValidator(opts);\n }\n\n if (opts.body !== undefined && opts.bodySerializer) {\n opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;\n }\n\n // remove Content-Type header if body is empty to avoid sending invalid requests\n if (opts.body === undefined || opts.serializedBody === '') {\n opts.headers.delete('Content-Type');\n }\n\n const resolvedOpts = opts as typeof opts &\n ResolvedRequestOptions<TResponseStyle, ThrowOnError, Url>;\n const url = buildUrl(resolvedOpts);\n\n return { opts: resolvedOpts, url };\n };\n\n const request: Client['request'] = async (options) => {\n const { opts, url } = await beforeRequest(options);\n const requestInit: ReqInit = {\n redirect: 'follow',\n ...opts,\n body: getValidRequestBody(opts),\n };\n\n let request = new Request(url, requestInit);\n\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = opts.fetch!;\n let response: Response;\n\n try {\n response = await _fetch(request);\n } catch (error) {\n // Handle fetch exceptions (AbortError, network errors, etc.)\n let finalError = error;\n\n for (const fn of interceptors.error.fns) {\n if (fn) {\n finalError = (await fn(error, undefined as any, request, opts)) as unknown;\n }\n }\n\n finalError = finalError || ({} as unknown);\n\n if (opts.throwOnError) {\n throw finalError;\n }\n\n // Return error response\n return opts.responseStyle === 'data'\n ? undefined\n : {\n error: finalError,\n request,\n response: undefined as any,\n };\n }\n\n for (const fn of interceptors.response.fns) {\n if (fn) {\n response = await fn(response, request, opts);\n }\n }\n\n const result = {\n request,\n response,\n };\n\n if (response.ok) {\n const parseAs =\n (opts.parseAs === 'auto'\n ? getParseAs(response.headers.get('Content-Type'))\n : opts.parseAs) ?? 'json';\n\n if (response.status === 204 || response.headers.get('Content-Length') === '0') {\n let emptyData: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'text':\n emptyData = await response[parseAs]();\n break;\n case 'formData':\n emptyData = new FormData();\n break;\n case 'stream':\n emptyData = response.body;\n break;\n case 'json':\n default:\n emptyData = {};\n break;\n }\n return opts.responseStyle === 'data'\n ? emptyData\n : {\n data: emptyData,\n ...result,\n };\n }\n\n let data: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'formData':\n case 'text':\n data = await response[parseAs]();\n break;\n case 'json': {\n // Some servers return 200 with no Content-Length and empty body.\n // response.json() would throw; read as text and parse if non-empty.\n const text = await response.text();\n data = text ? JSON.parse(text) : {};\n break;\n }\n case 'stream':\n return opts.responseStyle === 'data'\n ? response.body\n : {\n data: response.body,\n ...result,\n };\n }\n\n if (parseAs === 'json') {\n if (opts.responseValidator) {\n await opts.responseValidator(data);\n }\n\n if (opts.responseTransformer) {\n data = await opts.responseTransformer(data);\n }\n }\n\n return opts.responseStyle === 'data'\n ? data\n : {\n data,\n ...result,\n };\n }\n\n const textError = await response.text();\n let jsonError: unknown;\n\n try {\n jsonError = JSON.parse(textError);\n } catch {\n // noop\n }\n\n const error = jsonError ?? textError;\n let finalError = error;\n\n for (const fn of interceptors.error.fns) {\n if (fn) {\n finalError = (await fn(error, response, request, opts)) as string;\n }\n }\n\n finalError = finalError || ({} as string);\n\n if (opts.throwOnError) {\n throw finalError;\n }\n\n // TODO: we probably want to return error and improve types\n return opts.responseStyle === 'data'\n ? undefined\n : {\n error: finalError,\n ...result,\n };\n };\n\n const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>\n request({ ...options, method });\n\n const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {\n const { opts, url } = await beforeRequest(options);\n return createSseClient({\n ...opts,\n body: opts.body as BodyInit | null | undefined,\n headers: opts.headers as unknown as Record<string, string>,\n method,\n onRequest: async (url, init) => {\n let request = new Request(url, init);\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n return request;\n },\n serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,\n url,\n });\n };\n\n const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });\n\n return {\n buildUrl: _buildUrl,\n connect: makeMethodFn('CONNECT'),\n delete: makeMethodFn('DELETE'),\n get: makeMethodFn('GET'),\n getConfig,\n head: makeMethodFn('HEAD'),\n interceptors,\n options: makeMethodFn('OPTIONS'),\n patch: makeMethodFn('PATCH'),\n post: makeMethodFn('POST'),\n put: makeMethodFn('PUT'),\n request,\n setConfig,\n sse: {\n connect: makeSseFn('CONNECT'),\n delete: makeSseFn('DELETE'),\n get: makeSseFn('GET'),\n head: makeSseFn('HEAD'),\n options: makeSseFn('OPTIONS'),\n patch: makeSseFn('PATCH'),\n post: makeSseFn('POST'),\n put: makeSseFn('PUT'),\n trace: makeSseFn('TRACE'),\n },\n trace: makeMethodFn('TRACE'),\n } as Client;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type ClientOptions, type Config, createClient, createConfig } from './client';\nimport type { ClientOptions as ClientOptions2 } from './types.gen';\n\n/**\n * The `createClientConfig()` function will be called on client initialization\n * and the returned object will become the client's initial configuration.\n *\n * You may want to initialize your client this way instead of calling\n * `setConfig()`. This is useful for example if you're using Next.js\n * to ensure your client always has the correct values.\n */\nexport type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;\n\nexport const client = createClient(createConfig<ClientOptions2>({ baseUrl: 'http://localhost:9000/api/widget' }));\n","import { client } from './v1/client.gen';\n\nexport function setupWidgetClient(widgetUrl: string, widgetToken?: string) {\n client.setConfig({\n baseUrl: widgetUrl,\n headers: widgetToken\n ? {\n Authorization: `Bearer ${widgetToken}`,\n }\n : undefined,\n });\n}\n\nexport { client };\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client';\nimport { client } from './client.gen';\nimport type { DownloadWidgetAttachmentData, DownloadWidgetAttachmentErrors, DownloadWidgetAttachmentResponses, GetWidgetThreadData, GetWidgetThreadErrors, GetWidgetThreadResponses, ListWidgetThreadsData, ListWidgetThreadsErrors, ListWidgetThreadsResponses, UploadWidgetAttachmentData, UploadWidgetAttachmentErrors, UploadWidgetAttachmentResponses, WidgetLoginData, WidgetLoginErrors, WidgetLoginResponses } from './types.gen';\n\nexport type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {\n /**\n * You can provide a client instance returned by `createClient()` instead of\n * individual options. This might be also useful if you want to implement a\n * custom client.\n */\n client?: Client;\n /**\n * You can pass arbitrary values through the `meta` object. This can be\n * used to access values that aren't defined as part of the SDK function.\n */\n meta?: Record<string, unknown>;\n};\n\n/**\n * Widget authentication\n */\nexport const widgetLogin = <ThrowOnError extends boolean = false>(options: Options<WidgetLoginData, ThrowOnError>) => (options.client ?? client).post<WidgetLoginResponses, WidgetLoginErrors, ThrowOnError>({\n url: '/login',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * List user threads\n */\nexport const listWidgetThreads = <ThrowOnError extends boolean = false>(options?: Options<ListWidgetThreadsData, ThrowOnError>) => (options?.client ?? client).get<ListWidgetThreadsResponses, ListWidgetThreadsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/threads',\n ...options\n});\n\n/**\n * Get thread details\n */\nexport const getWidgetThread = <ThrowOnError extends boolean = false>(options: Options<GetWidgetThreadData, ThrowOnError>) => (options.client ?? client).get<GetWidgetThreadResponses, GetWidgetThreadErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/threads/{threadUid}',\n ...options\n});\n\n/**\n * Upload attachment\n */\nexport const uploadWidgetAttachment = <ThrowOnError extends boolean = false>(options: Options<UploadWidgetAttachmentData, ThrowOnError>) => (options.client ?? client).post<UploadWidgetAttachmentResponses, UploadWidgetAttachmentErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/attachments/upload',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * Download attachment\n */\nexport const downloadWidgetAttachment = <ThrowOnError extends boolean = false>(options: Options<DownloadWidgetAttachmentData, ThrowOnError>) => (options.client ?? client).get<DownloadWidgetAttachmentResponses, DownloadWidgetAttachmentErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/attachments/{filename}',\n ...options\n});\n","import '../shared/api/setup';\nimport {\n uploadWidgetAttachment,\n downloadWidgetAttachment,\n} from '../shared/api/v1/sdk.gen';\nimport type { AttachmentResponse } from '@/shared/api/v1/types.gen';\n\nexport type { AttachmentResponse };\n\nexport const attachmentApi = {\n upload: async (\n file: File,\n prefix: string,\n ocr?: boolean\n ): Promise<AttachmentResponse> => {\n const { data } = await uploadWidgetAttachment({\n body: { file, prefix, ocr },\n throwOnError: true,\n });\n return data!.data!;\n },\n\n download: async (\n filePath: string,\n originalName: string\n ): Promise<void> => {\n const parts = filePath.split('/');\n const filename = parts[parts.length - 1];\n const prefix = parts.slice(-3, -1).join('/');\n\n const { data } = await downloadWidgetAttachment({\n path: { filename },\n query: prefix ? { prefix } : {},\n parseAs: 'blob',\n throwOnError: true,\n });\n\n const url = URL.createObjectURL(data as Blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = originalName;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n },\n};\n","import { useState, useEffect, useRef, type KeyboardEvent } from 'react';\nimport type { InputProps } from '@copilotkit/react-ui';\nimport { Paperclip, X, Download } from 'lucide-react';\nimport { attachmentApi, type AttachmentResponse } from '../lib/attachment-api';\n\nexport type AttachedFile = {\n id: string;\n name: string;\n mimeType: string;\n status: 'uploading' | 'done' | 'error';\n response?: AttachmentResponse;\n errorMessage?: string;\n};\n\ntype EricaChatInputProps = InputProps & {\n threadId?: string;\n};\n\nexport function EricaChatInput({\n onSend,\n inProgress,\n threadId,\n}: EricaChatInputProps) {\n const [text, setText] = useState('');\n const [attachedFiles, setAttachedFiles] = useState<AttachedFile[]>([]);\n const [isDraggingOver, setIsDraggingOver] = useState(false);\n const [downloadingFileId, setDownloadingFileId] = useState<string | null>(null);\n \n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const dragCounter = useRef(0);\n\n useEffect(() => {\n const textarea = textareaRef.current;\n if (textarea) {\n textarea.style.height = 'auto';\n const scrollHeight = textarea.scrollHeight;\n textarea.style.height = `${scrollHeight}px`;\n }\n }, [text]);\n\n async function uploadFile(file: File) {\n const id = `${file.name}-${Date.now()}`;\n setAttachedFiles(prev => [\n ...prev,\n {\n id,\n name: file.name,\n mimeType: file.type || 'application/octet-stream',\n status: 'uploading',\n },\n ]);\n\n try {\n const response = await attachmentApi.upload(\n file,\n `thread/${threadId || crypto.randomUUID()}`,\n true\n );\n setAttachedFiles(prev =>\n prev.map(f => (f.id === id ? { ...f, status: 'done', response } : f))\n );\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'Upload failed';\n setAttachedFiles(prev =>\n prev.map(f =>\n f.id === id ? { ...f, status: 'error', errorMessage: msg } : f\n )\n );\n }\n }\n\n function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {\n const files = e.target.files;\n if (!files || files.length === 0) return;\n\n const existingNames = new Set(attachedFiles.map(f => f.name));\n Array.from(files)\n .filter(f => !existingNames.has(f.name))\n .forEach(uploadFile);\n\n e.target.value = '';\n }\n\n function removeFile(id: string) {\n setAttachedFiles(prev => prev.filter(f => f.id !== id));\n }\n\n async function handleDownloadFile(file: AttachedFile) {\n if (!file.response) return;\n \n setDownloadingFileId(file.id);\n try {\n await attachmentApi.download(\n file.response.file_path,\n file.response.original_name\n );\n } catch (err) {\n console.error('Download failed:', err);\n alert(`Failed to download ${file.name}`);\n } finally {\n setDownloadingFileId(null);\n }\n }\n\n function handleDragEnter(e: React.DragEvent) {\n e.preventDefault();\n dragCounter.current += 1;\n if (e.dataTransfer.types.includes('Files')) setIsDraggingOver(true);\n }\n\n function handleDragLeave(e: React.DragEvent) {\n e.preventDefault();\n dragCounter.current -= 1;\n if (dragCounter.current === 0) setIsDraggingOver(false);\n }\n\n function handleDragOver(e: React.DragEvent) {\n e.preventDefault();\n }\n\n function handleDrop(e: React.DragEvent) {\n e.preventDefault();\n dragCounter.current = 0;\n setIsDraggingOver(false);\n \n const files = Array.from(e.dataTransfer.files);\n if (files.length === 0) return;\n\n const existingNames = new Set(attachedFiles.map(f => f.name));\n files.filter(f => !existingNames.has(f.name)).forEach(uploadFile);\n }\n\n function handleSend() {\n if (!text.trim() && attachedFiles.length === 0) return;\n\n const doneAttachments = attachedFiles\n .filter(f => f.status === 'done')\n .filter(f => f.response !== null)\n .map(f => f.response!)\n .map(({ ocr_result, ...rest }) => ({\n ...rest,\n ocr_result: ocr_result?.markdown_files,\n }));\n\n let messageContent = text;\n\n if (doneAttachments.length > 0) {\n messageContent += `\\n\\n\\`\\`\\`attachments\\n${JSON.stringify(doneAttachments, null, 2)}\\n\\`\\`\\``;\n }\n\n onSend(messageContent);\n setText('');\n setAttachedFiles([]);\n }\n\n function handleKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSend();\n }\n }\n\n function handleContainerClick() {\n textareaRef.current?.focus();\n }\n\n return (\n <div\n className=\"copilotKitInputContainer relative\"\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n onDragOver={handleDragOver}\n onDrop={handleDrop}\n >\n {isDraggingOver && (\n <div className=\"absolute inset-0 z-50 bg-teal-50/90 rounded-lg flex items-center justify-center pointer-events-none\">\n <p className=\"text-sm font-medium text-teal-600\">\n Drop files to attach\n </p>\n </div>\n )}\n\n {attachedFiles.length > 0 && (\n <div className=\"flex flex-col gap-2 mb-2\">\n {attachedFiles.map(file => (\n <div\n key={file.id}\n className={`\n px-3 py-2 rounded-lg flex items-center justify-between\n ${file.status === 'error' ? 'bg-red-50' :\n file.status === 'done' ? 'bg-green-50' :\n 'bg-gray-100'}\n `}\n >\n <div\n className={`\n flex items-center gap-2 flex-1 rounded-lg transition-colors\n ${file.status === 'done' ? 'cursor-pointer hover:bg-green-100 -mx-3 -my-2 px-3 py-2' : ''}\n `}\n onClick={() => file.status === 'done' && handleDownloadFile(file)}\n role={file.status === 'done' ? 'button' : undefined}\n tabIndex={file.status === 'done' ? 0 : undefined}\n >\n {file.status === 'uploading' ? (\n <div className=\"w-4 h-4 border-2 border-gray-500 border-t-transparent rounded-full animate-spin\" />\n ) : downloadingFileId === file.id ? (\n <div className=\"w-4 h-4 border-2 border-green-500 border-t-transparent rounded-full animate-spin\" />\n ) : file.status === 'done' ? (\n <Paperclip className=\"w-4 h-4 text-green-600\" />\n ) : (\n <Paperclip className=\"w-4 h-4 text-red-600\" />\n )}\n \n <div className=\"flex-1 min-w-0\">\n <div className={`\n text-sm font-medium truncate\n ${file.status === 'error' ? 'text-red-700' :\n file.status === 'done' ? 'text-green-700' :\n 'text-gray-700'}\n `}>\n {file.name}\n {downloadingFileId === file.id && (\n <span className=\"ml-2 text-xs text-green-600\">Downloading...</span>\n )}\n </div>\n <div className=\"text-xs text-gray-500\">\n {file.status === 'uploading' && 'Uploading...'}\n {file.status === 'done' && 'Ready · Click to download'}\n {file.status === 'error' && (file.errorMessage || 'Upload failed')}\n </div>\n </div>\n\n {file.status === 'done' && !downloadingFileId && (\n <Download className=\"w-4 h-4 text-green-600 opacity-0 group-hover:opacity-100 transition-opacity\" />\n )}\n </div>\n\n <button\n onClick={(e) => {\n e.stopPropagation();\n removeFile(file.id);\n }}\n disabled={file.status === 'uploading'}\n className=\"ml-2 p-1 hover:bg-black/10 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed\"\n aria-label={`Remove ${file.name}`}\n >\n <X className=\"w-4 h-4 text-gray-500\" />\n </button>\n </div>\n ))}\n </div>\n )}\n\n <div className=\"copilotKitInput\" onClick={handleContainerClick}>\n <textarea\n ref={textareaRef}\n value={text}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={handleKeyDown}\n placeholder={\n attachedFiles.length > 0\n ? `Ask about ${attachedFiles.length} file${attachedFiles.length > 1 ? 's' : ''}...`\n : 'Type a message or attach files...'\n }\n className=\"overflow-auto resize-none\"\n rows={1}\n disabled={inProgress}\n />\n <div className=\"copilotKitInputControls\">\n <input\n ref={fileInputRef}\n type=\"file\"\n onChange={handleFileSelect}\n className=\"hidden\"\n disabled={inProgress}\n multiple\n />\n <button\n onClick={() => fileInputRef.current?.click()}\n disabled={inProgress}\n className=\"copilotKitInputControlButton mr-2\"\n aria-label=\"Attach files\"\n title=\"Attach files (drag & drop supported)\"\n >\n <Paperclip className=\"w-5 h-5\" />\n </button>\n <div className=\"grow\"></div>\n <button\n onClick={handleSend}\n disabled={inProgress || (!text.trim() && attachedFiles.filter(f => f.status === 'done').length === 0)}\n data-copilotkit-in-progress={inProgress}\n className=\"copilotKitInputControlButton\"\n >\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth=\"1.5\"\n stroke=\"currentColor\"\n width=\"24\"\n height=\"24\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M12 19V5m0 0l-7 7m7-7l7 7\"\n />\n </svg>\n </button>\n </div>\n </div>\n </div>\n );\n}\n","import '../shared/api/setup';\nimport {\n listWidgetThreads,\n getWidgetThread,\n} from '../shared/api/v1/sdk.gen';\nimport type { ThreadResponse } from '@/shared/api/v1/types.gen';\n\nexport type { ThreadResponse };\n\nexport const threadApi = {\n list: async (limit = 15) => {\n const { data } = await listWidgetThreads({\n query: { page: 1, page_size: limit },\n throwOnError: true,\n });\n return data!.data ?? [];\n },\n\n get: async (threadUid: string) => {\n const { data } = await getWidgetThread({\n path: { threadUid },\n throwOnError: true,\n });\n return data!.data!;\n },\n};\n","import { useQuery } from '@tanstack/react-query';\nimport { threadApi } from '../lib/thread-api';\n\nexport const threadKeys = {\n all: () => ['widget-threads'] as const,\n detail: (threadUid: string) => ['widget-threads', threadUid] as const,\n};\n\nexport const useThreads = (limit = 15) =>\n useQuery({\n queryKey: threadKeys.all(),\n queryFn: () => threadApi.list(limit),\n staleTime: 15_000,\n refetchOnWindowFocus: true,\n });\n\nexport const useThread = (threadUid: string) =>\n useQuery({\n queryKey: threadKeys.detail(threadUid),\n queryFn: () => threadApi.get(threadUid),\n enabled: !!threadUid,\n });\n","import { useState, useRef, useEffect } from 'react';\nimport { PenSquare, ChevronDown } from 'lucide-react';\nimport { useThreads } from '../hooks/use-threads';\nimport type { ThreadResponse } from '../lib/thread-api';\n\ntype EricaChatHeaderProps = {\n onNewChat?: () => void;\n onThreadSelect?: (threadUid: string) => void;\n};\n\nfunction normalizeAgentDisplay(agent: string | null | undefined): string {\n if (!agent) return '';\n const parts = agent.split(':');\n const name = parts.length > 1 ? parts.slice(1).join(' ') : agent;\n return name.replace(/[-_]/g, ' ').replace(/\\b\\w/g, c => c.toUpperCase());\n}\n\nfunction formatRelativeTime(dateStr: string | null | undefined): string {\n if (!dateStr) return '';\n const diffMs = Date.now() - new Date(dateStr).getTime();\n const diffMins = Math.floor(diffMs / 60_000);\n const diffHours = Math.floor(diffMins / 60);\n const diffDays = Math.floor(diffHours / 24);\n if (diffMins < 1) return 'just now';\n if (diffMins < 60) return `${diffMins}m ago`;\n if (diffHours < 24) return `${diffHours}h ago`;\n if (diffDays < 7) return `${diffDays}d ago`;\n return new Date(dateStr).toLocaleDateString();\n}\n\nexport function EricaChatHeader({\n onNewChat,\n onThreadSelect,\n}: EricaChatHeaderProps) {\n const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n const dropdownRef = useRef<HTMLDivElement>(null);\n\n const { data: threads = [], isLoading } = useThreads();\n\n useEffect(() => {\n function handleClickOutside(event: MouseEvent) {\n if (\n dropdownRef.current &&\n !dropdownRef.current.contains(event.target as Node)\n ) {\n setIsDropdownOpen(false);\n }\n }\n\n if (isDropdownOpen) {\n document.addEventListener('mousedown', handleClickOutside);\n return () => {\n document.removeEventListener('mousedown', handleClickOutside);\n };\n }\n }, [isDropdownOpen]);\n\n function handleThreadClick(threadUid: string) {\n setIsDropdownOpen(false);\n onThreadSelect?.(threadUid);\n }\n\n return (\n <div className=\"flex items-center justify-between px-4 py-3 border-b border-gray-200\">\n {/* Left: Title */}\n <h2 className=\"text-lg font-semibold text-gray-900\">\n Erica Assistant\n </h2>\n\n {/* Right: New Chat Button + Threads Dropdown */}\n <div className=\"flex items-center gap-2 relative\" ref={dropdownRef}>\n {/* New Chat Button (icon only) */}\n <button\n onClick={onNewChat}\n className=\"p-2 bg-gray-900 hover:bg-gray-700 text-white rounded-lg transition-colors\"\n title=\"Start new chat\"\n >\n <PenSquare className=\"w-4 h-4\" />\n </button>\n\n {/* Threads Dropdown Toggle */}\n <button\n onClick={() => setIsDropdownOpen(!isDropdownOpen)}\n className=\"flex items-center gap-1.5 px-3 py-2 hover:bg-gray-100 rounded-lg transition-colors\"\n title=\"Recent threads\"\n >\n <span className=\"text-sm font-medium text-gray-700\">\n Threads {threads.length > 0 && `(${threads.length})`}\n </span>\n <ChevronDown\n className={`w-4 h-4 text-gray-500 transition-transform ${\n isDropdownOpen ? 'rotate-180' : ''\n }`}\n />\n </button>\n\n {/* Threads Dropdown Menu */}\n {isDropdownOpen && (\n <div className=\"absolute top-full right-0 mt-1 w-72 bg-white rounded-lg shadow-lg border border-gray-200 z-50 max-h-80 overflow-y-auto\">\n <div className=\"p-2\">\n <div className=\"px-3 py-2 text-xs font-semibold text-gray-500 uppercase\">\n Recent Threads\n </div>\n\n {isLoading && (\n <div className=\"px-3 py-4 text-center text-sm text-gray-500\">\n Loading threads...\n </div>\n )}\n\n {!isLoading && threads.length === 0 && (\n <div className=\"px-3 py-4 text-center text-sm text-gray-500\">\n No conversations yet\n </div>\n )}\n\n {!isLoading &&\n threads.map((thread: ThreadResponse) => {\n const agentLabel = normalizeAgentDisplay(thread.agent);\n const time = formatRelativeTime(\n thread.last_run_at ?? thread.created_at\n );\n const title =\n typeof thread.thread_metadata?.title === 'string'\n ? thread.thread_metadata.title\n : thread.last_message ?? 'New conversation';\n\n return (\n <button\n key={thread.uid}\n onClick={() => handleThreadClick(thread.uid)}\n className=\"w-full text-left px-3 py-2 hover:bg-gray-100 rounded-lg transition-colors\"\n >\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-sm font-medium text-gray-900 truncate\">\n {title}\n </span>\n <div className=\"flex items-center justify-between gap-2\">\n {agentLabel && (\n <span className=\"text-xs text-gray-500 truncate flex-1\">\n {agentLabel}\n </span>\n )}\n {time && (\n <span className=\"text-xs text-gray-400 shrink-0\">\n {time}\n </span>\n )}\n </div>\n </div>\n </button>\n );\n })}\n </div>\n </div>\n )}\n </div>\n </div>\n );\n}\n","import { useCallback, useMemo, useState } from 'react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { CopilotKit } from \"@copilotkit/react-core\";\nimport { CopilotSidebar } from \"@copilotkit/react-ui\";\nimport \"@copilotkit/react-ui/styles.css\";\nimport { EricaChatInput } from './EricaChatInput';\nimport { EricaChatHeader } from './EricaChatHeader';\nimport { setupWidgetClient } from '../shared/api/setup';\nimport type { InputProps } from '@copilotkit/react-ui';\n\nconst queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n refetchOnWindowFocus: false,\n retry: 1,\n staleTime: 30_000,\n },\n },\n});\n\nexport interface EricaChatProps {\n runtimeUrl: string;\n widgetToken: string;\n}\n\nexport function EricaChat({\n runtimeUrl,\n widgetToken,\n}: EricaChatProps) {\n const [threadId, setThreadId] = useState<string | undefined>(undefined);\n\n // Extract base widget URL (remove accountUid path for widget API)\n const widgetBaseUrl = useMemo(() => {\n // runtimeUrl format: http://localhost:9000/api/widget/{accountUid}\n // We need: http://localhost:9000/api/widget\n const url = new URL(runtimeUrl);\n const pathParts = url.pathname.split('/').filter(Boolean);\n // Remove last part (accountUid) if present\n if (pathParts.length > 2) {\n pathParts.pop();\n }\n url.pathname = '/' + pathParts.join('/');\n return url.toString();\n }, [runtimeUrl]);\n\n // Setup client immediately before any render\n useMemo(() => {\n setupWidgetClient(widgetBaseUrl, widgetToken);\n }, [widgetBaseUrl, widgetToken]);\n\n const handleNewChat = useCallback(() => {\n setThreadId(undefined);\n console.log('New chat started');\n }, []);\n\n const handleThreadSelect = useCallback((threadUid: string) => {\n setThreadId(threadUid);\n console.log('Thread selected:', threadUid);\n }, []);\n\n const EricaChatInputWrapper = useCallback(\n (props: InputProps) => (\n <EricaChatInput {...props} threadId={threadId} />\n ),\n [threadId]\n );\n\n const EricaChatHeaderWrapper = useCallback(\n () => (\n <EricaChatHeader\n onNewChat={handleNewChat}\n onThreadSelect={handleThreadSelect}\n />\n ),\n [handleNewChat, handleThreadSelect]\n );\n\n return (\n <QueryClientProvider client={queryClient}>\n <div className=\"h-full w-full\">\n <CopilotKit\n runtimeUrl={runtimeUrl}\n headers={{\n Authorization: `Bearer ${widgetToken}`,\n }}\n properties={{\n agent: \"platform:ultimate\",\n }}\n threadId={threadId}\n >\n <CopilotSidebar\n labels={{\n initial: \"Hi! How can I help you today?\\n\\nYou can:\\n- Ask me questions\\n- Upload files using the attachment icon\\n- Drag & drop files to attach\",\n }}\n defaultOpen={true}\n clickOutsideToClose={true}\n Input={EricaChatInputWrapper}\n Header={EricaChatHeaderWrapper}\n />\n </CopilotKit>\n </div>\n </QueryClientProvider>\n );\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"mappings":";;;;;;AACA,IAAI,IAAe,MAAM;CACvB,cAAc;AAEZ,EADA,KAAK,4BAA4B,IAAI,KAAK,EAC1C,KAAK,YAAY,KAAK,UAAU,KAAK,KAAK;;CAE5C,UAAU,GAAU;AAGlB,SAFA,KAAK,UAAU,IAAI,EAAS,EAC5B,KAAK,aAAa,QACL;AAEX,GADA,KAAK,UAAU,OAAO,EAAS,EAC/B,KAAK,eAAe;;;CAGxB,eAAe;AACb,SAAO,KAAK,UAAU,OAAO;;CAE/B,cAAc;CAEd,gBAAgB;GC0Cd,IAAe,IA3DA,cAAc,EAAa;CAC5C;CACA;CACA;CAC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ACb,kBAAC,GAAD;IACc;IACZ,SAAS,EACP,eAAe,UAAU,KAC1B;IACD,YAAY,EACV,OAAO,qBACR;IACS;cAEV,kBAAC,GAAD;KACE,QAAQ,EACN,SAAS,0IACV;KACD,aAAa;KACb,qBAAqB;KACrB,OAAO;KACP,QAAQ;KACR,CAAA;IACS,CAAA;GACT,CAAA;EACc,CAAA"}
1
+ {"version":3,"file":"index.mjs","names":["#setup","#cleanup","#focused","#providerCalled","#provider","#setup","#cleanup","#online","#gcTimeout","#abortSignalConsumed","#defaultOptions","#client","#cache","#initialState","getDefaultState","#retryer","#dispatch","#isInitialPausedFetch","#revertState","#client","#selectError","#currentThenable","#currentQuery","#executeFetch","#updateTimers","#clearStaleTimeout","#clearRefetchInterval","#updateQuery","#updateStaleTimeout","#computeRefetchInterval","#currentRefetchInterval","#updateRefetchInterval","#currentResult","#currentResultOptions","#currentResultState","#trackedProps","#staleTimeoutId","#refetchIntervalId","#currentQueryInitialState","#lastQueryWithDefinedData","#selectFn","#selectResult","#notify","#client","#mutationCache","#observers","#retryer","#dispatch","#mutations","#scopes","#mutationId","#queries","#queryCache","#mutationCache","#defaultOptions","#queryDefaults","#mutationDefaults","#mountCount","#unsubscribeFocus","#unsubscribeOnline","__iconNode","__iconNode","__iconNode","__iconNode"],"sources":["../node_modules/@tanstack/query-core/build/modern/subscribable.js","../node_modules/@tanstack/query-core/build/modern/focusManager.js","../node_modules/@tanstack/query-core/build/modern/timeoutManager.js","../node_modules/@tanstack/query-core/build/modern/utils.js","../node_modules/@tanstack/query-core/build/modern/environmentManager.js","../node_modules/@tanstack/query-core/build/modern/thenable.js","../node_modules/@tanstack/query-core/build/modern/notifyManager.js","../node_modules/@tanstack/query-core/build/modern/onlineManager.js","../node_modules/@tanstack/query-core/build/modern/retryer.js","../node_modules/@tanstack/query-core/build/modern/removable.js","../node_modules/@tanstack/query-core/build/modern/query.js","../node_modules/@tanstack/query-core/build/modern/queryObserver.js","../node_modules/@tanstack/query-core/build/modern/infiniteQueryBehavior.js","../node_modules/@tanstack/query-core/build/modern/mutation.js","../node_modules/@tanstack/query-core/build/modern/mutationCache.js","../node_modules/@tanstack/query-core/build/modern/queryCache.js","../node_modules/@tanstack/query-core/build/modern/queryClient.js","../node_modules/@tanstack/react-query/build/modern/QueryClientProvider.js","../node_modules/@tanstack/react-query/build/modern/IsRestoringProvider.js","../node_modules/@tanstack/react-query/build/modern/QueryErrorResetBoundary.js","../node_modules/@tanstack/react-query/build/modern/errorBoundaryUtils.js","../node_modules/@tanstack/react-query/build/modern/suspense.js","../node_modules/@tanstack/react-query/build/modern/useBaseQuery.js","../node_modules/@tanstack/react-query/build/modern/useQuery.js","../node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.js","../node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.js","../node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.js","../node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.js","../node_modules/lucide-react/dist/esm/defaultAttributes.js","../node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.js","../node_modules/lucide-react/dist/esm/context.js","../node_modules/lucide-react/dist/esm/Icon.js","../node_modules/lucide-react/dist/esm/createLucideIcon.js","../node_modules/lucide-react/dist/esm/icons/chevron-down.js","../node_modules/lucide-react/dist/esm/icons/download.js","../node_modules/lucide-react/dist/esm/icons/paperclip.js","../node_modules/lucide-react/dist/esm/icons/square-pen.js","../node_modules/lucide-react/dist/esm/icons/x.js","../src/shared/api/v1/core/bodySerializer.gen.ts","../src/shared/api/v1/core/params.gen.ts","../src/shared/api/v1/core/serverSentEvents.gen.ts","../src/shared/api/v1/core/pathSerializer.gen.ts","../src/shared/api/v1/core/utils.gen.ts","../src/shared/api/v1/core/auth.gen.ts","../src/shared/api/v1/client/utils.gen.ts","../src/shared/api/v1/client/client.gen.ts","../src/shared/api/v1/client.gen.ts","../src/shared/api/setup.ts","../src/shared/api/v1/sdk.gen.ts","../src/lib/attachment-api.ts","../src/components/EricaChatInput.tsx","../src/lib/thread-api.ts","../src/hooks/use-threads.ts","../src/components/EricaChatHeader.tsx","../src/components/EricaChat.tsx"],"sourcesContent":["// src/subscribable.ts\nvar Subscribable = class {\n constructor() {\n this.listeners = /* @__PURE__ */ new Set();\n this.subscribe = this.subscribe.bind(this);\n }\n subscribe(listener) {\n this.listeners.add(listener);\n this.onSubscribe();\n return () => {\n this.listeners.delete(listener);\n this.onUnsubscribe();\n };\n }\n hasListeners() {\n return this.listeners.size > 0;\n }\n onSubscribe() {\n }\n onUnsubscribe() {\n }\n};\nexport {\n Subscribable\n};\n//# sourceMappingURL=subscribable.js.map","// src/focusManager.ts\nimport { Subscribable } from \"./subscribable.js\";\nvar FocusManager = class extends Subscribable {\n #focused;\n #cleanup;\n #setup;\n constructor() {\n super();\n this.#setup = (onFocus) => {\n if (typeof window !== \"undefined\" && window.addEventListener) {\n const listener = () => onFocus();\n window.addEventListener(\"visibilitychange\", listener, false);\n return () => {\n window.removeEventListener(\"visibilitychange\", listener);\n };\n }\n return;\n };\n }\n onSubscribe() {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup);\n }\n }\n onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.();\n this.#cleanup = void 0;\n }\n }\n setEventListener(setup) {\n this.#setup = setup;\n this.#cleanup?.();\n this.#cleanup = setup((focused) => {\n if (typeof focused === \"boolean\") {\n this.setFocused(focused);\n } else {\n this.onFocus();\n }\n });\n }\n setFocused(focused) {\n const changed = this.#focused !== focused;\n if (changed) {\n this.#focused = focused;\n this.onFocus();\n }\n }\n onFocus() {\n const isFocused = this.isFocused();\n this.listeners.forEach((listener) => {\n listener(isFocused);\n });\n }\n isFocused() {\n if (typeof this.#focused === \"boolean\") {\n return this.#focused;\n }\n return globalThis.document?.visibilityState !== \"hidden\";\n }\n};\nvar focusManager = new FocusManager();\nexport {\n FocusManager,\n focusManager\n};\n//# sourceMappingURL=focusManager.js.map","// src/timeoutManager.ts\nvar defaultTimeoutProvider = {\n // We need the wrapper function syntax below instead of direct references to\n // global setTimeout etc.\n //\n // BAD: `setTimeout: setTimeout`\n // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`\n //\n // If we use direct references here, then anything that wants to spy on or\n // replace the global setTimeout (like tests) won't work since we'll already\n // have a hard reference to the original implementation at the time when this\n // file was imported.\n setTimeout: (callback, delay) => setTimeout(callback, delay),\n clearTimeout: (timeoutId) => clearTimeout(timeoutId),\n setInterval: (callback, delay) => setInterval(callback, delay),\n clearInterval: (intervalId) => clearInterval(intervalId)\n};\nvar TimeoutManager = class {\n // We cannot have TimeoutManager<T> as we must instantiate it with a concrete\n // type at app boot; and if we leave that type, then any new timer provider\n // would need to support the default provider's concrete timer ID, which is\n // infeasible across environments.\n //\n // We settle for type safety for the TimeoutProvider type, and accept that\n // this class is unsafe internally to allow for extension.\n #provider = defaultTimeoutProvider;\n #providerCalled = false;\n setTimeoutProvider(provider) {\n if (process.env.NODE_ENV !== \"production\") {\n if (this.#providerCalled && provider !== this.#provider) {\n console.error(\n `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,\n { previous: this.#provider, provider }\n );\n }\n }\n this.#provider = provider;\n if (process.env.NODE_ENV !== \"production\") {\n this.#providerCalled = false;\n }\n }\n setTimeout(callback, delay) {\n if (process.env.NODE_ENV !== \"production\") {\n this.#providerCalled = true;\n }\n return this.#provider.setTimeout(callback, delay);\n }\n clearTimeout(timeoutId) {\n this.#provider.clearTimeout(timeoutId);\n }\n setInterval(callback, delay) {\n if (process.env.NODE_ENV !== \"production\") {\n this.#providerCalled = true;\n }\n return this.#provider.setInterval(callback, delay);\n }\n clearInterval(intervalId) {\n this.#provider.clearInterval(intervalId);\n }\n};\nvar timeoutManager = new TimeoutManager();\nfunction systemSetTimeoutZero(callback) {\n setTimeout(callback, 0);\n}\nexport {\n TimeoutManager,\n defaultTimeoutProvider,\n systemSetTimeoutZero,\n timeoutManager\n};\n//# sourceMappingURL=timeoutManager.js.map","// src/utils.ts\nimport { timeoutManager } from \"./timeoutManager.js\";\nvar isServer = typeof window === \"undefined\" || \"Deno\" in globalThis;\nfunction noop() {\n}\nfunction functionalUpdate(updater, input) {\n return typeof updater === \"function\" ? updater(input) : updater;\n}\nfunction isValidTimeout(value) {\n return typeof value === \"number\" && value >= 0 && value !== Infinity;\n}\nfunction timeUntilStale(updatedAt, staleTime) {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);\n}\nfunction resolveStaleTime(staleTime, query) {\n return typeof staleTime === \"function\" ? staleTime(query) : staleTime;\n}\nfunction resolveEnabled(enabled, query) {\n return typeof enabled === \"function\" ? enabled(query) : enabled;\n}\nfunction matchQuery(filters, query) {\n const {\n type = \"all\",\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale\n } = filters;\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false;\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false;\n }\n }\n if (type !== \"all\") {\n const isActive = query.isActive();\n if (type === \"active\" && !isActive) {\n return false;\n }\n if (type === \"inactive\" && isActive) {\n return false;\n }\n }\n if (typeof stale === \"boolean\" && query.isStale() !== stale) {\n return false;\n }\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false;\n }\n if (predicate && !predicate(query)) {\n return false;\n }\n return true;\n}\nfunction matchMutation(filters, mutation) {\n const { exact, status, predicate, mutationKey } = filters;\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false;\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false;\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false;\n }\n }\n if (status && mutation.state.status !== status) {\n return false;\n }\n if (predicate && !predicate(mutation)) {\n return false;\n }\n return true;\n}\nfunction hashQueryKeyByOptions(queryKey, options) {\n const hashFn = options?.queryKeyHashFn || hashKey;\n return hashFn(queryKey);\n}\nfunction hashKey(queryKey) {\n return JSON.stringify(\n queryKey,\n (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {\n result[key] = val[key];\n return result;\n }, {}) : val\n );\n}\nfunction partialMatchKey(a, b) {\n if (a === b) {\n return true;\n }\n if (typeof a !== typeof b) {\n return false;\n }\n if (a && b && typeof a === \"object\" && typeof b === \"object\") {\n return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]));\n }\n return false;\n}\nvar hasOwn = Object.prototype.hasOwnProperty;\nfunction replaceEqualDeep(a, b, depth = 0) {\n if (a === b) {\n return a;\n }\n if (depth > 500) return b;\n const array = isPlainArray(a) && isPlainArray(b);\n if (!array && !(isPlainObject(a) && isPlainObject(b))) return b;\n const aItems = array ? a : Object.keys(a);\n const aSize = aItems.length;\n const bItems = array ? b : Object.keys(b);\n const bSize = bItems.length;\n const copy = array ? new Array(bSize) : {};\n let equalItems = 0;\n for (let i = 0; i < bSize; i++) {\n const key = array ? i : bItems[i];\n const aItem = a[key];\n const bItem = b[key];\n if (aItem === bItem) {\n copy[key] = aItem;\n if (array ? i < aSize : hasOwn.call(a, key)) equalItems++;\n continue;\n }\n if (aItem === null || bItem === null || typeof aItem !== \"object\" || typeof bItem !== \"object\") {\n copy[key] = bItem;\n continue;\n }\n const v = replaceEqualDeep(aItem, bItem, depth + 1);\n copy[key] = v;\n if (v === aItem) equalItems++;\n }\n return aSize === bSize && equalItems === aSize ? a : copy;\n}\nfunction shallowEqualObjects(a, b) {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false;\n }\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false;\n }\n }\n return true;\n}\nfunction isPlainArray(value) {\n return Array.isArray(value) && value.length === Object.keys(value).length;\n}\nfunction isPlainObject(o) {\n if (!hasObjectPrototype(o)) {\n return false;\n }\n const ctor = o.constructor;\n if (ctor === void 0) {\n return true;\n }\n const prot = ctor.prototype;\n if (!hasObjectPrototype(prot)) {\n return false;\n }\n if (!prot.hasOwnProperty(\"isPrototypeOf\")) {\n return false;\n }\n if (Object.getPrototypeOf(o) !== Object.prototype) {\n return false;\n }\n return true;\n}\nfunction hasObjectPrototype(o) {\n return Object.prototype.toString.call(o) === \"[object Object]\";\n}\nfunction sleep(timeout) {\n return new Promise((resolve) => {\n timeoutManager.setTimeout(resolve, timeout);\n });\n}\nfunction replaceData(prevData, data, options) {\n if (typeof options.structuralSharing === \"function\") {\n return options.structuralSharing(prevData, data);\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== \"production\") {\n try {\n return replaceEqualDeep(prevData, data);\n } catch (error) {\n console.error(\n `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`\n );\n throw error;\n }\n }\n return replaceEqualDeep(prevData, data);\n }\n return data;\n}\nfunction keepPreviousData(previousData) {\n return previousData;\n}\nfunction addToEnd(items, item, max = 0) {\n const newItems = [...items, item];\n return max && newItems.length > max ? newItems.slice(1) : newItems;\n}\nfunction addToStart(items, item, max = 0) {\n const newItems = [item, ...items];\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems;\n}\nvar skipToken = /* @__PURE__ */ Symbol();\nfunction ensureQueryFn(options, fetchOptions) {\n if (process.env.NODE_ENV !== \"production\") {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`\n );\n }\n }\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise;\n }\n if (!options.queryFn || options.queryFn === skipToken) {\n return () => Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`));\n }\n return options.queryFn;\n}\nfunction shouldThrowError(throwOnError, params) {\n if (typeof throwOnError === \"function\") {\n return throwOnError(...params);\n }\n return !!throwOnError;\n}\nfunction addConsumeAwareSignal(object, getSignal, onCancelled) {\n let consumed = false;\n let signal;\n Object.defineProperty(object, \"signal\", {\n enumerable: true,\n get: () => {\n signal ??= getSignal();\n if (consumed) {\n return signal;\n }\n consumed = true;\n if (signal.aborted) {\n onCancelled();\n } else {\n signal.addEventListener(\"abort\", onCancelled, { once: true });\n }\n return signal;\n }\n });\n return object;\n}\nexport {\n addConsumeAwareSignal,\n addToEnd,\n addToStart,\n ensureQueryFn,\n functionalUpdate,\n hashKey,\n hashQueryKeyByOptions,\n isPlainArray,\n isPlainObject,\n isServer,\n isValidTimeout,\n keepPreviousData,\n matchMutation,\n matchQuery,\n noop,\n partialMatchKey,\n replaceData,\n replaceEqualDeep,\n resolveEnabled,\n resolveStaleTime,\n shallowEqualObjects,\n shouldThrowError,\n skipToken,\n sleep,\n timeUntilStale\n};\n//# sourceMappingURL=utils.js.map","// src/environmentManager.ts\nimport { isServer } from \"./utils.js\";\nvar environmentManager = /* @__PURE__ */ (() => {\n let isServerFn = () => isServer;\n return {\n /**\n * Returns whether the current runtime should be treated as a server environment.\n */\n isServer() {\n return isServerFn();\n },\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue) {\n isServerFn = isServerValue;\n }\n };\n})();\nexport {\n environmentManager\n};\n//# sourceMappingURL=environmentManager.js.map","// src/thenable.ts\nimport { noop } from \"./utils.js\";\nfunction pendingThenable() {\n let resolve;\n let reject;\n const thenable = new Promise((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n thenable.status = \"pending\";\n thenable.catch(() => {\n });\n function finalize(data) {\n Object.assign(thenable, data);\n delete thenable.resolve;\n delete thenable.reject;\n }\n thenable.resolve = (value) => {\n finalize({\n status: \"fulfilled\",\n value\n });\n resolve(value);\n };\n thenable.reject = (reason) => {\n finalize({\n status: \"rejected\",\n reason\n });\n reject(reason);\n };\n return thenable;\n}\nfunction tryResolveSync(promise) {\n let data;\n promise.then((result) => {\n data = result;\n return result;\n }, noop)?.catch(noop);\n if (data !== void 0) {\n return { data };\n }\n return void 0;\n}\nexport {\n pendingThenable,\n tryResolveSync\n};\n//# sourceMappingURL=thenable.js.map","// src/notifyManager.ts\nimport { systemSetTimeoutZero } from \"./timeoutManager.js\";\nvar defaultScheduler = systemSetTimeoutZero;\nfunction createNotifyManager() {\n let queue = [];\n let transactions = 0;\n let notifyFn = (callback) => {\n callback();\n };\n let batchNotifyFn = (callback) => {\n callback();\n };\n let scheduleFn = defaultScheduler;\n const schedule = (callback) => {\n if (transactions) {\n queue.push(callback);\n } else {\n scheduleFn(() => {\n notifyFn(callback);\n });\n }\n };\n const flush = () => {\n const originalQueue = queue;\n queue = [];\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback);\n });\n });\n });\n }\n };\n return {\n batch: (callback) => {\n let result;\n transactions++;\n try {\n result = callback();\n } finally {\n transactions--;\n if (!transactions) {\n flush();\n }\n }\n return result;\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: (callback) => {\n return (...args) => {\n schedule(() => {\n callback(...args);\n });\n };\n },\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn) => {\n notifyFn = fn;\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn) => {\n batchNotifyFn = fn;\n },\n setScheduler: (fn) => {\n scheduleFn = fn;\n }\n };\n}\nvar notifyManager = createNotifyManager();\nexport {\n createNotifyManager,\n defaultScheduler,\n notifyManager\n};\n//# sourceMappingURL=notifyManager.js.map","// src/onlineManager.ts\nimport { Subscribable } from \"./subscribable.js\";\nvar OnlineManager = class extends Subscribable {\n #online = true;\n #cleanup;\n #setup;\n constructor() {\n super();\n this.#setup = (onOnline) => {\n if (typeof window !== \"undefined\" && window.addEventListener) {\n const onlineListener = () => onOnline(true);\n const offlineListener = () => onOnline(false);\n window.addEventListener(\"online\", onlineListener, false);\n window.addEventListener(\"offline\", offlineListener, false);\n return () => {\n window.removeEventListener(\"online\", onlineListener);\n window.removeEventListener(\"offline\", offlineListener);\n };\n }\n return;\n };\n }\n onSubscribe() {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup);\n }\n }\n onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.();\n this.#cleanup = void 0;\n }\n }\n setEventListener(setup) {\n this.#setup = setup;\n this.#cleanup?.();\n this.#cleanup = setup(this.setOnline.bind(this));\n }\n setOnline(online) {\n const changed = this.#online !== online;\n if (changed) {\n this.#online = online;\n this.listeners.forEach((listener) => {\n listener(online);\n });\n }\n }\n isOnline() {\n return this.#online;\n }\n};\nvar onlineManager = new OnlineManager();\nexport {\n OnlineManager,\n onlineManager\n};\n//# sourceMappingURL=onlineManager.js.map","// src/retryer.ts\nimport { focusManager } from \"./focusManager.js\";\nimport { onlineManager } from \"./onlineManager.js\";\nimport { pendingThenable } from \"./thenable.js\";\nimport { environmentManager } from \"./environmentManager.js\";\nimport { sleep } from \"./utils.js\";\nfunction defaultRetryDelay(failureCount) {\n return Math.min(1e3 * 2 ** failureCount, 3e4);\n}\nfunction canFetch(networkMode) {\n return (networkMode ?? \"online\") === \"online\" ? onlineManager.isOnline() : true;\n}\nvar CancelledError = class extends Error {\n constructor(options) {\n super(\"CancelledError\");\n this.revert = options?.revert;\n this.silent = options?.silent;\n }\n};\nfunction isCancelledError(value) {\n return value instanceof CancelledError;\n}\nfunction createRetryer(config) {\n let isRetryCancelled = false;\n let failureCount = 0;\n let continueFn;\n const thenable = pendingThenable();\n const isResolved = () => thenable.status !== \"pending\";\n const cancel = (cancelOptions) => {\n if (!isResolved()) {\n const error = new CancelledError(cancelOptions);\n reject(error);\n config.onCancel?.(error);\n }\n };\n const cancelRetry = () => {\n isRetryCancelled = true;\n };\n const continueRetry = () => {\n isRetryCancelled = false;\n };\n const canContinue = () => focusManager.isFocused() && (config.networkMode === \"always\" || onlineManager.isOnline()) && config.canRun();\n const canStart = () => canFetch(config.networkMode) && config.canRun();\n const resolve = (value) => {\n if (!isResolved()) {\n continueFn?.();\n thenable.resolve(value);\n }\n };\n const reject = (value) => {\n if (!isResolved()) {\n continueFn?.();\n thenable.reject(value);\n }\n };\n const pause = () => {\n return new Promise((continueResolve) => {\n continueFn = (value) => {\n if (isResolved() || canContinue()) {\n continueResolve(value);\n }\n };\n config.onPause?.();\n }).then(() => {\n continueFn = void 0;\n if (!isResolved()) {\n config.onContinue?.();\n }\n });\n };\n const run = () => {\n if (isResolved()) {\n return;\n }\n let promiseOrValue;\n const initialPromise = failureCount === 0 ? config.initialPromise : void 0;\n try {\n promiseOrValue = initialPromise ?? config.fn();\n } catch (error) {\n promiseOrValue = Promise.reject(error);\n }\n Promise.resolve(promiseOrValue).then(resolve).catch((error) => {\n if (isResolved()) {\n return;\n }\n const retry = config.retry ?? (environmentManager.isServer() ? 0 : 3);\n const retryDelay = config.retryDelay ?? defaultRetryDelay;\n const delay = typeof retryDelay === \"function\" ? retryDelay(failureCount, error) : retryDelay;\n const shouldRetry = retry === true || typeof retry === \"number\" && failureCount < retry || typeof retry === \"function\" && retry(failureCount, error);\n if (isRetryCancelled || !shouldRetry) {\n reject(error);\n return;\n }\n failureCount++;\n config.onFail?.(failureCount, error);\n sleep(delay).then(() => {\n return canContinue() ? void 0 : pause();\n }).then(() => {\n if (isRetryCancelled) {\n reject(error);\n } else {\n run();\n }\n });\n });\n };\n return {\n promise: thenable,\n status: () => thenable.status,\n cancel,\n continue: () => {\n continueFn?.();\n return thenable;\n },\n cancelRetry,\n continueRetry,\n canStart,\n start: () => {\n if (canStart()) {\n run();\n } else {\n pause().then(run);\n }\n return thenable;\n }\n };\n}\nexport {\n CancelledError,\n canFetch,\n createRetryer,\n isCancelledError\n};\n//# sourceMappingURL=retryer.js.map","// src/removable.ts\nimport { timeoutManager } from \"./timeoutManager.js\";\nimport { environmentManager } from \"./environmentManager.js\";\nimport { isValidTimeout } from \"./utils.js\";\nvar Removable = class {\n #gcTimeout;\n destroy() {\n this.clearGcTimeout();\n }\n scheduleGc() {\n this.clearGcTimeout();\n if (isValidTimeout(this.gcTime)) {\n this.#gcTimeout = timeoutManager.setTimeout(() => {\n this.optionalRemove();\n }, this.gcTime);\n }\n }\n updateGcTime(newGcTime) {\n this.gcTime = Math.max(\n this.gcTime || 0,\n newGcTime ?? (environmentManager.isServer() ? Infinity : 5 * 60 * 1e3)\n );\n }\n clearGcTimeout() {\n if (this.#gcTimeout !== void 0) {\n timeoutManager.clearTimeout(this.#gcTimeout);\n this.#gcTimeout = void 0;\n }\n }\n};\nexport {\n Removable\n};\n//# sourceMappingURL=removable.js.map","// src/query.ts\nimport {\n ensureQueryFn,\n noop,\n replaceData,\n resolveEnabled,\n resolveStaleTime,\n skipToken,\n timeUntilStale\n} from \"./utils.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { CancelledError, canFetch, createRetryer } from \"./retryer.js\";\nimport { Removable } from \"./removable.js\";\nvar Query = class extends Removable {\n #initialState;\n #revertState;\n #cache;\n #client;\n #retryer;\n #defaultOptions;\n #abortSignalConsumed;\n constructor(config) {\n super();\n this.#abortSignalConsumed = false;\n this.#defaultOptions = config.defaultOptions;\n this.setOptions(config.options);\n this.observers = [];\n this.#client = config.client;\n this.#cache = this.#client.getQueryCache();\n this.queryKey = config.queryKey;\n this.queryHash = config.queryHash;\n this.#initialState = getDefaultState(this.options);\n this.state = config.state ?? this.#initialState;\n this.scheduleGc();\n }\n get meta() {\n return this.options.meta;\n }\n get promise() {\n return this.#retryer?.promise;\n }\n setOptions(options) {\n this.options = { ...this.#defaultOptions, ...options };\n this.updateGcTime(this.options.gcTime);\n if (this.state && this.state.data === void 0) {\n const defaultState = getDefaultState(this.options);\n if (defaultState.data !== void 0) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt)\n );\n this.#initialState = defaultState;\n }\n }\n }\n optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === \"idle\") {\n this.#cache.remove(this);\n }\n }\n setData(newData, options) {\n const data = replaceData(this.state.data, newData, this.options);\n this.#dispatch({\n data,\n type: \"success\",\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual\n });\n return data;\n }\n setState(state, setStateOptions) {\n this.#dispatch({ type: \"setState\", state, setStateOptions });\n }\n cancel(options) {\n const promise = this.#retryer?.promise;\n this.#retryer?.cancel(options);\n return promise ? promise.then(noop).catch(noop) : Promise.resolve();\n }\n destroy() {\n super.destroy();\n this.cancel({ silent: true });\n }\n get resetState() {\n return this.#initialState;\n }\n reset() {\n this.destroy();\n this.setState(this.resetState);\n }\n isActive() {\n return this.observers.some(\n (observer) => resolveEnabled(observer.options.enabled, this) !== false\n );\n }\n isDisabled() {\n if (this.getObserversCount() > 0) {\n return !this.isActive();\n }\n return this.options.queryFn === skipToken || !this.isFetched();\n }\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;\n }\n isStatic() {\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => resolveStaleTime(observer.options.staleTime, this) === \"static\"\n );\n }\n return false;\n }\n isStale() {\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale\n );\n }\n return this.state.data === void 0 || this.state.isInvalidated;\n }\n isStaleByTime(staleTime = 0) {\n if (this.state.data === void 0) {\n return true;\n }\n if (staleTime === \"static\") {\n return false;\n }\n if (this.state.isInvalidated) {\n return true;\n }\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime);\n }\n onFocus() {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());\n observer?.refetch({ cancelRefetch: false });\n this.#retryer?.continue();\n }\n onOnline() {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect());\n observer?.refetch({ cancelRefetch: false });\n this.#retryer?.continue();\n }\n addObserver(observer) {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer);\n this.clearGcTimeout();\n this.#cache.notify({ type: \"observerAdded\", query: this, observer });\n }\n }\n removeObserver(observer) {\n if (this.observers.includes(observer)) {\n this.observers = this.observers.filter((x) => x !== observer);\n if (!this.observers.length) {\n if (this.#retryer) {\n if (this.#abortSignalConsumed || this.#isInitialPausedFetch()) {\n this.#retryer.cancel({ revert: true });\n } else {\n this.#retryer.cancelRetry();\n }\n }\n this.scheduleGc();\n }\n this.#cache.notify({ type: \"observerRemoved\", query: this, observer });\n }\n }\n getObserversCount() {\n return this.observers.length;\n }\n #isInitialPausedFetch() {\n return this.state.fetchStatus === \"paused\" && this.state.status === \"pending\";\n }\n invalidate() {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: \"invalidate\" });\n }\n }\n async fetch(options, fetchOptions) {\n if (this.state.fetchStatus !== \"idle\" && // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== \"rejected\") {\n if (this.state.data !== void 0 && fetchOptions?.cancelRefetch) {\n this.cancel({ silent: true });\n } else if (this.#retryer) {\n this.#retryer.continueRetry();\n return this.#retryer.promise;\n }\n }\n if (options) {\n this.setOptions(options);\n }\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn);\n if (observer) {\n this.setOptions(observer.options);\n }\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`\n );\n }\n }\n const abortController = new AbortController();\n const addSignalProperty = (object) => {\n Object.defineProperty(object, \"signal\", {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true;\n return abortController.signal;\n }\n });\n };\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions);\n const createQueryFnContext = () => {\n const queryFnContext2 = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta\n };\n addSignalProperty(queryFnContext2);\n return queryFnContext2;\n };\n const queryFnContext = createQueryFnContext();\n this.#abortSignalConsumed = false;\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this\n );\n }\n return queryFn(queryFnContext);\n };\n const createFetchContext = () => {\n const context2 = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn\n };\n addSignalProperty(context2);\n return context2;\n };\n const context = createFetchContext();\n this.options.behavior?.onFetch(context, this);\n this.#revertState = this.state;\n if (this.state.fetchStatus === \"idle\" || this.state.fetchMeta !== context.fetchOptions?.meta) {\n this.#dispatch({ type: \"fetch\", meta: context.fetchOptions?.meta });\n }\n this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise,\n fn: context.fetchFn,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: \"idle\"\n });\n }\n abortController.abort();\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: \"failed\", failureCount, error });\n },\n onPause: () => {\n this.#dispatch({ type: \"pause\" });\n },\n onContinue: () => {\n this.#dispatch({ type: \"continue\" });\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true\n });\n try {\n const data = await this.#retryer.start();\n if (data === void 0) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`\n );\n }\n throw new Error(`${this.queryHash} data is undefined`);\n }\n this.setData(data);\n this.#cache.config.onSuccess?.(data, this);\n this.#cache.config.onSettled?.(\n data,\n this.state.error,\n this\n );\n return data;\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n return this.#retryer.promise;\n } else if (error.revert) {\n if (this.state.data === void 0) {\n throw error;\n }\n return this.state.data;\n }\n }\n this.#dispatch({\n type: \"error\",\n error\n });\n this.#cache.config.onError?.(\n error,\n this\n );\n this.#cache.config.onSettled?.(\n this.state.data,\n error,\n this\n );\n throw error;\n } finally {\n this.scheduleGc();\n }\n }\n #dispatch(action) {\n const reducer = (state) => {\n switch (action.type) {\n case \"failed\":\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error\n };\n case \"pause\":\n return {\n ...state,\n fetchStatus: \"paused\"\n };\n case \"continue\":\n return {\n ...state,\n fetchStatus: \"fetching\"\n };\n case \"fetch\":\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null\n };\n case \"success\":\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...!action.manual && {\n fetchStatus: \"idle\",\n fetchFailureCount: 0,\n fetchFailureReason: null\n }\n };\n this.#revertState = action.manual ? newState : void 0;\n return newState;\n case \"error\":\n const error = action.error;\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: \"idle\",\n status: \"error\",\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true\n };\n case \"invalidate\":\n return {\n ...state,\n isInvalidated: true\n };\n case \"setState\":\n return {\n ...state,\n ...action.state\n };\n }\n };\n this.state = reducer(this.state);\n notifyManager.batch(() => {\n this.observers.forEach((observer) => {\n observer.onQueryUpdate();\n });\n this.#cache.notify({ query: this, type: \"updated\", action });\n });\n }\n};\nfunction fetchState(data, options) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? \"fetching\" : \"paused\",\n ...data === void 0 && {\n error: null,\n status: \"pending\"\n }\n };\n}\nfunction successState(data, dataUpdatedAt) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: \"success\"\n };\n}\nfunction getDefaultState(options) {\n const data = typeof options.initialData === \"function\" ? options.initialData() : options.initialData;\n const hasData = data !== void 0;\n const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === \"function\" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? \"success\" : \"pending\",\n fetchStatus: \"idle\"\n };\n}\nexport {\n Query,\n fetchState\n};\n//# sourceMappingURL=query.js.map","// src/queryObserver.ts\nimport { focusManager } from \"./focusManager.js\";\nimport { environmentManager } from \"./environmentManager.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { fetchState } from \"./query.js\";\nimport { Subscribable } from \"./subscribable.js\";\nimport { pendingThenable } from \"./thenable.js\";\nimport {\n isValidTimeout,\n noop,\n replaceData,\n resolveEnabled,\n resolveStaleTime,\n shallowEqualObjects,\n timeUntilStale\n} from \"./utils.js\";\nimport { timeoutManager } from \"./timeoutManager.js\";\nvar QueryObserver = class extends Subscribable {\n constructor(client, options) {\n super();\n this.options = options;\n this.#client = client;\n this.#selectError = null;\n this.#currentThenable = pendingThenable();\n this.bindMethods();\n this.setOptions(options);\n }\n #client;\n #currentQuery = void 0;\n #currentQueryInitialState = void 0;\n #currentResult = void 0;\n #currentResultState;\n #currentResultOptions;\n #currentThenable;\n #selectError;\n #selectFn;\n #selectResult;\n // This property keeps track of the last query with defined data.\n // It will be used to pass the previous data and query to the placeholder function between renders.\n #lastQueryWithDefinedData;\n #staleTimeoutId;\n #refetchIntervalId;\n #currentRefetchInterval;\n #trackedProps = /* @__PURE__ */ new Set();\n bindMethods() {\n this.refetch = this.refetch.bind(this);\n }\n onSubscribe() {\n if (this.listeners.size === 1) {\n this.#currentQuery.addObserver(this);\n if (shouldFetchOnMount(this.#currentQuery, this.options)) {\n this.#executeFetch();\n } else {\n this.updateResult();\n }\n this.#updateTimers();\n }\n }\n onUnsubscribe() {\n if (!this.hasListeners()) {\n this.destroy();\n }\n }\n shouldFetchOnReconnect() {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnReconnect\n );\n }\n shouldFetchOnWindowFocus() {\n return shouldFetchOn(\n this.#currentQuery,\n this.options,\n this.options.refetchOnWindowFocus\n );\n }\n destroy() {\n this.listeners = /* @__PURE__ */ new Set();\n this.#clearStaleTimeout();\n this.#clearRefetchInterval();\n this.#currentQuery.removeObserver(this);\n }\n setOptions(options) {\n const prevOptions = this.options;\n const prevQuery = this.#currentQuery;\n this.options = this.#client.defaultQueryOptions(options);\n if (this.options.enabled !== void 0 && typeof this.options.enabled !== \"boolean\" && typeof this.options.enabled !== \"function\" && typeof resolveEnabled(this.options.enabled, this.#currentQuery) !== \"boolean\") {\n throw new Error(\n \"Expected enabled to be a boolean or a callback that returns a boolean\"\n );\n }\n this.#updateQuery();\n this.#currentQuery.setOptions(this.options);\n if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getQueryCache().notify({\n type: \"observerOptionsUpdated\",\n query: this.#currentQuery,\n observer: this\n });\n }\n const mounted = this.hasListeners();\n if (mounted && shouldFetchOptionally(\n this.#currentQuery,\n prevQuery,\n this.options,\n prevOptions\n )) {\n this.#executeFetch();\n }\n this.updateResult();\n if (mounted && (this.#currentQuery !== prevQuery || resolveEnabled(this.options.enabled, this.#currentQuery) !== resolveEnabled(prevOptions.enabled, this.#currentQuery) || resolveStaleTime(this.options.staleTime, this.#currentQuery) !== resolveStaleTime(prevOptions.staleTime, this.#currentQuery))) {\n this.#updateStaleTimeout();\n }\n const nextRefetchInterval = this.#computeRefetchInterval();\n if (mounted && (this.#currentQuery !== prevQuery || resolveEnabled(this.options.enabled, this.#currentQuery) !== resolveEnabled(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) {\n this.#updateRefetchInterval(nextRefetchInterval);\n }\n }\n getOptimisticResult(options) {\n const query = this.#client.getQueryCache().build(this.#client, options);\n const result = this.createResult(query, options);\n if (shouldAssignObserverCurrentProperties(this, result)) {\n this.#currentResult = result;\n this.#currentResultOptions = this.options;\n this.#currentResultState = this.#currentQuery.state;\n }\n return result;\n }\n getCurrentResult() {\n return this.#currentResult;\n }\n trackResult(result, onPropTracked) {\n return new Proxy(result, {\n get: (target, key) => {\n this.trackProp(key);\n onPropTracked?.(key);\n if (key === \"promise\") {\n this.trackProp(\"data\");\n if (!this.options.experimental_prefetchInRender && this.#currentThenable.status === \"pending\") {\n this.#currentThenable.reject(\n new Error(\n \"experimental_prefetchInRender feature flag is not enabled\"\n )\n );\n }\n }\n return Reflect.get(target, key);\n }\n });\n }\n trackProp(key) {\n this.#trackedProps.add(key);\n }\n getCurrentQuery() {\n return this.#currentQuery;\n }\n refetch({ ...options } = {}) {\n return this.fetch({\n ...options\n });\n }\n fetchOptimistic(options) {\n const defaultedOptions = this.#client.defaultQueryOptions(options);\n const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);\n return query.fetch().then(() => this.createResult(query, defaultedOptions));\n }\n fetch(fetchOptions) {\n return this.#executeFetch({\n ...fetchOptions,\n cancelRefetch: fetchOptions.cancelRefetch ?? true\n }).then(() => {\n this.updateResult();\n return this.#currentResult;\n });\n }\n #executeFetch(fetchOptions) {\n this.#updateQuery();\n let promise = this.#currentQuery.fetch(\n this.options,\n fetchOptions\n );\n if (!fetchOptions?.throwOnError) {\n promise = promise.catch(noop);\n }\n return promise;\n }\n #updateStaleTimeout() {\n this.#clearStaleTimeout();\n const staleTime = resolveStaleTime(\n this.options.staleTime,\n this.#currentQuery\n );\n if (environmentManager.isServer() || this.#currentResult.isStale || !isValidTimeout(staleTime)) {\n return;\n }\n const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime);\n const timeout = time + 1;\n this.#staleTimeoutId = timeoutManager.setTimeout(() => {\n if (!this.#currentResult.isStale) {\n this.updateResult();\n }\n }, timeout);\n }\n #computeRefetchInterval() {\n return (typeof this.options.refetchInterval === \"function\" ? this.options.refetchInterval(this.#currentQuery) : this.options.refetchInterval) ?? false;\n }\n #updateRefetchInterval(nextInterval) {\n this.#clearRefetchInterval();\n this.#currentRefetchInterval = nextInterval;\n if (environmentManager.isServer() || resolveEnabled(this.options.enabled, this.#currentQuery) === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {\n return;\n }\n this.#refetchIntervalId = timeoutManager.setInterval(() => {\n if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {\n this.#executeFetch();\n }\n }, this.#currentRefetchInterval);\n }\n #updateTimers() {\n this.#updateStaleTimeout();\n this.#updateRefetchInterval(this.#computeRefetchInterval());\n }\n #clearStaleTimeout() {\n if (this.#staleTimeoutId !== void 0) {\n timeoutManager.clearTimeout(this.#staleTimeoutId);\n this.#staleTimeoutId = void 0;\n }\n }\n #clearRefetchInterval() {\n if (this.#refetchIntervalId !== void 0) {\n timeoutManager.clearInterval(this.#refetchIntervalId);\n this.#refetchIntervalId = void 0;\n }\n }\n createResult(query, options) {\n const prevQuery = this.#currentQuery;\n const prevOptions = this.options;\n const prevResult = this.#currentResult;\n const prevResultState = this.#currentResultState;\n const prevResultOptions = this.#currentResultOptions;\n const queryChange = query !== prevQuery;\n const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;\n const { state } = query;\n let newState = { ...state };\n let isPlaceholderData = false;\n let data;\n if (options._optimisticResults) {\n const mounted = this.hasListeners();\n const fetchOnMount = !mounted && shouldFetchOnMount(query, options);\n const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);\n if (fetchOnMount || fetchOptionally) {\n newState = {\n ...newState,\n ...fetchState(state.data, query.options)\n };\n }\n if (options._optimisticResults === \"isRestoring\") {\n newState.fetchStatus = \"idle\";\n }\n }\n let { error, errorUpdatedAt, status } = newState;\n data = newState.data;\n let skipSelect = false;\n if (options.placeholderData !== void 0 && data === void 0 && status === \"pending\") {\n let placeholderData;\n if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {\n placeholderData = prevResult.data;\n skipSelect = true;\n } else {\n placeholderData = typeof options.placeholderData === \"function\" ? options.placeholderData(\n this.#lastQueryWithDefinedData?.state.data,\n this.#lastQueryWithDefinedData\n ) : options.placeholderData;\n }\n if (placeholderData !== void 0) {\n status = \"success\";\n data = replaceData(\n prevResult?.data,\n placeholderData,\n options\n );\n isPlaceholderData = true;\n }\n }\n if (options.select && data !== void 0 && !skipSelect) {\n if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) {\n data = this.#selectResult;\n } else {\n try {\n this.#selectFn = options.select;\n data = options.select(data);\n data = replaceData(prevResult?.data, data, options);\n this.#selectResult = data;\n this.#selectError = null;\n } catch (selectError) {\n this.#selectError = selectError;\n }\n }\n }\n if (this.#selectError) {\n error = this.#selectError;\n data = this.#selectResult;\n errorUpdatedAt = Date.now();\n status = \"error\";\n }\n const isFetching = newState.fetchStatus === \"fetching\";\n const isPending = status === \"pending\";\n const isError = status === \"error\";\n const isLoading = isPending && isFetching;\n const hasData = data !== void 0;\n const result = {\n status,\n fetchStatus: newState.fetchStatus,\n isPending,\n isSuccess: status === \"success\",\n isError,\n isInitialLoading: isLoading,\n isLoading,\n data,\n dataUpdatedAt: newState.dataUpdatedAt,\n error,\n errorUpdatedAt,\n failureCount: newState.fetchFailureCount,\n failureReason: newState.fetchFailureReason,\n errorUpdateCount: newState.errorUpdateCount,\n isFetched: query.isFetched(),\n isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,\n isFetching,\n isRefetching: isFetching && !isPending,\n isLoadingError: isError && !hasData,\n isPaused: newState.fetchStatus === \"paused\",\n isPlaceholderData,\n isRefetchError: isError && hasData,\n isStale: isStale(query, options),\n refetch: this.refetch,\n promise: this.#currentThenable,\n isEnabled: resolveEnabled(options.enabled, query) !== false\n };\n const nextResult = result;\n if (this.options.experimental_prefetchInRender) {\n const hasResultData = nextResult.data !== void 0;\n const isErrorWithoutData = nextResult.status === \"error\" && !hasResultData;\n const finalizeThenableIfPossible = (thenable) => {\n if (isErrorWithoutData) {\n thenable.reject(nextResult.error);\n } else if (hasResultData) {\n thenable.resolve(nextResult.data);\n }\n };\n const recreateThenable = () => {\n const pending = this.#currentThenable = nextResult.promise = pendingThenable();\n finalizeThenableIfPossible(pending);\n };\n const prevThenable = this.#currentThenable;\n switch (prevThenable.status) {\n case \"pending\":\n if (query.queryHash === prevQuery.queryHash) {\n finalizeThenableIfPossible(prevThenable);\n }\n break;\n case \"fulfilled\":\n if (isErrorWithoutData || nextResult.data !== prevThenable.value) {\n recreateThenable();\n }\n break;\n case \"rejected\":\n if (!isErrorWithoutData || nextResult.error !== prevThenable.reason) {\n recreateThenable();\n }\n break;\n }\n }\n return nextResult;\n }\n updateResult() {\n const prevResult = this.#currentResult;\n const nextResult = this.createResult(this.#currentQuery, this.options);\n this.#currentResultState = this.#currentQuery.state;\n this.#currentResultOptions = this.options;\n if (this.#currentResultState.data !== void 0) {\n this.#lastQueryWithDefinedData = this.#currentQuery;\n }\n if (shallowEqualObjects(nextResult, prevResult)) {\n return;\n }\n this.#currentResult = nextResult;\n const shouldNotifyListeners = () => {\n if (!prevResult) {\n return true;\n }\n const { notifyOnChangeProps } = this.options;\n const notifyOnChangePropsValue = typeof notifyOnChangeProps === \"function\" ? notifyOnChangeProps() : notifyOnChangeProps;\n if (notifyOnChangePropsValue === \"all\" || !notifyOnChangePropsValue && !this.#trackedProps.size) {\n return true;\n }\n const includedProps = new Set(\n notifyOnChangePropsValue ?? this.#trackedProps\n );\n if (this.options.throwOnError) {\n includedProps.add(\"error\");\n }\n return Object.keys(this.#currentResult).some((key) => {\n const typedKey = key;\n const changed = this.#currentResult[typedKey] !== prevResult[typedKey];\n return changed && includedProps.has(typedKey);\n });\n };\n this.#notify({ listeners: shouldNotifyListeners() });\n }\n #updateQuery() {\n const query = this.#client.getQueryCache().build(this.#client, this.options);\n if (query === this.#currentQuery) {\n return;\n }\n const prevQuery = this.#currentQuery;\n this.#currentQuery = query;\n this.#currentQueryInitialState = query.state;\n if (this.hasListeners()) {\n prevQuery?.removeObserver(this);\n query.addObserver(this);\n }\n }\n onQueryUpdate() {\n this.updateResult();\n if (this.hasListeners()) {\n this.#updateTimers();\n }\n }\n #notify(notifyOptions) {\n notifyManager.batch(() => {\n if (notifyOptions.listeners) {\n this.listeners.forEach((listener) => {\n listener(this.#currentResult);\n });\n }\n this.#client.getQueryCache().notify({\n query: this.#currentQuery,\n type: \"observerResultsUpdated\"\n });\n });\n }\n};\nfunction shouldLoadOnMount(query, options) {\n return resolveEnabled(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === \"error\" && options.retryOnMount === false);\n}\nfunction shouldFetchOnMount(query, options) {\n return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);\n}\nfunction shouldFetchOn(query, options, field) {\n if (resolveEnabled(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== \"static\") {\n const value = typeof field === \"function\" ? field(query) : field;\n return value === \"always\" || value !== false && isStale(query, options);\n }\n return false;\n}\nfunction shouldFetchOptionally(query, prevQuery, options, prevOptions) {\n return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== \"error\") && isStale(query, options);\n}\nfunction isStale(query, options) {\n return resolveEnabled(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query));\n}\nfunction shouldAssignObserverCurrentProperties(observer, optimisticResult) {\n if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {\n return true;\n }\n return false;\n}\nexport {\n QueryObserver\n};\n//# sourceMappingURL=queryObserver.js.map","// src/infiniteQueryBehavior.ts\nimport {\n addConsumeAwareSignal,\n addToEnd,\n addToStart,\n ensureQueryFn\n} from \"./utils.js\";\nfunction infiniteQueryBehavior(pages) {\n return {\n onFetch: (context, query) => {\n const options = context.options;\n const direction = context.fetchOptions?.meta?.fetchMore?.direction;\n const oldPages = context.state.data?.pages || [];\n const oldPageParams = context.state.data?.pageParams || [];\n let result = { pages: [], pageParams: [] };\n let currentPage = 0;\n const fetchFn = async () => {\n let cancelled = false;\n const addSignalProperty = (object) => {\n addConsumeAwareSignal(\n object,\n () => context.signal,\n () => cancelled = true\n );\n };\n const queryFn = ensureQueryFn(context.options, context.fetchOptions);\n const fetchPage = async (data, param, previous) => {\n if (cancelled) {\n return Promise.reject();\n }\n if (param == null && data.pages.length) {\n return Promise.resolve(data);\n }\n const createQueryFnContext = () => {\n const queryFnContext2 = {\n client: context.client,\n queryKey: context.queryKey,\n pageParam: param,\n direction: previous ? \"backward\" : \"forward\",\n meta: context.options.meta\n };\n addSignalProperty(queryFnContext2);\n return queryFnContext2;\n };\n const queryFnContext = createQueryFnContext();\n const page = await queryFn(queryFnContext);\n const { maxPages } = context.options;\n const addTo = previous ? addToStart : addToEnd;\n return {\n pages: addTo(data.pages, page, maxPages),\n pageParams: addTo(data.pageParams, param, maxPages)\n };\n };\n if (direction && oldPages.length) {\n const previous = direction === \"backward\";\n const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n const oldData = {\n pages: oldPages,\n pageParams: oldPageParams\n };\n const param = pageParamFn(options, oldData);\n result = await fetchPage(oldData, param, previous);\n } else {\n const remainingPages = pages ?? oldPages.length;\n do {\n const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);\n if (currentPage > 0 && param == null) {\n break;\n }\n result = await fetchPage(result, param);\n currentPage++;\n } while (currentPage < remainingPages);\n }\n return result;\n };\n if (context.options.persister) {\n context.fetchFn = () => {\n return context.options.persister?.(\n fetchFn,\n {\n client: context.client,\n queryKey: context.queryKey,\n meta: context.options.meta,\n signal: context.signal\n },\n query\n );\n };\n } else {\n context.fetchFn = fetchFn;\n }\n }\n };\n}\nfunction getNextPageParam(options, { pages, pageParams }) {\n const lastIndex = pages.length - 1;\n return pages.length > 0 ? options.getNextPageParam(\n pages[lastIndex],\n pages,\n pageParams[lastIndex],\n pageParams\n ) : void 0;\n}\nfunction getPreviousPageParam(options, { pages, pageParams }) {\n return pages.length > 0 ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams) : void 0;\n}\nfunction hasNextPage(options, data) {\n if (!data) return false;\n return getNextPageParam(options, data) != null;\n}\nfunction hasPreviousPage(options, data) {\n if (!data || !options.getPreviousPageParam) return false;\n return getPreviousPageParam(options, data) != null;\n}\nexport {\n hasNextPage,\n hasPreviousPage,\n infiniteQueryBehavior\n};\n//# sourceMappingURL=infiniteQueryBehavior.js.map","// src/mutation.ts\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Removable } from \"./removable.js\";\nimport { createRetryer } from \"./retryer.js\";\nvar Mutation = class extends Removable {\n #client;\n #observers;\n #mutationCache;\n #retryer;\n constructor(config) {\n super();\n this.#client = config.client;\n this.mutationId = config.mutationId;\n this.#mutationCache = config.mutationCache;\n this.#observers = [];\n this.state = config.state || getDefaultState();\n this.setOptions(config.options);\n this.scheduleGc();\n }\n setOptions(options) {\n this.options = options;\n this.updateGcTime(this.options.gcTime);\n }\n get meta() {\n return this.options.meta;\n }\n addObserver(observer) {\n if (!this.#observers.includes(observer)) {\n this.#observers.push(observer);\n this.clearGcTimeout();\n this.#mutationCache.notify({\n type: \"observerAdded\",\n mutation: this,\n observer\n });\n }\n }\n removeObserver(observer) {\n this.#observers = this.#observers.filter((x) => x !== observer);\n this.scheduleGc();\n this.#mutationCache.notify({\n type: \"observerRemoved\",\n mutation: this,\n observer\n });\n }\n optionalRemove() {\n if (!this.#observers.length) {\n if (this.state.status === \"pending\") {\n this.scheduleGc();\n } else {\n this.#mutationCache.remove(this);\n }\n }\n }\n continue() {\n return this.#retryer?.continue() ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before\n this.execute(this.state.variables);\n }\n async execute(variables) {\n const onContinue = () => {\n this.#dispatch({ type: \"continue\" });\n };\n const mutationFnContext = {\n client: this.#client,\n meta: this.options.meta,\n mutationKey: this.options.mutationKey\n };\n this.#retryer = createRetryer({\n fn: () => {\n if (!this.options.mutationFn) {\n return Promise.reject(new Error(\"No mutationFn found\"));\n }\n return this.options.mutationFn(variables, mutationFnContext);\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: \"failed\", failureCount, error });\n },\n onPause: () => {\n this.#dispatch({ type: \"pause\" });\n },\n onContinue,\n retry: this.options.retry ?? 0,\n retryDelay: this.options.retryDelay,\n networkMode: this.options.networkMode,\n canRun: () => this.#mutationCache.canRun(this)\n });\n const restored = this.state.status === \"pending\";\n const isPaused = !this.#retryer.canStart();\n try {\n if (restored) {\n onContinue();\n } else {\n this.#dispatch({ type: \"pending\", variables, isPaused });\n if (this.#mutationCache.config.onMutate) {\n await this.#mutationCache.config.onMutate(\n variables,\n this,\n mutationFnContext\n );\n }\n const context = await this.options.onMutate?.(\n variables,\n mutationFnContext\n );\n if (context !== this.state.context) {\n this.#dispatch({\n type: \"pending\",\n context,\n variables,\n isPaused\n });\n }\n }\n const data = await this.#retryer.start();\n await this.#mutationCache.config.onSuccess?.(\n data,\n variables,\n this.state.context,\n this,\n mutationFnContext\n );\n await this.options.onSuccess?.(\n data,\n variables,\n this.state.context,\n mutationFnContext\n );\n await this.#mutationCache.config.onSettled?.(\n data,\n null,\n this.state.variables,\n this.state.context,\n this,\n mutationFnContext\n );\n await this.options.onSettled?.(\n data,\n null,\n variables,\n this.state.context,\n mutationFnContext\n );\n this.#dispatch({ type: \"success\", data });\n return data;\n } catch (error) {\n try {\n await this.#mutationCache.config.onError?.(\n error,\n variables,\n this.state.context,\n this,\n mutationFnContext\n );\n } catch (e) {\n void Promise.reject(e);\n }\n try {\n await this.options.onError?.(\n error,\n variables,\n this.state.context,\n mutationFnContext\n );\n } catch (e) {\n void Promise.reject(e);\n }\n try {\n await this.#mutationCache.config.onSettled?.(\n void 0,\n error,\n this.state.variables,\n this.state.context,\n this,\n mutationFnContext\n );\n } catch (e) {\n void Promise.reject(e);\n }\n try {\n await this.options.onSettled?.(\n void 0,\n error,\n variables,\n this.state.context,\n mutationFnContext\n );\n } catch (e) {\n void Promise.reject(e);\n }\n this.#dispatch({ type: \"error\", error });\n throw error;\n } finally {\n this.#mutationCache.runNext(this);\n }\n }\n #dispatch(action) {\n const reducer = (state) => {\n switch (action.type) {\n case \"failed\":\n return {\n ...state,\n failureCount: action.failureCount,\n failureReason: action.error\n };\n case \"pause\":\n return {\n ...state,\n isPaused: true\n };\n case \"continue\":\n return {\n ...state,\n isPaused: false\n };\n case \"pending\":\n return {\n ...state,\n context: action.context,\n data: void 0,\n failureCount: 0,\n failureReason: null,\n error: null,\n isPaused: action.isPaused,\n status: \"pending\",\n variables: action.variables,\n submittedAt: Date.now()\n };\n case \"success\":\n return {\n ...state,\n data: action.data,\n failureCount: 0,\n failureReason: null,\n error: null,\n status: \"success\",\n isPaused: false\n };\n case \"error\":\n return {\n ...state,\n data: void 0,\n error: action.error,\n failureCount: state.failureCount + 1,\n failureReason: action.error,\n isPaused: false,\n status: \"error\"\n };\n }\n };\n this.state = reducer(this.state);\n notifyManager.batch(() => {\n this.#observers.forEach((observer) => {\n observer.onMutationUpdate(action);\n });\n this.#mutationCache.notify({\n mutation: this,\n type: \"updated\",\n action\n });\n });\n }\n};\nfunction getDefaultState() {\n return {\n context: void 0,\n data: void 0,\n error: null,\n failureCount: 0,\n failureReason: null,\n isPaused: false,\n status: \"idle\",\n variables: void 0,\n submittedAt: 0\n };\n}\nexport {\n Mutation,\n getDefaultState\n};\n//# sourceMappingURL=mutation.js.map","// src/mutationCache.ts\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Mutation } from \"./mutation.js\";\nimport { matchMutation, noop } from \"./utils.js\";\nimport { Subscribable } from \"./subscribable.js\";\nvar MutationCache = class extends Subscribable {\n constructor(config = {}) {\n super();\n this.config = config;\n this.#mutations = /* @__PURE__ */ new Set();\n this.#scopes = /* @__PURE__ */ new Map();\n this.#mutationId = 0;\n }\n #mutations;\n #scopes;\n #mutationId;\n build(client, options, state) {\n const mutation = new Mutation({\n client,\n mutationCache: this,\n mutationId: ++this.#mutationId,\n options: client.defaultMutationOptions(options),\n state\n });\n this.add(mutation);\n return mutation;\n }\n add(mutation) {\n this.#mutations.add(mutation);\n const scope = scopeFor(mutation);\n if (typeof scope === \"string\") {\n const scopedMutations = this.#scopes.get(scope);\n if (scopedMutations) {\n scopedMutations.push(mutation);\n } else {\n this.#scopes.set(scope, [mutation]);\n }\n }\n this.notify({ type: \"added\", mutation });\n }\n remove(mutation) {\n if (this.#mutations.delete(mutation)) {\n const scope = scopeFor(mutation);\n if (typeof scope === \"string\") {\n const scopedMutations = this.#scopes.get(scope);\n if (scopedMutations) {\n if (scopedMutations.length > 1) {\n const index = scopedMutations.indexOf(mutation);\n if (index !== -1) {\n scopedMutations.splice(index, 1);\n }\n } else if (scopedMutations[0] === mutation) {\n this.#scopes.delete(scope);\n }\n }\n }\n }\n this.notify({ type: \"removed\", mutation });\n }\n canRun(mutation) {\n const scope = scopeFor(mutation);\n if (typeof scope === \"string\") {\n const mutationsWithSameScope = this.#scopes.get(scope);\n const firstPendingMutation = mutationsWithSameScope?.find(\n (m) => m.state.status === \"pending\"\n );\n return !firstPendingMutation || firstPendingMutation === mutation;\n } else {\n return true;\n }\n }\n runNext(mutation) {\n const scope = scopeFor(mutation);\n if (typeof scope === \"string\") {\n const foundMutation = this.#scopes.get(scope)?.find((m) => m !== mutation && m.state.isPaused);\n return foundMutation?.continue() ?? Promise.resolve();\n } else {\n return Promise.resolve();\n }\n }\n clear() {\n notifyManager.batch(() => {\n this.#mutations.forEach((mutation) => {\n this.notify({ type: \"removed\", mutation });\n });\n this.#mutations.clear();\n this.#scopes.clear();\n });\n }\n getAll() {\n return Array.from(this.#mutations);\n }\n find(filters) {\n const defaultedFilters = { exact: true, ...filters };\n return this.getAll().find(\n (mutation) => matchMutation(defaultedFilters, mutation)\n );\n }\n findAll(filters = {}) {\n return this.getAll().filter((mutation) => matchMutation(filters, mutation));\n }\n notify(event) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event);\n });\n });\n }\n resumePausedMutations() {\n const pausedMutations = this.getAll().filter((x) => x.state.isPaused);\n return notifyManager.batch(\n () => Promise.all(\n pausedMutations.map((mutation) => mutation.continue().catch(noop))\n )\n );\n }\n};\nfunction scopeFor(mutation) {\n return mutation.options.scope?.id;\n}\nexport {\n MutationCache\n};\n//# sourceMappingURL=mutationCache.js.map","// src/queryCache.ts\nimport { hashQueryKeyByOptions, matchQuery } from \"./utils.js\";\nimport { Query } from \"./query.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { Subscribable } from \"./subscribable.js\";\nvar QueryCache = class extends Subscribable {\n constructor(config = {}) {\n super();\n this.config = config;\n this.#queries = /* @__PURE__ */ new Map();\n }\n #queries;\n build(client, options, state) {\n const queryKey = options.queryKey;\n const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);\n let query = this.get(queryHash);\n if (!query) {\n query = new Query({\n client,\n queryKey,\n queryHash,\n options: client.defaultQueryOptions(options),\n state,\n defaultOptions: client.getQueryDefaults(queryKey)\n });\n this.add(query);\n }\n return query;\n }\n add(query) {\n if (!this.#queries.has(query.queryHash)) {\n this.#queries.set(query.queryHash, query);\n this.notify({\n type: \"added\",\n query\n });\n }\n }\n remove(query) {\n const queryInMap = this.#queries.get(query.queryHash);\n if (queryInMap) {\n query.destroy();\n if (queryInMap === query) {\n this.#queries.delete(query.queryHash);\n }\n this.notify({ type: \"removed\", query });\n }\n }\n clear() {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n this.remove(query);\n });\n });\n }\n get(queryHash) {\n return this.#queries.get(queryHash);\n }\n getAll() {\n return [...this.#queries.values()];\n }\n find(filters) {\n const defaultedFilters = { exact: true, ...filters };\n return this.getAll().find(\n (query) => matchQuery(defaultedFilters, query)\n );\n }\n findAll(filters = {}) {\n const queries = this.getAll();\n return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;\n }\n notify(event) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event);\n });\n });\n }\n onFocus() {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onFocus();\n });\n });\n }\n onOnline() {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onOnline();\n });\n });\n }\n};\nexport {\n QueryCache\n};\n//# sourceMappingURL=queryCache.js.map","// src/queryClient.ts\nimport {\n functionalUpdate,\n hashKey,\n hashQueryKeyByOptions,\n noop,\n partialMatchKey,\n resolveStaleTime,\n skipToken\n} from \"./utils.js\";\nimport { QueryCache } from \"./queryCache.js\";\nimport { MutationCache } from \"./mutationCache.js\";\nimport { focusManager } from \"./focusManager.js\";\nimport { onlineManager } from \"./onlineManager.js\";\nimport { notifyManager } from \"./notifyManager.js\";\nimport { infiniteQueryBehavior } from \"./infiniteQueryBehavior.js\";\nvar QueryClient = class {\n #queryCache;\n #mutationCache;\n #defaultOptions;\n #queryDefaults;\n #mutationDefaults;\n #mountCount;\n #unsubscribeFocus;\n #unsubscribeOnline;\n constructor(config = {}) {\n this.#queryCache = config.queryCache || new QueryCache();\n this.#mutationCache = config.mutationCache || new MutationCache();\n this.#defaultOptions = config.defaultOptions || {};\n this.#queryDefaults = /* @__PURE__ */ new Map();\n this.#mutationDefaults = /* @__PURE__ */ new Map();\n this.#mountCount = 0;\n }\n mount() {\n this.#mountCount++;\n if (this.#mountCount !== 1) return;\n this.#unsubscribeFocus = focusManager.subscribe(async (focused) => {\n if (focused) {\n await this.resumePausedMutations();\n this.#queryCache.onFocus();\n }\n });\n this.#unsubscribeOnline = onlineManager.subscribe(async (online) => {\n if (online) {\n await this.resumePausedMutations();\n this.#queryCache.onOnline();\n }\n });\n }\n unmount() {\n this.#mountCount--;\n if (this.#mountCount !== 0) return;\n this.#unsubscribeFocus?.();\n this.#unsubscribeFocus = void 0;\n this.#unsubscribeOnline?.();\n this.#unsubscribeOnline = void 0;\n }\n isFetching(filters) {\n return this.#queryCache.findAll({ ...filters, fetchStatus: \"fetching\" }).length;\n }\n isMutating(filters) {\n return this.#mutationCache.findAll({ ...filters, status: \"pending\" }).length;\n }\n /**\n * Imperative (non-reactive) way to retrieve data for a QueryKey.\n * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.\n *\n * Hint: Do not use this function inside a component, because it won't receive updates.\n * Use `useQuery` to create a `QueryObserver` that subscribes to changes.\n */\n getQueryData(queryKey) {\n const options = this.defaultQueryOptions({ queryKey });\n return this.#queryCache.get(options.queryHash)?.state.data;\n }\n ensureQueryData(options) {\n const defaultedOptions = this.defaultQueryOptions(options);\n const query = this.#queryCache.build(this, defaultedOptions);\n const cachedData = query.state.data;\n if (cachedData === void 0) {\n return this.fetchQuery(options);\n }\n if (options.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) {\n void this.prefetchQuery(defaultedOptions);\n }\n return Promise.resolve(cachedData);\n }\n getQueriesData(filters) {\n return this.#queryCache.findAll(filters).map(({ queryKey, state }) => {\n const data = state.data;\n return [queryKey, data];\n });\n }\n setQueryData(queryKey, updater, options) {\n const defaultedOptions = this.defaultQueryOptions({ queryKey });\n const query = this.#queryCache.get(\n defaultedOptions.queryHash\n );\n const prevData = query?.state.data;\n const data = functionalUpdate(updater, prevData);\n if (data === void 0) {\n return void 0;\n }\n return this.#queryCache.build(this, defaultedOptions).setData(data, { ...options, manual: true });\n }\n setQueriesData(filters, updater, options) {\n return notifyManager.batch(\n () => this.#queryCache.findAll(filters).map(({ queryKey }) => [\n queryKey,\n this.setQueryData(queryKey, updater, options)\n ])\n );\n }\n getQueryState(queryKey) {\n const options = this.defaultQueryOptions({ queryKey });\n return this.#queryCache.get(\n options.queryHash\n )?.state;\n }\n removeQueries(filters) {\n const queryCache = this.#queryCache;\n notifyManager.batch(() => {\n queryCache.findAll(filters).forEach((query) => {\n queryCache.remove(query);\n });\n });\n }\n resetQueries(filters, options) {\n const queryCache = this.#queryCache;\n return notifyManager.batch(() => {\n queryCache.findAll(filters).forEach((query) => {\n query.reset();\n });\n return this.refetchQueries(\n {\n type: \"active\",\n ...filters\n },\n options\n );\n });\n }\n cancelQueries(filters, cancelOptions = {}) {\n const defaultedCancelOptions = { revert: true, ...cancelOptions };\n const promises = notifyManager.batch(\n () => this.#queryCache.findAll(filters).map((query) => query.cancel(defaultedCancelOptions))\n );\n return Promise.all(promises).then(noop).catch(noop);\n }\n invalidateQueries(filters, options = {}) {\n return notifyManager.batch(() => {\n this.#queryCache.findAll(filters).forEach((query) => {\n query.invalidate();\n });\n if (filters?.refetchType === \"none\") {\n return Promise.resolve();\n }\n return this.refetchQueries(\n {\n ...filters,\n type: filters?.refetchType ?? filters?.type ?? \"active\"\n },\n options\n );\n });\n }\n refetchQueries(filters, options = {}) {\n const fetchOptions = {\n ...options,\n cancelRefetch: options.cancelRefetch ?? true\n };\n const promises = notifyManager.batch(\n () => this.#queryCache.findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {\n let promise = query.fetch(void 0, fetchOptions);\n if (!fetchOptions.throwOnError) {\n promise = promise.catch(noop);\n }\n return query.state.fetchStatus === \"paused\" ? Promise.resolve() : promise;\n })\n );\n return Promise.all(promises).then(noop);\n }\n fetchQuery(options) {\n const defaultedOptions = this.defaultQueryOptions(options);\n if (defaultedOptions.retry === void 0) {\n defaultedOptions.retry = false;\n }\n const query = this.#queryCache.build(this, defaultedOptions);\n return query.isStaleByTime(\n resolveStaleTime(defaultedOptions.staleTime, query)\n ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);\n }\n prefetchQuery(options) {\n return this.fetchQuery(options).then(noop).catch(noop);\n }\n fetchInfiniteQuery(options) {\n options.behavior = infiniteQueryBehavior(options.pages);\n return this.fetchQuery(options);\n }\n prefetchInfiniteQuery(options) {\n return this.fetchInfiniteQuery(options).then(noop).catch(noop);\n }\n ensureInfiniteQueryData(options) {\n options.behavior = infiniteQueryBehavior(options.pages);\n return this.ensureQueryData(options);\n }\n resumePausedMutations() {\n if (onlineManager.isOnline()) {\n return this.#mutationCache.resumePausedMutations();\n }\n return Promise.resolve();\n }\n getQueryCache() {\n return this.#queryCache;\n }\n getMutationCache() {\n return this.#mutationCache;\n }\n getDefaultOptions() {\n return this.#defaultOptions;\n }\n setDefaultOptions(options) {\n this.#defaultOptions = options;\n }\n setQueryDefaults(queryKey, options) {\n this.#queryDefaults.set(hashKey(queryKey), {\n queryKey,\n defaultOptions: options\n });\n }\n getQueryDefaults(queryKey) {\n const defaults = [...this.#queryDefaults.values()];\n const result = {};\n defaults.forEach((queryDefault) => {\n if (partialMatchKey(queryKey, queryDefault.queryKey)) {\n Object.assign(result, queryDefault.defaultOptions);\n }\n });\n return result;\n }\n setMutationDefaults(mutationKey, options) {\n this.#mutationDefaults.set(hashKey(mutationKey), {\n mutationKey,\n defaultOptions: options\n });\n }\n getMutationDefaults(mutationKey) {\n const defaults = [...this.#mutationDefaults.values()];\n const result = {};\n defaults.forEach((queryDefault) => {\n if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {\n Object.assign(result, queryDefault.defaultOptions);\n }\n });\n return result;\n }\n defaultQueryOptions(options) {\n if (options._defaulted) {\n return options;\n }\n const defaultedOptions = {\n ...this.#defaultOptions.queries,\n ...this.getQueryDefaults(options.queryKey),\n ...options,\n _defaulted: true\n };\n if (!defaultedOptions.queryHash) {\n defaultedOptions.queryHash = hashQueryKeyByOptions(\n defaultedOptions.queryKey,\n defaultedOptions\n );\n }\n if (defaultedOptions.refetchOnReconnect === void 0) {\n defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== \"always\";\n }\n if (defaultedOptions.throwOnError === void 0) {\n defaultedOptions.throwOnError = !!defaultedOptions.suspense;\n }\n if (!defaultedOptions.networkMode && defaultedOptions.persister) {\n defaultedOptions.networkMode = \"offlineFirst\";\n }\n if (defaultedOptions.queryFn === skipToken) {\n defaultedOptions.enabled = false;\n }\n return defaultedOptions;\n }\n defaultMutationOptions(options) {\n if (options?._defaulted) {\n return options;\n }\n return {\n ...this.#defaultOptions.mutations,\n ...options?.mutationKey && this.getMutationDefaults(options.mutationKey),\n ...options,\n _defaulted: true\n };\n }\n clear() {\n this.#queryCache.clear();\n this.#mutationCache.clear();\n }\n};\nexport {\n QueryClient\n};\n//# sourceMappingURL=queryClient.js.map","\"use client\";\n\n// src/QueryClientProvider.tsx\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nvar QueryClientContext = React.createContext(\n void 0\n);\nvar useQueryClient = (queryClient) => {\n const client = React.useContext(QueryClientContext);\n if (queryClient) {\n return queryClient;\n }\n if (!client) {\n throw new Error(\"No QueryClient set, use QueryClientProvider to set one\");\n }\n return client;\n};\nvar QueryClientProvider = ({\n client,\n children\n}) => {\n React.useEffect(() => {\n client.mount();\n return () => {\n client.unmount();\n };\n }, [client]);\n return /* @__PURE__ */ jsx(QueryClientContext.Provider, { value: client, children });\n};\nexport {\n QueryClientContext,\n QueryClientProvider,\n useQueryClient\n};\n//# sourceMappingURL=QueryClientProvider.js.map","\"use client\";\n\n// src/IsRestoringProvider.ts\nimport * as React from \"react\";\nvar IsRestoringContext = React.createContext(false);\nvar useIsRestoring = () => React.useContext(IsRestoringContext);\nvar IsRestoringProvider = IsRestoringContext.Provider;\nexport {\n IsRestoringProvider,\n useIsRestoring\n};\n//# sourceMappingURL=IsRestoringProvider.js.map","\"use client\";\n\n// src/QueryErrorResetBoundary.tsx\nimport * as React from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\nfunction createValue() {\n let isReset = false;\n return {\n clearReset: () => {\n isReset = false;\n },\n reset: () => {\n isReset = true;\n },\n isReset: () => {\n return isReset;\n }\n };\n}\nvar QueryErrorResetBoundaryContext = React.createContext(createValue());\nvar useQueryErrorResetBoundary = () => React.useContext(QueryErrorResetBoundaryContext);\nvar QueryErrorResetBoundary = ({\n children\n}) => {\n const [value] = React.useState(() => createValue());\n return /* @__PURE__ */ jsx(QueryErrorResetBoundaryContext.Provider, { value, children: typeof children === \"function\" ? children(value) : children });\n};\nexport {\n QueryErrorResetBoundary,\n useQueryErrorResetBoundary\n};\n//# sourceMappingURL=QueryErrorResetBoundary.js.map","\"use client\";\n\n// src/errorBoundaryUtils.ts\nimport * as React from \"react\";\nimport { shouldThrowError } from \"@tanstack/query-core\";\nvar ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {\n const throwOnError = query?.state.error && typeof options.throwOnError === \"function\" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;\n if (options.suspense || options.experimental_prefetchInRender || throwOnError) {\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false;\n }\n }\n};\nvar useClearResetErrorBoundary = (errorResetBoundary) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset();\n }, [errorResetBoundary]);\n};\nvar getHasError = ({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense\n}) => {\n return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));\n};\nexport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary\n};\n//# sourceMappingURL=errorBoundaryUtils.js.map","// src/suspense.ts\nvar defaultThrowOnError = (_error, query) => query.state.data === void 0;\nvar ensureSuspenseTimers = (defaultedOptions) => {\n if (defaultedOptions.suspense) {\n const MIN_SUSPENSE_TIME_MS = 1e3;\n const clamp = (value) => value === \"static\" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);\n const originalStaleTime = defaultedOptions.staleTime;\n defaultedOptions.staleTime = typeof originalStaleTime === \"function\" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);\n if (typeof defaultedOptions.gcTime === \"number\") {\n defaultedOptions.gcTime = Math.max(\n defaultedOptions.gcTime,\n MIN_SUSPENSE_TIME_MS\n );\n }\n }\n};\nvar willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring;\nvar shouldSuspend = (defaultedOptions, result) => defaultedOptions?.suspense && result.isPending;\nvar fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {\n errorResetBoundary.clearReset();\n});\nexport {\n defaultThrowOnError,\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n willFetch\n};\n//# sourceMappingURL=suspense.js.map","\"use client\";\n\n// src/useBaseQuery.ts\nimport * as React from \"react\";\nimport { environmentManager, noop, notifyManager } from \"@tanstack/query-core\";\nimport { useQueryClient } from \"./QueryClientProvider.js\";\nimport { useQueryErrorResetBoundary } from \"./QueryErrorResetBoundary.js\";\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary\n} from \"./errorBoundaryUtils.js\";\nimport { useIsRestoring } from \"./IsRestoringProvider.js\";\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n willFetch\n} from \"./suspense.js\";\nfunction useBaseQuery(options, Observer, queryClient) {\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof options !== \"object\" || Array.isArray(options)) {\n throw new Error(\n 'Bad argument type. Starting with v5, only the \"Object\" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object'\n );\n }\n }\n const isRestoring = useIsRestoring();\n const errorResetBoundary = useQueryErrorResetBoundary();\n const client = useQueryClient(queryClient);\n const defaultedOptions = client.defaultQueryOptions(options);\n client.getDefaultOptions().queries?._experimental_beforeQuery?.(\n defaultedOptions\n );\n const query = client.getQueryCache().get(defaultedOptions.queryHash);\n if (process.env.NODE_ENV !== \"production\") {\n if (!defaultedOptions.queryFn) {\n console.error(\n `[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`\n );\n }\n }\n defaultedOptions._optimisticResults = isRestoring ? \"isRestoring\" : \"optimistic\";\n ensureSuspenseTimers(defaultedOptions);\n ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query);\n useClearResetErrorBoundary(errorResetBoundary);\n const isNewCacheEntry = !client.getQueryCache().get(defaultedOptions.queryHash);\n const [observer] = React.useState(\n () => new Observer(\n client,\n defaultedOptions\n )\n );\n const result = observer.getOptimisticResult(defaultedOptions);\n const shouldSubscribe = !isRestoring && options.subscribed !== false;\n React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) => {\n const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;\n observer.updateResult();\n return unsubscribe;\n },\n [observer, shouldSubscribe]\n ),\n () => observer.getCurrentResult(),\n () => observer.getCurrentResult()\n );\n React.useEffect(() => {\n observer.setOptions(defaultedOptions);\n }, [defaultedOptions, observer]);\n if (shouldSuspend(defaultedOptions, result)) {\n throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);\n }\n if (getHasError({\n result,\n errorResetBoundary,\n throwOnError: defaultedOptions.throwOnError,\n query,\n suspense: defaultedOptions.suspense\n })) {\n throw result.error;\n }\n ;\n client.getDefaultOptions().queries?._experimental_afterQuery?.(\n defaultedOptions,\n result\n );\n if (defaultedOptions.experimental_prefetchInRender && !environmentManager.isServer() && willFetch(result, isRestoring)) {\n const promise = isNewCacheEntry ? (\n // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted\n fetchOptimistic(defaultedOptions, observer, errorResetBoundary)\n ) : (\n // subscribe to the \"cache promise\" so that we can finalize the currentThenable once data comes in\n query?.promise\n );\n promise?.catch(noop).finally(() => {\n observer.updateResult();\n });\n }\n return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;\n}\nexport {\n useBaseQuery\n};\n//# sourceMappingURL=useBaseQuery.js.map","\"use client\";\n\n// src/useQuery.ts\nimport { QueryObserver } from \"@tanstack/query-core\";\nimport { useBaseQuery } from \"./useBaseQuery.js\";\nfunction useQuery(options, queryClient) {\n return useBaseQuery(options, QueryObserver, queryClient);\n}\nexport {\n useQuery\n};\n//# sourceMappingURL=useQuery.js.map","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst mergeClasses = (...classes) => classes.filter((className, index, array) => {\n return Boolean(className) && className.trim() !== \"\" && array.indexOf(className) === index;\n}).join(\" \").trim();\n\nexport { mergeClasses };\n//# sourceMappingURL=mergeClasses.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n\nexport { toKebabCase };\n//# sourceMappingURL=toKebabCase.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst toCamelCase = (string) => string.replace(\n /^([A-Z])|[\\s-_]+(\\w)/g,\n (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()\n);\n\nexport { toCamelCase };\n//# sourceMappingURL=toCamelCase.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { toCamelCase } from './toCamelCase.js';\n\nconst toPascalCase = (string) => {\n const camelCase = toCamelCase(string);\n return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);\n};\n\nexport { toPascalCase };\n//# sourceMappingURL=toPascalCase.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nvar defaultAttributes = {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: 2,\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n};\n\nexport { defaultAttributes as default };\n//# sourceMappingURL=defaultAttributes.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst hasA11yProp = (props) => {\n for (const prop in props) {\n if (prop.startsWith(\"aria-\") || prop === \"role\" || prop === \"title\") {\n return true;\n }\n }\n return false;\n};\n\nexport { hasA11yProp };\n//# sourceMappingURL=hasA11yProp.js.map\n","\"use strict\";\n\"use client\";\n/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { createContext, useContext, useMemo, createElement } from 'react';\n\nconst LucideContext = createContext({});\nfunction LucideProvider({\n children,\n size,\n color,\n strokeWidth,\n absoluteStrokeWidth,\n className\n}) {\n const value = useMemo(\n () => ({\n size,\n color,\n strokeWidth,\n absoluteStrokeWidth,\n className\n }),\n [size, color, strokeWidth, absoluteStrokeWidth, className]\n );\n return createElement(LucideContext.Provider, { value }, children);\n}\nconst useLucideContext = () => useContext(LucideContext);\n\nexport { LucideProvider, useLucideContext };\n//# sourceMappingURL=context.js.map\n","\"use strict\";\n\"use client\";\n/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes.js';\nimport { hasA11yProp } from './shared/src/utils/hasA11yProp.js';\nimport { mergeClasses } from './shared/src/utils/mergeClasses.js';\nimport { useLucideContext } from './context.js';\n\nconst Icon = forwardRef(\n ({ color, size, strokeWidth, absoluteStrokeWidth, className = \"\", children, iconNode, ...rest }, ref) => {\n const {\n size: contextSize = 24,\n strokeWidth: contextStrokeWidth = 2,\n absoluteStrokeWidth: contextAbsoluteStrokeWidth = false,\n color: contextColor = \"currentColor\",\n className: contextClass = \"\"\n } = useLucideContext() ?? {};\n const calculatedStrokeWidth = absoluteStrokeWidth ?? contextAbsoluteStrokeWidth ? Number(strokeWidth ?? contextStrokeWidth) * 24 / Number(size ?? contextSize) : strokeWidth ?? contextStrokeWidth;\n return createElement(\n \"svg\",\n {\n ref,\n ...defaultAttributes,\n width: size ?? contextSize ?? defaultAttributes.width,\n height: size ?? contextSize ?? defaultAttributes.height,\n stroke: color ?? contextColor,\n strokeWidth: calculatedStrokeWidth,\n className: mergeClasses(\"lucide\", contextClass, className),\n ...!children && !hasA11yProp(rest) && { \"aria-hidden\": \"true\" },\n ...rest\n },\n [\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...Array.isArray(children) ? children : [children]\n ]\n );\n }\n);\n\nexport { Icon as default };\n//# sourceMappingURL=Icon.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport { mergeClasses } from './shared/src/utils/mergeClasses.js';\nimport { toKebabCase } from './shared/src/utils/toKebabCase.js';\nimport { toPascalCase } from './shared/src/utils/toPascalCase.js';\nimport Icon from './Icon.js';\n\nconst createLucideIcon = (iconName, iconNode) => {\n const Component = forwardRef(\n ({ className, ...props }, ref) => createElement(Icon, {\n ref,\n iconNode,\n className: mergeClasses(\n `lucide-${toKebabCase(toPascalCase(iconName))}`,\n `lucide-${iconName}`,\n className\n ),\n ...props\n })\n );\n Component.displayName = toPascalCase(iconName);\n return Component;\n};\n\nexport { createLucideIcon as default };\n//# sourceMappingURL=createLucideIcon.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [[\"path\", { d: \"m6 9 6 6 6-6\", key: \"qrunsl\" }]];\nconst ChevronDown = createLucideIcon(\"chevron-down\", __iconNode);\n\nexport { __iconNode, ChevronDown as default };\n//# sourceMappingURL=chevron-down.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M12 15V3\", key: \"m9g1x1\" }],\n [\"path\", { d: \"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\", key: \"ih7n3h\" }],\n [\"path\", { d: \"m7 10 5 5 5-5\", key: \"brsn70\" }]\n];\nconst Download = createLucideIcon(\"download\", __iconNode);\n\nexport { __iconNode, Download as default };\n//# sourceMappingURL=download.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\n \"path\",\n {\n d: \"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551\",\n key: \"1miecu\"\n }\n ]\n];\nconst Paperclip = createLucideIcon(\"paperclip\", __iconNode);\n\nexport { __iconNode, Paperclip as default };\n//# sourceMappingURL=paperclip.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7\", key: \"1m0v6g\" }],\n [\n \"path\",\n {\n d: \"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z\",\n key: \"ohrbg2\"\n }\n ]\n];\nconst SquarePen = createLucideIcon(\"square-pen\", __iconNode);\n\nexport { __iconNode, SquarePen as default };\n//# sourceMappingURL=square-pen.js.map\n","/**\n * @license lucide-react v1.8.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M18 6 6 18\", key: \"1bl5f8\" }],\n [\"path\", { d: \"m6 6 12 12\", key: \"d8bk6v\" }]\n];\nconst X = createLucideIcon(\"x\", __iconNode);\n\nexport { __iconNode, X as default };\n//# sourceMappingURL=x.js.map\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen';\n\nexport type QuerySerializer = (query: Record<string, unknown>) => string;\n\nexport type BodySerializer = (body: unknown) => unknown;\n\ntype QuerySerializerOptionsObject = {\n allowReserved?: boolean;\n array?: Partial<SerializerOptions<ArrayStyle>>;\n object?: Partial<SerializerOptions<ObjectStyle>>;\n};\n\nexport type QuerySerializerOptions = QuerySerializerOptionsObject & {\n /**\n * Per-parameter serialization overrides. When provided, these settings\n * override the global array/object settings for specific parameter names.\n */\n parameters?: Record<string, QuerySerializerOptionsObject>;\n};\n\nconst serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {\n if (typeof value === 'string' || value instanceof Blob) {\n data.append(key, value);\n } else if (value instanceof Date) {\n data.append(key, value.toISOString());\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nconst serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {\n if (typeof value === 'string') {\n data.append(key, value);\n } else {\n data.append(key, JSON.stringify(value));\n }\n};\n\nexport const formDataBodySerializer = {\n bodySerializer: (body: unknown): FormData => {\n const data = new FormData();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeFormDataPair(data, key, v));\n } else {\n serializeFormDataPair(data, key, value);\n }\n });\n\n return data;\n },\n};\n\nexport const jsonBodySerializer = {\n bodySerializer: (body: unknown): string =>\n JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),\n};\n\nexport const urlSearchParamsBodySerializer = {\n bodySerializer: (body: unknown): string => {\n const data = new URLSearchParams();\n\n Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {\n if (value === undefined || value === null) {\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));\n } else {\n serializeUrlSearchParamsPair(data, key, value);\n }\n });\n\n return data.toString();\n },\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\ntype Slot = 'body' | 'headers' | 'path' | 'query';\n\nexport type Field =\n | {\n in: Exclude<Slot, 'body'>;\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If omitted, we use the same value as `key`.\n */\n map?: string;\n }\n | {\n in: Extract<Slot, 'body'>;\n /**\n * Key isn't required for bodies.\n */\n key?: string;\n map?: string;\n }\n | {\n /**\n * Field name. This is the name we want the user to see and use.\n */\n key: string;\n /**\n * Field mapped name. This is the name we want to use in the request.\n * If `in` is omitted, `map` aliases `key` to the transport layer.\n */\n map: Slot;\n };\n\nexport interface Fields {\n allowExtra?: Partial<Record<Slot, boolean>>;\n args?: ReadonlyArray<Field>;\n}\n\nexport type FieldsConfig = ReadonlyArray<Field | Fields>;\n\nconst extraPrefixesMap: Record<string, Slot> = {\n $body_: 'body',\n $headers_: 'headers',\n $path_: 'path',\n $query_: 'query',\n};\nconst extraPrefixes = Object.entries(extraPrefixesMap);\n\ntype KeyMap = Map<\n string,\n | {\n in: Slot;\n map?: string;\n }\n | {\n in?: never;\n map: Slot;\n }\n>;\n\nconst buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {\n if (!map) {\n map = new Map();\n }\n\n for (const config of fields) {\n if ('in' in config) {\n if (config.key) {\n map.set(config.key, {\n in: config.in,\n map: config.map,\n });\n }\n } else if ('key' in config) {\n map.set(config.key, {\n map: config.map,\n });\n } else if (config.args) {\n buildKeyMap(config.args, map);\n }\n }\n\n return map;\n};\n\ninterface Params {\n body: unknown;\n headers: Record<string, unknown>;\n path: Record<string, unknown>;\n query: Record<string, unknown>;\n}\n\nconst stripEmptySlots = (params: Params) => {\n for (const [slot, value] of Object.entries(params)) {\n if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {\n delete params[slot as Slot];\n }\n }\n};\n\nexport const buildClientParams = (args: ReadonlyArray<unknown>, fields: FieldsConfig) => {\n const params: Params = {\n body: {},\n headers: {},\n path: {},\n query: {},\n };\n\n const map = buildKeyMap(fields);\n\n let config: FieldsConfig[number] | undefined;\n\n for (const [index, arg] of args.entries()) {\n if (fields[index]) {\n config = fields[index];\n }\n\n if (!config) {\n continue;\n }\n\n if ('in' in config) {\n if (config.key) {\n const field = map.get(config.key)!;\n const name = field.map || config.key;\n if (field.in) {\n (params[field.in] as Record<string, unknown>)[name] = arg;\n }\n } else {\n params.body = arg;\n }\n } else {\n for (const [key, value] of Object.entries(arg ?? {})) {\n const field = map.get(key);\n\n if (field) {\n if (field.in) {\n const name = field.map || key;\n (params[field.in] as Record<string, unknown>)[name] = value;\n } else {\n params[field.map] = value;\n }\n } else {\n const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));\n\n if (extra) {\n const [prefix, slot] = extra;\n (params[slot] as Record<string, unknown>)[key.slice(prefix.length)] = value;\n } else if ('allowExtra' in config && config.allowExtra) {\n for (const [slot, allowed] of Object.entries(config.allowExtra)) {\n if (allowed) {\n (params[slot as Slot] as Record<string, unknown>)[key] = value;\n break;\n }\n }\n }\n }\n }\n }\n }\n\n stripEmptySlots(params);\n\n return params;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { Config } from './types.gen';\n\nexport type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &\n Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {\n /**\n * Fetch API implementation. You can use this option to provide a custom\n * fetch instance.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * Implementing clients can call request interceptors inside this hook.\n */\n onRequest?: (url: string, init: RequestInit) => Promise<Request>;\n /**\n * Callback invoked when a network or parsing error occurs during streaming.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param error The error that occurred.\n */\n onSseError?: (error: unknown) => void;\n /**\n * Callback invoked when an event is streamed from the server.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @param event Event streamed from the server.\n * @returns Nothing (void).\n */\n onSseEvent?: (event: StreamEvent<TData>) => void;\n serializedBody?: RequestInit['body'];\n /**\n * Default retry delay in milliseconds.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 3000\n */\n sseDefaultRetryDelay?: number;\n /**\n * Maximum number of retry attempts before giving up.\n */\n sseMaxRetryAttempts?: number;\n /**\n * Maximum retry delay in milliseconds.\n *\n * Applies only when exponential backoff is used.\n *\n * This option applies only if the endpoint returns a stream of events.\n *\n * @default 30000\n */\n sseMaxRetryDelay?: number;\n /**\n * Optional sleep function for retry backoff.\n *\n * Defaults to using `setTimeout`.\n */\n sseSleepFn?: (ms: number) => Promise<void>;\n url: string;\n };\n\nexport interface StreamEvent<TData = unknown> {\n data: TData;\n event?: string;\n id?: string;\n retry?: number;\n}\n\nexport type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {\n stream: AsyncGenerator<\n TData extends Record<string, unknown> ? TData[keyof TData] : TData,\n TReturn,\n TNext\n >;\n};\n\nexport function createSseClient<TData = unknown>({\n onRequest,\n onSseError,\n onSseEvent,\n responseTransformer,\n responseValidator,\n sseDefaultRetryDelay,\n sseMaxRetryAttempts,\n sseMaxRetryDelay,\n sseSleepFn,\n url,\n ...options\n}: ServerSentEventsOptions): ServerSentEventsResult<TData> {\n let lastEventId: string | undefined;\n\n const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));\n\n const createStream = async function* () {\n let retryDelay: number = sseDefaultRetryDelay ?? 3000;\n let attempt = 0;\n const signal = options.signal ?? new AbortController().signal;\n\n while (true) {\n if (signal.aborted) break;\n\n attempt++;\n\n const headers =\n options.headers instanceof Headers\n ? options.headers\n : new Headers(options.headers as Record<string, string> | undefined);\n\n if (lastEventId !== undefined) {\n headers.set('Last-Event-ID', lastEventId);\n }\n\n try {\n const requestInit: RequestInit = {\n redirect: 'follow',\n ...options,\n body: options.serializedBody,\n headers,\n signal,\n };\n let request = new Request(url, requestInit);\n if (onRequest) {\n request = await onRequest(url, requestInit);\n }\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = options.fetch ?? globalThis.fetch;\n const response = await _fetch(request);\n\n if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);\n\n if (!response.body) throw new Error('No body in SSE response');\n\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n\n let buffer = '';\n\n const abortHandler = () => {\n try {\n reader.cancel();\n } catch {\n // noop\n }\n };\n\n signal.addEventListener('abort', abortHandler);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += value;\n buffer = buffer.replace(/\\r\\n?/g, '\\n'); // normalize line endings\n\n const chunks = buffer.split('\\n\\n');\n buffer = chunks.pop() ?? '';\n\n for (const chunk of chunks) {\n const lines = chunk.split('\\n');\n const dataLines: Array<string> = [];\n let eventName: string | undefined;\n\n for (const line of lines) {\n if (line.startsWith('data:')) {\n dataLines.push(line.replace(/^data:\\s*/, ''));\n } else if (line.startsWith('event:')) {\n eventName = line.replace(/^event:\\s*/, '');\n } else if (line.startsWith('id:')) {\n lastEventId = line.replace(/^id:\\s*/, '');\n } else if (line.startsWith('retry:')) {\n const parsed = Number.parseInt(line.replace(/^retry:\\s*/, ''), 10);\n if (!Number.isNaN(parsed)) {\n retryDelay = parsed;\n }\n }\n }\n\n let data: unknown;\n let parsedJson = false;\n\n if (dataLines.length) {\n const rawData = dataLines.join('\\n');\n try {\n data = JSON.parse(rawData);\n parsedJson = true;\n } catch {\n data = rawData;\n }\n }\n\n if (parsedJson) {\n if (responseValidator) {\n await responseValidator(data);\n }\n\n if (responseTransformer) {\n data = await responseTransformer(data);\n }\n }\n\n onSseEvent?.({\n data,\n event: eventName,\n id: lastEventId,\n retry: retryDelay,\n });\n\n if (dataLines.length) {\n yield data as any;\n }\n }\n }\n } finally {\n signal.removeEventListener('abort', abortHandler);\n reader.releaseLock();\n }\n\n break; // exit loop on normal completion\n } catch (error) {\n // connection failed or aborted; retry after delay\n onSseError?.(error);\n\n if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {\n break; // stop after firing error\n }\n\n // exponential backoff: double retry each attempt, cap at 30s\n const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);\n await sleep(backoff);\n }\n }\n };\n\n const stream = createStream();\n\n return { stream };\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\ninterface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}\n\ninterface SerializePrimitiveOptions {\n allowReserved?: boolean;\n name: string;\n}\n\nexport interface SerializerOptions<T> {\n /**\n * @default true\n */\n explode: boolean;\n style: T;\n}\n\nexport type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';\nexport type ArraySeparatorStyle = ArrayStyle | MatrixStyle;\ntype MatrixStyle = 'label' | 'matrix' | 'simple';\nexport type ObjectStyle = 'form' | 'deepObject';\ntype ObjectSeparatorStyle = ObjectStyle | MatrixStyle;\n\ninterface SerializePrimitiveParam extends SerializePrimitiveOptions {\n value: string;\n}\n\nexport const separatorArrayExplode = (style: ArraySeparatorStyle) => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {\n switch (style) {\n case 'form':\n return ',';\n case 'pipeDelimited':\n return '|';\n case 'spaceDelimited':\n return '%20';\n default:\n return ',';\n }\n};\n\nexport const separatorObjectExplode = (style: ObjectSeparatorStyle) => {\n switch (style) {\n case 'label':\n return '.';\n case 'matrix':\n return ';';\n case 'simple':\n return ',';\n default:\n return '&';\n }\n};\n\nexport const serializeArrayParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n}: SerializeOptions<ArraySeparatorStyle> & {\n value: unknown[];\n}) => {\n if (!explode) {\n const joinedValues = (\n allowReserved ? value : value.map((v) => encodeURIComponent(v as string))\n ).join(separatorArrayNoExplode(style));\n switch (style) {\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n case 'simple':\n return joinedValues;\n default:\n return `${name}=${joinedValues}`;\n }\n }\n\n const separator = separatorArrayExplode(style);\n const joinedValues = value\n .map((v) => {\n if (style === 'label' || style === 'simple') {\n return allowReserved ? v : encodeURIComponent(v as string);\n }\n\n return serializePrimitiveParam({\n allowReserved,\n name,\n value: v as string,\n });\n })\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n\nexport const serializePrimitiveParam = ({\n allowReserved,\n name,\n value,\n}: SerializePrimitiveParam) => {\n if (value === undefined || value === null) {\n return '';\n }\n\n if (typeof value === 'object') {\n throw new Error(\n 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',\n );\n }\n\n return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;\n};\n\nexport const serializeObjectParam = ({\n allowReserved,\n explode,\n name,\n style,\n value,\n valueOnly,\n}: SerializeOptions<ObjectSeparatorStyle> & {\n value: Record<string, unknown> | Date;\n valueOnly?: boolean;\n}) => {\n if (value instanceof Date) {\n return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;\n }\n\n if (style !== 'deepObject' && !explode) {\n let values: string[] = [];\n Object.entries(value).forEach(([key, v]) => {\n values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];\n });\n const joinedValues = values.join(',');\n switch (style) {\n case 'form':\n return `${name}=${joinedValues}`;\n case 'label':\n return `.${joinedValues}`;\n case 'matrix':\n return `;${name}=${joinedValues}`;\n default:\n return joinedValues;\n }\n }\n\n const separator = separatorObjectExplode(style);\n const joinedValues = Object.entries(value)\n .map(([key, v]) =>\n serializePrimitiveParam({\n allowReserved,\n name: style === 'deepObject' ? `${name}[${key}]` : key,\n value: v as string,\n }),\n )\n .join(separator);\n return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { BodySerializer, QuerySerializer } from './bodySerializer.gen';\nimport {\n type ArraySeparatorStyle,\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from './pathSerializer.gen';\n\nexport interface PathSerializer {\n path: Record<string, unknown>;\n url: string;\n}\n\nexport const PATH_PARAM_RE = /\\{[^{}]+\\}/g;\n\nexport const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {\n let url = _url;\n const matches = _url.match(PATH_PARAM_RE);\n if (matches) {\n for (const match of matches) {\n let explode = false;\n let name = match.substring(1, match.length - 1);\n let style: ArraySeparatorStyle = 'simple';\n\n if (name.endsWith('*')) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n\n if (name.startsWith('.')) {\n name = name.substring(1);\n style = 'label';\n } else if (name.startsWith(';')) {\n name = name.substring(1);\n style = 'matrix';\n }\n\n const value = path[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n url = url.replace(match, serializeArrayParam({ explode, name, style, value }));\n continue;\n }\n\n if (typeof value === 'object') {\n url = url.replace(\n match,\n serializeObjectParam({\n explode,\n name,\n style,\n value: value as Record<string, unknown>,\n valueOnly: true,\n }),\n );\n continue;\n }\n\n if (style === 'matrix') {\n url = url.replace(\n match,\n `;${serializePrimitiveParam({\n name,\n value: value as string,\n })}`,\n );\n continue;\n }\n\n const replaceValue = encodeURIComponent(\n style === 'label' ? `.${value as string}` : (value as string),\n );\n url = url.replace(match, replaceValue);\n }\n }\n return url;\n};\n\nexport const getUrl = ({\n baseUrl,\n path,\n query,\n querySerializer,\n url: _url,\n}: {\n baseUrl?: string;\n path?: Record<string, unknown>;\n query?: Record<string, unknown>;\n querySerializer: QuerySerializer;\n url: string;\n}) => {\n const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;\n let url = (baseUrl ?? '') + pathUrl;\n if (path) {\n url = defaultPathSerializer({ path, url });\n }\n let search = query ? querySerializer(query) : '';\n if (search.startsWith('?')) {\n search = search.substring(1);\n }\n if (search) {\n url += `?${search}`;\n }\n return url;\n};\n\nexport function getValidRequestBody(options: {\n body?: unknown;\n bodySerializer?: BodySerializer | null;\n serializedBody?: unknown;\n}) {\n const hasBody = options.body !== undefined;\n const isSerializedBody = hasBody && options.bodySerializer;\n\n if (isSerializedBody) {\n if ('serializedBody' in options) {\n const hasSerializedBody =\n options.serializedBody !== undefined && options.serializedBody !== '';\n\n return hasSerializedBody ? options.serializedBody : null;\n }\n\n // not all clients implement a serializedBody property (i.e., client-axios)\n return options.body !== '' ? options.body : null;\n }\n\n // plain/text body\n if (hasBody) {\n return options.body;\n }\n\n // no body was provided\n return undefined;\n}\n","// This file is auto-generated by @hey-api/openapi-ts\n\nexport type AuthToken = string | undefined;\n\nexport interface Auth {\n /**\n * Which part of the request do we use to send the auth?\n *\n * @default 'header'\n */\n in?: 'header' | 'query' | 'cookie';\n /**\n * Header or query parameter name.\n *\n * @default 'Authorization'\n */\n name?: string;\n scheme?: 'basic' | 'bearer';\n type: 'apiKey' | 'http';\n}\n\nexport const getAuthToken = async (\n auth: Auth,\n callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,\n): Promise<string | undefined> => {\n const token = typeof callback === 'function' ? await callback(auth) : callback;\n\n if (!token) {\n return;\n }\n\n if (auth.scheme === 'bearer') {\n return `Bearer ${token}`;\n }\n\n if (auth.scheme === 'basic') {\n return `Basic ${btoa(token)}`;\n }\n\n return token;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { getAuthToken } from '../core/auth.gen';\nimport type { QuerySerializerOptions } from '../core/bodySerializer.gen';\nimport { jsonBodySerializer } from '../core/bodySerializer.gen';\nimport {\n serializeArrayParam,\n serializeObjectParam,\n serializePrimitiveParam,\n} from '../core/pathSerializer.gen';\nimport { getUrl } from '../core/utils.gen';\nimport type { Client, ClientOptions, Config, RequestOptions } from './types.gen';\n\nexport const createQuerySerializer = <T = unknown>({\n parameters = {},\n ...args\n}: QuerySerializerOptions = {}) => {\n const querySerializer = (queryParams: T) => {\n const search: string[] = [];\n if (queryParams && typeof queryParams === 'object') {\n for (const name in queryParams) {\n const value = queryParams[name];\n\n if (value === undefined || value === null) {\n continue;\n }\n\n const options = parameters[name] || args;\n\n if (Array.isArray(value)) {\n const serializedArray = serializeArrayParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'form',\n value,\n ...options.array,\n });\n if (serializedArray) search.push(serializedArray);\n } else if (typeof value === 'object') {\n const serializedObject = serializeObjectParam({\n allowReserved: options.allowReserved,\n explode: true,\n name,\n style: 'deepObject',\n value: value as Record<string, unknown>,\n ...options.object,\n });\n if (serializedObject) search.push(serializedObject);\n } else {\n const serializedPrimitive = serializePrimitiveParam({\n allowReserved: options.allowReserved,\n name,\n value: value as string,\n });\n if (serializedPrimitive) search.push(serializedPrimitive);\n }\n }\n }\n return search.join('&');\n };\n return querySerializer;\n};\n\n/**\n * Infers parseAs value from provided Content-Type header.\n */\nexport const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {\n if (!contentType) {\n // If no Content-Type header is provided, the best we can do is return the raw response body,\n // which is effectively the same as the 'stream' option.\n return 'stream';\n }\n\n const cleanContent = contentType.split(';')[0]?.trim();\n\n if (!cleanContent) {\n return;\n }\n\n if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {\n return 'json';\n }\n\n if (cleanContent === 'multipart/form-data') {\n return 'formData';\n }\n\n if (\n ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))\n ) {\n return 'blob';\n }\n\n if (cleanContent.startsWith('text/')) {\n return 'text';\n }\n\n return;\n};\n\nconst checkForExistence = (\n options: Pick<RequestOptions, 'auth' | 'query'> & {\n headers: Headers;\n },\n name?: string,\n): boolean => {\n if (!name) {\n return false;\n }\n if (\n options.headers.has(name) ||\n options.query?.[name] ||\n options.headers.get('Cookie')?.includes(`${name}=`)\n ) {\n return true;\n }\n return false;\n};\n\nexport const setAuthParams = async ({\n security,\n ...options\n}: Pick<Required<RequestOptions>, 'security'> &\n Pick<RequestOptions, 'auth' | 'query'> & {\n headers: Headers;\n }) => {\n for (const auth of security) {\n if (checkForExistence(options, auth.name)) {\n continue;\n }\n\n const token = await getAuthToken(auth, options.auth);\n\n if (!token) {\n continue;\n }\n\n const name = auth.name ?? 'Authorization';\n\n switch (auth.in) {\n case 'query':\n if (!options.query) {\n options.query = {};\n }\n options.query[name] = token;\n break;\n case 'cookie':\n options.headers.append('Cookie', `${name}=${token}`);\n break;\n case 'header':\n default:\n options.headers.set(name, token);\n break;\n }\n }\n};\n\nexport const buildUrl: Client['buildUrl'] = (options) =>\n getUrl({\n baseUrl: options.baseUrl as string,\n path: options.path,\n query: options.query,\n querySerializer:\n typeof options.querySerializer === 'function'\n ? options.querySerializer\n : createQuerySerializer(options.querySerializer),\n url: options.url,\n });\n\nexport const mergeConfigs = (a: Config, b: Config): Config => {\n const config = { ...a, ...b };\n if (config.baseUrl?.endsWith('/')) {\n config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);\n }\n config.headers = mergeHeaders(a.headers, b.headers);\n return config;\n};\n\nconst headersEntries = (headers: Headers): Array<[string, string]> => {\n const entries: Array<[string, string]> = [];\n headers.forEach((value, key) => {\n entries.push([key, value]);\n });\n return entries;\n};\n\nexport const mergeHeaders = (\n ...headers: Array<Required<Config>['headers'] | undefined>\n): Headers => {\n const mergedHeaders = new Headers();\n for (const header of headers) {\n if (!header) {\n continue;\n }\n\n const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);\n\n for (const [key, value] of iterator) {\n if (value === null) {\n mergedHeaders.delete(key);\n } else if (Array.isArray(value)) {\n for (const v of value) {\n mergedHeaders.append(key, v as string);\n }\n } else if (value !== undefined) {\n // assume object headers are meant to be JSON stringified, i.e., their\n // content value in OpenAPI specification is 'application/json'\n mergedHeaders.set(\n key,\n typeof value === 'object' ? JSON.stringify(value) : (value as string),\n );\n }\n }\n }\n return mergedHeaders;\n};\n\ntype ErrInterceptor<Err, Res, Req, Options> = (\n error: Err,\n response: Res,\n request: Req,\n options: Options,\n) => Err | Promise<Err>;\n\ntype ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;\n\ntype ResInterceptor<Res, Req, Options> = (\n response: Res,\n request: Req,\n options: Options,\n) => Res | Promise<Res>;\n\nclass Interceptors<Interceptor> {\n fns: Array<Interceptor | null> = [];\n\n clear(): void {\n this.fns = [];\n }\n\n eject(id: number | Interceptor): void {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = null;\n }\n }\n\n exists(id: number | Interceptor): boolean {\n const index = this.getInterceptorIndex(id);\n return Boolean(this.fns[index]);\n }\n\n getInterceptorIndex(id: number | Interceptor): number {\n if (typeof id === 'number') {\n return this.fns[id] ? id : -1;\n }\n return this.fns.indexOf(id);\n }\n\n update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {\n const index = this.getInterceptorIndex(id);\n if (this.fns[index]) {\n this.fns[index] = fn;\n return id;\n }\n return false;\n }\n\n use(fn: Interceptor): number {\n this.fns.push(fn);\n return this.fns.length - 1;\n }\n}\n\nexport interface Middleware<Req, Res, Err, Options> {\n error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;\n request: Interceptors<ReqInterceptor<Req, Options>>;\n response: Interceptors<ResInterceptor<Res, Req, Options>>;\n}\n\nexport const createInterceptors = <Req, Res, Err, Options>(): Middleware<\n Req,\n Res,\n Err,\n Options\n> => ({\n error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),\n request: new Interceptors<ReqInterceptor<Req, Options>>(),\n response: new Interceptors<ResInterceptor<Res, Req, Options>>(),\n});\n\nconst defaultQuerySerializer = createQuerySerializer({\n allowReserved: false,\n array: {\n explode: true,\n style: 'form',\n },\n object: {\n explode: true,\n style: 'deepObject',\n },\n});\n\nconst defaultHeaders = {\n 'Content-Type': 'application/json',\n};\n\nexport const createConfig = <T extends ClientOptions = ClientOptions>(\n override: Config<Omit<ClientOptions, keyof T> & T> = {},\n): Config<Omit<ClientOptions, keyof T> & T> => ({\n ...jsonBodySerializer,\n headers: defaultHeaders,\n parseAs: 'auto',\n querySerializer: defaultQuerySerializer,\n ...override,\n});\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { createSseClient } from '../core/serverSentEvents.gen';\nimport type { HttpMethod } from '../core/types.gen';\nimport { getValidRequestBody } from '../core/utils.gen';\nimport type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen';\nimport {\n buildUrl,\n createConfig,\n createInterceptors,\n getParseAs,\n mergeConfigs,\n mergeHeaders,\n setAuthParams,\n} from './utils.gen';\n\ntype ReqInit = Omit<RequestInit, 'body' | 'headers'> & {\n body?: any;\n headers: ReturnType<typeof mergeHeaders>;\n};\n\nexport const createClient = (config: Config = {}): Client => {\n let _config = mergeConfigs(createConfig(), config);\n\n const getConfig = (): Config => ({ ..._config });\n\n const setConfig = (config: Config): Config => {\n _config = mergeConfigs(_config, config);\n return getConfig();\n };\n\n const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();\n\n const beforeRequest = async <\n TData = unknown,\n TResponseStyle extends 'data' | 'fields' = 'fields',\n ThrowOnError extends boolean = boolean,\n Url extends string = string,\n >(\n options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,\n ) => {\n const opts = {\n ..._config,\n ...options,\n fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,\n headers: mergeHeaders(_config.headers, options.headers),\n serializedBody: undefined as string | undefined,\n };\n\n if (opts.security) {\n await setAuthParams({\n ...opts,\n security: opts.security,\n });\n }\n\n if (opts.requestValidator) {\n await opts.requestValidator(opts);\n }\n\n if (opts.body !== undefined && opts.bodySerializer) {\n opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;\n }\n\n // remove Content-Type header if body is empty to avoid sending invalid requests\n if (opts.body === undefined || opts.serializedBody === '') {\n opts.headers.delete('Content-Type');\n }\n\n const resolvedOpts = opts as typeof opts &\n ResolvedRequestOptions<TResponseStyle, ThrowOnError, Url>;\n const url = buildUrl(resolvedOpts);\n\n return { opts: resolvedOpts, url };\n };\n\n const request: Client['request'] = async (options) => {\n const { opts, url } = await beforeRequest(options);\n const requestInit: ReqInit = {\n redirect: 'follow',\n ...opts,\n body: getValidRequestBody(opts),\n };\n\n let request = new Request(url, requestInit);\n\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n\n // fetch must be assigned here, otherwise it would throw the error:\n // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation\n const _fetch = opts.fetch!;\n let response: Response;\n\n try {\n response = await _fetch(request);\n } catch (error) {\n // Handle fetch exceptions (AbortError, network errors, etc.)\n let finalError = error;\n\n for (const fn of interceptors.error.fns) {\n if (fn) {\n finalError = (await fn(error, undefined as any, request, opts)) as unknown;\n }\n }\n\n finalError = finalError || ({} as unknown);\n\n if (opts.throwOnError) {\n throw finalError;\n }\n\n // Return error response\n return opts.responseStyle === 'data'\n ? undefined\n : {\n error: finalError,\n request,\n response: undefined as any,\n };\n }\n\n for (const fn of interceptors.response.fns) {\n if (fn) {\n response = await fn(response, request, opts);\n }\n }\n\n const result = {\n request,\n response,\n };\n\n if (response.ok) {\n const parseAs =\n (opts.parseAs === 'auto'\n ? getParseAs(response.headers.get('Content-Type'))\n : opts.parseAs) ?? 'json';\n\n if (response.status === 204 || response.headers.get('Content-Length') === '0') {\n let emptyData: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'text':\n emptyData = await response[parseAs]();\n break;\n case 'formData':\n emptyData = new FormData();\n break;\n case 'stream':\n emptyData = response.body;\n break;\n case 'json':\n default:\n emptyData = {};\n break;\n }\n return opts.responseStyle === 'data'\n ? emptyData\n : {\n data: emptyData,\n ...result,\n };\n }\n\n let data: any;\n switch (parseAs) {\n case 'arrayBuffer':\n case 'blob':\n case 'formData':\n case 'text':\n data = await response[parseAs]();\n break;\n case 'json': {\n // Some servers return 200 with no Content-Length and empty body.\n // response.json() would throw; read as text and parse if non-empty.\n const text = await response.text();\n data = text ? JSON.parse(text) : {};\n break;\n }\n case 'stream':\n return opts.responseStyle === 'data'\n ? response.body\n : {\n data: response.body,\n ...result,\n };\n }\n\n if (parseAs === 'json') {\n if (opts.responseValidator) {\n await opts.responseValidator(data);\n }\n\n if (opts.responseTransformer) {\n data = await opts.responseTransformer(data);\n }\n }\n\n return opts.responseStyle === 'data'\n ? data\n : {\n data,\n ...result,\n };\n }\n\n const textError = await response.text();\n let jsonError: unknown;\n\n try {\n jsonError = JSON.parse(textError);\n } catch {\n // noop\n }\n\n const error = jsonError ?? textError;\n let finalError = error;\n\n for (const fn of interceptors.error.fns) {\n if (fn) {\n finalError = (await fn(error, response, request, opts)) as string;\n }\n }\n\n finalError = finalError || ({} as string);\n\n if (opts.throwOnError) {\n throw finalError;\n }\n\n // TODO: we probably want to return error and improve types\n return opts.responseStyle === 'data'\n ? undefined\n : {\n error: finalError,\n ...result,\n };\n };\n\n const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>\n request({ ...options, method });\n\n const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {\n const { opts, url } = await beforeRequest(options);\n return createSseClient({\n ...opts,\n body: opts.body as BodyInit | null | undefined,\n headers: opts.headers as unknown as Record<string, string>,\n method,\n onRequest: async (url, init) => {\n let request = new Request(url, init);\n for (const fn of interceptors.request.fns) {\n if (fn) {\n request = await fn(request, opts);\n }\n }\n return request;\n },\n serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,\n url,\n });\n };\n\n const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });\n\n return {\n buildUrl: _buildUrl,\n connect: makeMethodFn('CONNECT'),\n delete: makeMethodFn('DELETE'),\n get: makeMethodFn('GET'),\n getConfig,\n head: makeMethodFn('HEAD'),\n interceptors,\n options: makeMethodFn('OPTIONS'),\n patch: makeMethodFn('PATCH'),\n post: makeMethodFn('POST'),\n put: makeMethodFn('PUT'),\n request,\n setConfig,\n sse: {\n connect: makeSseFn('CONNECT'),\n delete: makeSseFn('DELETE'),\n get: makeSseFn('GET'),\n head: makeSseFn('HEAD'),\n options: makeSseFn('OPTIONS'),\n patch: makeSseFn('PATCH'),\n post: makeSseFn('POST'),\n put: makeSseFn('PUT'),\n trace: makeSseFn('TRACE'),\n },\n trace: makeMethodFn('TRACE'),\n } as Client;\n};\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type ClientOptions, type Config, createClient, createConfig } from './client';\nimport type { ClientOptions as ClientOptions2 } from './types.gen';\n\n/**\n * The `createClientConfig()` function will be called on client initialization\n * and the returned object will become the client's initial configuration.\n *\n * You may want to initialize your client this way instead of calling\n * `setConfig()`. This is useful for example if you're using Next.js\n * to ensure your client always has the correct values.\n */\nexport type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;\n\nexport const client = createClient(createConfig<ClientOptions2>({ baseUrl: 'http://localhost:9000/api/widget' }));\n","import { client } from './v1/client.gen';\n\nexport function setupWidgetClient(widgetUrl: string, widgetToken?: string) {\n client.setConfig({\n baseUrl: widgetUrl,\n headers: widgetToken\n ? {\n Authorization: `Bearer ${widgetToken}`,\n }\n : undefined,\n });\n}\n\nexport { client };\n","// This file is auto-generated by @hey-api/openapi-ts\n\nimport { type Client, formDataBodySerializer, type Options as Options2, type TDataShape } from './client';\nimport { client } from './client.gen';\nimport type { DownloadWidgetAttachmentData, DownloadWidgetAttachmentErrors, DownloadWidgetAttachmentResponses, GetWidgetThreadData, GetWidgetThreadErrors, GetWidgetThreadResponses, ListWidgetThreadsData, ListWidgetThreadsErrors, ListWidgetThreadsResponses, UploadWidgetAttachmentData, UploadWidgetAttachmentErrors, UploadWidgetAttachmentResponses, WidgetLoginData, WidgetLoginErrors, WidgetLoginResponses } from './types.gen';\n\nexport type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {\n /**\n * You can provide a client instance returned by `createClient()` instead of\n * individual options. This might be also useful if you want to implement a\n * custom client.\n */\n client?: Client;\n /**\n * You can pass arbitrary values through the `meta` object. This can be\n * used to access values that aren't defined as part of the SDK function.\n */\n meta?: Record<string, unknown>;\n};\n\n/**\n * Widget authentication\n */\nexport const widgetLogin = <ThrowOnError extends boolean = false>(options: Options<WidgetLoginData, ThrowOnError>) => (options.client ?? client).post<WidgetLoginResponses, WidgetLoginErrors, ThrowOnError>({\n url: '/login',\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...options.headers\n }\n});\n\n/**\n * List user threads\n */\nexport const listWidgetThreads = <ThrowOnError extends boolean = false>(options?: Options<ListWidgetThreadsData, ThrowOnError>) => (options?.client ?? client).get<ListWidgetThreadsResponses, ListWidgetThreadsErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/threads',\n ...options\n});\n\n/**\n * Get thread details\n */\nexport const getWidgetThread = <ThrowOnError extends boolean = false>(options: Options<GetWidgetThreadData, ThrowOnError>) => (options.client ?? client).get<GetWidgetThreadResponses, GetWidgetThreadErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/threads/{threadUid}',\n ...options\n});\n\n/**\n * Upload attachment\n */\nexport const uploadWidgetAttachment = <ThrowOnError extends boolean = false>(options: Options<UploadWidgetAttachmentData, ThrowOnError>) => (options.client ?? client).post<UploadWidgetAttachmentResponses, UploadWidgetAttachmentErrors, ThrowOnError>({\n ...formDataBodySerializer,\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/attachments/upload',\n ...options,\n headers: {\n 'Content-Type': null,\n ...options.headers\n }\n});\n\n/**\n * Download attachment\n */\nexport const downloadWidgetAttachment = <ThrowOnError extends boolean = false>(options: Options<DownloadWidgetAttachmentData, ThrowOnError>) => (options.client ?? client).get<DownloadWidgetAttachmentResponses, DownloadWidgetAttachmentErrors, ThrowOnError>({\n security: [{ scheme: 'bearer', type: 'http' }],\n url: '/attachments/{filename}',\n ...options\n});\n","import '../shared/api/setup';\nimport {\n uploadWidgetAttachment,\n downloadWidgetAttachment,\n} from '../shared/api/v1/sdk.gen';\nimport type { AttachmentResponse } from '@/shared/api/v1/types.gen';\n\nexport type { AttachmentResponse };\n\nexport const attachmentApi = {\n upload: async (\n file: File,\n prefix: string,\n ocr?: boolean\n ): Promise<AttachmentResponse> => {\n const { data } = await uploadWidgetAttachment({\n body: { file, prefix, ocr },\n throwOnError: true,\n });\n return data!.data!;\n },\n\n download: async (\n filePath: string,\n originalName: string\n ): Promise<void> => {\n const parts = filePath.split('/');\n const filename = parts[parts.length - 1];\n const prefix = parts.slice(-3, -1).join('/');\n\n const { data } = await downloadWidgetAttachment({\n path: { filename },\n query: prefix ? { prefix } : {},\n parseAs: 'blob',\n throwOnError: true,\n });\n\n const url = URL.createObjectURL(data as Blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = originalName;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n },\n};\n","import { useState, useEffect, useRef, type KeyboardEvent } from 'react';\nimport type { InputProps } from '@copilotkit/react-ui';\nimport { Paperclip, X, Download } from 'lucide-react';\nimport { attachmentApi, type AttachmentResponse } from '../lib/attachment-api';\nimport './erica-components.css';\n\nexport type AttachedFile = {\n id: string;\n name: string;\n mimeType: string;\n status: 'uploading' | 'done' | 'error';\n response?: AttachmentResponse;\n errorMessage?: string;\n};\n\ntype EricaChatInputProps = InputProps & {\n threadId?: string;\n};\n\nexport function EricaChatInput({\n onSend,\n inProgress,\n threadId,\n}: EricaChatInputProps) {\n const [text, setText] = useState('');\n const [attachedFiles, setAttachedFiles] = useState<AttachedFile[]>([]);\n const [isDraggingOver, setIsDraggingOver] = useState(false);\n const [downloadingFileId, setDownloadingFileId] = useState<string | null>(null);\n \n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const dragCounter = useRef(0);\n\n useEffect(() => {\n const textarea = textareaRef.current;\n if (textarea) {\n textarea.style.height = 'auto';\n const scrollHeight = textarea.scrollHeight;\n textarea.style.height = `${scrollHeight}px`;\n }\n }, [text]);\n\n async function uploadFile(file: File) {\n const id = `${file.name}-${Date.now()}`;\n setAttachedFiles(prev => [\n ...prev,\n {\n id,\n name: file.name,\n mimeType: file.type || 'application/octet-stream',\n status: 'uploading',\n },\n ]);\n\n try {\n const response = await attachmentApi.upload(\n file,\n `thread/${threadId || crypto.randomUUID()}`,\n true\n );\n setAttachedFiles(prev =>\n prev.map(f => (f.id === id ? { ...f, status: 'done', response } : f))\n );\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'Upload failed';\n setAttachedFiles(prev =>\n prev.map(f =>\n f.id === id ? { ...f, status: 'error', errorMessage: msg } : f\n )\n );\n }\n }\n\n function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {\n const files = e.target.files;\n if (!files || files.length === 0) return;\n\n const existingNames = new Set(attachedFiles.map(f => f.name));\n Array.from(files)\n .filter(f => !existingNames.has(f.name))\n .forEach(uploadFile);\n\n e.target.value = '';\n }\n\n function removeFile(id: string) {\n setAttachedFiles(prev => prev.filter(f => f.id !== id));\n }\n\n async function handleDownloadFile(file: AttachedFile) {\n if (!file.response) return;\n \n setDownloadingFileId(file.id);\n try {\n await attachmentApi.download(\n file.response.file_path,\n file.response.original_name\n );\n } catch (err) {\n console.error('Download failed:', err);\n alert(`Failed to download ${file.name}`);\n } finally {\n setDownloadingFileId(null);\n }\n }\n\n function handleDragEnter(e: React.DragEvent) {\n e.preventDefault();\n dragCounter.current += 1;\n if (e.dataTransfer.types.includes('Files')) setIsDraggingOver(true);\n }\n\n function handleDragLeave(e: React.DragEvent) {\n e.preventDefault();\n dragCounter.current -= 1;\n if (dragCounter.current === 0) setIsDraggingOver(false);\n }\n\n function handleDragOver(e: React.DragEvent) {\n e.preventDefault();\n }\n\n function handleDrop(e: React.DragEvent) {\n e.preventDefault();\n dragCounter.current = 0;\n setIsDraggingOver(false);\n \n const files = Array.from(e.dataTransfer.files);\n if (files.length === 0) return;\n\n const existingNames = new Set(attachedFiles.map(f => f.name));\n files.filter(f => !existingNames.has(f.name)).forEach(uploadFile);\n }\n\n function handleSend() {\n if (!text.trim() && attachedFiles.length === 0) return;\n\n const doneAttachments = attachedFiles\n .filter(f => f.status === 'done')\n .filter(f => f.response !== null)\n .map(f => f.response!)\n .map(({ ocr_result, ...rest }) => ({\n ...rest,\n ocr_result: ocr_result?.markdown_files,\n }));\n\n let messageContent = text;\n\n if (doneAttachments.length > 0) {\n messageContent += `\\n\\n\\`\\`\\`attachments\\n${JSON.stringify(doneAttachments, null, 2)}\\n\\`\\`\\``;\n }\n\n onSend(messageContent);\n setText('');\n setAttachedFiles([]);\n }\n\n function handleKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSend();\n }\n }\n\n function handleContainerClick() {\n textareaRef.current?.focus();\n }\n\n return (\n <div\n className=\"copilotKitInputContainer relative\"\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n onDragOver={handleDragOver}\n onDrop={handleDrop}\n >\n {isDraggingOver && (\n <div className=\"erica-drag-overlay\">\n <p className=\"erica-drag-overlay-text\">\n Drop files to attach\n </p>\n </div>\n )}\n\n {attachedFiles.length > 0 && (\n <div className=\"erica-file-list\">\n {attachedFiles.map(file => (\n <div\n key={file.id}\n className={`erica-file-item ${\n file.status === 'error' ? 'erica-file-item--error' :\n file.status === 'done' ? 'erica-file-item--done' :\n 'erica-file-item--uploading'\n }`}\n >\n <div\n className={`erica-file-content ${\n file.status === 'done' ? 'erica-file-content--clickable' : ''\n }`}\n onClick={() => file.status === 'done' && handleDownloadFile(file)}\n role={file.status === 'done' ? 'button' : undefined}\n tabIndex={file.status === 'done' ? 0 : undefined}\n >\n {file.status === 'uploading' ? (\n <div className=\"erica-spinner erica-spinner--gray\" />\n ) : downloadingFileId === file.id ? (\n <div className=\"erica-spinner erica-spinner--green\" />\n ) : file.status === 'done' ? (\n <Paperclip className=\"erica-icon-sm erica-icon-green\" />\n ) : (\n <Paperclip className=\"erica-icon-sm erica-icon-red\" />\n )}\n \n <div className=\"erica-file-info\">\n <div className={`erica-file-name ${\n file.status === 'error' ? 'erica-file-name--error' :\n file.status === 'done' ? 'erica-file-name--done' :\n 'erica-file-name--uploading'\n }`}>\n {file.name}\n {downloadingFileId === file.id && (\n <span className=\"erica-downloading-badge\">Downloading...</span>\n )}\n </div>\n <div className=\"erica-file-status\">\n {file.status === 'uploading' && 'Uploading...'}\n {file.status === 'done' && 'Ready · Click to download'}\n {file.status === 'error' && (file.errorMessage || 'Upload failed')}\n </div>\n </div>\n\n {file.status === 'done' && !downloadingFileId && (\n <Download className=\"erica-download-icon\" />\n )}\n </div>\n\n <button\n onClick={(e) => {\n e.stopPropagation();\n removeFile(file.id);\n }}\n disabled={file.status === 'uploading'}\n className=\"erica-remove-button\"\n aria-label={`Remove ${file.name}`}\n >\n <X className=\"erica-icon-sm erica-icon-gray\" />\n </button>\n </div>\n ))}\n </div>\n )}\n\n <div className=\"copilotKitInput\" onClick={handleContainerClick}>\n <textarea\n ref={textareaRef}\n value={text}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={handleKeyDown}\n placeholder={\n attachedFiles.length > 0\n ? `Ask about ${attachedFiles.length} file${attachedFiles.length > 1 ? 's' : ''}...`\n : 'Type a message or attach files...'\n }\n className=\"erica-textarea\"\n rows={1}\n disabled={inProgress}\n />\n <div className=\"copilotKitInputControls\">\n <input\n ref={fileInputRef}\n type=\"file\"\n onChange={handleFileSelect}\n className=\"erica-file-input\"\n disabled={inProgress}\n multiple\n />\n <button\n onClick={() => fileInputRef.current?.click()}\n disabled={inProgress}\n className=\"copilotKitInputControlButton erica-attach-button\"\n aria-label=\"Attach files\"\n title=\"Attach files (drag & drop supported)\"\n >\n <Paperclip className=\"erica-icon-md\" />\n </button>\n <div className=\"erica-spacer\"></div>\n <button\n onClick={handleSend}\n disabled={inProgress || (!text.trim() && attachedFiles.filter(f => f.status === 'done').length === 0)}\n data-copilotkit-in-progress={inProgress}\n className=\"copilotKitInputControlButton\"\n >\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth=\"1.5\"\n stroke=\"currentColor\"\n width=\"24\"\n height=\"24\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M12 19V5m0 0l-7 7m7-7l7 7\"\n />\n </svg>\n </button>\n </div>\n </div>\n </div>\n );\n}\n","import '../shared/api/setup';\nimport {\n listWidgetThreads,\n getWidgetThread,\n} from '../shared/api/v1/sdk.gen';\nimport type { ThreadResponse } from '@/shared/api/v1/types.gen';\n\nexport type { ThreadResponse };\n\nexport const threadApi = {\n list: async (limit = 15) => {\n const { data } = await listWidgetThreads({\n query: { page: 1, page_size: limit },\n throwOnError: true,\n });\n return data!.data ?? [];\n },\n\n get: async (threadUid: string) => {\n const { data } = await getWidgetThread({\n path: { threadUid },\n throwOnError: true,\n });\n return data!.data!;\n },\n};\n","import { useQuery } from '@tanstack/react-query';\nimport { threadApi } from '../lib/thread-api';\n\nexport const threadKeys = {\n all: () => ['widget-threads'] as const,\n detail: (threadUid: string) => ['widget-threads', threadUid] as const,\n};\n\nexport const useThreads = (limit = 15) =>\n useQuery({\n queryKey: threadKeys.all(),\n queryFn: () => threadApi.list(limit),\n staleTime: 15_000,\n refetchOnWindowFocus: true,\n });\n\nexport const useThread = (threadUid: string) =>\n useQuery({\n queryKey: threadKeys.detail(threadUid),\n queryFn: () => threadApi.get(threadUid),\n enabled: !!threadUid,\n });\n","import { useState, useRef, useEffect } from 'react';\nimport { PenSquare, ChevronDown } from 'lucide-react';\nimport { useThreads } from '../hooks/use-threads';\nimport type { ThreadResponse } from '../lib/thread-api';\nimport './erica-components.css';\n\ntype EricaChatHeaderProps = {\n onNewChat?: () => void;\n onThreadSelect?: (threadUid: string) => void;\n};\n\nfunction normalizeAgentDisplay(agent: string | null | undefined): string {\n if (!agent) return '';\n const parts = agent.split(':');\n const name = parts.length > 1 ? parts.slice(1).join(' ') : agent;\n return name.replace(/[-_]/g, ' ').replace(/\\b\\w/g, c => c.toUpperCase());\n}\n\nfunction formatRelativeTime(dateStr: string | null | undefined): string {\n if (!dateStr) return '';\n const diffMs = Date.now() - new Date(dateStr).getTime();\n const diffMins = Math.floor(diffMs / 60_000);\n const diffHours = Math.floor(diffMins / 60);\n const diffDays = Math.floor(diffHours / 24);\n if (diffMins < 1) return 'just now';\n if (diffMins < 60) return `${diffMins}m ago`;\n if (diffHours < 24) return `${diffHours}h ago`;\n if (diffDays < 7) return `${diffDays}d ago`;\n return new Date(dateStr).toLocaleDateString();\n}\n\nexport function EricaChatHeader({\n onNewChat,\n onThreadSelect,\n}: EricaChatHeaderProps) {\n const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n const dropdownRef = useRef<HTMLDivElement>(null);\n\n const { data: threads = [], isLoading } = useThreads();\n\n useEffect(() => {\n function handleClickOutside(event: MouseEvent) {\n if (\n dropdownRef.current &&\n !dropdownRef.current.contains(event.target as Node)\n ) {\n setIsDropdownOpen(false);\n }\n }\n\n if (isDropdownOpen) {\n document.addEventListener('mousedown', handleClickOutside);\n return () => {\n document.removeEventListener('mousedown', handleClickOutside);\n };\n }\n }, [isDropdownOpen]);\n\n function handleThreadClick(threadUid: string) {\n setIsDropdownOpen(false);\n onThreadSelect?.(threadUid);\n }\n\n return (\n <div className=\"erica-header\">\n {/* Left: Title */}\n <h2 className=\"erica-header-title\">\n Erica Assistant\n </h2>\n\n {/* Right: New Chat Button + Threads Dropdown */}\n <div className=\"erica-header-controls\" ref={dropdownRef}>\n {/* New Chat Button (icon only) */}\n <button\n onClick={onNewChat}\n className=\"erica-new-chat-button\"\n title=\"Start new chat\"\n >\n <PenSquare className=\"erica-icon-sm\" />\n </button>\n\n {/* Threads Dropdown Toggle */}\n <button\n onClick={() => setIsDropdownOpen(!isDropdownOpen)}\n className=\"erica-threads-toggle\"\n title=\"Recent threads\"\n >\n <span className=\"erica-threads-toggle-text\">\n Threads {threads.length > 0 && `(${threads.length})`}\n </span>\n <ChevronDown\n className={`erica-threads-toggle-icon ${\n isDropdownOpen ? 'erica-threads-toggle-icon--open' : ''\n }`}\n />\n </button>\n\n {/* Threads Dropdown Menu */}\n {isDropdownOpen && (\n <div className=\"erica-threads-dropdown\">\n <div className=\"erica-threads-dropdown-content\">\n <div className=\"erica-threads-dropdown-header\">\n Recent Threads\n </div>\n\n {isLoading && (\n <div className=\"erica-threads-empty\">\n Loading threads...\n </div>\n )}\n\n {!isLoading && threads.length === 0 && (\n <div className=\"erica-threads-empty\">\n No conversations yet\n </div>\n )}\n\n {!isLoading &&\n threads.map((thread: ThreadResponse) => {\n const agentLabel = normalizeAgentDisplay(thread.agent);\n const time = formatRelativeTime(\n thread.last_run_at ?? thread.created_at\n );\n const title =\n typeof thread.thread_metadata?.title === 'string'\n ? thread.thread_metadata.title\n : thread.last_message ?? 'New conversation';\n\n return (\n <button\n key={thread.uid}\n onClick={() => handleThreadClick(thread.uid)}\n className=\"erica-thread-item\"\n >\n <div className=\"erica-thread-item-content\">\n <span className=\"erica-thread-title\">\n {title}\n </span>\n <div className=\"erica-thread-meta\">\n {agentLabel && (\n <span className=\"erica-thread-agent\">\n {agentLabel}\n </span>\n )}\n {time && (\n <span className=\"erica-thread-time\">\n {time}\n </span>\n )}\n </div>\n </div>\n </button>\n );\n })}\n </div>\n </div>\n )}\n </div>\n </div>\n );\n}\n","import { useCallback, useMemo, useState } from 'react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { CopilotKit } from \"@copilotkit/react-core\";\nimport { CopilotSidebar } from \"@copilotkit/react-ui\";\nimport \"@copilotkit/react-ui/styles.css\";\nimport { EricaChatInput } from './EricaChatInput';\nimport { EricaChatHeader } from './EricaChatHeader';\nimport { setupWidgetClient } from '../shared/api/setup';\nimport type { InputProps } from '@copilotkit/react-ui';\n\nconst queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n refetchOnWindowFocus: false,\n retry: 1,\n staleTime: 30_000,\n },\n },\n});\n\nexport interface EricaChatProps {\n runtimeUrl: string;\n widgetToken: string;\n}\n\nexport function EricaChat({\n runtimeUrl,\n widgetToken,\n}: EricaChatProps) {\n const [threadId, setThreadId] = useState<string | undefined>(undefined);\n\n // Extract base widget URL (remove accountUid path for widget API)\n const widgetBaseUrl = useMemo(() => {\n // runtimeUrl format: http://localhost:9000/api/widget/{accountUid}\n // We need: http://localhost:9000/api/widget\n const url = new URL(runtimeUrl);\n const pathParts = url.pathname.split('/').filter(Boolean);\n // Remove last part (accountUid) if present\n if (pathParts.length > 2) {\n pathParts.pop();\n }\n url.pathname = '/' + pathParts.join('/');\n return url.toString();\n }, [runtimeUrl]);\n\n // Setup client immediately before any render\n useMemo(() => {\n setupWidgetClient(widgetBaseUrl, widgetToken);\n }, [widgetBaseUrl, widgetToken]);\n\n const handleNewChat = useCallback(() => {\n setThreadId(undefined);\n console.log('New chat started');\n }, []);\n\n const handleThreadSelect = useCallback((threadUid: string) => {\n setThreadId(threadUid);\n console.log('Thread selected:', threadUid);\n }, []);\n\n const EricaChatInputWrapper = useCallback(\n (props: InputProps) => (\n <EricaChatInput {...props} threadId={threadId} />\n ),\n [threadId]\n );\n\n const EricaChatHeaderWrapper = useCallback(\n () => (\n <EricaChatHeader\n onNewChat={handleNewChat}\n onThreadSelect={handleThreadSelect}\n />\n ),\n [handleNewChat, handleThreadSelect]\n );\n\n return (\n <QueryClientProvider client={queryClient}>\n <div className=\"h-full w-full\">\n <CopilotKit\n runtimeUrl={runtimeUrl}\n headers={{\n Authorization: `Bearer ${widgetToken}`,\n }}\n properties={{\n agent: \"platform:ultimate\",\n }}\n threadId={threadId}\n >\n <CopilotSidebar\n labels={{\n initial: \"Hi! How can I help you today?\\n\\nYou can:\\n- Ask me questions\\n- Upload files using the attachment icon\\n- Drag & drop files to attach\",\n }}\n defaultOpen={true}\n clickOutsideToClose={true}\n Input={EricaChatInputWrapper}\n Header={EricaChatHeaderWrapper}\n />\n </CopilotKit>\n </div>\n </QueryClientProvider>\n );\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"mappings":";;;;;;AACA,IAAI,IAAe,MAAM;CACvB,cAAc;AAEZ,EADA,KAAK,4BAA4B,IAAI,KAAK,EAC1C,KAAK,YAAY,KAAK,UAAU,KAAK,KAAK;;CAE5C,UAAU,GAAU;AAGlB,SAFA,KAAK,UAAU,IAAI,EAAS,EAC5B,KAAK,aAAa,QACL;AAEX,GADA,KAAK,UAAU,OAAO,EAAS,EAC/B,KAAK,eAAe;;;CAGxB,eAAe;AACb,SAAO,KAAK,UAAU,OAAO;;CAE/B,cAAc;CAEd,gBAAgB;GC0Cd,IAAe,IA3DA,cAAc,EAAa;CAC5C;CACA;CACA;CACA,cAAc;AAEZ,EADA,OAAO,EACP,MAAA,KAAe,MAAY;AACzB,OAAI,OAAO,SAAW,OAAe,OAAO,kBAAkB;IAC5D,IAAM,UAAiB,GAAS;AAEhC,WADA,OAAO,iBAAiB,oBAAoB,GAAU,GAAM,QAC/C;AACX,YAAO,oBAAoB,oBAAoB,EAAS;;;;;CAMhE,cAAc;AACZ,EAAK,MAAA,KACH,KAAK,iBAAiB,MAAA,EAAY;;CAGtC,gBAAgB;AACd,EAAK,KAAK,cAAc,KACtB,MAAA,KAAiB,EACjB,MAAA,IAAgB,KAAK;;CAGzB,iBAAiB,GAAO;AAGtB,EAFA,MAAA,IAAc,GACd,MAAA,KAAiB,EACj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