@zeno-lib/query 0.0.3 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,5 @@
1
1
  import { DehydratedState } from "@tanstack/react-query";
2
2
  import { ReactNode } from "react";
3
- //#region src/prefetched-queries.d.ts
4
3
  /** Whether the nearest `PrefetchedQueries` above was handed at least one dehydrated query. */
5
4
  export declare function useHasPrefetchedQueries(): boolean;
6
5
  export type PrefetchedQueriesProps = {
@@ -12,5 +11,4 @@ export type PrefetchedQueriesProps = {
12
11
  * render** (on the server pass as well as in the browser), so a `useSuspenseQuery` below it
13
12
  * resolves synchronously in both and the two passes produce the same markup.
14
13
  */
15
- export declare function PrefetchedQueries({ children, state }: PrefetchedQueriesProps): import("react").JSX.Element;
16
- //#endregion
14
+ export declare function PrefetchedQueries({ children, state }: PrefetchedQueriesProps): import("react").JSX.Element;
@@ -2,7 +2,7 @@
2
2
  import { HydrationBoundary } from "@tanstack/react-query";
3
3
  import { createContext, useContext } from "react";
4
4
  import { jsx } from "react/jsx-runtime";
5
- //#region src/prefetched-queries.tsx
5
+ // src/prefetched-queries.tsx
6
6
  /**
7
7
  * True inside a subtree that was handed a filled dehydrated cache.
8
8
  *
@@ -33,5 +33,4 @@ function PrefetchedQueries({ children, state }) {
33
33
  })
34
34
  });
35
35
  }
36
- //#endregion
37
36
  export { PrefetchedQueries, useHasPrefetchedQueries };
@@ -0,0 +1,46 @@
1
+ import { t as QueryMap } from "./query-map-Catubr0X.mjs";
2
+ import { QueryClient } from "@tanstack/react-query";
3
+ /** The part of TanStack's `QueryFunctionContext` a call reads. */
4
+ export type QueryCallContext = {
5
+ /** Finds the queries a `QueryHydrationBoundary` bound for its server pass. */
6
+ client?: QueryClient;
7
+ /** Abandons the request when TanStack cancels the query. */
8
+ signal?: AbortSignal;
9
+ };
10
+ /** What `name` takes: its one argument, or nothing. */
11
+ export type QueryInput<TQueries extends QueryMap, TName extends keyof TQueries> = Parameters<TQueries[TName]>[0];
12
+ /** What `name` resolves to. */
13
+ export type QueryData<TQueries extends QueryMap, TName extends keyof TQueries> = Awaited<ReturnType<TQueries[TName]>>;
14
+ /** A query the route answered with an error status. */
15
+ export declare class QueryRequestError extends Error {
16
+ readonly query: string;
17
+ readonly status: number;
18
+ constructor(query: string, status: number);
19
+ }
20
+ export type QueryCaller<TQueries extends QueryMap> = <TName extends keyof TQueries & string>(name: TName, input: QueryInput<TQueries, TName>, context?: QueryCallContext) => Promise<QueryData<TQueries, TName>>;
21
+ /**
22
+ * Builds the browser side of `createQueryRoute`: `callQuery(name, input,
23
+ * context)` posts to `${path}/${name}` and resolves to the query's data. Type
24
+ * it with the map the route serves, imported as a type only, so no server code
25
+ * reaches the bundle:
26
+ *
27
+ * ```ts
28
+ * import type { queries } from "./queries"
29
+ *
30
+ * export const callQuery = createQueryCaller<typeof queries>({
31
+ * path: "/api/queries",
32
+ * })
33
+ *
34
+ * queryFn: (context) => callQuery("selectPosts", { authorId }, context)
35
+ * ```
36
+ *
37
+ * Unlike a Server Function, each call is its own request, so a screen's
38
+ * queries run in parallel, and TanStack's `signal` cancels them. During a
39
+ * `QueryHydrationBoundary` prefetch, the call runs the bound server function
40
+ * in-process instead.
41
+ */
42
+ export declare function createQueryCaller<TQueries extends QueryMap>({ path }: {
43
+ /** Where the route is mounted, without the trailing name segment. */
44
+ path: string;
45
+ }): QueryCaller<TQueries>;
46
+ export type { QueryMap };
@@ -0,0 +1,70 @@
1
+ import { i as getBoundQueries, r as findQuery, t as QUERY_CONTENT_TYPE } from "./query-map-DD9UrwSx.mjs";
2
+ import { parse, stringify } from "devalue";
3
+ // src/query-caller.ts
4
+ /** A query the route answered with an error status. */
5
+ var QueryRequestError = class extends Error {
6
+ constructor(query, status) {
7
+ super(`Query ${query} failed with status ${status}`);
8
+ this.name = "QueryRequestError";
9
+ this.query = query;
10
+ this.status = status;
11
+ }
12
+ };
13
+ /**
14
+ * Builds the browser side of `createQueryRoute`: `callQuery(name, input,
15
+ * context)` posts to `${path}/${name}` and resolves to the query's data. Type
16
+ * it with the map the route serves, imported as a type only, so no server code
17
+ * reaches the bundle:
18
+ *
19
+ * ```ts
20
+ * import type { queries } from "./queries"
21
+ *
22
+ * export const callQuery = createQueryCaller<typeof queries>({
23
+ * path: "/api/queries",
24
+ * })
25
+ *
26
+ * queryFn: (context) => callQuery("selectPosts", { authorId }, context)
27
+ * ```
28
+ *
29
+ * Unlike a Server Function, each call is its own request, so a screen's
30
+ * queries run in parallel, and TanStack's `signal` cancels them. During a
31
+ * `QueryHydrationBoundary` prefetch, the call runs the bound server function
32
+ * in-process instead.
33
+ */
34
+ function createQueryCaller({ path }) {
35
+ return async (name, input, context = {}) => {
36
+ const bound = context.client && getBoundQueries(context.client);
37
+ if (bound) {
38
+ const query = findQuery(bound, name);
39
+ if (!query) throw new Error(`callQuery: "${name}" is not in the queries bound to this QueryHydrationBoundary`);
40
+ return await query(input);
41
+ }
42
+ if (typeof window === "undefined") throw new Error(`callQuery: "${name}" ran on the server outside a QueryHydrationBoundary that binds its queries`);
43
+ const response = await fetch(`${path}/${encodeURIComponent(name)}`, {
44
+ body: stringify(input),
45
+ headers: { "content-type": QUERY_CONTENT_TYPE },
46
+ method: "POST",
47
+ redirect: "manual",
48
+ signal: context.signal
49
+ });
50
+ if (response.type === "opaqueredirect") {
51
+ reloadOnce();
52
+ throw new QueryRequestError(name, 401);
53
+ }
54
+ if (!(response.ok && response.headers.get("content-type")?.startsWith("application/json"))) throw new QueryRequestError(name, response.status);
55
+ return parse(await response.text());
56
+ };
57
+ }
58
+ const RELOADED_AT_KEY = "zeno-query:reloaded-at";
59
+ /**
60
+ * Reloads the page, unless a redirect already did within the last minute: a
61
+ * redirect the reload does not clear (a trailing-slash rule, a middleware that
62
+ * redirects only API paths) would otherwise reload forever.
63
+ */
64
+ function reloadOnce() {
65
+ const reloadedAt = Number(sessionStorage.getItem(RELOADED_AT_KEY));
66
+ if (Date.now() - reloadedAt < 6e4) return;
67
+ sessionStorage.setItem(RELOADED_AT_KEY, String(Date.now()));
68
+ window.location.reload();
69
+ }
70
+ export { QueryRequestError, createQueryCaller };
@@ -1,4 +1,3 @@
1
- //#region src/query-defaults.d.ts
2
1
  /**
3
2
  * Timing presets to spread as the first property of a `queryOptions(…)` call, so freshness stays
4
3
  * consistent across a codebase instead of every query inventing its own `staleTime`.
@@ -36,5 +35,4 @@ export declare const cachedQueryDefaults: {
36
35
  /** Effectively immutable data: never stale. */
37
36
  export declare const staticQueryDefaults: {
38
37
  readonly staleTime: number;
39
- };
40
- //#endregion
38
+ };
@@ -1,4 +1,4 @@
1
- //#region src/query-defaults.ts
1
+ // src/query-defaults.ts
2
2
  /**
3
3
  * Timing presets to spread as the first property of a `queryOptions(…)` call, so freshness stays
4
4
  * consistent across a codebase instead of every query inventing its own `staleTime`.
@@ -33,5 +33,4 @@ const cachedQueryDefaults = {
33
33
  };
34
34
  /** Effectively immutable data: never stale. */
35
35
  const staticQueryDefaults = { staleTime: Number.POSITIVE_INFINITY };
36
- //#endregion
37
36
  export { cachedQueryDefaults, liveBackgroundQueryDefaults, liveQueryDefaults, longLivedQueryDefaults, shortLivedQueryDefaults, staticQueryDefaults };
@@ -1,6 +1,6 @@
1
+ import { t as QueryMap } from "./query-map-Catubr0X.mjs";
1
2
  import { DehydrateOptions, QueryClient } from "@tanstack/react-query";
2
3
  import { ReactNode } from "react";
3
- //#region src/query-hydration-boundary.d.ts
4
4
  export type QueryHydrationBoundaryProps = {
5
5
  children: ReactNode;
6
6
  /**
@@ -17,6 +17,11 @@ export type QueryHydrationBoundaryProps = {
17
17
  createQueryClient?: () => QueryClient;
18
18
  /** Forwarded to TanStack's `dehydrate` (e.g. to also dehydrate pending queries). */
19
19
  dehydrateOptions?: DehydrateOptions;
20
+ /**
21
+ * The map your query route serves. A `queryFn` built on `createQueryCaller` then calls these
22
+ * functions in-process during `prefetch`, since the server has no URL to fetch them from.
23
+ */
24
+ queries?: QueryMap;
20
25
  };
21
26
  /**
22
27
  * Async **server component**: runs `prefetch` against a fresh `QueryClient` and dehydrates the
@@ -32,5 +37,4 @@ export type QueryHydrationBoundaryProps = {
32
37
  * </QueryHydrationBoundary>
33
38
  * ```
34
39
  */
35
- export declare function QueryHydrationBoundary({ children, createQueryClient, dehydrateOptions, prefetch }: QueryHydrationBoundaryProps): Promise<import("react").JSX.Element>;
36
- //#endregion
40
+ export declare function QueryHydrationBoundary({ children, createQueryClient, dehydrateOptions, prefetch, queries }: QueryHydrationBoundaryProps): Promise<import("react").JSX.Element>;
@@ -1,7 +1,8 @@
1
1
  import { PrefetchedQueries } from "./prefetched-queries.mjs";
2
+ import { n as bindQueries } from "./query-map-DD9UrwSx.mjs";
2
3
  import { QueryClient, dehydrate } from "@tanstack/react-query";
3
4
  import { jsx } from "react/jsx-runtime";
4
- //#region src/query-hydration-boundary.tsx
5
+ // src/query-hydration-boundary.tsx
5
6
  /**
6
7
  * Async **server component**: runs `prefetch` against a fresh `QueryClient` and dehydrates the
7
8
  * result into `PrefetchedQueries`, so the suspense queries below resolve from the cache in the
@@ -16,13 +17,13 @@ import { jsx } from "react/jsx-runtime";
16
17
  * </QueryHydrationBoundary>
17
18
  * ```
18
19
  */
19
- async function QueryHydrationBoundary({ children, createQueryClient = () => new QueryClient(), dehydrateOptions, prefetch }) {
20
+ async function QueryHydrationBoundary({ children, createQueryClient = () => new QueryClient(), dehydrateOptions, prefetch, queries }) {
20
21
  const queryClient = createQueryClient();
22
+ if (queries) bindQueries(queryClient, queries);
21
23
  await prefetch(queryClient);
22
24
  return /* @__PURE__ */ jsx(PrefetchedQueries, {
23
25
  state: dehydrate(queryClient, dehydrateOptions),
24
26
  children
25
27
  });
26
28
  }
27
- //#endregion
28
29
  export { QueryHydrationBoundary };
@@ -0,0 +1,7 @@
1
+ import { QueryClient } from "@tanstack/react-query";
2
+ /**
3
+ * The server functions a query route serves, keyed by the name the browser
4
+ * calls them by. Each takes one argument and resolves to the query's data.
5
+ */
6
+ type QueryMap = Record<string, (input: any) => Promise<unknown>>;
7
+ export { QueryMap as t };
@@ -0,0 +1,25 @@
1
+ // src/query-map.ts
2
+ /**
3
+ * The function `queries` serves as `name`. `Object.hasOwn`, so `constructor` or
4
+ * `__proto__` is not a query, and the type check, so a module namespace's
5
+ * `__esModule` flag is not one either.
6
+ */
7
+ function findQuery(queries, name) {
8
+ const query = Object.hasOwn(queries, name) ? queries[name] : void 0;
9
+ return typeof query === "function" ? query : void 0;
10
+ }
11
+ /** The body type both ways; the route refuses any other. */
12
+ const QUERY_CONTENT_TYPE = "application/json";
13
+ /**
14
+ * The queries bound to a server `QueryClient`. A query function that runs
15
+ * against that client calls the server function in-process instead of going
16
+ * through the route, which a server render has no URL for.
17
+ */
18
+ const boundQueries = /* @__PURE__ */ new WeakMap();
19
+ function bindQueries(client, queries) {
20
+ boundQueries.set(client, queries);
21
+ }
22
+ function getBoundQueries(client) {
23
+ return boundQueries.get(client);
24
+ }
25
+ export { getBoundQueries as i, bindQueries as n, findQuery as r, QUERY_CONTENT_TYPE as t };
@@ -0,0 +1,21 @@
1
+ import { t as QueryMap } from "./query-map-Catubr0X.mjs";
2
+ /**
3
+ * Builds the `POST` handler of a route that serves `queries` to the browser,
4
+ * one request per call, so the reads of a screen run in parallel. Mount it on a
5
+ * dynamic segment whose last part is the query's name:
6
+ *
7
+ * ```ts
8
+ * // app/api/queries/[query]/route.ts
9
+ * export const { POST } = createQueryRoute(queries)
10
+ * ```
11
+ *
12
+ * The body and the result travel through `devalue`, so a `Date`, a `Map`, a
13
+ * `bigint` or an `undefined` arrives as it was sent. An error the query throws
14
+ * is left to the framework, which answers 500 and reports it. Every entry of
15
+ * `queries` is a public endpoint: authorize inside it, as you would in a
16
+ * server action.
17
+ */
18
+ export declare function createQueryRoute(queries: QueryMap): {
19
+ POST: (request: Request) => Promise<Response>;
20
+ };
21
+ export type { QueryMap };
@@ -0,0 +1,53 @@
1
+ import { r as findQuery, t as QUERY_CONTENT_TYPE } from "./query-map-DD9UrwSx.mjs";
2
+ import { parse, stringify } from "devalue";
3
+ // src/query-route.ts
4
+ /** The largest body the route parses, the default Server Functions accept. */
5
+ const MAX_BODY_BYTES = 1048576;
6
+ const TRAILING_SLASH = /\/$/u;
7
+ /**
8
+ * Builds the `POST` handler of a route that serves `queries` to the browser,
9
+ * one request per call, so the reads of a screen run in parallel. Mount it on a
10
+ * dynamic segment whose last part is the query's name:
11
+ *
12
+ * ```ts
13
+ * // app/api/queries/[query]/route.ts
14
+ * export const { POST } = createQueryRoute(queries)
15
+ * ```
16
+ *
17
+ * The body and the result travel through `devalue`, so a `Date`, a `Map`, a
18
+ * `bigint` or an `undefined` arrives as it was sent. An error the query throws
19
+ * is left to the framework, which answers 500 and reports it. Every entry of
20
+ * `queries` is a public endpoint: authorize inside it, as you would in a
21
+ * server action.
22
+ */
23
+ function createQueryRoute(queries) {
24
+ return { POST: async (request) => {
25
+ const query = findQuery(queries, queryName(request));
26
+ if (!query) return new Response(null, { status: 404 });
27
+ if (!request.headers.get("content-type")?.startsWith("application/json")) return new Response(null, { status: 415 });
28
+ if (Number(request.headers.get("content-length")) > MAX_BODY_BYTES) return new Response(null, { status: 413 });
29
+ const body = await request.text();
30
+ if (body.length > MAX_BODY_BYTES) return new Response(null, { status: 413 });
31
+ let input;
32
+ try {
33
+ input = parse(body);
34
+ } catch {
35
+ return new Response(null, { status: 400 });
36
+ }
37
+ const data = await query(input);
38
+ return new Response(stringify(data), { headers: {
39
+ "cache-control": "private, no-store",
40
+ "content-type": QUERY_CONTENT_TYPE
41
+ } });
42
+ } };
43
+ }
44
+ /** The path's last segment, or `""` when it is not a valid escape. */
45
+ function queryName(request) {
46
+ const segment = new URL(request.url).pathname.replace(TRAILING_SLASH, "").split("/").at(-1);
47
+ try {
48
+ return decodeURIComponent(segment ?? "");
49
+ } catch {
50
+ return "";
51
+ }
52
+ }
53
+ export { createQueryRoute };
@@ -1,10 +1,8 @@
1
1
  import { ComponentPropsWithoutRef } from "react";
2
- //#region src/query-suspense-loading.d.ts
3
2
  export type QuerySuspenseLoadingProps = ComponentPropsWithoutRef<"div">;
4
3
  /**
5
4
  * Single layout root for Suspense loading UI: set `className` and children here so `aria-busy` /
6
5
  * `aria-live` apply to the same element as your skeleton stack (no inner wrapper div). Accepts
7
6
  * all `div` props; the `aria-busy` and `aria-live` defaults can be overridden.
8
7
  */
9
- export declare function QuerySuspenseLoading({ "aria-busy": ariaBusy, "aria-live": ariaLive, children, ...props }: QuerySuspenseLoadingProps): import("react").JSX.Element;
10
- //#endregion
8
+ export declare function QuerySuspenseLoading({ "aria-busy": ariaBusy, "aria-live": ariaLive, children, ...props }: QuerySuspenseLoadingProps): import("react").JSX.Element;
@@ -1,5 +1,5 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
- //#region src/query-suspense-loading.tsx
2
+ // src/query-suspense-loading.tsx
3
3
  /**
4
4
  * Single layout root for Suspense loading UI: set `className` and children here so `aria-busy` /
5
5
  * `aria-live` apply to the same element as your skeleton stack (no inner wrapper div). Accepts
@@ -13,5 +13,4 @@ function QuerySuspenseLoading({ "aria-busy": ariaBusy = true, "aria-live": ariaL
13
13
  children
14
14
  });
15
15
  }
16
- //#endregion
17
16
  export { QuerySuspenseLoading };
@@ -1,5 +1,4 @@
1
1
  import { ReactNode } from "react";
2
- //#region src/query-suspense.d.ts
3
2
  export type QuerySuspenseErrorFallbackProps = {
4
3
  error: Error;
5
4
  onRetry: () => void;
@@ -25,5 +24,4 @@ export type QuerySuspenseProps = {
25
24
  * hydration gate: `fallback` is all it renders on the server and through hydration, unless a
26
25
  * `PrefetchedQueries` (e.g. from `QueryHydrationBoundary`) above it was handed dehydrated queries.
27
26
  */
28
- export declare function QuerySuspense({ children, errorFallback, fallback, debugState }: QuerySuspenseProps): import("react").JSX.Element;
29
- //#endregion
27
+ export declare function QuerySuspense({ children, errorFallback, fallback, debugState }: QuerySuspenseProps): import("react").JSX.Element;
@@ -3,7 +3,7 @@ import { useHasPrefetchedQueries } from "./prefetched-queries.mjs";
3
3
  import { QueryErrorResetBoundary } from "@tanstack/react-query";
4
4
  import { Component, Suspense, useSyncExternalStore } from "react";
5
5
  import { Fragment, jsx } from "react/jsx-runtime";
6
- //#region src/query-suspense.tsx
6
+ // src/query-suspense.tsx
7
7
  const debugStateEnabled = process.env.NODE_ENV !== "production";
8
8
  const subscribeToNothing = () => () => {};
9
9
  const useIsHydrated = () => useSyncExternalStore(subscribeToNothing, () => true, () => false);
@@ -59,5 +59,4 @@ function QuerySuspense({ children, errorFallback, fallback, debugState }) {
59
59
  })
60
60
  }) });
61
61
  }
62
- //#endregion
63
62
  export { QuerySuspense };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeno-lib/query",
3
- "version": "0.0.3",
3
+ "version": "0.1.1",
4
4
  "repository": {
5
5
  "url": "https://github.com/zeno-lib/zeno.git",
6
6
  "directory": "packages/query"
@@ -17,11 +17,21 @@
17
17
  "import": "./dist/query-defaults.mjs",
18
18
  "default": "./dist/query-defaults.mjs"
19
19
  },
20
+ "./query-caller": {
21
+ "types": "./dist/query-caller.d.mts",
22
+ "import": "./dist/query-caller.mjs",
23
+ "default": "./dist/query-caller.mjs"
24
+ },
20
25
  "./query-hydration-boundary": {
21
26
  "types": "./dist/query-hydration-boundary.d.mts",
22
27
  "import": "./dist/query-hydration-boundary.mjs",
23
28
  "default": "./dist/query-hydration-boundary.mjs"
24
29
  },
30
+ "./query-route": {
31
+ "types": "./dist/query-route.d.mts",
32
+ "import": "./dist/query-route.mjs",
33
+ "default": "./dist/query-route.mjs"
34
+ },
25
35
  "./query-suspense": {
26
36
  "types": "./dist/query-suspense.d.mts",
27
37
  "import": "./dist/query-suspense.mjs",
@@ -36,23 +46,26 @@
36
46
  "files": [
37
47
  "dist"
38
48
  ],
49
+ "dependencies": {
50
+ "devalue": "^6.0.3"
51
+ },
39
52
  "devDependencies": {
40
- "@tanstack/react-query": "^5.104.1",
41
- "@types/node": "26.6.4",
53
+ "@tanstack/react-query": "^5.105.0",
54
+ "@types/node": "26.6.5",
42
55
  "@types/react": "19.3.0",
43
56
  "@types/react-dom": "19.3.0",
44
- "@zeno-lib/test": "^0.1.1",
45
- "@zeno-lib/typescript": "^1.1.0",
57
+ "@zeno-lib/test": "^0.1.2",
58
+ "@zeno-lib/typescript": "^1.2.0",
46
59
  "@zeno-lib/ui": "^0.0.1",
47
- "react": "^19.3.0",
48
- "react-dom": "^19.3.0",
49
- "tsdown": "^0.23.0",
60
+ "react": "^19.3.1",
61
+ "react-dom": "^19.3.1",
62
+ "tsdown": "^0.23.1",
50
63
  "typescript": "7.0.2",
51
- "vite": "8.3.3",
52
- "vitest": "5.0.3"
64
+ "vite": "8.3.5",
65
+ "vitest": "5.0.5"
53
66
  },
54
67
  "peerDependencies": {
55
- "@tanstack/react-query": ">=5",
68
+ "@tanstack/react-query": ">=5.66.0",
56
69
  "react": ">=19"
57
70
  },
58
71
  "publishConfig": {