@ahoo-wang/wow-react 10.0.0-alpha.5 → 10.0.0-alpha.7
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.
- package/README.md +138 -105
- package/README.zh-CN.md +115 -85
- package/dist/hooks/useAggregateQuery.d.ts +69 -0
- package/dist/hooks/useCountQuery.d.ts +5 -8
- package/dist/hooks/useCursorQuery.d.ts +90 -0
- package/dist/hooks/useListQuery.d.ts +7 -10
- package/dist/hooks/usePagedQuery.d.ts +8 -11
- package/dist/hooks/useSingleQuery.d.ts +14 -13
- package/dist/hooks/useStreamQuery.d.ts +109 -0
- package/dist/index.d.ts +3 -6
- package/dist/index.es.js +158 -178
- package/dist/index.es.js.map +1 -1
- package/dist/internal/queryTransitions.d.ts +6 -6
- package/dist/internal/readStreamRows.d.ts +5 -3
- package/dist/internal/useQueryRunner.d.ts +11 -9
- package/dist/types.d.ts +34 -22
- package/package.json +9 -11
- package/dist/hooks/useFetcherCountQuery.d.ts +0 -66
- package/dist/hooks/useFetcherListQuery.d.ts +0 -80
- package/dist/hooks/useFetcherListStreamQuery.d.ts +0 -66
- package/dist/hooks/useFetcherPagedQuery.d.ts +0 -75
- package/dist/hooks/useFetcherSingleQuery.d.ts +0 -71
- package/dist/hooks/useListStreamQuery.d.ts +0 -93
- package/dist/internal/endpoint.d.ts +0 -38
- package/dist/internal/useEndpointRunner.d.ts +0 -8
- package/dist/internal/useListStream.d.ts +0 -11
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","names":["QueryStatus","QueryState","status","result","R","error","E","QueryEvent","type","initialQueryState","runsOnMount","undefined","queryTransition","state","event","dequal","useCallback","useEffect","useLayoutEffect","useRef","useState","QueryHookOptions","QueryHookReturn","initialQueryState","queryTransition","QueryEvent","QueryState","useContentStable","value","kept","setKept","notify","name","callback","T","Promise","thrown","console","warn","isAbortError","error","Error","useQueryRunner","options","Q","R","E","identity","retainResult","autoExecute","query","state","setState","initialQuery","undefined","latest","current","request","id","controller","AbortController","mounted","settle","event","cancel","abort","execute","type","requestOptions","result","signal","aborted","onSuccess","onError","reset","getQuery","setQuery","previousQuery","cleared","status","loading","CountQuery","CountResult","useQueryRunner","QueryHookOptions","QueryHookReturn","UseCountQueryOptions","Error","FIELDS","Q","E","UseCountQueryReturn","useCountQuery","options","Fetcher","DEFAULT_FETCHER_NAME","getFetcher","QueryModelClient","ListStreamExecutor","QueryExecutor","Endpoint","url","fetcher","QueryKind","clientOf","postQuery","endpoint","kind","Q","R","query","options","client","run","Promise","call","postQueryStream","listStream","endpointIdentity","by","undefined","name","urlBuilder","baseURL","JSON","stringify","QueryHookOptions","QueryHookReturn","Endpoint","endpointIdentity","postQuery","QueryKind","useQueryRunner","useEndpointRunner","options","kind","$","_c","fetcher","rest","url","t0","t1","execute","t2","_c","CountQuery","CountResult","Endpoint","useEndpointRunner","QueryHookOptions","QueryHookReturn","UseFetcherCountQueryOptions","Error","FIELDS","Omit","Q","E","UseFetcherCountQueryReturn","useFetcherCountQuery","options","FilterListQuery","Endpoint","useEndpointRunner","QueryHookOptions","QueryHookReturn","UseFetcherListQueryOptions","Error","FIELDS","Omit","Q","R","E","UseFetcherListQueryReturn","useFetcherListQuery","options","PUBLISH_INTERVAL_MS","readStreamRows","stream","ReadableStream","R","signal","AbortSignal","publish","rows","Promise","reader","getReader","published","publishedAt","Infinity","timer","ReturnType","setTimeout","flush","undefined","clearTimeout","aborted","length","Date","now","slice","schedule","wait","Math","max","cancel","reason","catch","addEventListener","once","done","value","read","push","error","removeEventListener","releaseLock","useCallback","useState","FilterListQuery","UseListStreamQueryOptions","UseListStreamQueryReturn","readStreamRows","useQueryRunner","useListStream","options","identity","$","_c","items","setItems","_temp","openStream","execute","t0","query","options_0","stream","signal","t1","status","loading","error","abort","reset","getQuery","setQuery","t2","resetRows","t3","t4","done","_c","FilterListQuery","Endpoint","endpointIdentity","postQueryStream","useListStream","UseListStreamQueryOptions","UseListStreamQueryReturn","UseFetcherListStreamQueryOptions","Error","FIELDS","Omit","R","E","Q","UseFetcherListStreamQueryReturn","useFetcherListStreamQuery","options","$","_c","fetcher","rest","url","t0","t1","execute","t2","_c","PagedQuery","PagedResult","Endpoint","useEndpointRunner","QueryHookOptions","QueryHookReturn","UseFetcherPagedQueryOptions","Error","FIELDS","Omit","Q","R","E","UseFetcherPagedQueryReturn","useFetcherPagedQuery","options","FilterSingleQuery","Endpoint","useEndpointRunner","QueryHookOptions","QueryHookReturn","UseFetcherSingleQueryOptions","Error","FIELDS","Omit","Q","R","E","UseFetcherSingleQueryReturn","useFetcherSingleQuery","options","FilterListQuery","useQueryRunner","QueryHookOptions","QueryHookReturn","UseListQueryOptions","Error","FIELDS","Q","R","E","UseListQueryReturn","useListQuery","options","FilterListQuery","useListStream","ListStreamExecutor","QueryHookOptions","QueryHookReturn","UseListStreamQueryOptions","Error","FIELDS","Omit","Q","R","E","execute","UseListStreamQueryReturn","items","done","useListStreamQuery","options","PagedQuery","PagedResult","useQueryRunner","QueryHookOptions","QueryHookReturn","UsePagedQueryOptions","Error","FIELDS","Q","R","E","UsePagedQueryReturn","usePagedQuery","options","FilterSingleQuery","useQueryRunner","QueryHookOptions","QueryHookReturn","UseSingleQueryOptions","Error","FIELDS","Q","R","E","UseSingleQueryReturn","useSingleQuery","options","runsOnMount","event","state","kept","setKept","useState","value","dequal","callback","thrown","name","error","autoExecute","options","query","setState","latest","useRef","current","request","mounted","settle","useCallback","id","state_0","cancel","controller","execute_0","query_0","controller_0","id_0","state_1","result","execute","requestOptions","retainResult","abort","state_2","reset","state_3","getQuery","setQuery","query_1","previousQuery","useEffect","cleared","identity","QueryModelClient","url","getFetcher","fetcher","client","endpoint","kind","by","DEFAULT_FETCHER_NAME","$","c","rest","t0","t1","t2","reader","stream","rows","published","publishedAt","timer","publish","wait","signal","done","items","setItems","openStream","options_0","resetRows","t3","status","t4","loading"],"sources":["../src/internal/queryTransitions.ts","../src/internal/useQueryRunner.ts","../src/hooks/useCountQuery.ts","../src/internal/endpoint.ts","../src/internal/useEndpointRunner.ts","../src/hooks/useFetcherCountQuery.ts","../src/hooks/useFetcherListQuery.ts","../src/internal/readStreamRows.ts","../src/internal/useListStream.ts","../src/hooks/useFetcherListStreamQuery.ts","../src/hooks/useFetcherPagedQuery.ts","../src/hooks/useFetcherSingleQuery.ts","../src/hooks/useListQuery.ts","../src/hooks/useListStreamQuery.ts","../src/hooks/usePagedQuery.ts","../src/hooks/useSingleQuery.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*\n * What a query hook shows, and how each event changes it: section 3 of\n * docs/design/architecture.md as pure functions, with no React. The\n * request itself (aborting it, ignoring a late answer) is useQueryRunner's.\n */\n\nimport type { QueryStatus } from '../types.js';\n\n/** What a query hook shows at one moment. */\nexport interface QueryState<R, E> {\n status: QueryStatus;\n result: R | undefined;\n error: E | undefined;\n}\n\n/** Something that happens to a query hook. */\nexport type QueryEvent<R, E> =\n | { type: 'start' }\n | { type: 'succeed'; result: R | undefined }\n | { type: 'fail'; error: E }\n | { type: 'abort' }\n | { type: 'reset' };\n\n/**\n * The first state. A hook that will run its query as soon as it mounts\n * starts `loading`, so the server and the first client frame already show\n * what the next frames show; any other starts `idle`.\n */\nexport function initialQueryState<R, E>(\n runsOnMount: boolean,\n): QueryState<R, E> {\n return {\n status: runsOnMount ? 'loading' : 'idle',\n result: undefined,\n error: undefined,\n };\n}\n\n/**\n * The state after one event:\n *\n * - `start`: `loading`; the last result stays until the new one arrives, the\n * error goes.\n * - `succeed`: `success` with the new result (`undefined` for a hook that\n * keeps its own, as the list-stream hooks keep `items`).\n * - `fail`: `error`; the last result stays, so a failed refresh does not\n * blank what was shown.\n * - `abort`: `idle`; the last result stays, the error goes.\n * - `reset`: `idle`, with neither result nor error.\n */\nexport function queryTransition<R, E>(\n state: QueryState<R, E>,\n event: QueryEvent<R, E>,\n): QueryState<R, E> {\n switch (event.type) {\n case 'start':\n return { status: 'loading', result: state.result, error: undefined };\n case 'succeed':\n return { status: 'success', result: event.result, error: undefined };\n case 'fail':\n return { status: 'error', result: state.result, error: event.error };\n case 'abort':\n return { status: 'idle', result: state.result, error: undefined };\n case 'reset':\n return { status: 'idle', result: undefined, error: undefined };\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport {\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\nimport {\n initialQueryState,\n queryTransition,\n type QueryEvent,\n type QueryState,\n} from './queryTransitions.js';\n\n/**\n * `value`, or the one of an earlier render when that one has the same\n * content, so that an object rebuilt on every render keeps one identity.\n */\nfunction useContentStable<T>(value: T): T {\n const [kept, setKept] = useState(value);\n if (kept === value || dequal(kept, value)) return kept;\n setKept(value);\n return value;\n}\n\n/** Hands a callback its argument; one that throws never breaks the state. */\nasync function notify<T>(\n name: string,\n callback: ((value: T) => void | Promise<void>) | undefined,\n value: T,\n): Promise<void> {\n try {\n await callback?.(value);\n } catch (thrown) {\n // The state already shows the outcome; the host learns of its broken\n // callback without the hook swallowing it.\n // eslint-disable-next-line no-console\n console.warn(`wow-react: ${name} threw`, thrown);\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && error.name === 'AbortError';\n}\n\n/**\n * The one request state machine every hook runs on.\n *\n * - Latest wins: every run takes a new number and aborts the one before; an\n * answer that is no longer the latest, arrives after `abort()` or\n * `reset()`, or arrives after unmount, changes nothing.\n * - A run starts on mount, whenever the query changes by content or through\n * `setQuery()`, whenever `identity` changes, and when `autoExecute` turns\n * on; `execute()` starts one by hand.\n * - `abort()`, `reset()` and unmount abort the request in flight.\n * - StrictMode's second mount aborts the first run and starts one more, so\n * exactly one answer lands.\n *\n * `identity` is what else a run depends on besides the query: the endpoint\n * of a `useFetcher…` hook. With `retainResult` off the runner hands a run's\n * result to `onSuccess` but does not keep it as `result`: the list-stream\n * hooks keep their rows as `items` already. `execute`, `requestOptions` and the callbacks are read\n * when a run starts or settles, so a change to them never starts one.\n */\nexport function useQueryRunner<Q, R, E>(\n options: QueryHookOptions<Q, R, E>,\n identity?: string,\n retainResult = true,\n): QueryHookReturn<Q, R, E> {\n const autoExecute = options.autoExecute ?? true;\n const query = useContentStable(options.query);\n const [state, setState] = useState<QueryState<R, E>>(() =>\n initialQueryState(\n autoExecute && (options.query ?? options.initialQuery) !== undefined,\n ),\n );\n const latest = useRef(options);\n const current = useRef<Q | undefined>(options.query ?? options.initialQuery);\n const request = useRef<{ id: number; controller?: AbortController }>({\n id: 0,\n });\n const mounted = useRef(false);\n\n useLayoutEffect(() => {\n latest.current = options;\n });\n\n /** Applies an event unless run `id` is no longer the one that counts. */\n const settle = useCallback((id: number, event: QueryEvent<R, E>) => {\n if (!mounted.current || request.current.id !== id) return false;\n setState(state => queryTransition(state, event));\n return true;\n }, []);\n\n /** Stops the run in flight: no answer of it changes anything any more. */\n const cancel = useCallback(() => {\n const { controller } = request.current;\n request.current = { id: request.current.id + 1 };\n controller?.abort();\n }, []);\n\n const execute = useCallback(async () => {\n const query = current.current;\n if (!mounted.current || query === undefined) return;\n request.current.controller?.abort();\n const controller = new AbortController();\n const id = request.current.id + 1;\n request.current = { id, controller };\n setState(state => queryTransition(state, { type: 'start' }));\n const { execute, requestOptions } = latest.current;\n try {\n const result = await execute(query, {\n ...requestOptions,\n signal: controller.signal,\n });\n if (controller.signal.aborted) {\n settle(id, { type: 'abort' });\n } else if (\n settle(id, {\n type: 'succeed',\n result: retainResult ? result : undefined,\n })\n ) {\n await notify('onSuccess', latest.current.onSuccess, result);\n }\n } catch (error) {\n if (controller.signal.aborted || isAbortError(error)) {\n settle(id, { type: 'abort' });\n } else if (settle(id, { type: 'fail', error: error as E })) {\n await notify('onError', latest.current.onError, error as E);\n }\n } finally {\n if (request.current.controller === controller)\n request.current = { id: request.current.id };\n }\n }, [settle, retainResult]);\n\n const abort = useCallback(() => {\n cancel();\n setState(state => queryTransition(state, { type: 'abort' }));\n }, [cancel]);\n\n const reset = useCallback(() => {\n cancel();\n setState(state => queryTransition(state, { type: 'reset' }));\n }, [cancel]);\n\n const getQuery = useCallback(() => current.current, []);\n\n const setQuery = useCallback(\n (query: Q) => {\n current.current = query;\n if (latest.current.autoExecute ?? true) void execute();\n },\n [execute],\n );\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n cancel();\n };\n }, [cancel]);\n\n const previousQuery = useRef(query);\n useEffect(() => {\n const cleared = query === undefined && previousQuery.current !== undefined;\n previousQuery.current = query;\n if (cleared) {\n // A controlled query set to `undefined` (`id ? singleQuery(…) :\n // undefined`) means nothing to run: stop, keep what was shown.\n current.current = undefined;\n abort();\n return;\n }\n if (query !== undefined) current.current = query;\n if (autoExecute) void execute();\n }, [query, identity, autoExecute, execute, abort]);\n\n return {\n status: state.status,\n loading: state.status === 'loading',\n result: state.result,\n error: state.error,\n execute,\n abort,\n reset,\n getQuery,\n setQuery,\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { CountQuery, CountResult } from '@ahoo-wang/wow-client';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useCountQuery}: a filter and an `execute` that resolves to\n * how many rows it matches.\n *\n * @template FIELDS - The field names the filter may use\n * @template E - The error type, `Error` by default\n * @template Q - The filter type: `FilterExpression` by default\n */\nexport interface UseCountQueryOptions<\n FIELDS extends string = string,\n E = Error,\n Q extends CountQuery<FIELDS> = CountQuery<FIELDS>,\n> extends QueryHookOptions<Q, CountResult, E> {}\n\n/**\n * What {@link useCountQuery} returns: the count as `result`.\n *\n * @template FIELDS - The field names the filter may use\n * @template E - The error type, `Error` by default\n * @template Q - The filter type: `FilterExpression` by default\n */\nexport interface UseCountQueryReturn<\n FIELDS extends string = string,\n E = Error,\n Q extends CountQuery<FIELDS> = CountQuery<FIELDS>,\n> extends QueryHookReturn<Q, CountResult, E> {}\n\n/**\n * Counts what a filter matches through your own `execute` function and keeps\n * the count as state: typically a query client's `count`.\n *\n * `execute` receives the filter and the request options of the run, its\n * `signal` included; hand them on so that a newer query, `abort()`\n * or an unmount cancels the request. The count runs on mount and whenever\n * `query` or `setQuery()` changes the filter; set `autoExecute: false` to run\n * it only through `execute()`.\n *\n * Returns `result` (the count, or `undefined` before the first success),\n * `loading`, `error`, `status`, `execute`, `abort`, `reset`, `getQuery` and\n * `setQuery`.\n *\n * @template FIELDS - The field names the filter may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here; inferred from the first filter, they would admit only its\n * fields in `setQuery()`\n * @template E - The error type, `Error` by default\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient } from '@ahoo-wang/wow-client';\n * import { filter } from '@ahoo-wang/wow-client/dsl';\n * import { useCountQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidCount({ client }: { client: SnapshotQueryClient<OrderState, OrderFields> }) {\n * const { result, error } = useCountQuery<OrderFields>({\n * initialQuery: { filter: filter.eq('state.status', 'PAID') },\n * execute: (query, options) =>\n * client.count(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * return <p>{result?.count ?? '…'} paid orders</p>;\n * }\n * ```\n */\nexport function useCountQuery<FIELDS extends string = string, E = Error>(\n options: UseCountQueryOptions<FIELDS, E, CountQuery<FIELDS>>,\n): UseCountQueryReturn<FIELDS, E, CountQuery<FIELDS>>;\n/**\n * {@link useCountQuery} typed by a query `Q` of your own, a subtype of\n * `CountQuery`.\n */\nexport function useCountQuery<\n FIELDS extends string = string,\n E = Error,\n Q extends CountQuery<FIELDS> = CountQuery<FIELDS>,\n>(\n options: UseCountQueryOptions<FIELDS, E, Q>,\n): UseCountQueryReturn<FIELDS, E, Q>;\nexport function useCountQuery<\n FIELDS extends string,\n E,\n Q extends CountQuery<FIELDS>,\n>(\n options: UseCountQueryOptions<FIELDS, E, Q>,\n): UseCountQueryReturn<FIELDS, E, Q> {\n return useQueryRunner<Q, CountResult, E>(options);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*\n * The Wow query route protocol, in one place: a query is POSTed to the\n * model's query route (`/{context}/{aggregate}/{model}/query`) with a `kind`\n * naming the operation; wow-client's `QueryModelClient` speaks it. The\n * `useFetcher…` hooks are the matching `use…Query` hook with one of these\n * executors as `execute`.\n */\n\nimport type { Fetcher } from '@ahoo-wang/fetcher';\nimport { DEFAULT_FETCHER_NAME, getFetcher } from '@ahoo-wang/fetcher';\nimport { QueryModelClient } from '@ahoo-wang/wow-client';\nimport type { ListStreamExecutor, QueryExecutor } from '../types.js';\n\n/**\n * Where a `useFetcher…` hook sends its query. Every `useFetcher…Options`\n * extends it, so the two members are declared, and documented, once.\n */\nexport interface Endpoint {\n /**\n * The query route, resolved against the Fetcher's `baseURL`: for example\n * `/shop/order/snapshot/query` for the snapshots of the `order` aggregate\n * of the `shop` context.\n */\n url: string;\n /**\n * The Fetcher that sends the request, or the name of a registered one; the\n * default Fetcher when omitted.\n */\n fetcher?: string | Fetcher;\n}\n\n/** The operations of a query route that answer JSON. */\nexport type QueryKind = 'single' | 'list' | 'paged' | 'count';\n\n/**\n * The query route's client. The Fetcher is resolved when the request is\n * sent, so a name that is not registered fails that request, and the hook\n * reports it as its `error`.\n */\nfunction clientOf({ url, fetcher }: Endpoint): QueryModelClient<unknown> {\n return new QueryModelClient(url, { fetcher: getFetcher(fetcher) });\n}\n\n/** Runs a query of `kind` on the route and reads the JSON answer. */\nexport function postQuery<Q extends object, R>(\n endpoint: Endpoint,\n kind: QueryKind,\n): QueryExecutor<Q, R> {\n return (query, options) => {\n const client = clientOf(endpoint);\n const run = client[kind] as (query: Q, options: object) => Promise<R>;\n return run.call(client, query, options);\n };\n}\n\n/**\n * Opens the stream of a list query on the route: server-sent events, read\n * one record at a time; the stream errors with the problem the server sends\n * midway.\n */\nexport function postQueryStream<R, Q extends object>(\n endpoint: Endpoint,\n): ListStreamExecutor<R, Q> {\n return (query, options) =>\n (clientOf(endpoint) as QueryModelClient<R>).listStream(\n query as never,\n options,\n );\n}\n\n/**\n * What identifies an endpoint across renders: the url, and the Fetcher by\n * its name, or by its `baseURL` when it has none. A hook runs its query\n * again when this changes; a `new Fetcher({ baseURL })` written inline in\n * render keeps the same identity, so it does not run the query on every\n * render. Two unnamed Fetchers with one `baseURL` but different\n * interceptors count as the same; name them to tell them apart.\n */\nexport function endpointIdentity({ url, fetcher }: Endpoint): string {\n let by: string;\n if (fetcher === undefined) by = `name:${DEFAULT_FETCHER_NAME}`;\n else if (typeof fetcher === 'string') by = `name:${fetcher}`;\n else if ('name' in fetcher && typeof fetcher.name === 'string')\n by = `name:${fetcher.name}`;\n else by = `baseURL:${fetcher.urlBuilder.baseURL}`;\n return JSON.stringify([url, by]);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\nimport {\n type Endpoint,\n endpointIdentity,\n postQuery,\n type QueryKind,\n} from './endpoint.js';\nimport { useQueryRunner } from './useQueryRunner.js';\n\n/**\n * The request `useFetcher…` hooks: the runner with the endpoint's executor as\n * `execute`, and the endpoint as part of the request's identity, so a change\n * of `url` or `fetcher` runs the query again.\n */\nexport function useEndpointRunner<Q extends object, R, E>(\n options: Omit<QueryHookOptions<Q, R, E>, 'execute'> & Endpoint,\n kind: QueryKind,\n): QueryHookReturn<Q, R, E> {\n const { url, fetcher, ...rest } = options;\n return useQueryRunner<Q, R, E>(\n { ...rest, execute: postQuery<Q, R>({ url, fetcher }, kind) },\n endpointIdentity({ url, fetcher }),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { CountQuery, CountResult } from '@ahoo-wang/wow-client';\nimport type { Endpoint } from '../internal/endpoint.js';\nimport { useEndpointRunner } from '../internal/useEndpointRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useFetcherCountQuery}: those of every query hook, with\n * the endpoint and the Fetcher in place of `execute`.\n *\n * @template FIELDS - The field names the filter may use\n * @template E - The error type, `Error` by default\n * @template Q - The filter type: `FilterExpression` by default\n */\nexport interface UseFetcherCountQueryOptions<\n FIELDS extends string = string,\n E = Error,\n Q extends CountQuery<FIELDS> = CountQuery<FIELDS>,\n>\n extends Omit<QueryHookOptions<Q, CountResult, E>, 'execute'>, Endpoint {}\n\n/**\n * What {@link useFetcherCountQuery} returns: the count as `result`.\n *\n * @template FIELDS - The field names the filter may use\n * @template E - The error type, `Error` by default\n * @template Q - The filter type: `FilterExpression` by default\n */\nexport interface UseFetcherCountQueryReturn<\n FIELDS extends string = string,\n E = Error,\n Q extends CountQuery<FIELDS> = CountQuery<FIELDS>,\n> extends QueryHookReturn<Q, CountResult, E> {}\n\n/**\n * POSTs a count to a Wow query route through a Fetcher and keeps the\n * count as state.\n *\n * `url` is resolved against the Fetcher's `baseURL`; `fetcher` is a Fetcher\n * or the name of a registered one, the default Fetcher when omitted. The\n * count runs on mount and whenever `query` or `setQuery()` changes the\n * filter; set `autoExecute: false` to run it only through `execute()`. A\n * newer filter aborts the request in flight, so a late response never\n * overwrites a newer one; an unmount aborts it too.\n *\n * A change of `url`, or of `fetcher`, runs the query again. A Fetcher is\n * compared by its name, or by its `baseURL` when it has none, so one created\n * inline in render does not run it on every render.\n *\n * Returns `result` (the count, or `undefined` before the first success),\n * `loading`, `error`, `status`, `execute`, `abort`, `reset`, `getQuery` and\n * `setQuery`. A failed request sets `error` to the\n * `WowProblemError` the route answered with.\n *\n * @template FIELDS - The field names the filter may use\n * @template E - The error type, `Error` by default\n *\n * @example\n * ```tsx\n * import { filter } from '@ahoo-wang/wow-client/dsl';\n * import { useFetcherCountQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidCount() {\n * const { result, error } = useFetcherCountQuery({\n * url: '/shop/order/snapshot/query',\n * initialQuery: { filter: filter.eq('state.status', 'PAID') },\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * return <p>{result?.count ?? '…'} paid orders</p>;\n * }\n * ```\n */\nexport function useFetcherCountQuery<FIELDS extends string = string, E = Error>(\n options: UseFetcherCountQueryOptions<FIELDS, E, CountQuery<FIELDS>>,\n): UseFetcherCountQueryReturn<FIELDS, E, CountQuery<FIELDS>>;\n/**\n * {@link useFetcherCountQuery} typed by a query `Q` of your own, a subtype of\n * `CountQuery`.\n */\nexport function useFetcherCountQuery<\n FIELDS extends string = string,\n E = Error,\n Q extends CountQuery<FIELDS> = CountQuery<FIELDS>,\n>(\n options: UseFetcherCountQueryOptions<FIELDS, E, Q>,\n): UseFetcherCountQueryReturn<FIELDS, E, Q>;\nexport function useFetcherCountQuery<\n FIELDS extends string,\n E,\n Q extends CountQuery<FIELDS>,\n>(\n options: UseFetcherCountQueryOptions<FIELDS, E, Q>,\n): UseFetcherCountQueryReturn<FIELDS, E, Q> {\n return useEndpointRunner<Q, CountResult, E>(options, 'count');\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterListQuery } from '@ahoo-wang/wow-client/dsl';\nimport type { Endpoint } from '../internal/endpoint.js';\nimport { useEndpointRunner } from '../internal/useEndpointRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useFetcherListQuery}: those of every query hook, with the\n * endpoint and the Fetcher in place of `execute`.\n *\n * @template R - One row of the list\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterListQuery` by default\n */\nexport interface UseFetcherListQueryOptions<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n>\n extends Omit<QueryHookOptions<Q, R[], E>, 'execute'>, Endpoint {}\n\n/**\n * What {@link useFetcherListQuery} returns: the rows as `result`.\n *\n * @template R - One row of the list\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterListQuery` by default\n */\nexport interface UseFetcherListQueryReturn<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends QueryHookReturn<Q, R[], E> {}\n\n/**\n * POSTs a list query to a Wow query route through a Fetcher and keeps the rows\n * as state.\n *\n * `url` is resolved against the Fetcher's `baseURL`; `fetcher` is a Fetcher\n * or the name of a registered one, the default Fetcher when omitted. The\n * query runs on mount and whenever `query` or `setQuery()` changes it; set\n * `autoExecute: false` to run it only through `execute()`. A newer query\n * aborts the request in flight, so a late response never overwrites a newer\n * one; an unmount aborts it too.\n *\n * A change of `url`, or of `fetcher`, runs the query again. A Fetcher is\n * compared by its name, or by its `baseURL` when it has none, so one created\n * inline in render does not run it on every render.\n *\n * Returns `result` (the rows, or `undefined` before the first success),\n * `loading`, `error`, `status`, `execute`, `abort`, `reset`, `getQuery` and\n * `setQuery`. A failed request sets `error` to the\n * `WowProblemError` the route answered with.\n *\n * @template R - One row of the list\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n *\n * @example\n * ```tsx\n * import { desc, filter, listQuery } from '@ahoo-wang/wow-client/dsl';\n * import type { SnapshotRecord } from '@ahoo-wang/wow-client';\n * import { useFetcherListQuery } from '@ahoo-wang/wow-react';\n *\n * function LatestOrders() {\n * const { result, loading, error, execute } = useFetcherListQuery<SnapshotRecord<OrderState>>({\n * url: '/shop/order/snapshot/query',\n * initialQuery: listQuery({\n * filter: filter.eq('state.status', 'PAID'),\n * sort: [desc('createTime')],\n * limit: 20,\n * }),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * if (loading || !result) return <p>Loading…</p>;\n * return (\n * <>\n * <ul>{result.map(order => <li key={order.aggregateId}>{order.state.status}</li>)}</ul>\n * <button onClick={execute}>Refresh</button>\n * </>\n * );\n * }\n * ```\n */\nexport function useFetcherListQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n>(\n options: UseFetcherListQueryOptions<R, FIELDS, E, FilterListQuery<FIELDS>>,\n): UseFetcherListQueryReturn<R, FIELDS, E, FilterListQuery<FIELDS>>;\n/**\n * {@link useFetcherListQuery} typed by a query `Q` of your own, a subtype of\n * `FilterListQuery`, such as one whose literal projection narrows the result.\n */\nexport function useFetcherListQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n>(\n options: UseFetcherListQueryOptions<R, FIELDS, E, Q>,\n): UseFetcherListQueryReturn<R, FIELDS, E, Q>;\nexport function useFetcherListQuery<\n R,\n FIELDS extends string,\n E,\n Q extends FilterListQuery<FIELDS>,\n>(\n options: UseFetcherListQueryOptions<R, FIELDS, E, Q>,\n): UseFetcherListQueryReturn<R, FIELDS, E, Q> {\n return useEndpointRunner<Q, R[], E>(options, 'list');\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The least time between two publishes while a stream is read: about one\n * frame, so the rows keep up with the screen while a long stream costs a\n * bounded number of renders.\n */\nexport const PUBLISH_INTERVAL_MS = 16;\n\n/**\n * Reads a stream of rows to its end and resolves to every row, in order.\n *\n * While it reads, it hands the rows received so far to `publish`: the first\n * rows on the next macrotask, then at most once every\n * {@link PUBLISH_INTERVAL_MS}. Publishing by time, not by network chunk,\n * bounds how often a long stream renders and copies its rows: one render per\n * interval however many chunks arrive in it, and each `publish` still gets a\n * new array. It publishes the last rows before it\n * resolves or rejects, so the rows before a failure stay visible.\n *\n * `signal` aborting cancels the stream — a fake or already-buffered body\n * does not end with the request — and stops every later `publish`: a newer\n * query or an unmount has taken over, and its rows must not be overwritten.\n * The reader is always released, so the stream never stays locked.\n *\n * Internal: not exported from the package.\n */\nexport async function readStreamRows<R>(\n stream: ReadableStream<R>,\n signal: AbortSignal,\n publish: (rows: R[]) => void,\n): Promise<R[]> {\n const reader = stream.getReader();\n const rows: R[] = [];\n let published = 0;\n let publishedAt = -Infinity;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const flush = () => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n if (signal.aborted || published === rows.length) return;\n published = rows.length;\n publishedAt = Date.now();\n publish(rows.slice());\n };\n const schedule = () => {\n if (timer !== undefined) return;\n const wait = Math.max(0, publishedAt + PUBLISH_INTERVAL_MS - Date.now());\n timer = setTimeout(flush, wait);\n };\n const cancel = () => {\n reader.cancel(signal.reason).catch(() => {\n // The stream had already failed; that failure is the one reported.\n });\n };\n if (signal.aborted) cancel();\n else signal.addEventListener('abort', cancel, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n rows.push(value);\n schedule();\n }\n flush();\n return rows;\n } catch (error) {\n flush();\n throw error;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n signal.removeEventListener('abort', cancel);\n reader.releaseLock();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useState } from 'react';\nimport type { FilterListQuery } from '@ahoo-wang/wow-client/dsl';\nimport type {\n UseListStreamQueryOptions,\n UseListStreamQueryReturn,\n} from '../hooks/useListStreamQuery.js';\nimport { readStreamRows } from './readStreamRows.js';\nimport { useQueryRunner } from './useQueryRunner.js';\n\n/**\n * The list-stream hooks on the request state machine: a run opens the\n * stream and reads it into `items`. Each run starts from no rows; `abort()`\n * and an error keep the rows received; `reset()` empties them. The runner\n * aborts the run's signal whenever the run stops counting, and\n * readStreamRows stops publishing then, so rows of a stale stream never\n * reach `items`.\n */\nexport function useListStream<\n R,\n FIELDS extends string,\n E,\n Q extends FilterListQuery<FIELDS>,\n>(\n options: UseListStreamQueryOptions<R, FIELDS, E, Q>,\n identity?: string,\n): UseListStreamQueryReturn<R, FIELDS, E, Q> {\n const [items, setItems] = useState<R[]>(() => []);\n const openStream = options.execute;\n const { status, loading, error, execute, abort, reset, getQuery, setQuery } =\n useQueryRunner<Q, R[], E>(\n {\n ...options,\n execute: async (query, options) => {\n setItems([]);\n const stream = await openStream(query, options);\n return readStreamRows(stream, options.signal, setItems);\n },\n },\n identity,\n false,\n );\n const resetRows = useCallback(() => {\n reset();\n setItems([]);\n }, [reset]);\n return {\n items,\n done: status === 'success',\n loading,\n error,\n status,\n execute,\n abort,\n reset: resetRows,\n getQuery,\n setQuery,\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterListQuery } from '@ahoo-wang/wow-client/dsl';\nimport {\n type Endpoint,\n endpointIdentity,\n postQueryStream,\n} from '../internal/endpoint.js';\nimport { useListStream } from '../internal/useListStream.js';\nimport {\n type UseListStreamQueryOptions,\n type UseListStreamQueryReturn,\n} from './useListStreamQuery.js';\n\n/**\n * Options of {@link useFetcherListStreamQuery}: those of `useListStreamQuery`,\n * with the endpoint and the Fetcher in place of `execute`.\n *\n * @template R - One row of the stream: the `data` of each event\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default: a failed request\n * rejects with a `WowProblemError`, and so does an error event in the\n * stream\n * @template Q - The query type: `FilterListQuery` by default\n */\nexport interface UseFetcherListStreamQueryOptions<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n>\n extends\n Omit<UseListStreamQueryOptions<R, FIELDS, E, Q>, 'execute'>,\n Endpoint {}\n\n/**\n * What {@link useFetcherListStreamQuery} returns; see\n * {@link UseListStreamQueryReturn}.\n */\nexport interface UseFetcherListStreamQueryReturn<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends UseListStreamQueryReturn<R, FIELDS, E, Q> {}\n\n/**\n * Streams the rows of a list query from a Wow query route and keeps them as\n * state; see `useListStreamQuery` for the state it returns.\n *\n * It POSTs the query to `url` through `fetcher` (the default Fetcher when\n * omitted) with `Accept: text/event-stream`, the header a Wow service needs\n * to answer with an event stream rather than JSON. An error event in the\n * stream ends it with a `WowProblemError` in `error`.\n *\n * A change of `url`, or of `fetcher`, runs the query again. A Fetcher is\n * compared by its name, or by its `baseURL` when it has none, so one created\n * inline in render does not run it on every render.\n *\n * @template R - One row of the stream: the `data` of each event\n * @template FIELDS - The field names the query may use\n * @template E - The error type\n *\n * @example\n * ```tsx\n * import { filter, listQuery } from '@ahoo-wang/wow-client/dsl';\n * import type { SnapshotRecord } from '@ahoo-wang/wow-client';\n * import { useFetcherListStreamQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidOrders() {\n * const { items, done, loading, error } = useFetcherListStreamQuery<SnapshotRecord<OrderState>>({\n * url: '/shop/order/snapshot/query',\n * initialQuery: listQuery({ filter: filter.eq('state.status', 'PAID') }),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * return (\n * <>\n * <ul>{items.map(order => <li key={order.aggregateId}>{order.state.status}</li>)}</ul>\n * {loading ? <p>Loading…</p> : done && <p>{items.length} orders</p>}\n * </>\n * );\n * }\n * ```\n */\nexport function useFetcherListStreamQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n>(\n options: UseFetcherListStreamQueryOptions<\n R,\n FIELDS,\n E,\n FilterListQuery<FIELDS>\n >,\n): UseFetcherListStreamQueryReturn<R, FIELDS, E, FilterListQuery<FIELDS>>;\n/**\n * {@link useFetcherListStreamQuery} typed by a query `Q` of your own, a subtype of\n * `FilterListQuery`, such as one whose literal projection narrows the result.\n */\nexport function useFetcherListStreamQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n>(\n options: UseFetcherListStreamQueryOptions<R, FIELDS, E, Q>,\n): UseFetcherListStreamQueryReturn<R, FIELDS, E, Q>;\nexport function useFetcherListStreamQuery<\n R,\n FIELDS extends string,\n E,\n Q extends FilterListQuery<FIELDS>,\n>(\n options: UseFetcherListStreamQueryOptions<R, FIELDS, E, Q>,\n): UseFetcherListStreamQueryReturn<R, FIELDS, E, Q> {\n const { url, fetcher, ...rest } = options;\n return useListStream<R, FIELDS, E, Q>(\n { ...rest, execute: postQueryStream<R, Q>({ url, fetcher }) },\n endpointIdentity({ url, fetcher }),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PagedQuery, PagedResult } from '@ahoo-wang/wow-client';\nimport type { Endpoint } from '../internal/endpoint.js';\nimport { useEndpointRunner } from '../internal/useEndpointRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useFetcherPagedQuery}: those of every query hook, with\n * the endpoint and the Fetcher in place of `execute`.\n *\n * @template R - One row of the page\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterPagedQuery` by default\n */\nexport interface UseFetcherPagedQueryOptions<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends PagedQuery<FIELDS> = PagedQuery<FIELDS>,\n>\n extends Omit<QueryHookOptions<Q, PagedResult<R>, E>, 'execute'>, Endpoint {}\n\n/**\n * What {@link useFetcherPagedQuery} returns: the page (`total` and `list`)\n * as `result`.\n *\n * @template R - One row of the page\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterPagedQuery` by default\n */\nexport interface UseFetcherPagedQueryReturn<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends PagedQuery<FIELDS> = PagedQuery<FIELDS>,\n> extends QueryHookReturn<Q, PagedResult<R>, E> {}\n\n/**\n * POSTs a paged query to a Wow query route through a Fetcher and keeps the page\n * as state.\n *\n * `url` is resolved against the Fetcher's `baseURL`; `fetcher` is a Fetcher\n * or the name of a registered one, the default Fetcher when omitted. The\n * query runs on mount and whenever `query` or `setQuery()` changes it — turn\n * pages with `setQuery()`; set `autoExecute: false` to run it only through\n * `execute()`. A newer query aborts the request in flight, so a late response\n * never overwrites a newer one; an unmount aborts it too.\n *\n * A change of `url`, or of `fetcher`, runs the query again. A Fetcher is\n * compared by its name, or by its `baseURL` when it has none, so one created\n * inline in render does not run it on every render.\n *\n * Returns `result` (`{ total, list }`, or `undefined` before the first\n * success), `loading`, `error`, `status`, `execute`, `abort`, `reset`,\n * `getQuery` and `setQuery`. A failed request sets `error` to the\n * `WowProblemError` the route answered with.\n *\n * @template R - One row of the page\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n *\n * @example\n * ```tsx\n * import { filter, pagedQuery } from '@ahoo-wang/wow-client/dsl';\n * import type { SnapshotRecord } from '@ahoo-wang/wow-client';\n * import { useFetcherPagedQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidOrders({ page }: { page: number }) {\n * const { result, loading, error } = useFetcherPagedQuery<SnapshotRecord<OrderState>>({\n * url: '/shop/order/snapshot/query',\n * query: pagedQuery({\n * filter: filter.eq('state.status', 'PAID'),\n * pagination: { index: page, size: 20 },\n * }),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * if (loading || !result) return <p>Loading…</p>;\n * return <p>{result.list.length} of {result.total}</p>;\n * }\n * ```\n */\nexport function useFetcherPagedQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n>(\n options: UseFetcherPagedQueryOptions<R, FIELDS, E, PagedQuery<FIELDS>>,\n): UseFetcherPagedQueryReturn<R, FIELDS, E, PagedQuery<FIELDS>>;\n/**\n * {@link useFetcherPagedQuery} typed by a query `Q` of your own, a subtype of\n * `PagedQuery`, such as one whose literal projection narrows the result.\n */\nexport function useFetcherPagedQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends PagedQuery<FIELDS> = PagedQuery<FIELDS>,\n>(\n options: UseFetcherPagedQueryOptions<R, FIELDS, E, Q>,\n): UseFetcherPagedQueryReturn<R, FIELDS, E, Q>;\nexport function useFetcherPagedQuery<\n R,\n FIELDS extends string,\n E,\n Q extends PagedQuery<FIELDS>,\n>(\n options: UseFetcherPagedQueryOptions<R, FIELDS, E, Q>,\n): UseFetcherPagedQueryReturn<R, FIELDS, E, Q> {\n return useEndpointRunner<Q, PagedResult<R>, E>(options, 'paged');\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterSingleQuery } from '@ahoo-wang/wow-client/dsl';\nimport type { Endpoint } from '../internal/endpoint.js';\nimport { useEndpointRunner } from '../internal/useEndpointRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useFetcherSingleQuery}: those of every query hook, with\n * the endpoint and the Fetcher in place of `execute`.\n *\n * @template R - The item the query returns\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterSingleQuery` by default\n */\nexport interface UseFetcherSingleQueryOptions<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterSingleQuery<FIELDS> = FilterSingleQuery<FIELDS>,\n>\n extends Omit<QueryHookOptions<Q, R, E>, 'execute'>, Endpoint {}\n\n/**\n * What {@link useFetcherSingleQuery} returns: the item as `result`.\n *\n * @template R - The item the query returns\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterSingleQuery` by default\n */\nexport interface UseFetcherSingleQueryReturn<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterSingleQuery<FIELDS> = FilterSingleQuery<FIELDS>,\n> extends QueryHookReturn<Q, R, E> {}\n\n/**\n * POSTs a single query to a Wow query route through a Fetcher and keeps the\n * result as state.\n *\n * `url` is resolved against the Fetcher's `baseURL`; `fetcher` is a Fetcher\n * or the name of a registered one, the default Fetcher when omitted. The\n * query runs on mount and whenever `query` or `setQuery()` changes it; set\n * `autoExecute: false` to run it only through `execute()`. A newer query\n * aborts the request in flight, so a late response never overwrites a newer\n * one; an unmount aborts it too.\n *\n * A change of `url`, or of `fetcher`, runs the query again. A Fetcher is\n * compared by its name, or by its `baseURL` when it has none, so one created\n * inline in render does not run it on every render.\n *\n * Returns `result` (the item, or `undefined` before the first success),\n * `loading`, `error`, `status`, `execute`, `abort`, `reset`, `getQuery` and\n * `setQuery`. A failed request sets `error` to the\n * `WowProblemError` the route answered with.\n *\n * @template R - The item the query returns\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n *\n * @example\n * ```tsx\n * import { filter, singleQuery } from '@ahoo-wang/wow-client/dsl';\n * import type { SnapshotRecord } from '@ahoo-wang/wow-client';\n * import { useFetcherSingleQuery } from '@ahoo-wang/wow-react';\n *\n * function OrderStatus({ id }: { id: string }) {\n * const { result, loading, error } = useFetcherSingleQuery<SnapshotRecord<OrderState>>({\n * url: '/shop/order/snapshot/query',\n * query: singleQuery({ filter: filter.id(id) }),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * if (loading || !result) return <p>Loading…</p>;\n * return <p>{result.state.status}</p>;\n * }\n * ```\n */\nexport function useFetcherSingleQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n>(\n options: UseFetcherSingleQueryOptions<\n R,\n FIELDS,\n E,\n FilterSingleQuery<FIELDS>\n >,\n): UseFetcherSingleQueryReturn<R, FIELDS, E, FilterSingleQuery<FIELDS>>;\n/**\n * {@link useFetcherSingleQuery} typed by a query `Q` of your own, a subtype of\n * `FilterSingleQuery`, such as one whose literal projection narrows the result.\n */\nexport function useFetcherSingleQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterSingleQuery<FIELDS> = FilterSingleQuery<FIELDS>,\n>(\n options: UseFetcherSingleQueryOptions<R, FIELDS, E, Q>,\n): UseFetcherSingleQueryReturn<R, FIELDS, E, Q>;\nexport function useFetcherSingleQuery<\n R,\n FIELDS extends string,\n E,\n Q extends FilterSingleQuery<FIELDS>,\n>(\n options: UseFetcherSingleQueryOptions<R, FIELDS, E, Q>,\n): UseFetcherSingleQueryReturn<R, FIELDS, E, Q> {\n return useEndpointRunner<Q, R, E>(options, 'single');\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterListQuery } from '@ahoo-wang/wow-client/dsl';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useListQuery}: a list query and an `execute` that resolves\n * to its rows.\n *\n * @template R - One row of the list\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterListQuery` by default\n */\nexport interface UseListQueryOptions<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends QueryHookOptions<Q, R[], E> {}\n\n/**\n * What {@link useListQuery} returns: the rows as `result`.\n *\n * @template R - One row of the list\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterListQuery` by default\n */\nexport interface UseListQueryReturn<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends QueryHookReturn<Q, R[], E> {}\n\n/**\n * Runs a list query through your own `execute` function and keeps the rows\n * as state: typically a query client's `list` or `listState`.\n *\n * `execute` receives the query and the request options of the run, its\n * `signal` included; hand them on so that a newer query, `abort()`\n * or an unmount cancels the request. The query runs on mount and whenever\n * `query` or `setQuery()` changes it; set `autoExecute: false` to run it only\n * through `execute()`.\n *\n * Returns `result` (the rows, or `undefined` before the first success),\n * `loading`, `error`, `status`, `execute`, `abort`, `reset`, `getQuery` and\n * `setQuery`.\n *\n * @template R - One row of the list\n * @template FIELDS - The field names the query may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here: TypeScript does not infer them from `execute` once `R` is given\n * @template E - The error type, `Error` by default\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient, SnapshotRecord } from '@ahoo-wang/wow-client';\n * import { desc, filter, listQuery } from '@ahoo-wang/wow-client/dsl';\n * import { useListQuery } from '@ahoo-wang/wow-react';\n *\n * function LatestOrders({ client }: { client: SnapshotQueryClient<OrderState, OrderFields> }) {\n * const { result, loading, error } = useListQuery<SnapshotRecord<OrderState>, OrderFields>({\n * initialQuery: listQuery({\n * filter: filter.eq('state.status', 'PAID'),\n * sort: [desc('createTime')],\n * limit: 20,\n * }),\n * execute: (query, options) =>\n * client.list(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * if (loading || !result) return <p>Loading…</p>;\n * return <ul>{result.map(order => <li key={order.aggregateId}>{order.state.status}</li>)}</ul>;\n * }\n * ```\n */\nexport function useListQuery<R, FIELDS extends string = string, E = Error>(\n options: UseListQueryOptions<R, FIELDS, E, FilterListQuery<FIELDS>>,\n): UseListQueryReturn<R, FIELDS, E, FilterListQuery<FIELDS>>;\n/**\n * {@link useListQuery} typed by a query `Q` of your own, a subtype of\n * `FilterListQuery`, such as one whose literal projection narrows the result.\n */\nexport function useListQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n>(\n options: UseListQueryOptions<R, FIELDS, E, Q>,\n): UseListQueryReturn<R, FIELDS, E, Q>;\nexport function useListQuery<\n R,\n FIELDS extends string,\n E,\n Q extends FilterListQuery<FIELDS>,\n>(\n options: UseListQueryOptions<R, FIELDS, E, Q>,\n): UseListQueryReturn<R, FIELDS, E, Q> {\n return useQueryRunner<Q, R[], E>(options);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterListQuery } from '@ahoo-wang/wow-client/dsl';\nimport { useListStream } from '../internal/useListStream.js';\nimport type {\n ListStreamExecutor,\n QueryHookOptions,\n QueryHookReturn,\n} from '../types.js';\n\n/**\n * Options of {@link useListStreamQuery}: those of every query hook, with an\n * `execute` that opens the stream.\n *\n * `onSuccess` receives every row once the stream has ended.\n *\n * @template R - One row of the stream: the `data` of each event\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default: a failed request\n * rejects with a `WowProblemError`, and so does an error event in the\n * stream\n * @template Q - The query type: `FilterListQuery` by default\n */\nexport interface UseListStreamQueryOptions<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends Omit<QueryHookOptions<Q, R[], E>, 'execute'> {\n /** Opens the stream for a query. */\n execute: ListStreamExecutor<R, Q>;\n}\n\n/**\n * What {@link useListStreamQuery} and `useFetcherListStreamQuery` return: the\n * rows as they arrive, and whether the stream has ended.\n *\n * - `items` — the rows of the current query received so far, in order,\n * updated at most about once a frame (every 16 ms) while they arrive. A new\n * query starts from an empty list; `reset()` empties it; `abort()` and an\n * error keep the rows received before them.\n * - `done` — the stream ended normally and `items` holds every row.\n * - `loading` — from the request until the stream ends, fails or is aborted.\n * - `error` — the request failed, or the server sent an error event in the\n * stream: a `WowProblemError`, with the problem's `code`.\n * - `status` — `idle`, `loading`, `success` (the same as `done`) or `error`.\n * - `execute()` runs the current query again and aborts the stream in flight;\n * `abort()` stops the stream; `reset()` stops it and empties `items`.\n */\nexport interface UseListStreamQueryReturn<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends Omit<QueryHookReturn<Q, R[], E>, 'result'> {\n /**\n * The rows of the current query received so far, a new array at every\n * update.\n */\n items: R[];\n /** Whether the stream ended normally, so `items` holds every row. */\n done: boolean;\n}\n\n/**\n * Streams the rows of a list query as server-sent events and keeps them as\n * state.\n *\n * The hook owns the stream: it reads it, collects the rows into `items`, and\n * cancels it when a newer query starts, on `abort()` or `reset()`, and on\n * unmount. Components render `items` and never hold a reader, so the hook is\n * safe under StrictMode. `autoExecute` defaults to `true`.\n *\n * Pass a query client's `listStream` as `execute` — it sends\n * `Accept: text/event-stream` and turns error events into a\n * `WowProblemError` — or\n * use `useFetcherListStreamQuery` with a URL.\n *\n * @template R - One row of the stream: the `data` of each event\n * @template FIELDS - The field names the query may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here: TypeScript does not infer them from `execute` once `R` is given\n * @template E - The error type\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient, SnapshotRecord } from '@ahoo-wang/wow-client';\n * import { filter, listQuery } from '@ahoo-wang/wow-client/dsl';\n * import { useListStreamQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidOrders({ client }: { client: SnapshotQueryClient<OrderState, OrderFields> }) {\n * const { items, done, loading, error, abort } = useListStreamQuery<SnapshotRecord<OrderState>, OrderFields>({\n * initialQuery: listQuery({ filter: filter.eq('state.status', 'PAID') }),\n * execute: (query, options) =>\n * client.listStream(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * return (\n * <>\n * <ul>{items.map(order => <li key={order.aggregateId}>{order.state.status}</li>)}</ul>\n * {loading && <button onClick={abort}>Stop</button>}\n * {done && <p>{items.length} orders</p>}\n * </>\n * );\n * }\n * ```\n */\nexport function useListStreamQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n>(\n options: UseListStreamQueryOptions<R, FIELDS, E, FilterListQuery<FIELDS>>,\n): UseListStreamQueryReturn<R, FIELDS, E, FilterListQuery<FIELDS>>;\n/**\n * {@link useListStreamQuery} typed by a query `Q` of your own, a subtype of\n * `FilterListQuery`, such as one whose literal projection narrows the result.\n */\nexport function useListStreamQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n>(\n options: UseListStreamQueryOptions<R, FIELDS, E, Q>,\n): UseListStreamQueryReturn<R, FIELDS, E, Q>;\nexport function useListStreamQuery<\n R,\n FIELDS extends string,\n E,\n Q extends FilterListQuery<FIELDS>,\n>(\n options: UseListStreamQueryOptions<R, FIELDS, E, Q>,\n): UseListStreamQueryReturn<R, FIELDS, E, Q> {\n return useListStream<R, FIELDS, E, Q>(options);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PagedQuery, PagedResult } from '@ahoo-wang/wow-client';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link usePagedQuery}: a paged query and an `execute` that\n * resolves to one page.\n *\n * @template R - One row of the page\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterPagedQuery` by default\n */\nexport interface UsePagedQueryOptions<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends PagedQuery<FIELDS> = PagedQuery<FIELDS>,\n> extends QueryHookOptions<Q, PagedResult<R>, E> {}\n\n/**\n * What {@link usePagedQuery} returns: the page (`total` and `list`) as\n * `result`.\n *\n * @template R - One row of the page\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterPagedQuery` by default\n */\nexport interface UsePagedQueryReturn<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends PagedQuery<FIELDS> = PagedQuery<FIELDS>,\n> extends QueryHookReturn<Q, PagedResult<R>, E> {}\n\n/**\n * Runs a paged query through your own `execute` function and keeps the page\n * as state: typically a query client's `paged` or `pagedState`.\n *\n * `execute` receives the query and the request options of the run, its\n * `signal` included; hand them on so that a newer query, `abort()`\n * or an unmount cancels the request. The query runs on mount and whenever\n * `query` or `setQuery()` changes it — turn pages with `setQuery()`; set\n * `autoExecute: false` to run it only through `execute()`.\n *\n * Returns `result` (`{ total, list }`, or `undefined` before the first\n * success), `loading`, `error`, `status`, `execute`, `abort`, `reset`,\n * `getQuery` and `setQuery`.\n *\n * @template R - One row of the page\n * @template FIELDS - The field names the query may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here: TypeScript does not infer them from `execute` once `R` is given\n * @template E - The error type, `Error` by default\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient, SnapshotRecord } from '@ahoo-wang/wow-client';\n * import { filter, pagedQuery } from '@ahoo-wang/wow-client/dsl';\n * import { usePagedQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidOrders({ client, page }: { client: SnapshotQueryClient<OrderState, OrderFields>; page: number }) {\n * const { result, loading, error } = usePagedQuery<SnapshotRecord<OrderState>, OrderFields>({\n * query: pagedQuery({\n * filter: filter.eq('state.status', 'PAID'),\n * pagination: { index: page, size: 20 },\n * }),\n * execute: (query, options) =>\n * client.paged(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * if (loading || !result) return <p>Loading…</p>;\n * return <p>{result.list.length} of {result.total}</p>;\n * }\n * ```\n */\nexport function usePagedQuery<R, FIELDS extends string = string, E = Error>(\n options: UsePagedQueryOptions<R, FIELDS, E, PagedQuery<FIELDS>>,\n): UsePagedQueryReturn<R, FIELDS, E, PagedQuery<FIELDS>>;\n/**\n * {@link usePagedQuery} typed by a query `Q` of your own, a subtype of\n * `PagedQuery`, such as one whose literal projection narrows the result.\n */\nexport function usePagedQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends PagedQuery<FIELDS> = PagedQuery<FIELDS>,\n>(\n options: UsePagedQueryOptions<R, FIELDS, E, Q>,\n): UsePagedQueryReturn<R, FIELDS, E, Q>;\nexport function usePagedQuery<\n R,\n FIELDS extends string,\n E,\n Q extends PagedQuery<FIELDS>,\n>(\n options: UsePagedQueryOptions<R, FIELDS, E, Q>,\n): UsePagedQueryReturn<R, FIELDS, E, Q> {\n return useQueryRunner<Q, PagedResult<R>, E>(options);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterSingleQuery } from '@ahoo-wang/wow-client/dsl';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useSingleQuery}: a single query and an `execute` that\n * resolves to one item.\n *\n * @template R - The item the query returns\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterSingleQuery` by default\n */\nexport interface UseSingleQueryOptions<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterSingleQuery<FIELDS> = FilterSingleQuery<FIELDS>,\n> extends QueryHookOptions<Q, R, E> {}\n\n/**\n * What {@link useSingleQuery} returns: the item as `result`.\n *\n * @template R - The item the query returns\n * @template FIELDS - The field names the query may use\n * @template E - The error type, `Error` by default\n * @template Q - The query type: `FilterSingleQuery` by default\n */\nexport interface UseSingleQueryReturn<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterSingleQuery<FIELDS> = FilterSingleQuery<FIELDS>,\n> extends QueryHookReturn<Q, R, E> {}\n\n/**\n * Runs a single query through your own `execute` function and keeps the\n * result as state: typically a query client's `single` or `singleState`.\n *\n * `execute` receives the query and the request options of the run, its\n * `signal` included; hand them on so that a newer query, `abort()`\n * or an unmount cancels the request. The query runs on mount and whenever\n * `query` or `setQuery()` changes it; set `autoExecute: false` to run it only\n * through `execute()`.\n *\n * Returns `result` (the item, or `undefined` before the first success),\n * `loading`, `error`, `status`, `execute`, `abort`, `reset`, `getQuery` and\n * `setQuery`.\n *\n * @template R - The item the query returns\n * @template FIELDS - The field names the query may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here: TypeScript does not infer them from `execute` once `R` is given\n * @template E - The error type, `Error` by default\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient, SnapshotRecord } from '@ahoo-wang/wow-client';\n * import { filter, singleQuery } from '@ahoo-wang/wow-client/dsl';\n * import { useSingleQuery } from '@ahoo-wang/wow-react';\n *\n * function OrderStatus({ client, id }: { client: SnapshotQueryClient<OrderState, OrderFields>; id: string }) {\n * const { result, loading, error } = useSingleQuery<SnapshotRecord<OrderState>, OrderFields>({\n * query: singleQuery({ filter: filter.id(id) }),\n * execute: (query, options) =>\n * client.single(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * if (loading || !result) return <p>Loading…</p>;\n * return <p>{result.state.status}</p>;\n * }\n * ```\n */\nexport function useSingleQuery<R, FIELDS extends string = string, E = Error>(\n options: UseSingleQueryOptions<R, FIELDS, E, FilterSingleQuery<FIELDS>>,\n): UseSingleQueryReturn<R, FIELDS, E, FilterSingleQuery<FIELDS>>;\n/**\n * {@link useSingleQuery} typed by a query `Q` of your own, a subtype of\n * `FilterSingleQuery`, such as one whose literal projection narrows the result.\n */\nexport function useSingleQuery<\n R,\n FIELDS extends string = string,\n E = Error,\n Q extends FilterSingleQuery<FIELDS> = FilterSingleQuery<FIELDS>,\n>(\n options: UseSingleQueryOptions<R, FIELDS, E, Q>,\n): UseSingleQueryReturn<R, FIELDS, E, Q>;\nexport function useSingleQuery<\n R,\n FIELDS extends string,\n E,\n Q extends FilterSingleQuery<FIELDS>,\n>(\n options: UseSingleQueryOptions<R, FIELDS, E, Q>,\n): UseSingleQueryReturn<R, FIELDS, E, Q> {\n return useQueryRunner<Q, R, E>(options);\n}\n"],"mappings":";;;;;;;AAyCA,SAAgBS,kBACdC,GACkB;CAClB,OAAO;EACLR,QAAQQ,IAAc,YAAY;EAClCP,QAAQQ,KAAAA;EACRN,OAAOM,KAAAA;CACT;AACF;AAcA,SAAgBC,gBACdC,GACAC,GACkB;CAClB,QAAQA,EAAMN,MAAd;EACE,KAAK,SACH,OAAO;GAAEN,QAAQ;GAAWC,QAAQU,EAAMV;GAAQE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AAAK,KAA3DC,IAAA;EAAA,GAAKH;EAAII,SAAWF;CAAwC,GAACL,EAAA,KAAAG,GAAAH,EAAA,KAAAK,GAAAL,EAAA,KAAAM,KAAAA,IAAAN,EAAA;CAAA,IAAAQ;CAC3B,OAD2BR,EAAA,QAAAE,KAAAF,EAAA,QAAAI,KAC7DI,IAAAvB,iBAAiB;EAAAmB;EAAAF;CAAe,CAAC,GAACF,EAAA,MAAAE,GAAAF,EAAA,MAAAI,GAAAJ,EAAA,MAAAQ,KAAAA,IAAAR,EAAA,KAF7Bb,cACLmB,GACAE,CACF;AAAC;;;ACjBH,SAAOgB,qBAAAC,GAAA;CAAA,OAQEZ,kBAAwCY,GAAS,OAAO;AAAC;;;ACPlE,SAAOc,sBAAAC,GAAA;CAAA,OAQEZ,kBAA2BY,GAAS,QAAQ;AAAC;;;AClBtD,SAAOY,aAAAC,GAAA;CAAA,OAQEX,eAA0BW,CAAO;AAAC;;;ACwB3C,SAAOiB,mBAAAC,GAAA;CAAA,OAQEhB,cAA+BgB,CAAO;AAAC;;;ACxChD,SAAOa,cAAAC,GAAA;CAAA,OAQEX,eAAqCW,CAAO;AAAC;;;ACZtD,SAAOY,eAAAC,GAAA;CAAA,OAQEX,eAAwBW,CAAO;AAAC"}
|
|
1
|
+
{"version":3,"file":"index.es.js","names":["QueryStatus","QueryState","status","result","R","error","Error","QueryEvent","type","initialQueryState","runsOnMount","undefined","queryTransition","state","event","dequal","useCallback","useEffect","useLayoutEffect","useRef","useState","RequestOptions","toWowProblemError","WowProblemError","QueryHookOptions","QueryHookReturn","initialQueryState","queryTransition","QueryEvent","QueryState","useContentStable","value","kept","setKept","notify","name","callback","T","Promise","thrown","console","warn","isAbortError","error","Error","failureOf","problem","String","cause","useQueryRunner","options","Q","R","O","retainResult","autoExecute","query","requestOptions","state","setState","initialQuery","undefined","latest","current","request","id","controller","AbortController","mounted","settle","event","cancel","abort","execute","type","result","signal","AbortSignal","aborted","onSuccess","onError","reset","getQuery","setQuery","previousQuery","cleared","status","loading","AggregationQuery","useQueryRunner","QueryHookOptions","QueryHookReturn","UseAggregateQueryOptions","FIELDS","Q","ROW","UseAggregateQueryReturn","useAggregateQuery","options","CountQuery","CountResult","useQueryRunner","QueryHookOptions","QueryHookReturn","UseCountQueryOptions","FIELDS","Q","UseCountQueryReturn","useCountQuery","options","CursorPage","CursorQuery","useCallback","useRef","useState","useQueryRunner","QueryExecutor","QueryHookOptions","QueryHookReturn","UseCursorQueryOptions","Omit","FIELDS","Q","R","execute","cursor","UseCursorQueryReturn","items","hasMore","fetchNext","Promise","Pages","nextCursor","useCursorQuery","options","$","_c","pages","setPages","noPages","next","readPage","t0","query","options_0","current","page","signal","aborted","pages_0","list","t1","status","loading","error","problem","abort","reset","getQuery","setQuery","t2","run","t3","resetPages","t4","undefined","_c","FilterListQuery","useQueryRunner","QueryHookOptions","QueryHookReturn","UseListQueryOptions","FIELDS","Q","R","UseListQueryReturn","useListQuery","options","PagedQuery","PagedList","useQueryRunner","QueryHookOptions","QueryHookReturn","UsePagedQueryOptions","FIELDS","Q","R","UsePagedQueryReturn","usePagedQuery","options","FilterSingleQuery","useQueryRunner","QueryHookOptions","QueryHookReturn","UseSingleQueryOptions","FIELDS","Q","R","UseSingleQueryReturn","useSingleQuery","options","Positioned","PUBLISH_INTERVAL_MS","readStreamRows","stream","ReadableStream","R","signal","AbortSignal","publish","rows","position","Promise","reader","getReader","published","publishedAt","Infinity","timer","ReturnType","setTimeout","flush","undefined","clearTimeout","aborted","length","Date","now","slice","schedule","wait","Math","max","cancel","reason","catch","addEventListener","once","done","value","read","push","row","error","removeEventListener","releaseLock","StreamOptions","FilterListQuery","useCallback","useState","readStreamRows","useQueryRunner","QueryHookOptions","QueryHookReturn","StreamExecutor","UseStreamQueryOptions","FIELDS","Omit","Q","R","execute","UseStreamQueryReturn","items","position","done","Rows","useStreamQuery","options","$","_c","rows","setRows","noRows","openStream","t0","query","options_0","stream","signal","t1","status","loading","error","problem","abort","reset","getQuery","setQuery","t2","resetRows","t3","t4","undefined","_c","runsOnMount","event","state","kept","setKept","useState","value","dequal","callback","thrown","name","error","toWowProblemError","autoExecute","options","query","requestOptions","setState","latest","useRef","current","request","mounted","settle","useCallback","id","state_0","cancel","controller","execute_0","query_0","controller_0","id_0","state_1","requestOptions_0","result","execute","retainResult","abort","state_2","reset","state_3","getQuery","setQuery","query_1","previousQuery","useEffect","cleared","WowProblemError","$","pages","setPages","next","readPage","cursor","page","options_0","pages_0","t1","hasMore","loading","run","fetchNext","resetPages","t4","problem","status","reader","stream","rows","position","published","publishedAt","timer","publish","wait","signal","done","setRows","openStream","resetRows","t3"],"sources":["../src/internal/queryTransitions.ts","../src/internal/useQueryRunner.ts","../src/hooks/useAggregateQuery.ts","../src/hooks/useCountQuery.ts","../src/hooks/useCursorQuery.ts","../src/hooks/useListQuery.ts","../src/hooks/usePagedQuery.ts","../src/hooks/useSingleQuery.ts","../src/internal/readStreamRows.ts","../src/hooks/useStreamQuery.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*\n * What a query hook shows, and how each event changes it: section 3 of\n * docs/design/architecture.md as pure functions, with no React. The\n * request itself (aborting it, ignoring a late answer) is useQueryRunner's.\n */\n\nimport type { QueryStatus } from '../types.js';\n\n/** What a query hook shows at one moment. */\nexport interface QueryState<R> {\n status: QueryStatus;\n result: R | undefined;\n error: Error | undefined;\n}\n\n/** Something that happens to a query hook. */\nexport type QueryEvent<R> =\n | { type: 'start' }\n | { type: 'succeed'; result: R | undefined }\n | { type: 'fail'; error: Error }\n | { type: 'abort' }\n | { type: 'reset' };\n\n/**\n * The first state. A hook that will run its query as soon as it mounts\n * starts `loading`, so the server and the first client frame already show\n * what the next frames show; any other starts `idle`.\n */\nexport function initialQueryState<R>(runsOnMount: boolean): QueryState<R> {\n return {\n status: runsOnMount ? 'loading' : 'idle',\n result: undefined,\n error: undefined,\n };\n}\n\n/**\n * The state after one event:\n *\n * - `start`: `loading`; the last result stays until the new one arrives, the\n * error goes.\n * - `succeed`: `success` with the new result (`undefined` for a hook that\n * keeps its own, as the list-stream hooks keep `items`).\n * - `fail`: `error`; the last result stays, so a failed refresh does not\n * blank what was shown.\n * - `abort`: `idle`; the last result stays, the error goes.\n * - `reset`: `idle`, with neither result nor error.\n */\nexport function queryTransition<R>(\n state: QueryState<R>,\n event: QueryEvent<R>,\n): QueryState<R> {\n switch (event.type) {\n case 'start':\n return { status: 'loading', result: state.result, error: undefined };\n case 'succeed':\n return { status: 'success', result: event.result, error: undefined };\n case 'fail':\n return { status: 'error', result: state.result, error: event.error };\n case 'abort':\n return { status: 'idle', result: state.result, error: undefined };\n case 'reset':\n return { status: 'idle', result: undefined, error: undefined };\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport {\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\nimport {\n type RequestOptions,\n toWowProblemError,\n WowProblemError,\n} from '@ahoo-wang/wow-client';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\nimport {\n initialQueryState,\n queryTransition,\n type QueryEvent,\n type QueryState,\n} from './queryTransitions.js';\n\n/**\n * `value`, or the one of an earlier render when that one has the same\n * content, so that an object rebuilt on every render keeps one identity.\n */\nfunction useContentStable<T>(value: T): T {\n const [kept, setKept] = useState(value);\n if (kept === value || dequal(kept, value)) return kept;\n setKept(value);\n return value;\n}\n\n/** Hands a callback its argument; one that throws never breaks the state. */\nasync function notify<T>(\n name: string,\n callback: ((value: T) => void | Promise<void>) | undefined,\n value: T,\n): Promise<void> {\n try {\n await callback?.(value);\n } catch (thrown) {\n // The state already shows the outcome; the host learns of its broken\n // callback without the hook swallowing it.\n // eslint-disable-next-line no-console\n console.warn(`wow-react: ${name} threw`, thrown);\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && error.name === 'AbortError';\n}\n\n/**\n * What a run failed with, as the hook reports it: the problem a Wow service\n * answered with when the failure carries one (a fetcher's `ExchangeError` of\n * a response that is not 2xx is read as its problem), else the error itself,\n * a value thrown that is not an `Error` wrapped in one.\n */\nasync function failureOf(thrown: unknown): Promise<Error> {\n const problem = await toWowProblemError(thrown);\n if (problem) return problem;\n return thrown instanceof Error\n ? thrown\n : new Error(String(thrown), { cause: thrown });\n}\n\n/**\n * The one request state machine every hook runs on.\n *\n * - Latest wins: every run takes a new number and aborts the one before; an\n * answer that is no longer the latest, arrives after `abort()` or\n * `reset()`, or arrives after unmount, changes nothing.\n * - A run starts on mount, whenever the query or `requestOptions` changes\n * by content, through `setQuery()`, and when `autoExecute` turns on;\n * `execute()` starts one by hand.\n * - `abort()`, `reset()` and unmount abort the request in flight.\n * - StrictMode's second mount aborts the first run and starts one more, so\n * exactly one answer lands.\n * - A failure is reported as an `Error`, and as `problem` too when a Wow\n * service answered it.\n *\n * With `retainResult` off the runner hands a run's result to `onSuccess`\n * but does not keep it as `result`: the list-stream and cursor hooks keep\n * their rows as `items` already. `execute` and the callbacks are read when a\n * run starts or settles, so a change to them never starts one.\n */\nexport function useQueryRunner<Q, R, O extends RequestOptions = RequestOptions>(\n options: QueryHookOptions<Q, R, O>,\n retainResult = true,\n): QueryHookReturn<Q, R> {\n const autoExecute = options.autoExecute ?? true;\n const query = useContentStable(options.query);\n const requestOptions = useContentStable(options.requestOptions);\n const [state, setState] = useState<QueryState<R>>(() =>\n initialQueryState(\n autoExecute && (options.query ?? options.initialQuery) !== undefined,\n ),\n );\n const latest = useRef(options);\n const current = useRef<Q | undefined>(options.query ?? options.initialQuery);\n const request = useRef<{ id: number; controller?: AbortController }>({\n id: 0,\n });\n const mounted = useRef(false);\n\n useLayoutEffect(() => {\n latest.current = options;\n });\n\n /** Applies an event unless run `id` is no longer the one that counts. */\n const settle = useCallback((id: number, event: QueryEvent<R>) => {\n if (!mounted.current || request.current.id !== id) return false;\n setState(state => queryTransition(state, event));\n return true;\n }, []);\n\n /** Stops the run in flight: no answer of it changes anything any more. */\n const cancel = useCallback(() => {\n const { controller } = request.current;\n request.current = { id: request.current.id + 1 };\n controller?.abort();\n }, []);\n\n const execute = useCallback(async () => {\n const query = current.current;\n if (!mounted.current || query === undefined) return;\n request.current.controller?.abort();\n const controller = new AbortController();\n const id = request.current.id + 1;\n request.current = { id, controller };\n setState(state => queryTransition(state, { type: 'start' }));\n const { execute, requestOptions } = latest.current;\n try {\n const result = await execute(query, {\n ...requestOptions,\n signal: controller.signal,\n } as O & { readonly signal: AbortSignal });\n if (controller.signal.aborted) {\n settle(id, { type: 'abort' });\n } else if (\n settle(id, {\n type: 'succeed',\n result: retainResult ? result : undefined,\n })\n ) {\n await notify('onSuccess', latest.current.onSuccess, result);\n }\n } catch (thrown) {\n if (controller.signal.aborted || isAbortError(thrown)) {\n settle(id, { type: 'abort' });\n return;\n }\n const error = await failureOf(thrown);\n if (settle(id, { type: 'fail', error })) {\n await notify('onError', latest.current.onError, error);\n }\n } finally {\n if (request.current.controller === controller)\n request.current = { id: request.current.id };\n }\n }, [settle, retainResult]);\n\n const abort = useCallback(() => {\n cancel();\n setState(state => queryTransition(state, { type: 'abort' }));\n }, [cancel]);\n\n const reset = useCallback(() => {\n cancel();\n setState(state => queryTransition(state, { type: 'reset' }));\n }, [cancel]);\n\n const getQuery = useCallback(() => current.current, []);\n\n const setQuery = useCallback(\n (query: Q) => {\n current.current = query;\n if (latest.current.autoExecute ?? true) void execute();\n },\n [execute],\n );\n\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n cancel();\n };\n }, [cancel]);\n\n const previousQuery = useRef(query);\n useEffect(() => {\n const cleared = query === undefined && previousQuery.current !== undefined;\n previousQuery.current = query;\n if (cleared) {\n // A controlled query set to `undefined` (`id ? singleQuery(…) :\n // undefined`) means nothing to run: stop, keep what was shown.\n current.current = undefined;\n abort();\n return;\n }\n if (query !== undefined) current.current = query;\n if (autoExecute) void execute();\n }, [query, requestOptions, autoExecute, execute, abort]);\n\n return {\n status: state.status,\n loading: state.status === 'loading',\n result: state.result,\n error: state.error,\n problem: state.error instanceof WowProblemError ? state.error : undefined,\n execute,\n abort,\n reset,\n getQuery,\n setQuery,\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AggregationQuery } from '@ahoo-wang/wow-client/dsl';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useAggregateQuery}: an aggregation and an `execute` that\n * resolves to its rows, as a query client's `aggregate` does.\n *\n * @template ROW - One row of the result: the groups and metrics by alias\n * @template FIELDS - The field names the aggregation may use\n * @template Q - The aggregation type: `AggregationQuery` by default\n */\nexport interface UseAggregateQueryOptions<\n ROW,\n FIELDS extends string = string,\n Q extends AggregationQuery<FIELDS, string> = AggregationQuery<FIELDS, string>,\n> extends QueryHookOptions<Q, ROW[]> {}\n\n/**\n * What {@link useAggregateQuery} returns: the rows as `result`.\n *\n * @template ROW - One row of the result\n * @template FIELDS - The field names the aggregation may use\n * @template Q - The aggregation type: `AggregationQuery` by default\n */\nexport interface UseAggregateQueryReturn<\n ROW,\n FIELDS extends string = string,\n Q extends AggregationQuery<FIELDS, string> = AggregationQuery<FIELDS, string>,\n> extends QueryHookReturn<Q, ROW[]> {}\n\n/**\n * Runs an aggregation through your own `execute` function and keeps its rows\n * as state: typically a query client's `aggregate`, one row per group.\n *\n * `execute` receives the aggregation and the request options of the run, its\n * `signal` included; hand them on so that a newer query, `abort()`\n * or an unmount cancels the request. The aggregation runs on mount and\n * whenever `query` or `setQuery()` changes it; set `autoExecute: false` to\n * run it only through `execute()`.\n *\n * Returns `result` (the rows, or `undefined` before the first success),\n * `loading`, `error`, `problem`, `status`, `execute`, `abort`, `reset`,\n * `getQuery` and `setQuery`.\n *\n * @template ROW - One row of the result: the groups and metrics by alias\n * @template FIELDS - The field names the aggregation may use. With a client\n * whose fields are narrower than `string`, as a generated client's are,\n * pass them here: TypeScript does not infer them from `execute` once\n * `ROW` is given\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient } from '@ahoo-wang/wow-client';\n * import { aggregation } from '@ahoo-wang/wow-client/dsl';\n * import { useAggregateQuery } from '@ahoo-wang/wow-react';\n *\n * type StatusCount = { status: string; orders: number };\n *\n * function OrdersByStatus({ client }: { client: SnapshotQueryClient<OrderState, OrderFields> }) {\n * const { result, error } = useAggregateQuery<StatusCount, OrderFields>({\n * query: {\n * groupBy: [aggregation.terms('state.status', 'status')],\n * metrics: [aggregation.count('orders')],\n * },\n * execute: (query, options) =>\n * client.aggregate<StatusCount>(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * return <ul>{result?.map(row => <li key={row.status}>{row.status}: {row.orders}</li>)}</ul>;\n * }\n * ```\n */\nexport function useAggregateQuery<ROW, FIELDS extends string = string>(\n options: UseAggregateQueryOptions<\n ROW,\n FIELDS,\n AggregationQuery<FIELDS, string>\n >,\n): UseAggregateQueryReturn<ROW, FIELDS, AggregationQuery<FIELDS, string>>;\n/**\n * {@link useAggregateQuery} typed by an aggregation `Q` of your own, a\n * subtype of `AggregationQuery`.\n */\nexport function useAggregateQuery<\n ROW,\n FIELDS extends string = string,\n Q extends AggregationQuery<FIELDS, string> = AggregationQuery<FIELDS, string>,\n>(\n options: UseAggregateQueryOptions<ROW, FIELDS, Q>,\n): UseAggregateQueryReturn<ROW, FIELDS, Q>;\nexport function useAggregateQuery<\n ROW,\n FIELDS extends string,\n Q extends AggregationQuery<FIELDS, string>,\n>(\n options: UseAggregateQueryOptions<ROW, FIELDS, Q>,\n): UseAggregateQueryReturn<ROW, FIELDS, Q> {\n return useQueryRunner<Q, ROW[]>(options);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { CountQuery, CountResult } from '@ahoo-wang/wow-client';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useCountQuery}: a filter and an `execute` that resolves to\n * how many rows it matches.\n *\n * @template FIELDS - The field names the filter may use\n * @template Q - The filter type: `FilterExpression` by default\n */\nexport interface UseCountQueryOptions<\n FIELDS extends string = string,\n Q extends CountQuery<FIELDS> = CountQuery<FIELDS>,\n> extends QueryHookOptions<Q, CountResult> {}\n\n/**\n * What {@link useCountQuery} returns: the count as `result`.\n *\n * @template FIELDS - The field names the filter may use\n * @template Q - The filter type: `FilterExpression` by default\n */\nexport interface UseCountQueryReturn<\n FIELDS extends string = string,\n Q extends CountQuery<FIELDS> = CountQuery<FIELDS>,\n> extends QueryHookReturn<Q, CountResult> {}\n\n/**\n * Counts what a filter matches through your own `execute` function and keeps\n * the count as state: typically a query client's `count`.\n *\n * `execute` receives the filter and the request options of the run, its\n * `signal` included; hand them on so that a newer query, `abort()`\n * or an unmount cancels the request. The count runs on mount and whenever\n * `query` or `setQuery()` changes the filter; set `autoExecute: false` to run\n * it only through `execute()`.\n *\n * Returns `result` (the count, or `undefined` before the first success),\n * `loading`, `error`, `problem`, `status`, `execute`, `abort`, `reset`, `getQuery` and\n * `setQuery`.\n *\n * @template FIELDS - The field names the filter may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here; inferred from the first filter, they would admit only its\n * fields in `setQuery()`\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient } from '@ahoo-wang/wow-client';\n * import { filter } from '@ahoo-wang/wow-client/dsl';\n * import { useCountQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidCount({ client }: { client: SnapshotQueryClient<OrderState, OrderFields> }) {\n * const { result, error } = useCountQuery<OrderFields>({\n * initialQuery: { filter: filter.eq('state.status', 'PAID') },\n * execute: (query, options) =>\n * client.count(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * return <p>{result?.count ?? '…'} paid orders</p>;\n * }\n * ```\n */\nexport function useCountQuery<FIELDS extends string = string>(\n options: UseCountQueryOptions<FIELDS, CountQuery<FIELDS>>,\n): UseCountQueryReturn<FIELDS, CountQuery<FIELDS>>;\n/**\n * {@link useCountQuery} typed by a query `Q` of your own, a subtype of\n * `CountQuery`.\n */\nexport function useCountQuery<\n FIELDS extends string = string,\n Q extends CountQuery<FIELDS> = CountQuery<FIELDS>,\n>(options: UseCountQueryOptions<FIELDS, Q>): UseCountQueryReturn<FIELDS, Q>;\nexport function useCountQuery<\n FIELDS extends string,\n Q extends CountQuery<FIELDS>,\n>(options: UseCountQueryOptions<FIELDS, Q>): UseCountQueryReturn<FIELDS, Q> {\n return useQueryRunner<Q, CountResult>(options);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { CursorPage, CursorQuery } from '@ahoo-wang/wow-client/dsl';\nimport { useCallback, useRef, useState } from 'react';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type {\n QueryExecutor,\n QueryHookOptions,\n QueryHookReturn,\n} from '../types.js';\n\n/**\n * Options of {@link useCursorQuery}: a cursor query without its `cursor`,\n * which the hook owns, and an `execute` that reads one page, as a query\n * client's `cursor` does.\n *\n * `onSuccess` receives each page as it arrives.\n *\n * @template R - One row of a page\n * @template FIELDS - The field names the query may use\n * @template Q - The query type: `CursorQuery` without `cursor` by default\n */\nexport interface UseCursorQueryOptions<\n R,\n FIELDS extends string = string,\n Q extends Omit<CursorQuery<FIELDS>, 'cursor'> = Omit<\n CursorQuery<FIELDS>,\n 'cursor'\n >,\n> extends Omit<QueryHookOptions<Q, CursorPage<R>>, 'execute'> {\n /**\n * Reads one page: the query with the `cursor` of the page, `null` for\n * the first.\n */\n execute: QueryExecutor<Q & { cursor: string | null }, CursorPage<R>>;\n}\n\n/**\n * What {@link useCursorQuery} returns: the rows of every page read so far,\n * and how to read the next one.\n *\n * - `items` — the rows of the pages read so far, in order. A new query and\n * `execute()` start again from the first page with no rows; `reset()`\n * empties them; `abort()` and an error keep them.\n * - `hasMore` — whether a page follows the last one read.\n * - `fetchNext()` — reads the next page and appends its rows; it does\n * nothing while a page is loading or when no page follows. A failed\n * `fetchNext()` keeps the rows, so calling it again retries that page.\n */\nexport interface UseCursorQueryReturn<\n R,\n FIELDS extends string = string,\n Q extends Omit<CursorQuery<FIELDS>, 'cursor'> = Omit<\n CursorQuery<FIELDS>,\n 'cursor'\n >,\n> extends Omit<QueryHookReturn<Q, CursorPage<R>>, 'result'> {\n /** The rows of every page read so far, a new array at every page. */\n items: R[];\n /** Whether a page follows the last one read. */\n hasMore: boolean;\n /** Reads the next page and appends its rows. */\n fetchNext: () => Promise<void>;\n}\n\n/** The rows read so far, and the cursor of the page after them. */\ninterface Pages<R> {\n items: R[];\n /** `undefined` before the first page, `null` after the last. */\n nextCursor: string | null | undefined;\n}\n\n/**\n * Reads a forward-only cursor query page by page and keeps the rows as\n * state: typically a query client's `cursor`, for a list that grows as the\n * reader scrolls.\n *\n * The hook owns the cursor: every run of the query starts at the first page,\n * and `fetchNext()` hands `execute` the `nextCursor` of the page before.\n * `execute` receives the request options of the run, its `signal` included;\n * hand them on so that a newer query, `abort()` or an unmount cancels the\n * request. The first page is read on mount and whenever `query` or\n * `setQuery()` changes the query; set `autoExecute: false` to read it only\n * through `execute()`.\n *\n * @template R - One row of a page\n * @template FIELDS - The field names the query may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here: TypeScript does not infer them from `execute` once `R` is\n * given\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient, Snapshot } from '@ahoo-wang/wow-client';\n * import { filter } from '@ahoo-wang/wow-client/dsl';\n * import { useCursorQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidOrders({ client }: { client: SnapshotQueryClient<OrderState, OrderFields> }) {\n * const { items, hasMore, loading, error, fetchNext } = useCursorQuery<Snapshot<OrderState>, OrderFields>({\n * query: { filter: filter.eq('state.status', 'PAID'), size: 50 },\n * execute: (query, options) =>\n * client.cursor(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * return (\n * <>\n * <ul>{items.map(order => <li key={order.aggregateId}>{order.state.status}</li>)}</ul>\n * {hasMore && <button disabled={loading} onClick={() => void fetchNext()}>More</button>}\n * </>\n * );\n * }\n * ```\n */\nexport function useCursorQuery<R, FIELDS extends string = string>(\n options: UseCursorQueryOptions<\n R,\n FIELDS,\n Omit<CursorQuery<FIELDS>, 'cursor'>\n >,\n): UseCursorQueryReturn<R, FIELDS, Omit<CursorQuery<FIELDS>, 'cursor'>>;\n/**\n * {@link useCursorQuery} typed by a query `Q` of your own, a subtype of\n * `CursorQuery` without `cursor`, such as one whose literal projection\n * narrows the rows.\n */\nexport function useCursorQuery<\n R,\n FIELDS extends string = string,\n Q extends Omit<CursorQuery<FIELDS>, 'cursor'> = Omit<\n CursorQuery<FIELDS>,\n 'cursor'\n >,\n>(\n options: UseCursorQueryOptions<R, FIELDS, Q>,\n): UseCursorQueryReturn<R, FIELDS, Q>;\nexport function useCursorQuery<\n R,\n FIELDS extends string,\n Q extends Omit<CursorQuery<FIELDS>, 'cursor'>,\n>(\n options: UseCursorQueryOptions<R, FIELDS, Q>,\n): UseCursorQueryReturn<R, FIELDS, Q> {\n const [pages, setPages] = useState<Pages<R>>(noPages);\n // The cursor the next run reads from, set by fetchNext() just before it\n // starts the run; any other run (a new query, execute(), setQuery()) finds\n // none and reads the first page.\n const next = useRef<string | null>(null);\n const readPage = options.execute;\n const {\n status,\n loading,\n error,\n problem,\n execute,\n abort,\n reset,\n getQuery,\n setQuery,\n } = useQueryRunner<Q, CursorPage<R>>(\n {\n ...options,\n execute: async (query, options) => {\n const cursor = next.current;\n next.current = null;\n if (cursor === null) setPages(noPages());\n const page = await readPage({ ...query, cursor }, options);\n // A run that no longer counts was aborted by the runner: its page\n // belongs to a query the rows have moved on from.\n if (!options.signal.aborted) {\n setPages(pages => ({\n items:\n cursor === null ? [...page.list] : [...pages.items, ...page.list],\n nextCursor: page.nextCursor,\n }));\n }\n return page;\n },\n },\n false,\n );\n const hasMore = typeof pages.nextCursor === 'string';\n const fetchNext = useCallback(async () => {\n if (loading || typeof pages.nextCursor !== 'string') return;\n next.current = pages.nextCursor;\n // The runner hands the cursor to the executor before it first awaits;\n // clear it in case the run did not start (no query, unmounted).\n const run = execute();\n next.current = null;\n await run;\n }, [loading, pages.nextCursor, execute]);\n const resetPages = useCallback(() => {\n reset();\n setPages(noPages());\n }, [reset]);\n return {\n items: pages.items,\n hasMore,\n fetchNext,\n loading,\n error,\n problem,\n status,\n execute,\n abort,\n reset: resetPages,\n getQuery,\n setQuery,\n };\n}\n\nfunction noPages<R>(): Pages<R> {\n return { items: [], nextCursor: undefined };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterListQuery } from '@ahoo-wang/wow-client/dsl';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useListQuery}: a list query and an `execute` that resolves\n * to its rows.\n *\n * @template R - One row of the list\n * @template FIELDS - The field names the query may use\n * @template Q - The query type: `FilterListQuery` by default\n */\nexport interface UseListQueryOptions<\n R,\n FIELDS extends string = string,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends QueryHookOptions<Q, R[]> {}\n\n/**\n * What {@link useListQuery} returns: the rows as `result`.\n *\n * @template R - One row of the list\n * @template FIELDS - The field names the query may use\n * @template Q - The query type: `FilterListQuery` by default\n */\nexport interface UseListQueryReturn<\n R,\n FIELDS extends string = string,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends QueryHookReturn<Q, R[]> {}\n\n/**\n * Runs a list query through your own `execute` function and keeps the rows\n * as state: typically a query client's `list` or `listState`.\n *\n * `execute` receives the query and the request options of the run, its\n * `signal` included; hand them on so that a newer query, `abort()`\n * or an unmount cancels the request. The query runs on mount and whenever\n * `query` or `setQuery()` changes it; set `autoExecute: false` to run it only\n * through `execute()`.\n *\n * Returns `result` (the rows, or `undefined` before the first success),\n * `loading`, `error`, `problem`, `status`, `execute`, `abort`, `reset`, `getQuery` and\n * `setQuery`.\n *\n * @template R - One row of the list\n * @template FIELDS - The field names the query may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here: TypeScript does not infer them from `execute` once `R` is given\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient, Snapshot } from '@ahoo-wang/wow-client';\n * import { desc, filter, listQuery } from '@ahoo-wang/wow-client/dsl';\n * import { useListQuery } from '@ahoo-wang/wow-react';\n *\n * function LatestOrders({ client }: { client: SnapshotQueryClient<OrderState, OrderFields> }) {\n * const { result, loading, error } = useListQuery<Snapshot<OrderState>, OrderFields>({\n * initialQuery: listQuery({\n * filter: filter.eq('state.status', 'PAID'),\n * sort: [desc('createTime')],\n * limit: 20,\n * }),\n * execute: (query, options) =>\n * client.list(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * if (loading || !result) return <p>Loading…</p>;\n * return <ul>{result.map(order => <li key={order.aggregateId}>{order.state.status}</li>)}</ul>;\n * }\n * ```\n */\nexport function useListQuery<R, FIELDS extends string = string>(\n options: UseListQueryOptions<R, FIELDS, FilterListQuery<FIELDS>>,\n): UseListQueryReturn<R, FIELDS, FilterListQuery<FIELDS>>;\n/**\n * {@link useListQuery} typed by a query `Q` of your own, a subtype of\n * `FilterListQuery`, such as one whose literal projection narrows the result.\n */\nexport function useListQuery<\n R,\n FIELDS extends string = string,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n>(options: UseListQueryOptions<R, FIELDS, Q>): UseListQueryReturn<R, FIELDS, Q>;\nexport function useListQuery<\n R,\n FIELDS extends string,\n Q extends FilterListQuery<FIELDS>,\n>(\n options: UseListQueryOptions<R, FIELDS, Q>,\n): UseListQueryReturn<R, FIELDS, Q> {\n return useQueryRunner<Q, R[]>(options);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PagedQuery, PagedList } from '@ahoo-wang/wow-client/dsl';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link usePagedQuery}: a paged query and an `execute` that\n * resolves to one page.\n *\n * @template R - One row of the page\n * @template FIELDS - The field names the query may use\n * @template Q - The query type: `FilterPagedQuery` by default\n */\nexport interface UsePagedQueryOptions<\n R,\n FIELDS extends string = string,\n Q extends PagedQuery<FIELDS> = PagedQuery<FIELDS>,\n> extends QueryHookOptions<Q, PagedList<R>> {}\n\n/**\n * What {@link usePagedQuery} returns: the page (`total` and `list`) as\n * `result`.\n *\n * @template R - One row of the page\n * @template FIELDS - The field names the query may use\n * @template Q - The query type: `FilterPagedQuery` by default\n */\nexport interface UsePagedQueryReturn<\n R,\n FIELDS extends string = string,\n Q extends PagedQuery<FIELDS> = PagedQuery<FIELDS>,\n> extends QueryHookReturn<Q, PagedList<R>> {}\n\n/**\n * Runs a paged query through your own `execute` function and keeps the page\n * as state: typically a query client's `paged` or `pagedState`.\n *\n * `execute` receives the query and the request options of the run, its\n * `signal` included; hand them on so that a newer query, `abort()`\n * or an unmount cancels the request. The query runs on mount and whenever\n * `query` or `setQuery()` changes it — turn pages with `setQuery()`; set\n * `autoExecute: false` to run it only through `execute()`.\n *\n * Returns `result` (`{ total, list }`, or `undefined` before the first\n * success), `loading`, `error`, `problem`, `status`, `execute`, `abort`, `reset`,\n * `getQuery` and `setQuery`.\n *\n * @template R - One row of the page\n * @template FIELDS - The field names the query may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here: TypeScript does not infer them from `execute` once `R` is given\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient, Snapshot } from '@ahoo-wang/wow-client';\n * import { filter, pagedQuery } from '@ahoo-wang/wow-client/dsl';\n * import { usePagedQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidOrders({ client, page }: { client: SnapshotQueryClient<OrderState, OrderFields>; page: number }) {\n * const { result, loading, error } = usePagedQuery<Snapshot<OrderState>, OrderFields>({\n * query: pagedQuery({\n * filter: filter.eq('state.status', 'PAID'),\n * pagination: { index: page, size: 20 },\n * }),\n * execute: (query, options) =>\n * client.paged(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * if (loading || !result) return <p>Loading…</p>;\n * return <p>{result.list.length} of {result.total}</p>;\n * }\n * ```\n */\nexport function usePagedQuery<R, FIELDS extends string = string>(\n options: UsePagedQueryOptions<R, FIELDS, PagedQuery<FIELDS>>,\n): UsePagedQueryReturn<R, FIELDS, PagedQuery<FIELDS>>;\n/**\n * {@link usePagedQuery} typed by a query `Q` of your own, a subtype of\n * `PagedQuery`, such as one whose literal projection narrows the result.\n */\nexport function usePagedQuery<\n R,\n FIELDS extends string = string,\n Q extends PagedQuery<FIELDS> = PagedQuery<FIELDS>,\n>(\n options: UsePagedQueryOptions<R, FIELDS, Q>,\n): UsePagedQueryReturn<R, FIELDS, Q>;\nexport function usePagedQuery<\n R,\n FIELDS extends string,\n Q extends PagedQuery<FIELDS>,\n>(\n options: UsePagedQueryOptions<R, FIELDS, Q>,\n): UsePagedQueryReturn<R, FIELDS, Q> {\n return useQueryRunner<Q, PagedList<R>>(options);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterSingleQuery } from '@ahoo-wang/wow-client/dsl';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type { QueryHookOptions, QueryHookReturn } from '../types.js';\n\n/**\n * Options of {@link useSingleQuery}: a single query and an `execute` that\n * resolves to one item, or `undefined` when nothing matches, as a query\n * client's `single` does.\n *\n * @template R - The item the query returns\n * @template FIELDS - The field names the query may use\n * @template Q - The query type: `FilterSingleQuery` by default\n */\nexport interface UseSingleQueryOptions<\n R,\n FIELDS extends string = string,\n Q extends FilterSingleQuery<FIELDS> = FilterSingleQuery<FIELDS>,\n> extends QueryHookOptions<Q, R | undefined> {}\n\n/**\n * What {@link useSingleQuery} returns: the item as `result`, `undefined`\n * before the first run and when nothing matched (tell them apart by\n * `status`).\n *\n * @template R - The item the query returns\n * @template FIELDS - The field names the query may use\n * @template Q - The query type: `FilterSingleQuery` by default\n */\nexport interface UseSingleQueryReturn<\n R,\n FIELDS extends string = string,\n Q extends FilterSingleQuery<FIELDS> = FilterSingleQuery<FIELDS>,\n> extends QueryHookReturn<Q, R | undefined> {}\n\n/**\n * Runs a single query through your own `execute` function and keeps the\n * result as state: typically a query client's `single` or `singleState`.\n *\n * `execute` receives the query and the request options of the run, its\n * `signal` included; hand them on so that a newer query, `abort()`\n * or an unmount cancels the request. The query runs on mount and whenever\n * `query` or `setQuery()` changes it; set `autoExecute: false` to run it only\n * through `execute()`.\n *\n * Returns `result` (the item, or `undefined` before the first success),\n * `loading`, `error`, `problem`, `status`, `execute`, `abort`, `reset`, `getQuery` and\n * `setQuery`.\n *\n * @template R - The item the query returns\n * @template FIELDS - The field names the query may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here: TypeScript does not infer them from `execute` once `R` is given\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient, Snapshot } from '@ahoo-wang/wow-client';\n * import { filter, singleQuery } from '@ahoo-wang/wow-client/dsl';\n * import { useSingleQuery } from '@ahoo-wang/wow-react';\n *\n * function OrderStatus({ client, id }: { client: SnapshotQueryClient<OrderState, OrderFields>; id: string }) {\n * const { result, loading, error } = useSingleQuery<Snapshot<OrderState>, OrderFields>({\n * query: singleQuery({ filter: filter.id(id) }),\n * execute: (query, options) =>\n * client.single(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * if (loading) return <p>Loading…</p>;\n * if (!result) return <p>No such order.</p>;\n * return <p>{result.state.status}</p>;\n * }\n * ```\n */\nexport function useSingleQuery<R, FIELDS extends string = string>(\n options: UseSingleQueryOptions<R, FIELDS, FilterSingleQuery<FIELDS>>,\n): UseSingleQueryReturn<R, FIELDS, FilterSingleQuery<FIELDS>>;\n/**\n * {@link useSingleQuery} typed by a query `Q` of your own, a subtype of\n * `FilterSingleQuery`, such as one whose literal projection narrows the result.\n */\nexport function useSingleQuery<\n R,\n FIELDS extends string = string,\n Q extends FilterSingleQuery<FIELDS> = FilterSingleQuery<FIELDS>,\n>(\n options: UseSingleQueryOptions<R, FIELDS, Q>,\n): UseSingleQueryReturn<R, FIELDS, Q>;\nexport function useSingleQuery<\n R,\n FIELDS extends string,\n Q extends FilterSingleQuery<FIELDS>,\n>(\n options: UseSingleQueryOptions<R, FIELDS, Q>,\n): UseSingleQueryReturn<R, FIELDS, Q> {\n return useQueryRunner<Q, R | undefined>(options);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Positioned } from '@ahoo-wang/wow-client';\n\n/**\n * The least time between two publishes while a stream is read: about one\n * frame, so the rows keep up with the screen while a long stream costs a\n * bounded number of renders.\n */\nexport const PUBLISH_INTERVAL_MS = 16;\n\n/**\n * Reads a stream of rows to its end and resolves to every record, in order.\n *\n * While it reads, it hands the records received so far, and the position of\n * the last row that had one, to `publish`: the first\n * rows on the next macrotask, then at most once every\n * {@link PUBLISH_INTERVAL_MS}. Publishing by time, not by network chunk,\n * bounds how often a long stream renders and copies its rows: one render per\n * interval however many chunks arrive in it, and each `publish` still gets a\n * new array. It publishes the last rows before it\n * resolves or rejects, so the rows before a failure stay visible.\n *\n * `signal` aborting cancels the stream — a fake or already-buffered body\n * does not end with the request — and stops every later `publish`: a newer\n * query or an unmount has taken over, and its rows must not be overwritten.\n * The reader is always released, so the stream never stays locked.\n *\n * Internal: not exported from the package.\n */\nexport async function readStreamRows<R>(\n stream: ReadableStream<Positioned<R>>,\n signal: AbortSignal,\n publish: (rows: R[], position: string | undefined) => void,\n): Promise<R[]> {\n const reader = stream.getReader();\n const rows: R[] = [];\n let position: string | undefined;\n let published = 0;\n let publishedAt = -Infinity;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const flush = () => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n if (signal.aborted || published === rows.length) return;\n published = rows.length;\n publishedAt = Date.now();\n publish(rows.slice(), position);\n };\n const schedule = () => {\n if (timer !== undefined) return;\n const wait = Math.max(0, publishedAt + PUBLISH_INTERVAL_MS - Date.now());\n timer = setTimeout(flush, wait);\n };\n const cancel = () => {\n reader.cancel(signal.reason).catch(() => {\n // The stream had already failed; that failure is the one reported.\n });\n };\n if (signal.aborted) cancel();\n else signal.addEventListener('abort', cancel, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n rows.push(value.row);\n if (value.position !== undefined) position = value.position;\n schedule();\n }\n flush();\n return rows;\n } catch (error) {\n flush();\n throw error;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n signal.removeEventListener('abort', cancel);\n reader.releaseLock();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { StreamOptions } from '@ahoo-wang/wow-client';\nimport type { FilterListQuery } from '@ahoo-wang/wow-client/dsl';\nimport { useCallback, useState } from 'react';\nimport { readStreamRows } from '../internal/readStreamRows.js';\nimport { useQueryRunner } from '../internal/useQueryRunner.js';\nimport type {\n QueryHookOptions,\n QueryHookReturn,\n StreamExecutor,\n} from '../types.js';\n\n/**\n * Options of {@link useStreamQuery}: those of every query hook, with an\n * `execute` that opens the stream and `requestOptions` that take the\n * stream's `resume`.\n *\n * `onSuccess` receives every record once the stream has ended.\n *\n * @template R - One record of the stream\n * @template FIELDS - The field names the query may use\n * @template Q - The query type: `FilterListQuery` by default\n */\nexport interface UseStreamQueryOptions<\n R,\n FIELDS extends string = string,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends Omit<QueryHookOptions<Q, R[], StreamOptions>, 'execute'> {\n /**\n * Opens the stream for a query: a query client's `streamRows`, which\n * answers each record with its position.\n */\n execute: StreamExecutor<R, Q>;\n}\n\n/**\n * What {@link useStreamQuery} returns: the records as they arrive, whether\n * the stream has ended, and where it stopped.\n *\n * - `items` — the records of the current query received so far, in order,\n * updated at most about once a frame (every 16 ms) while they arrive. A new\n * query starts from an empty list; `reset()` empties it; `abort()` and an\n * error keep the records received before them.\n * - `position` — the position of the last record in `items` that had one.\n * - `done` — the stream ended normally and `items` holds every record.\n * - `loading` — from the request until the stream ends, fails or is aborted.\n * - `error` — the request failed, or the server sent an error event in the\n * stream; `problem` is then the `WowProblemError`, with the problem's\n * `code`.\n * - `status` — `idle`, `loading`, `success` (the same as `done`) or `error`.\n * - `execute()` runs the current query again and aborts the stream in flight;\n * `abort()` stops the stream; `reset()` stops it and empties `items`.\n */\nexport interface UseStreamQueryReturn<\n R,\n FIELDS extends string = string,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n> extends Omit<QueryHookReturn<Q, R[]>, 'result'> {\n /**\n * The records of the current query received so far, a new array at every\n * update.\n */\n items: R[];\n /**\n * The position of the last record received that had one, or `undefined`\n * before the first such record: hand it back as\n * `requestOptions.resume.lastEventId` to go on after it, on a later mount.\n * A new query and `reset()` clear it with `items`.\n */\n position: string | undefined;\n /** Whether the stream ended normally, so `items` holds every record. */\n done: boolean;\n}\n\n/** The records read so far, and where they stopped. */\ninterface Rows<R> {\n items: R[];\n position: string | undefined;\n}\n\n/**\n * Streams the records of a list query as server-sent events and keeps them\n * as state.\n *\n * The hook owns the stream: it reads it, collects the records into `items`,\n * and cancels it when a newer query starts, on `abort()` or `reset()`, and on\n * unmount. Components render `items` and never hold a reader, so the hook is\n * safe under StrictMode. `autoExecute` defaults to `true`.\n *\n * Pass a query client's `streamRows` as `execute`: it sends\n * `Accept: text/event-stream`, resumes a stream the server ends to be\n * resumed or that is cut off, turns error events into a `WowProblemError`,\n * and answers each record with its position, which the hook keeps as\n * `position`.\n *\n * To go on where a stream stopped after the component remounts (a page\n * change, a reload), keep `position` somewhere that outlives it and hand it\n * back as `requestOptions: { resume: { lastEventId: saved } }`; the first\n * request then asks for the records after it.\n *\n * @template R - One record of the stream\n * @template FIELDS - The field names the query may use. With a client whose\n * fields are narrower than `string`, as a generated client's are, pass\n * them here: TypeScript does not infer them from `execute` once `R` is given\n *\n * @example\n * ```tsx\n * import type { SnapshotQueryClient, Snapshot } from '@ahoo-wang/wow-client';\n * import { filter, listQuery } from '@ahoo-wang/wow-client/dsl';\n * import { useStreamQuery } from '@ahoo-wang/wow-react';\n *\n * function PaidOrders({ client }: { client: SnapshotQueryClient<OrderState, OrderFields> }) {\n * const { items, done, loading, error, abort } = useStreamQuery<Snapshot<OrderState>, OrderFields>({\n * initialQuery: listQuery({ filter: filter.eq('state.status', 'PAID') }),\n * execute: (query, options) =>\n * client.streamRows(query, options),\n * });\n * if (error) return <p role=\"alert\">{error.message}</p>;\n * return (\n * <>\n * <ul>{items.map(order => <li key={order.aggregateId}>{order.state.status}</li>)}</ul>\n * {loading && <button onClick={abort}>Stop</button>}\n * {done && <p>{items.length} orders</p>}\n * </>\n * );\n * }\n * ```\n */\nexport function useStreamQuery<R, FIELDS extends string = string>(\n options: UseStreamQueryOptions<R, FIELDS, FilterListQuery<FIELDS>>,\n): UseStreamQueryReturn<R, FIELDS, FilterListQuery<FIELDS>>;\n/**\n * {@link useStreamQuery} typed by a query `Q` of your own, a subtype of\n * `FilterListQuery`, such as one whose literal projection narrows the result.\n */\nexport function useStreamQuery<\n R,\n FIELDS extends string = string,\n Q extends FilterListQuery<FIELDS> = FilterListQuery<FIELDS>,\n>(\n options: UseStreamQueryOptions<R, FIELDS, Q>,\n): UseStreamQueryReturn<R, FIELDS, Q>;\nexport function useStreamQuery<\n R,\n FIELDS extends string,\n Q extends FilterListQuery<FIELDS>,\n>(\n options: UseStreamQueryOptions<R, FIELDS, Q>,\n): UseStreamQueryReturn<R, FIELDS, Q> {\n // Each run starts from no records; `abort()` and an error keep the records\n // received; `reset()` empties them. The runner aborts the run's signal\n // whenever the run stops counting, and readStreamRows stops publishing\n // then, so records of a stale stream never reach `items`.\n const [rows, setRows] = useState<Rows<R>>(noRows);\n const openStream = options.execute;\n const {\n status,\n loading,\n error,\n problem,\n execute,\n abort,\n reset,\n getQuery,\n setQuery,\n } = useQueryRunner<Q, R[], StreamOptions>(\n {\n ...options,\n execute: async (query, options) => {\n setRows(noRows());\n const stream = await openStream(query, options);\n return readStreamRows(stream, options.signal, (items, position) =>\n setRows({ items, position }),\n );\n },\n },\n false,\n );\n const resetRows = useCallback(() => {\n reset();\n setRows(noRows());\n }, [reset]);\n return {\n items: rows.items,\n position: rows.position,\n done: status === 'success',\n loading,\n error,\n problem,\n status,\n execute,\n abort,\n reset: resetRows,\n getQuery,\n setQuery,\n };\n}\n\nfunction noRows<R>(): Rows<R> {\n return { items: [], position: undefined };\n}\n"],"mappings":";;;;;AAyCA,SAAgBS,kBAAqBC,GAAqC;CACxE,OAAO;EACLR,QAAQQ,IAAc,YAAY;EAClCP,QAAQQ,KAAAA;EACRN,OAAOM,KAAAA;CACT;AACF;AAcA,SAAgBC,gBACdC,GACAC,GACe;CACf,QAAQA,EAAMN,MAAd;EACE,KAAK,SACH,OAAO;GAAEN,QAAQ;GAAWC,QAAQU,EAAMV;GAAQE,OAAOM,KAAAA;EAAU;EACrE,KAAK,WACH,OAAO;GAAET,QAAQ;GAAWC,QAAQW,EAAMX;GAAQE,OAAOM,KAAAA;EAAU;EACrE,KAAK,QACH,OAAO;GAAET,QAAQ;GAASC,QAAQU,EAAMV;GAAQE,OAAOS,EAAMT;EAAM;EACrE,KAAK,SACH,OAAO;GAAEH,QAAQ;GAAQC,QAAQU,EAAMV;GAAQE,OAAOM,KAAAA;EAAU;EAClE,KAAK,SACH,OAAO;GAAET,QAAQ;GAAQC,QAAQQ,KAAAA;GAAWN,OAAOM,KAAAA;EAAU;CACjE;AACF;;ACvCA,SAAAmB,iBAAAC,GAAA;CAC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AAAY,KAAAZ,EAAA,QAAAsB,KAHrBC,IAAA;EAAA7B,OACEQ,EAAIR;EAAMC,UACPO,EAAIP;EAASC,MACjB0B;EAAoBT;EAAAC;EAAAC;EAAAH;EAAApB;EAAAwB;EAAAC,OAOnBI;EAASH;EAAAC;CAGlB,GAACnB,EAAA,KAAAgB,GAAAhB,EAAA,KAAAc,GAAAd,EAAA,KAAAR,GAAAQ,EAAA,MAAAkB,GAAAlB,EAAA,MAAAa,GAAAb,EAAA,MAAAe,GAAAf,EAAA,MAAAqB,GAAArB,EAAA,MAAAE,EAAAR,OAAAM,EAAA,MAAAE,EAAAP,UAAAK,EAAA,MAAAmB,GAAAnB,EAAA,MAAAY,GAAAZ,EAAA,MAAAsB,GAAAtB,EAAA,MAAAuB,KAAAA,IAAAvB,EAAA,KAbMuB;AAaN;AAGH,SAASnB,SAAqB;CAC5B,OAAO;EAAEV,OAAO,CAAA;EAAIC,UAAU6B,KAAAA;CAAU;AAC1C"}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import { QueryStatus } from '../types.js';
|
|
2
2
|
/** What a query hook shows at one moment. */
|
|
3
|
-
export interface QueryState<R
|
|
3
|
+
export interface QueryState<R> {
|
|
4
4
|
status: QueryStatus;
|
|
5
5
|
result: R | undefined;
|
|
6
|
-
error:
|
|
6
|
+
error: Error | undefined;
|
|
7
7
|
}
|
|
8
8
|
/** Something that happens to a query hook. */
|
|
9
|
-
export type QueryEvent<R
|
|
9
|
+
export type QueryEvent<R> = {
|
|
10
10
|
type: 'start';
|
|
11
11
|
} | {
|
|
12
12
|
type: 'succeed';
|
|
13
13
|
result: R | undefined;
|
|
14
14
|
} | {
|
|
15
15
|
type: 'fail';
|
|
16
|
-
error:
|
|
16
|
+
error: Error;
|
|
17
17
|
} | {
|
|
18
18
|
type: 'abort';
|
|
19
19
|
} | {
|
|
@@ -24,7 +24,7 @@ export type QueryEvent<R, E> = {
|
|
|
24
24
|
* starts `loading`, so the server and the first client frame already show
|
|
25
25
|
* what the next frames show; any other starts `idle`.
|
|
26
26
|
*/
|
|
27
|
-
export declare function initialQueryState<R
|
|
27
|
+
export declare function initialQueryState<R>(runsOnMount: boolean): QueryState<R>;
|
|
28
28
|
/**
|
|
29
29
|
* The state after one event:
|
|
30
30
|
*
|
|
@@ -37,4 +37,4 @@ export declare function initialQueryState<R, E>(runsOnMount: boolean): QueryStat
|
|
|
37
37
|
* - `abort`: `idle`; the last result stays, the error goes.
|
|
38
38
|
* - `reset`: `idle`, with neither result nor error.
|
|
39
39
|
*/
|
|
40
|
-
export declare function queryTransition<R
|
|
40
|
+
export declare function queryTransition<R>(state: QueryState<R>, event: QueryEvent<R>): QueryState<R>;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Positioned } from '@ahoo-wang/wow-client';
|
|
1
2
|
/**
|
|
2
3
|
* The least time between two publishes while a stream is read: about one
|
|
3
4
|
* frame, so the rows keep up with the screen while a long stream costs a
|
|
@@ -5,9 +6,10 @@
|
|
|
5
6
|
*/
|
|
6
7
|
export declare const PUBLISH_INTERVAL_MS = 16;
|
|
7
8
|
/**
|
|
8
|
-
* Reads a stream of rows to its end and resolves to every
|
|
9
|
+
* Reads a stream of rows to its end and resolves to every record, in order.
|
|
9
10
|
*
|
|
10
|
-
* While it reads, it hands the
|
|
11
|
+
* While it reads, it hands the records received so far, and the position of
|
|
12
|
+
* the last row that had one, to `publish`: the first
|
|
11
13
|
* rows on the next macrotask, then at most once every
|
|
12
14
|
* {@link PUBLISH_INTERVAL_MS}. Publishing by time, not by network chunk,
|
|
13
15
|
* bounds how often a long stream renders and copies its rows: one render per
|
|
@@ -22,4 +24,4 @@ export declare const PUBLISH_INTERVAL_MS = 16;
|
|
|
22
24
|
*
|
|
23
25
|
* Internal: not exported from the package.
|
|
24
26
|
*/
|
|
25
|
-
export declare function readStreamRows<R>(stream: ReadableStream<R
|
|
27
|
+
export declare function readStreamRows<R>(stream: ReadableStream<Positioned<R>>, signal: AbortSignal, publish: (rows: R[], position: string | undefined) => void): Promise<R[]>;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { RequestOptions } from '@ahoo-wang/wow-client';
|
|
1
2
|
import { QueryHookOptions, QueryHookReturn } from '../types.js';
|
|
2
3
|
/**
|
|
3
4
|
* The one request state machine every hook runs on.
|
|
@@ -5,17 +6,18 @@ import { QueryHookOptions, QueryHookReturn } from '../types.js';
|
|
|
5
6
|
* - Latest wins: every run takes a new number and aborts the one before; an
|
|
6
7
|
* answer that is no longer the latest, arrives after `abort()` or
|
|
7
8
|
* `reset()`, or arrives after unmount, changes nothing.
|
|
8
|
-
* - A run starts on mount, whenever the query
|
|
9
|
-
* `setQuery()`,
|
|
10
|
-
*
|
|
9
|
+
* - A run starts on mount, whenever the query or `requestOptions` changes
|
|
10
|
+
* by content, through `setQuery()`, and when `autoExecute` turns on;
|
|
11
|
+
* `execute()` starts one by hand.
|
|
11
12
|
* - `abort()`, `reset()` and unmount abort the request in flight.
|
|
12
13
|
* - StrictMode's second mount aborts the first run and starts one more, so
|
|
13
14
|
* exactly one answer lands.
|
|
15
|
+
* - A failure is reported as an `Error`, and as `problem` too when a Wow
|
|
16
|
+
* service answered it.
|
|
14
17
|
*
|
|
15
|
-
* `
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* when a run starts or settles, so a change to them never starts one.
|
|
18
|
+
* With `retainResult` off the runner hands a run's result to `onSuccess`
|
|
19
|
+
* but does not keep it as `result`: the list-stream and cursor hooks keep
|
|
20
|
+
* their rows as `items` already. `execute` and the callbacks are read when a
|
|
21
|
+
* run starts or settles, so a change to them never starts one.
|
|
20
22
|
*/
|
|
21
|
-
export declare function useQueryRunner<Q, R,
|
|
23
|
+
export declare function useQueryRunner<Q, R, O extends RequestOptions = RequestOptions>(options: QueryHookOptions<Q, R, O>, retainResult?: boolean): QueryHookReturn<Q, R>;
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { RequestOptions } from '@ahoo-wang/wow-client';
|
|
1
|
+
import { RequestOptions, Positioned, StreamOptions, WowProblemError } from '@ahoo-wang/wow-client';
|
|
2
2
|
/**
|
|
3
3
|
* Where a query hook stands:
|
|
4
4
|
*
|
|
@@ -27,29 +27,30 @@ export type QueryStatus = 'idle' | 'loading' | 'success' | 'error';
|
|
|
27
27
|
*
|
|
28
28
|
* @template Q - The query
|
|
29
29
|
* @template R - What the query resolves to
|
|
30
|
+
* @template O - The request options the hook hands on
|
|
30
31
|
*/
|
|
31
|
-
export type QueryExecutor<Q, R> = (query: Q, options:
|
|
32
|
+
export type QueryExecutor<Q, R, O extends RequestOptions = RequestOptions> = (query: Q, options: O & {
|
|
32
33
|
readonly signal: AbortSignal;
|
|
33
34
|
}) => Promise<R>;
|
|
34
35
|
/**
|
|
35
|
-
* Opens the event stream of one query: a query client's `
|
|
36
|
-
*
|
|
37
|
-
*
|
|
36
|
+
* Opens the event stream of one query: a query client's `streamRows`, which
|
|
37
|
+
* answers each record with its position, so the hook can say where the
|
|
38
|
+
* stream stopped. It receives the query and the stream options of this run,
|
|
39
|
+
* `resume` included, with the run's `signal`.
|
|
38
40
|
*
|
|
39
|
-
* @template R - One
|
|
41
|
+
* @template R - One record of the stream
|
|
40
42
|
* @template Q - The query
|
|
41
43
|
*/
|
|
42
|
-
export type
|
|
44
|
+
export type StreamExecutor<R, Q> = QueryExecutor<Q, ReadableStream<Positioned<R>>, StreamOptions>;
|
|
43
45
|
/**
|
|
44
46
|
* The options every query hook takes. Each `Use…QueryOptions` extends it with
|
|
45
|
-
* its own query and result types
|
|
46
|
-
* `fetcher` in place of `execute`.
|
|
47
|
+
* its own query and result types.
|
|
47
48
|
*
|
|
48
49
|
* @template Q - The query
|
|
49
50
|
* @template R - What the query resolves to
|
|
50
|
-
* @template
|
|
51
|
+
* @template O - The request options the hook hands on
|
|
51
52
|
*/
|
|
52
|
-
export interface QueryHookOptions<Q, R,
|
|
53
|
+
export interface QueryHookOptions<Q, R, O extends RequestOptions = RequestOptions> {
|
|
53
54
|
/**
|
|
54
55
|
* The query, controlled: the hook runs it again whenever it changes by
|
|
55
56
|
* content, so a new object with the same content does not. Set to
|
|
@@ -67,27 +68,29 @@ export interface QueryHookOptions<Q, R, E = Error> {
|
|
|
67
68
|
autoExecute?: boolean;
|
|
68
69
|
/**
|
|
69
70
|
* Handed to `execute` with every run, with the run's `signal`: the scope,
|
|
70
|
-
* the space or more headers of the request.
|
|
71
|
-
*
|
|
71
|
+
* the space or more headers of the request. Part of what identifies a run,
|
|
72
|
+
* as the query is: a change by content runs the query again, since the
|
|
73
|
+
* scope, the space and the headers can change the answer. A header whose
|
|
74
|
+
* value changes on every render, such as a timestamp, therefore restarts
|
|
75
|
+
* the run on every render; keep such values stable.
|
|
72
76
|
*/
|
|
73
|
-
requestOptions?: Omit<
|
|
77
|
+
requestOptions?: Omit<O, 'signal'>;
|
|
74
78
|
/** Runs one query. */
|
|
75
|
-
execute: QueryExecutor<Q, R>;
|
|
79
|
+
execute: QueryExecutor<Q, R, O>;
|
|
76
80
|
/** Called with the result of each run that succeeds. */
|
|
77
81
|
onSuccess?: (result: R) => void | Promise<void>;
|
|
78
|
-
/** Called with the error of each run that fails
|
|
79
|
-
onError?: (error:
|
|
82
|
+
/** Called with the error of each run that fails, the hook's `error`. */
|
|
83
|
+
onError?: (error: Error) => void | Promise<void>;
|
|
80
84
|
}
|
|
81
85
|
/**
|
|
82
86
|
* What every query hook returns. Each `Use…QueryReturn` extends it with its own
|
|
83
|
-
* query and result types; the list-stream hooks return `items`
|
|
87
|
+
* query and result types; the list-stream and cursor hooks return `items` in
|
|
84
88
|
* place of `result`.
|
|
85
89
|
*
|
|
86
90
|
* @template Q - The query
|
|
87
91
|
* @template R - What the query resolves to
|
|
88
|
-
* @template E - The error the hook reports, `Error` by default
|
|
89
92
|
*/
|
|
90
|
-
export interface QueryHookReturn<Q, R
|
|
93
|
+
export interface QueryHookReturn<Q, R> {
|
|
91
94
|
/** Where the hook stands; see {@link QueryStatus}. */
|
|
92
95
|
status: QueryStatus;
|
|
93
96
|
/** Whether a request is in flight: the same as `status === 'loading'`. */
|
|
@@ -98,8 +101,17 @@ export interface QueryHookReturn<Q, R, E = Error> {
|
|
|
98
101
|
* `reset()` clears it.
|
|
99
102
|
*/
|
|
100
103
|
result: R | undefined;
|
|
101
|
-
/**
|
|
102
|
-
|
|
104
|
+
/**
|
|
105
|
+
* Why the latest run failed, or `undefined`. A value thrown that is not an
|
|
106
|
+
* `Error` arrives wrapped, as `new Error(String(thrown), { cause: thrown })`.
|
|
107
|
+
*/
|
|
108
|
+
error: Error | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* The problem a Wow service answered the latest run with: `error` when it
|
|
111
|
+
* is a `WowProblemError`, with its `code`, `status` and retry hint;
|
|
112
|
+
* `undefined` for a failure no service answered, such as a network error.
|
|
113
|
+
*/
|
|
114
|
+
problem: WowProblemError | undefined;
|
|
103
115
|
/** Runs the current query again, aborting the request in flight. */
|
|
104
116
|
execute: () => Promise<void>;
|
|
105
117
|
/**
|