@softistx/riva-react-router 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,178 @@
1
- # Temporary Holding Version
1
+ # @softistx/riva-react-router
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React Router host for riva: one `RivaClient` per request, server-side loading with `dehydrate`, browser hydration and a merge of each navigation's data. Built for React Router 8 framework mode (and `@softistx/alxia-react-router`, which hosts the same routes); it never imports alxia.
4
+
5
+ ```sh
6
+ bun add @softistx/riva-react-router @softistx/riva @softistx/riva-react react react-router
7
+ ```
8
+
9
+ Peers: `@softistx/riva`, `@softistx/riva-react`, `react` ^19 and `react-router` ^8. `@softistx/alxia-react-router` is an optional peer, for hosting the routes with alxia.
10
+
11
+ ## Setup
12
+
13
+ `middleware` on a route module needs React Router 8 framework mode. The middleware goes on the root route, the provider in the root component:
14
+
15
+ ```ts
16
+ // app/riva.server.ts: built in a *.server.ts module, so /server stays out of the browser bundle
17
+ import { createGraphQLClient } from '@softistx/graphql-client';
18
+ import { graphqlClientTransport, provideGraphQL } from '@softistx/riva-graphql';
19
+ import { rivaMiddleware } from '@softistx/riva-react-router/server';
20
+
21
+ const API_URL = 'https://api.example.com/graphql'; // schematic: your API
22
+
23
+ export const rivaMw = rivaMiddleware({
24
+ // the caller port of the request: here its session cookie goes to the API
25
+ setup: (client, { request }) =>
26
+ provideGraphQL(
27
+ client,
28
+ graphqlClientTransport(
29
+ createGraphQLClient({
30
+ url: API_URL,
31
+ headers: { cookie: request.headers.get('cookie') ?? '' },
32
+ }),
33
+ ),
34
+ ),
35
+ });
36
+ ```
37
+
38
+ ```tsx
39
+ // app/root.tsx
40
+ import { createGraphQLClient } from '@softistx/graphql-client';
41
+ import { graphqlClientTransport, provideGraphQL } from '@softistx/riva-graphql';
42
+ import { RivaRouterProvider } from '@softistx/riva-react-router';
43
+ import { Outlet } from 'react-router';
44
+ import { rivaMw } from './riva.server';
45
+
46
+ const API_URL = 'https://api.example.com/graphql'; // schematic: your API
47
+
48
+ export const middleware = [rivaMw];
49
+
50
+ export default function Root() {
51
+ return (
52
+ <RivaRouterProvider
53
+ // the client the render and the browser use; the data itself comes from the loaders
54
+ setup={(client) =>
55
+ provideGraphQL(client, graphqlClientTransport(createGraphQLClient({ url: API_URL })))
56
+ }
57
+ >
58
+ <Outlet />
59
+ </RivaRouterProvider>
60
+ );
61
+ }
62
+ ```
63
+
64
+ Keep `/server` out of the browser bundle (it imports `node:async_hooks`): build the middleware in a `*.server.ts` module. Declare it once, on the root route; the provider's `client` prop must stay the same object. [Guide](./docs/guide/setup.md).
65
+
66
+ ## The loader pattern
67
+
68
+ Define the query once, read it in the loader and in the component:
69
+
70
+ ```tsx
71
+ // app/patients.tsx
72
+ import { query } from '@softistx/riva-graphql';
73
+ import { useQuery } from '@softistx/riva-react';
74
+ import { riva, rivaOf } from '@softistx/riva-react-router';
75
+ import { PATIENTS_QUERY } from './graphql'; // schematic: your document
76
+ import type { Route } from './+types/patients';
77
+
78
+ export const patients = query(PATIENTS_QUERY, { staleTime: '30s' });
79
+
80
+ export async function loader({ context, params }: Route.LoaderArgs) {
81
+ await patients.ensure(rivaOf(context), { school: params.school });
82
+ return riva(context);
83
+ }
84
+
85
+ export default function Patients({ params }: Route.ComponentProps) {
86
+ const { data } = useQuery(patients, { school: params.school });
87
+ return <ul>{data?.patients.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
88
+ }
89
+ ```
90
+
91
+ `rivaOf` and `riva` are for server loaders and actions only; return `riva(context)` from one loader per request. [Guide](./docs/guide/loader.md).
92
+
93
+ ## The `/_data` route
94
+
95
+ `dataRoute` lets the browser run allowlisted operations through your server, with the session of the request. Mount it on a route with an action; the browser's `bffTransport` (`@softistx/riva-graphql/bff`) posts to it.
96
+
97
+ ```ts
98
+ // app/routes/_data.ts
99
+ import { dataRoute } from '@softistx/riva-react-router/server';
100
+ import { allowlist } from '@softistx/riva-graphql/server';
101
+ import manifest from '../generated/allowlist.json';
102
+
103
+ const route = dataRoute({
104
+ sources: [allowlist(manifest)],
105
+ });
106
+ export const action = route.action;
107
+ export const loader = route.loader; // 405
108
+ ```
109
+
110
+ For REST, add `operations(api)` from `@softistx/riva-rest/server` to `sources`. Options: `sources`, `origin`, `maxBytes` (262144), `onError`. Refusals carry `RIVA_DATA_*` codes. [Guide](./docs/guide/data-route.md).
111
+
112
+ ## After a write
113
+
114
+ - `useActionResult(result, { into, vars, select? })` writes an action's result into a query's entry, once per result.
115
+ - `revalidate` is a query: invalidating it re-runs the route loaders. It needs `RivaRouterProvider` above the caller.
116
+ - `<RivaRouterProvider invalidateOnAction={[patients, revalidate]}>` invalidates that list each time a non-GET navigation or fetcher settles.
117
+
118
+ [Guide](./docs/guide/after-a-write.md).
119
+
120
+ ```tsx
121
+ // app/patients.tsx
122
+ import { mutation } from '@softistx/riva-graphql';
123
+ import { useQuery } from '@softistx/riva-react';
124
+ import { revalidate, useActionResult } from '@softistx/riva-react-router';
125
+ import { useActionData } from 'react-router';
126
+ import type { Route } from './+types/patients';
127
+ import { patients } from './patients.queries'; // the query of "The loader pattern"
128
+ import { RENAME_PATIENT_MUTATION } from './graphql'; // schematic: your document
129
+
130
+ // A mutation run in the browser re-runs the route loaders too.
131
+ export const renamePatient = mutation(RENAME_PATIENT_MUTATION, {
132
+ invalidates: [revalidate],
133
+ });
134
+
135
+ // app/root.tsx: a plain <Form> post settles, then these are invalidated.
136
+ // <RivaRouterProvider invalidateOnAction={[patients, revalidate]}>
137
+
138
+ export async function action({ request, context }: Route.ActionArgs) {
139
+ // ...run the write on the server, then answer with the new row
140
+ return { list: { patients: [{ id: '1', name: 'Ada' }] } };
141
+ }
142
+
143
+ export default function Patients({ params }: Route.ComponentProps) {
144
+ const data = useActionData<typeof action>();
145
+ // The action's answer fills the entry at once, no refetch needed.
146
+ useActionResult(data, {
147
+ into: patients,
148
+ vars: { school: params.school },
149
+ select: (r) => r.list, // the query's data, out of the answer
150
+ });
151
+ const { data: list } = useQuery(patients, { school: params.school });
152
+ return <ul>{list?.patients.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
153
+ }
154
+ ```
155
+
156
+ ## Exports
157
+
158
+ | Export | From | What |
159
+ | --- | --- | --- |
160
+ | `rivaMiddleware(opts?)` | `/server` | Root middleware: creates the client (`create`), awaits `setup`, sets the context, runs the rest of the request in the ambient scope. |
161
+ | `rivaOf(context)` | `.` | The request's client; `RivaScopeError` when the middleware did not run. |
162
+ | `riva(context)` | `.` | `{ '~riva': Snapshot }`, to spread into loader data. |
163
+ | `rivaContext` | `.` | The router context key. |
164
+ | `RivaRouterProvider` | `.` | `client?`, `setup?`, `invalidateOnAction?`, `children`. |
165
+ | `useActionResult` | `.` | Writes an action's result into a query entry. |
166
+ | `revalidate` | `.` | Query that re-runs the route loaders when invalidated. |
167
+ | `dataRoute(opts)` | `/server` | The `/_data` action and loader. |
168
+
169
+ Types: `ContextLike` (what `rivaOf` and `riva` accept, a `context.get`), `RivaRouterProviderProps` from `.`; `RivaMiddlewareOptions`, `MiddlewareArgs`, `DataRouteOptions`, `DataRoute`, `DataSource` and `DataOperation` from `/server`.
170
+
171
+ ## Notes for hosts
172
+
173
+ - The ambient scope is one `AsyncLocalStorage` per process, wired by importing `/server` (`setScopeResolver` is one per process: another resolver replaces it).
174
+ - With `@softistx/alxia-react-router` the same middleware and loaders apply; put `rivaMiddleware` in the root route's `middleware`, beside alxia's own.
175
+ - `Snapshot` keeps its brand through `useLoaderData`, so `data['~riva']` can be handed to `hydrate` by hand.
176
+ - Errors travel as codes: a failed query rehydrates as its class (`instanceof RivaRequestError` holds) with an empty message.
177
+
178
+ More: [guides](https://github.com/softistx/riva/blob/develop/packages/riva-react-router/docs/README.md), [troubleshooting](https://github.com/softistx/riva/blob/develop/packages/riva-react-router/docs/troubleshooting.md), [spec](https://github.com/softistx/riva/blob/develop/docs/spec.md).
@@ -0,0 +1,21 @@
1
+ import type { Query } from '@softistx/riva';
2
+ /**
3
+ * Writes an action's result into a query's entry, once per result: pass
4
+ * `useActionData()` or a fetcher's `data`. The result is the entry's data, or
5
+ * `select` picks it (required when the types differ); a result that selects
6
+ * `undefined` (a validation error, say) writes nothing.
7
+ */
8
+ export declare function useActionResult<R, V, D>(result: R | undefined, opts: {
9
+ /** The query whose entry receives the result. */
10
+ into: Query<V, D>;
11
+ /** The entry's variables. */
12
+ vars: V;
13
+ /** Picks the data out of the result; `undefined` writes nothing. */
14
+ select: (result: NoInfer<R>) => D | undefined;
15
+ }): void;
16
+ export declare function useActionResult<V, D>(result: D | undefined, opts: {
17
+ into: Query<V, D>;
18
+ vars: V;
19
+ select?: undefined;
20
+ }): void;
21
+ //# sourceMappingURL=action-result.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"action-result.d.ts","sourceRoot":"","sources":["../src/action-result.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAI5C;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EACtC,MAAM,EAAE,CAAC,GAAG,SAAS,EACrB,IAAI,EAAE;IACL,iDAAiD;IACjD,IAAI,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAClB,6BAA6B;IAC7B,IAAI,EAAE,CAAC,CAAC;IACR,oEAAoE;IACpE,MAAM,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,SAAS,CAAC;CAC9C,GACC,IAAI,CAAC;AACR,wBAAgB,eAAe,CAAC,CAAC,EAAE,CAAC,EACnC,MAAM,EAAE,CAAC,GAAG,SAAS,EACrB,IAAI,EAAE;IAAE,IAAI,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAAC,IAAI,EAAE,CAAC,CAAC;IAAC,MAAM,CAAC,EAAE,SAAS,CAAA;CAAE,GACtD,IAAI,CAAC"}
@@ -0,0 +1,19 @@
1
+ // src/context.ts
2
+ import { RivaScopeError } from "@softistx/riva";
3
+ import { dehydrate } from "@softistx/riva/ssr";
4
+ import { createContext } from "react-router";
5
+ var rivaContext2 = createContext(null);
6
+ function rivaOf2(context) {
7
+ const client = context.get(rivaContext2);
8
+ if (!client)
9
+ throw new RivaScopeError("No RivaClient in this request: add rivaMiddleware() from @softistx/riva-react-router/server to the root route's middleware.");
10
+ return client;
11
+ }
12
+ function riva2(context) {
13
+ return { "~riva": dehydrate(rivaOf2(context)) };
14
+ }
15
+
16
+ export { rivaContext2, rivaOf2, riva2 };
17
+
18
+ //# debugId=8557F9FA371239D164756E2164756E21
19
+ //# sourceMappingURL=index-xeba9w49.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/context.ts"],
4
+ "sourcesContent": [
5
+ "import { type RivaClient, RivaScopeError } from '@softistx/riva';\nimport { dehydrate, type Snapshot } from '@softistx/riva/ssr';\nimport { createContext, type RouterContextProvider } from 'react-router';\n\n/** What the helpers need of a React Router context: its `get`. */\nexport type ContextLike = Pick<Readonly<RouterContextProvider>, 'get'>;\n\n/** Holds the request's `RivaClient`; `rivaMiddleware` (from `/server`) sets it. */\nexport const rivaContext = createContext<RivaClient | null>(null);\n\n/** The request's `RivaClient`; throws a `RivaScopeError` when `rivaMiddleware` did not run. */\nexport function rivaOf(context: ContextLike): RivaClient {\n\tconst client = context.get(rivaContext);\n\tif (!client)\n\t\tthrow new RivaScopeError(\n\t\t\t\"No RivaClient in this request: add rivaMiddleware() from @softistx/riva-react-router/server to the root route's middleware.\",\n\t\t);\n\treturn client;\n}\n\n/** The loader payload: the request client's settled entries, under the `~riva` key the provider reads. */\nexport function riva(context: ContextLike): { readonly '~riva': Snapshot } {\n\treturn { '~riva': dehydrate(rivaOf(context)) };\n}\n"
6
+ ],
7
+ "mappings": ";AAAA;AACA;AACA;AAMO,IAAM,eAAc,cAAiC,IAAI;AAGzD,SAAS,OAAM,CAAC,SAAkC;AAAA,EACxD,MAAM,SAAS,QAAQ,IAAI,YAAW;AAAA,EACtC,IAAI,CAAC;AAAA,IACJ,MAAM,IAAI,eACT,6HACD;AAAA,EACD,OAAO;AAAA;AAID,SAAS,KAAI,CAAC,SAAsD;AAAA,EAC1E,OAAO,EAAE,SAAS,UAAU,QAAO,OAAO,CAAC,EAAE;AAAA;",
8
+ "debugId": "8557F9FA371239D164756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,14 @@
1
+ import { type RivaClient } from '@softistx/riva';
2
+ import { type Snapshot } from '@softistx/riva/ssr';
3
+ import { type RouterContextProvider } from 'react-router';
4
+ /** What the helpers need of a React Router context: its `get`. */
5
+ export type ContextLike = Pick<Readonly<RouterContextProvider>, 'get'>;
6
+ /** Holds the request's `RivaClient`; `rivaMiddleware` (from `/server`) sets it. */
7
+ export declare const rivaContext: import("react-router").RouterContext<RivaClient | null>;
8
+ /** The request's `RivaClient`; throws a `RivaScopeError` when `rivaMiddleware` did not run. */
9
+ export declare function rivaOf(context: ContextLike): RivaClient;
10
+ /** The loader payload: the request client's settled entries, under the `~riva` key the provider reads. */
11
+ export declare function riva(context: ContextLike): {
12
+ readonly '~riva': Snapshot;
13
+ };
14
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAkB,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAa,KAAK,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAiB,KAAK,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAEzE,kEAAkE;AAClE,MAAM,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,qBAAqB,CAAC,EAAE,KAAK,CAAC,CAAC;AAEvE,mFAAmF;AACnF,eAAO,MAAM,WAAW,yDAAyC,CAAC;AAElE,+FAA+F;AAC/F,wBAAgB,MAAM,CAAC,OAAO,EAAE,WAAW,GAAG,UAAU,CAOvD;AAED,0GAA0G;AAC1G,wBAAgB,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG;IAAE,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAA;CAAE,CAEzE"}
@@ -0,0 +1,5 @@
1
+ export { useActionResult } from './action-result';
2
+ export { type ContextLike, riva, rivaContext, rivaOf } from './context';
3
+ export { RivaRouterProvider, type RivaRouterProviderProps } from './provider';
4
+ export { revalidate } from './revalidate';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,KAAK,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACxE,OAAO,EAAE,kBAAkB,EAAE,KAAK,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,149 @@
1
+ import {
2
+ rivaContext2,
3
+ rivaOf2,
4
+ riva2
5
+ } from "./chunks/index-xeba9w49.js";
6
+
7
+ // src/action-result.ts
8
+ import { useClient } from "@softistx/riva-react";
9
+ import { useEffect, useRef } from "react";
10
+ function useActionResult(result, opts) {
11
+ const client = useClient();
12
+ const last = useRef(undefined);
13
+ const latest = useRef(opts);
14
+ latest.current = opts;
15
+ useEffect(() => {
16
+ if (result === undefined || Object.is(last.current, result))
17
+ return;
18
+ last.current = result;
19
+ const { select, into, vars } = latest.current;
20
+ const data = select ? select(result) : result;
21
+ if (data !== undefined)
22
+ into.setData(client, vars, data);
23
+ }, [result, client]);
24
+ }
25
+ // src/provider.ts
26
+ import {
27
+ createRivaClient
28
+ } from "@softistx/riva";
29
+ import { hydrate } from "@softistx/riva/ssr";
30
+ import { RivaProvider } from "@softistx/riva-react";
31
+ import {
32
+ createElement,
33
+ useEffect as useEffect3,
34
+ useLayoutEffect,
35
+ useRef as useRef3,
36
+ useState
37
+ } from "react";
38
+ import { useMatches, useRevalidator } from "react-router";
39
+
40
+ // src/invalidate-on-action.ts
41
+ import { useEffect as useEffect2, useRef as useRef2 } from "react";
42
+ import { useFetchers, useNavigation } from "react-router";
43
+ var isWrite = (method) => method !== undefined && method.toUpperCase() !== "GET";
44
+ function useInvalidateOnAction(client, list) {
45
+ const navigation = useNavigation();
46
+ const fetchers = useFetchers();
47
+ const running = useRef2(new Set);
48
+ const now = new Set;
49
+ if (navigation.state !== "idle" && isWrite(navigation.formMethod))
50
+ now.add("");
51
+ for (const f of fetchers)
52
+ if (f.state !== "idle" && isWrite(f.formMethod))
53
+ now.add(`~${f.key}`);
54
+ useEffect2(() => {
55
+ const settled = [...running.current].some((k) => !now.has(k));
56
+ running.current = now;
57
+ if (!settled || !list?.length)
58
+ return;
59
+ client.batch(() => {
60
+ for (const t of list)
61
+ if ("query" in t)
62
+ t.query.invalidate(client, t.vars);
63
+ else
64
+ t.invalidate(client);
65
+ });
66
+ });
67
+ }
68
+
69
+ // src/revalidate.ts
70
+ import { query, RivaAbortError, RivaScopeError } from "@softistx/riva";
71
+ var REVALIDATOR = {};
72
+ var revalidate = query({
73
+ id: "~riva/revalidate",
74
+ staleTime: Number.POSITIVE_INFINITY,
75
+ retry: 0,
76
+ fetch: async (_vars, { client, signal }) => {
77
+ await null;
78
+ if (signal.aborted)
79
+ throw new RivaAbortError;
80
+ const run = client.slots.get(REVALIDATOR);
81
+ if (!run)
82
+ throw new RivaScopeError("revalidate is observed by RivaRouterProvider: render it above the component that invalidates it.");
83
+ return run();
84
+ }
85
+ });
86
+
87
+ // src/provider.ts
88
+ var snapshotOf = (data) => data?.["~riva"];
89
+ function RivaRouterProvider({
90
+ client,
91
+ setup,
92
+ invalidateOnAction,
93
+ children
94
+ }) {
95
+ const [own] = useState(() => {
96
+ const c = client ?? createRivaClient();
97
+ setup?.(c, { server: typeof document === "undefined" });
98
+ return c;
99
+ });
100
+ const active = client ?? own;
101
+ const seen = useRef3(new WeakSet);
102
+ const started = useRef3(false);
103
+ const later = useRef3([]);
104
+ const first = !started.current;
105
+ started.current = true;
106
+ for (const m of useMatches()) {
107
+ const snap = snapshotOf(m.loaderData);
108
+ if (!snap || seen.current.has(snap))
109
+ continue;
110
+ seen.current.add(snap);
111
+ const rest = hydrate(active, snap, first ? undefined : { deferObserved: true });
112
+ if (rest)
113
+ later.current.push(rest);
114
+ }
115
+ const router = useRevalidator();
116
+ const run = useRef3(router.revalidate);
117
+ run.current = router.revalidate;
118
+ useEffect3(() => {
119
+ let runs = 0;
120
+ active.slots.set(REVALIDATOR, async () => {
121
+ await run.current();
122
+ runs += 1;
123
+ return runs;
124
+ });
125
+ revalidate.setData(active, undefined, 0);
126
+ const stop = active.subscribe(revalidate, () => {});
127
+ return () => {
128
+ stop();
129
+ active.slots.delete(REVALIDATOR);
130
+ };
131
+ }, [active]);
132
+ useInvalidateOnAction(active, invalidateOnAction);
133
+ useLayoutEffect(() => {
134
+ for (const rest of later.current.splice(0))
135
+ hydrate(active, rest);
136
+ });
137
+ return createElement(RivaProvider, { client: active }, children);
138
+ }
139
+ export {
140
+ RivaRouterProvider,
141
+ revalidate,
142
+ riva2 as riva,
143
+ rivaContext2 as rivaContext,
144
+ rivaOf2 as rivaOf,
145
+ useActionResult
146
+ };
147
+
148
+ //# debugId=2F68185A1FBBDD1064756E2164756E21
149
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/action-result.ts", "../src/provider.ts", "../src/invalidate-on-action.ts", "../src/revalidate.ts"],
4
+ "sourcesContent": [
5
+ "import type { Query } from '@softistx/riva';\nimport { useClient } from '@softistx/riva-react';\nimport { useEffect, useRef } from 'react';\n\n/**\n * Writes an action's result into a query's entry, once per result: pass\n * `useActionData()` or a fetcher's `data`. The result is the entry's data, or\n * `select` picks it (required when the types differ); a result that selects\n * `undefined` (a validation error, say) writes nothing.\n */\nexport function useActionResult<R, V, D>(\n\tresult: R | undefined,\n\topts: {\n\t\t/** The query whose entry receives the result. */\n\t\tinto: Query<V, D>;\n\t\t/** The entry's variables. */\n\t\tvars: V;\n\t\t/** Picks the data out of the result; `undefined` writes nothing. */\n\t\tselect: (result: NoInfer<R>) => D | undefined;\n\t},\n): void;\nexport function useActionResult<V, D>(\n\tresult: D | undefined,\n\topts: { into: Query<V, D>; vars: V; select?: undefined },\n): void;\nexport function useActionResult<R, V, D>(\n\tresult: R | undefined,\n\topts: {\n\t\tinto: Query<V, D>;\n\t\tvars: V;\n\t\tselect?: ((result: R) => D | undefined) | undefined;\n\t},\n): void {\n\tconst client = useClient();\n\tconst last = useRef<unknown>(undefined);\n\tconst latest = useRef(opts);\n\tlatest.current = opts;\n\tuseEffect(() => {\n\t\tif (result === undefined || Object.is(last.current, result)) return;\n\t\tlast.current = result;\n\t\tconst { select, into, vars } = latest.current;\n\t\tconst data = select ? select(result) : (result as unknown as D);\n\t\tif (data !== undefined) into.setData(client, vars, data);\n\t}, [result, client]);\n}\n",
6
+ "import {\n\tcreateRivaClient,\n\ttype Invalidation,\n\ttype RivaClient,\n} from '@softistx/riva';\nimport { hydrate, type Snapshot } from '@softistx/riva/ssr';\nimport { RivaProvider } from '@softistx/riva-react';\nimport {\n\tcreateElement,\n\ttype ReactElement,\n\ttype ReactNode,\n\tuseEffect,\n\tuseLayoutEffect,\n\tuseRef,\n\tuseState,\n} from 'react';\nimport { useMatches, useRevalidator } from 'react-router';\nimport { useInvalidateOnAction } from './invalidate-on-action';\nimport { REVALIDATOR, revalidate } from './revalidate';\n\nexport interface RivaRouterProviderProps {\n\t/**\n\t * The client of this tree. By default one is created per mount. It must stay\n\t * the same object for the lifetime of the mount: the provider reads it once\n\t * and does not follow a new one.\n\t */\n\tclient?: RivaClient;\n\t/**\n\t * Runs on the client of this mount, before any loader snapshot is read\n\t * (e.g. `provideGraphQL`). It must be idempotent: React StrictMode runs the\n\t * initial state twice in development, so it can be called twice.\n\t */\n\tsetup?: (client: RivaClient, env: { server: boolean }) => void;\n\t/** Invalidated each time a non-GET navigation or fetcher settles. */\n\tinvalidateOnAction?: readonly Invalidation[];\n\tchildren?: ReactNode;\n}\n\n/** What a loader's data holds under `~riva`; React Router's serialized types do not keep the `Snapshot` brand. */\nconst snapshotOf = (data: unknown): Snapshot | undefined =>\n\t(data as { '~riva'?: Snapshot } | null | undefined)?.['~riva'];\n\n/**\n * Puts a client in scope and keeps it in step with the loaders: every match's\n * `~riva` snapshot (see `riva(context)`) is hydrated once. The first render\n * seeds the client before its children read it, so the server markup and the\n * browser's first render agree; on a navigation or a revalidation, what\n * observed entries or entities could reach is held back and applied in a\n * layout effect. Place it in the root route component.\n */\nexport function RivaRouterProvider({\n\tclient,\n\tsetup,\n\tinvalidateOnAction,\n\tchildren,\n}: RivaRouterProviderProps): ReactElement {\n\tconst [own] = useState(() => {\n\t\tconst c = client ?? createRivaClient();\n\t\tsetup?.(c, { server: typeof document === 'undefined' });\n\t\treturn c;\n\t});\n\tconst active = client ?? own;\n\tconst seen = useRef(new WeakSet<object>());\n\tconst started = useRef(false);\n\tconst later = useRef<Snapshot[]>([]);\n\tconst first = !started.current;\n\tstarted.current = true;\n\tfor (const m of useMatches()) {\n\t\tconst snap = snapshotOf(m.loaderData);\n\t\tif (!snap || seen.current.has(snap)) continue;\n\t\tseen.current.add(snap);\n\t\tconst rest = hydrate(\n\t\t\tactive,\n\t\t\tsnap,\n\t\t\tfirst ? undefined : { deferObserved: true },\n\t\t);\n\t\tif (rest) later.current.push(rest);\n\t}\n\tconst router = useRevalidator();\n\tconst run = useRef(router.revalidate);\n\trun.current = router.revalidate;\n\tuseEffect(() => {\n\t\tlet runs = 0;\n\t\tactive.slots.set(REVALIDATOR, async () => {\n\t\t\tawait run.current();\n\t\t\truns += 1;\n\t\t\treturn runs;\n\t\t});\n\t\trevalidate.setData(active, undefined, 0);\n\t\tconst stop = active.subscribe(revalidate, () => {});\n\t\treturn () => {\n\t\t\tstop();\n\t\t\tactive.slots.delete(REVALIDATOR);\n\t\t};\n\t}, [active]);\n\tuseInvalidateOnAction(active, invalidateOnAction);\n\tuseLayoutEffect(() => {\n\t\tfor (const rest of later.current.splice(0)) hydrate(active, rest);\n\t});\n\treturn createElement(RivaProvider, { client: active }, children);\n}\n",
7
+ "import type { Invalidation, RivaClient } from '@softistx/riva';\nimport { useEffect, useRef } from 'react';\nimport { useFetchers, useNavigation } from 'react-router';\n\nconst isWrite = (method: string | undefined) =>\n\tmethod !== undefined && method.toUpperCase() !== 'GET';\n\n/**\n * Invalidates `list` each time a write settles: a navigation that submitted a\n * form (non-GET) or a fetcher that did, once it is idle again, loaders\n * included.\n */\nexport function useInvalidateOnAction(\n\tclient: RivaClient,\n\tlist: readonly Invalidation[] | undefined,\n): void {\n\tconst navigation = useNavigation();\n\tconst fetchers = useFetchers();\n\tconst running = useRef(new Set<string>());\n\tconst now = new Set<string>();\n\tif (navigation.state !== 'idle' && isWrite(navigation.formMethod))\n\t\tnow.add('');\n\tfor (const f of fetchers)\n\t\tif (f.state !== 'idle' && isWrite(f.formMethod)) now.add(`~${f.key}`);\n\tuseEffect(() => {\n\t\tconst settled = [...running.current].some((k) => !now.has(k));\n\t\trunning.current = now;\n\t\tif (!settled || !list?.length) return;\n\t\tclient.batch(() => {\n\t\t\tfor (const t of list)\n\t\t\t\tif ('query' in t) t.query.invalidate(client, t.vars);\n\t\t\t\telse t.invalidate(client);\n\t\t});\n\t});\n}\n",
8
+ "import { query, RivaAbortError, RivaScopeError } from '@softistx/riva';\n\n/** Where `RivaRouterProvider` leaves the router's revalidator on its client: it resolves to the count of runs. */\nexport const REVALIDATOR = {};\n\n/**\n * Re-runs the route loaders. `RivaRouterProvider` observes it, so invalidating\n * it (`invalidates: [revalidate]` on a mutation, or `revalidate.invalidate(client)`)\n * calls the router's `revalidate()`; several invalidations in one tick make one\n * run. The data is a count of the runs.\n */\nexport const revalidate = query<void, number>({\n\tid: '~riva/revalidate',\n\tstaleTime: Number.POSITIVE_INFINITY,\n\tretry: 0,\n\tfetch: async (_vars, { client, signal }) => {\n\t\t// An invalidation restarts the fetch and aborts the one before it: let a\n\t\t// burst in one tick settle, so only its last fetch runs the loaders.\n\t\tawait null;\n\t\tif (signal.aborted) throw new RivaAbortError();\n\t\tconst run = client.slots.get(REVALIDATOR) as\n\t\t\t| (() => Promise<number>)\n\t\t\t| undefined;\n\t\tif (!run)\n\t\t\tthrow new RivaScopeError(\n\t\t\t\t'revalidate is observed by RivaRouterProvider: render it above the component that invalidates it.',\n\t\t\t);\n\t\treturn run();\n\t},\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,IACpC,IAAI,CAAC,QAAQ,KAAK,QAAQ,IAAI,IAAI;AAAA,MAAG;AAAA,IACrC,KAAK,QAAQ,IAAI,IAAI;AAAA,IACrB,MAAM,OAAO,QACZ,QACA,MACA,QAAQ,YAAY,EAAE,eAAe,KAAK,CAC3C;AAAA,IACA,IAAI;AAAA,MAAM,MAAM,QAAQ,KAAK,IAAI;AAAA,EAClC;AAAA,EACA,MAAM,SAAS,eAAe;AAAA,EAC9B,MAAM,MAAM,QAAO,OAAO,UAAU;AAAA,EACpC,IAAI,UAAU,OAAO;AAAA,EACrB,WAAU,MAAM;AAAA,IACf,IAAI,OAAO;AAAA,IACX,OAAO,MAAM,IAAI,aAAa,YAAY;AAAA,MACzC,MAAM,IAAI,QAAQ;AAAA,MAClB,QAAQ;AAAA,MACR,OAAO;AAAA,KACP;AAAA,IACD,WAAW,QAAQ,QAAQ,WAAW,CAAC;AAAA,IACvC,MAAM,OAAO,OAAO,UAAU,YAAY,MAAM,EAAE;AAAA,IAClD,OAAO,MAAM;AAAA,MACZ,KAAK;AAAA,MACL,OAAO,MAAM,OAAO,WAAW;AAAA;AAAA,KAE9B,CAAC,MAAM,CAAC;AAAA,EACX,sBAAsB,QAAQ,kBAAkB;AAAA,EAChD,gBAAgB,MAAM;AAAA,IACrB,WAAW,QAAQ,MAAM,QAAQ,OAAO,CAAC;AAAA,MAAG,QAAQ,QAAQ,IAAI;AAAA,GAChE;AAAA,EACD,OAAO,cAAc,cAAc,EAAE,QAAQ,OAAO,GAAG,QAAQ;AAAA;",
11
+ "debugId": "2F68185A1FBBDD1064756E2164756E21",
12
+ "names": []
13
+ }
@@ -0,0 +1,8 @@
1
+ import type { Invalidation, RivaClient } from '@softistx/riva';
2
+ /**
3
+ * Invalidates `list` each time a write settles: a navigation that submitted a
4
+ * form (non-GET) or a fetcher that did, once it is idle again, loaders
5
+ * included.
6
+ */
7
+ export declare function useInvalidateOnAction(client: RivaClient, list: readonly Invalidation[] | undefined): void;
8
+ //# sourceMappingURL=invalidate-on-action.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invalidate-on-action.d.ts","sourceRoot":"","sources":["../src/invalidate-on-action.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAO/D;;;;GAIG;AACH,wBAAgB,qBAAqB,CACpC,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,SAAS,YAAY,EAAE,GAAG,SAAS,GACvC,IAAI,CAmBN"}
@@ -0,0 +1,31 @@
1
+ import { type Invalidation, type RivaClient } from '@softistx/riva';
2
+ import { type ReactElement, type ReactNode } from 'react';
3
+ export interface RivaRouterProviderProps {
4
+ /**
5
+ * The client of this tree. By default one is created per mount. It must stay
6
+ * the same object for the lifetime of the mount: the provider reads it once
7
+ * and does not follow a new one.
8
+ */
9
+ client?: RivaClient;
10
+ /**
11
+ * Runs on the client of this mount, before any loader snapshot is read
12
+ * (e.g. `provideGraphQL`). It must be idempotent: React StrictMode runs the
13
+ * initial state twice in development, so it can be called twice.
14
+ */
15
+ setup?: (client: RivaClient, env: {
16
+ server: boolean;
17
+ }) => void;
18
+ /** Invalidated each time a non-GET navigation or fetcher settles. */
19
+ invalidateOnAction?: readonly Invalidation[];
20
+ children?: ReactNode;
21
+ }
22
+ /**
23
+ * Puts a client in scope and keeps it in step with the loaders: every match's
24
+ * `~riva` snapshot (see `riva(context)`) is hydrated once. The first render
25
+ * seeds the client before its children read it, so the server markup and the
26
+ * browser's first render agree; on a navigation or a revalidation, what
27
+ * observed entries or entities could reach is held back and applied in a
28
+ * layout effect. Place it in the root route component.
29
+ */
30
+ export declare function RivaRouterProvider({ client, setup, invalidateOnAction, children, }: RivaRouterProviderProps): ReactElement;
31
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAEN,KAAK,YAAY,EACjB,KAAK,SAAS,EAKd,MAAM,OAAO,CAAC;AAKf,MAAM,WAAW,uBAAuB;IACvC;;;;OAIG;IACH,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB;;;;OAIG;IACH,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,CAAC;IAC/D,qEAAqE;IACrE,kBAAkB,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;IAC7C,QAAQ,CAAC,EAAE,SAAS,CAAC;CACrB;AAMD;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,EAClC,MAAM,EACN,KAAK,EACL,kBAAkB,EAClB,QAAQ,GACR,EAAE,uBAAuB,GAAG,YAAY,CA6CxC"}
@@ -0,0 +1,10 @@
1
+ /** Where `RivaRouterProvider` leaves the router's revalidator on its client: it resolves to the count of runs. */
2
+ export declare const REVALIDATOR: {};
3
+ /**
4
+ * Re-runs the route loaders. `RivaRouterProvider` observes it, so invalidating
5
+ * it (`invalidates: [revalidate]` on a mutation, or `revalidate.invalidate(client)`)
6
+ * calls the router's `revalidate()`; several invalidations in one tick make one
7
+ * run. The data is a count of the runs.
8
+ */
9
+ export declare const revalidate: import("@softistx/riva").Query<void, number, import("@softistx/riva").QueryState<number>>;
10
+ //# sourceMappingURL=revalidate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"revalidate.d.ts","sourceRoot":"","sources":["../src/revalidate.ts"],"names":[],"mappings":"AAEA,kHAAkH;AAClH,eAAO,MAAM,WAAW,IAAK,CAAC;AAE9B;;;;;GAKG;AACH,eAAO,MAAM,UAAU,2FAkBrB,CAAC"}
@@ -0,0 +1,32 @@
1
+ import { type DataOperation, type DataSource } from '@softistx/riva';
2
+ import type { RouterContextProvider } from 'react-router';
3
+ export type { DataOperation, DataSource };
4
+ /** The codes of the route's own refusals. */
5
+ export type DataRouteCode = 'RIVA_DATA_METHOD' | 'RIVA_DATA_CROSS_SITE' | 'RIVA_DATA_MEDIA_TYPE' | 'RIVA_DATA_TOO_LARGE' | 'RIVA_DATA_BAD_REQUEST' | 'RIVA_DATA_UNKNOWN' | 'RIVA_DATA_INTERNAL';
6
+ export interface DataRouteOptions {
7
+ /** Asked in order; the first that knows the id runs it. */
8
+ sources: readonly DataSource[];
9
+ /** The one origin allowed to call, e.g. behind a proxy. Default: the request's own origin. */
10
+ origin?: string | (() => string | undefined);
11
+ /** The largest body read, in bytes. Default 262144. */
12
+ maxBytes?: number;
13
+ /** Called with what an operation threw that the browser does not see in full: a 500, or a network or HTTP failure of the API (the browser gets a generic message). */
14
+ onError?: (error: unknown, request: Request) => void;
15
+ }
16
+ export interface DataRoute {
17
+ action(args: {
18
+ request: Request;
19
+ context: Readonly<RouterContextProvider>;
20
+ }): Promise<Response>;
21
+ /** A GET (or any loader call) is refused with 405. */
22
+ loader(): Response;
23
+ }
24
+ /**
25
+ * The route behind `bffTransport`: it runs the allowlisted operations the
26
+ * browser names, on the request's client (so with the session `setup` gave
27
+ * it). The id picks an operation from the `sources`; the browser never sends
28
+ * a document. Refusals come back as `{ error: { code, message, status } }` in
29
+ * this order: method, same-site, media type, size, shape, unknown id.
30
+ */
31
+ export declare function dataRoute(opts: DataRouteOptions): DataRoute;
32
+ //# sourceMappingURL=data-route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-route.d.ts","sourceRoot":"","sources":["../../src/server/data-route.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,UAAU,EAIf,MAAM,gBAAgB,CAAC;AAExB,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAG1D,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,CAAC;AAE1C,6CAA6C;AAC7C,MAAM,MAAM,aAAa,GACtB,kBAAkB,GAClB,sBAAsB,GACtB,sBAAsB,GACtB,qBAAqB,GACrB,uBAAuB,GACvB,mBAAmB,GACnB,oBAAoB,CAAC;AAExB,MAAM,WAAW,gBAAgB;IAChC,2DAA2D;IAC3D,OAAO,EAAE,SAAS,UAAU,EAAE,CAAC;IAC/B,8FAA8F;IAC9F,MAAM,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,GAAG,SAAS,CAAC,CAAC;IAC7C,uDAAuD;IACvD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sKAAsK;IACtK,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;CACrD;AAED,MAAM,WAAW,SAAS;IACzB,MAAM,CAAC,IAAI,EAAE;QACZ,OAAO,EAAE,OAAO,CAAC;QACjB,OAAO,EAAE,QAAQ,CAAC,qBAAqB,CAAC,CAAC;KACzC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IACtB,sDAAsD;IACtD,MAAM,IAAI,QAAQ,CAAC;CACnB;AAuHD;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,gBAAgB,GAAG,SAAS,CAgD3D"}
@@ -0,0 +1,20 @@
1
+ import { type RivaClient } from '@softistx/riva';
2
+ import type { MiddlewareFunction, RouterContextProvider } from 'react-router';
3
+ export type MiddlewareArgs = Parameters<MiddlewareFunction>[0];
4
+ export interface RivaMiddlewareOptions {
5
+ /** Makes the request's client. By default `createRivaClient()`. */
6
+ create?: (args: MiddlewareArgs) => RivaClient;
7
+ /** Wires the client before the loaders run: the caller port of the request (e.g. `provideGraphQL`). */
8
+ setup?: (client: RivaClient, args: {
9
+ request: Request;
10
+ context: Readonly<RouterContextProvider>;
11
+ }) => void | Promise<void>;
12
+ }
13
+ /**
14
+ * Root-route middleware: one `RivaClient` per request, in the router context
15
+ * (`rivaOf(context)`) and as the ambient scope of the whole request, so
16
+ * `signal.get()` and `def.ensure` resolve after an `await` in a loader.
17
+ */
18
+ export declare function rivaMiddleware<Result = unknown>(opts?: RivaMiddlewareOptions): MiddlewareFunction<Result>;
19
+ export { type DataOperation, type DataRoute, type DataRouteCode, type DataRouteOptions, type DataSource, dataRoute, } from './data-route';
20
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,KAAK,UAAU,EAEf,MAAM,gBAAgB,CAAC;AAExB,OAAO,KAAK,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAS9E,MAAM,MAAM,cAAc,GAAG,UAAU,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAC;AAE/D,MAAM,WAAW,qBAAqB;IACrC,mEAAmE;IACnE,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,UAAU,CAAC;IAC9C,uGAAuG;IACvG,KAAK,CAAC,EAAE,CACP,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,OAAO,EAAE,QAAQ,CAAC,qBAAqB,CAAC,CAAA;KAAE,KAChE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,MAAM,GAAG,OAAO,EAC9C,IAAI,GAAE,qBAA0B,GAC9B,kBAAkB,CAAC,MAAM,CAAC,CAY5B;AAED,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,UAAU,EACf,SAAS,GACT,MAAM,cAAc,CAAC"}
@@ -0,0 +1,146 @@
1
+ import {
2
+ rivaContext2,
3
+ rivaOf2
4
+ } from "../chunks/index-xeba9w49.js";
5
+
6
+ // src/server/index.ts
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ import {
9
+ createRivaClient,
10
+ RivaScopeError
11
+ } from "@softistx/riva";
12
+ import { setScopeResolver } from "@softistx/riva/ssr";
13
+
14
+ // src/server/data-route.ts
15
+ import {
16
+ RivaHttpError,
17
+ RivaNetworkError,
18
+ RivaRequestError
19
+ } from "@softistx/riva";
20
+ import { decode, encode } from "@softistx/riva/ssr";
21
+ var refusal = (status, code, message, headers) => Response.json({ error: { code, message, status } }, { status, headers: { "cache-control": "no-store", ...headers } });
22
+ var notPost = () => refusal(405, "RIVA_DATA_METHOD", "Use POST.", { allow: "POST" });
23
+ async function readText(request, max) {
24
+ const declared = Number(request.headers.get("content-length"));
25
+ if (declared > max)
26
+ return null;
27
+ const reader = request.body?.getReader();
28
+ if (!reader)
29
+ return "";
30
+ const chunks = [];
31
+ let size = 0;
32
+ for (;; ) {
33
+ const { done, value } = await reader.read();
34
+ if (done)
35
+ break;
36
+ size += value.byteLength;
37
+ if (size > max) {
38
+ await reader.cancel();
39
+ return null;
40
+ }
41
+ chunks.push(value);
42
+ }
43
+ const all = new Uint8Array(size);
44
+ let at = 0;
45
+ for (const c of chunks) {
46
+ all.set(c, at);
47
+ at += c.byteLength;
48
+ }
49
+ return new TextDecoder().decode(all);
50
+ }
51
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
52
+ function crossSite(request, opts) {
53
+ const allowed = (typeof opts.origin === "function" ? opts.origin() : opts.origin) ?? new URL(request.url).origin;
54
+ const origin = request.headers.get("origin");
55
+ const site = request.headers.get("sec-fetch-site");
56
+ return origin !== null && origin !== allowed || site !== null && site !== "same-origin" && site !== "none";
57
+ }
58
+ var badRequest = () => refusal(400, "RIVA_DATA_BAD_REQUEST", 'Send { "id": string, "variables"?: object }.');
59
+ function parseBody(text) {
60
+ let body;
61
+ try {
62
+ body = JSON.parse(text);
63
+ } catch {
64
+ return badRequest();
65
+ }
66
+ if (!isRecord(body) || typeof body["id"] !== "string" || body["variables"] !== undefined && !isRecord(body["variables"]))
67
+ return badRequest();
68
+ try {
69
+ return { id: body["id"], variables: decode(body["variables"]) };
70
+ } catch {
71
+ return badRequest();
72
+ }
73
+ }
74
+ function failure(error, request, opts) {
75
+ const report = () => {
76
+ try {
77
+ opts.onError?.(error, request);
78
+ } catch {}
79
+ };
80
+ if (error instanceof RivaRequestError) {
81
+ const status = error.status !== undefined && error.status >= 400 && error.status <= 599 ? error.status : 502;
82
+ if (error instanceof RivaNetworkError || error instanceof RivaHttpError) {
83
+ report();
84
+ return refusal(status, error.code, "The API is unavailable.");
85
+ }
86
+ return refusal(status, error.code, error.message);
87
+ }
88
+ report();
89
+ return refusal(500, "RIVA_DATA_INTERNAL", "Internal error.");
90
+ }
91
+ function dataRoute(opts) {
92
+ const max = opts.maxBytes ?? 262144;
93
+ return {
94
+ loader: notPost,
95
+ async action({ request, context }) {
96
+ if (request.method !== "POST")
97
+ return notPost();
98
+ if (crossSite(request, opts))
99
+ return refusal(403, "RIVA_DATA_CROSS_SITE", "Cross-site requests are refused.");
100
+ if (!/^application\/json\s*(;|$)/i.test(request.headers.get("content-type") ?? ""))
101
+ return refusal(415, "RIVA_DATA_MEDIA_TYPE", "Send application/json.");
102
+ const text = await readText(request, max);
103
+ if (text === null)
104
+ return refusal(413, "RIVA_DATA_TOO_LARGE", `The body is over ${max} bytes.`);
105
+ const body = parseBody(text);
106
+ if (body instanceof Response)
107
+ return body;
108
+ let op;
109
+ for (const source of opts.sources) {
110
+ op = source.find(body.id);
111
+ if (op)
112
+ break;
113
+ }
114
+ if (!op)
115
+ return refusal(404, "RIVA_DATA_UNKNOWN", "Unknown operation.");
116
+ try {
117
+ const data = await op.run(rivaOf2(context), body.variables, request.signal);
118
+ return Response.json({ data: encode(data) }, { headers: { "cache-control": "no-store" } });
119
+ } catch (error) {
120
+ return failure(error, request, opts);
121
+ }
122
+ }
123
+ };
124
+ }
125
+
126
+ // src/server/index.ts
127
+ var als = new AsyncLocalStorage;
128
+ setScopeResolver(() => als.getStore());
129
+ function rivaMiddleware(opts = {}) {
130
+ return async (args, next) => {
131
+ const { request, context } = args;
132
+ if (context.get(rivaContext2))
133
+ throw new RivaScopeError("rivaMiddleware ran twice in one request: declare it once, on the root route.");
134
+ const client = opts.create?.(args) ?? createRivaClient();
135
+ await opts.setup?.(client, { request, context });
136
+ context.set(rivaContext2, client);
137
+ return als.run(client, next);
138
+ };
139
+ }
140
+ export {
141
+ dataRoute,
142
+ rivaMiddleware
143
+ };
144
+
145
+ //# debugId=75E6AF639ED3E56664756E2164756E21
146
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/server/index.ts", "../src/server/data-route.ts"],
4
+ "sourcesContent": [
5
+ "import { AsyncLocalStorage } from 'node:async_hooks';\nimport {\n\tcreateRivaClient,\n\ttype RivaClient,\n\tRivaScopeError,\n} from '@softistx/riva';\nimport { setScopeResolver } from '@softistx/riva/ssr';\nimport type { MiddlewareFunction, RouterContextProvider } from 'react-router';\nimport { rivaContext } from '../context';\n\n// The one module-level state of this package, by design: the ambient scope\n// of a server request must follow its async work, and `setScopeResolver` is\n// one per process. It holds a request's client only while `next()` runs.\nconst als = new AsyncLocalStorage<RivaClient>();\nsetScopeResolver(() => als.getStore());\n\nexport type MiddlewareArgs = Parameters<MiddlewareFunction>[0];\n\nexport interface RivaMiddlewareOptions {\n\t/** Makes the request's client. By default `createRivaClient()`. */\n\tcreate?: (args: MiddlewareArgs) => RivaClient;\n\t/** Wires the client before the loaders run: the caller port of the request (e.g. `provideGraphQL`). */\n\tsetup?: (\n\t\tclient: RivaClient,\n\t\targs: { request: Request; context: Readonly<RouterContextProvider> },\n\t) => void | Promise<void>;\n}\n\n/**\n * Root-route middleware: one `RivaClient` per request, in the router context\n * (`rivaOf(context)`) and as the ambient scope of the whole request, so\n * `signal.get()` and `def.ensure` resolve after an `await` in a loader.\n */\nexport function rivaMiddleware<Result = unknown>(\n\topts: RivaMiddlewareOptions = {},\n): MiddlewareFunction<Result> {\n\treturn async (args, next) => {\n\t\tconst { request, context } = args;\n\t\tif (context.get(rivaContext))\n\t\t\tthrow new RivaScopeError(\n\t\t\t\t'rivaMiddleware ran twice in one request: declare it once, on the root route.',\n\t\t\t);\n\t\tconst client = opts.create?.(args) ?? createRivaClient();\n\t\tawait opts.setup?.(client, { request, context });\n\t\tcontext.set(rivaContext, client);\n\t\treturn als.run(client, next);\n\t};\n}\n\nexport {\n\ttype DataOperation,\n\ttype DataRoute,\n\ttype DataRouteCode,\n\ttype DataRouteOptions,\n\ttype DataSource,\n\tdataRoute,\n} from './data-route';\n",
6
+ "import {\n\ttype DataOperation,\n\ttype DataSource,\n\tRivaHttpError,\n\tRivaNetworkError,\n\tRivaRequestError,\n} from '@softistx/riva';\nimport { decode, encode } from '@softistx/riva/ssr';\nimport type { RouterContextProvider } from 'react-router';\nimport { rivaOf } from '../context';\n\nexport type { DataOperation, DataSource };\n\n/** The codes of the route's own refusals. */\nexport type DataRouteCode =\n\t| 'RIVA_DATA_METHOD'\n\t| 'RIVA_DATA_CROSS_SITE'\n\t| 'RIVA_DATA_MEDIA_TYPE'\n\t| 'RIVA_DATA_TOO_LARGE'\n\t| 'RIVA_DATA_BAD_REQUEST'\n\t| 'RIVA_DATA_UNKNOWN'\n\t| 'RIVA_DATA_INTERNAL';\n\nexport interface DataRouteOptions {\n\t/** Asked in order; the first that knows the id runs it. */\n\tsources: readonly DataSource[];\n\t/** The one origin allowed to call, e.g. behind a proxy. Default: the request's own origin. */\n\torigin?: string | (() => string | undefined);\n\t/** The largest body read, in bytes. Default 262144. */\n\tmaxBytes?: number;\n\t/** Called with what an operation threw that the browser does not see in full: a 500, or a network or HTTP failure of the API (the browser gets a generic message). */\n\tonError?: (error: unknown, request: Request) => void;\n}\n\nexport interface DataRoute {\n\taction(args: {\n\t\trequest: Request;\n\t\tcontext: Readonly<RouterContextProvider>;\n\t}): Promise<Response>;\n\t/** A GET (or any loader call) is refused with 405. */\n\tloader(): Response;\n}\n\nconst refusal = (\n\tstatus: number,\n\tcode: DataRouteCode | (string & {}),\n\tmessage: string,\n\theaders?: HeadersInit,\n) =>\n\tResponse.json(\n\t\t{ error: { code, message, status } },\n\t\t{ status, headers: { 'cache-control': 'no-store', ...headers } },\n\t);\n\nconst notPost = () =>\n\trefusal(405, 'RIVA_DATA_METHOD', 'Use POST.', { allow: 'POST' });\n\n/** `null` when the body went over `max` bytes. */\nasync function readText(request: Request, max: number): Promise<string | null> {\n\tconst declared = Number(request.headers.get('content-length'));\n\tif (declared > max) return null;\n\tconst reader = request.body?.getReader();\n\tif (!reader) return '';\n\tconst chunks: Uint8Array[] = [];\n\tlet size = 0;\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\tsize += value.byteLength;\n\t\tif (size > max) {\n\t\t\tawait reader.cancel();\n\t\t\treturn null;\n\t\t}\n\t\tchunks.push(value);\n\t}\n\tconst all = new Uint8Array(size);\n\tlet at = 0;\n\tfor (const c of chunks) {\n\t\tall.set(c, at);\n\t\tat += c.byteLength;\n\t}\n\treturn new TextDecoder().decode(all);\n}\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n\ttypeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** True when the request does not come from the allowed origin or site. */\nfunction crossSite(request: Request, opts: DataRouteOptions): boolean {\n\tconst allowed =\n\t\t(typeof opts.origin === 'function' ? opts.origin() : opts.origin) ??\n\t\tnew URL(request.url).origin;\n\tconst origin = request.headers.get('origin');\n\tconst site = request.headers.get('sec-fetch-site');\n\treturn (\n\t\t(origin !== null && origin !== allowed) ||\n\t\t(site !== null && site !== 'same-origin' && site !== 'none')\n\t);\n}\n\nconst badRequest = () =>\n\trefusal(\n\t\t400,\n\t\t'RIVA_DATA_BAD_REQUEST',\n\t\t'Send { \"id\": string, \"variables\"?: object }.',\n\t);\n\n/** The body's id and decoded variables, or the refusal to send. */\nfunction parseBody(\n\ttext: string,\n): { id: string; variables: unknown } | Response {\n\tlet body: unknown;\n\ttry {\n\t\tbody = JSON.parse(text);\n\t} catch {\n\t\treturn badRequest();\n\t}\n\tif (\n\t\t!isRecord(body) ||\n\t\ttypeof body['id'] !== 'string' ||\n\t\t(body['variables'] !== undefined && !isRecord(body['variables']))\n\t)\n\t\treturn badRequest();\n\ttry {\n\t\treturn { id: body['id'], variables: decode(body['variables']) };\n\t} catch {\n\t\treturn badRequest();\n\t}\n}\n\n/** What an operation threw, as the response the browser gets. */\nfunction failure(\n\terror: unknown,\n\trequest: Request,\n\topts: DataRouteOptions,\n): Response {\n\tconst report = () => {\n\t\ttry {\n\t\t\topts.onError?.(error, request);\n\t\t} catch {\n\t\t\t// A failing logger must not turn a 500 into a crash.\n\t\t}\n\t};\n\tif (error instanceof RivaRequestError) {\n\t\tconst status =\n\t\t\terror.status !== undefined && error.status >= 400 && error.status <= 599\n\t\t\t\t? error.status\n\t\t\t\t: 502;\n\t\t// A network or HTTP failure of the API carries its own wording (a URL,\n\t\t// a proxy page): the browser gets the code and a generic message.\n\t\tif (error instanceof RivaNetworkError || error instanceof RivaHttpError) {\n\t\t\treport();\n\t\t\treturn refusal(status, error.code, 'The API is unavailable.');\n\t\t}\n\t\treturn refusal(status, error.code, error.message);\n\t}\n\treport();\n\treturn refusal(500, 'RIVA_DATA_INTERNAL', 'Internal error.');\n}\n\n/**\n * The route behind `bffTransport`: it runs the allowlisted operations the\n * browser names, on the request's client (so with the session `setup` gave\n * it). The id picks an operation from the `sources`; the browser never sends\n * a document. Refusals come back as `{ error: { code, message, status } }` in\n * this order: method, same-site, media type, size, shape, unknown id.\n */\nexport function dataRoute(opts: DataRouteOptions): DataRoute {\n\tconst max = opts.maxBytes ?? 262144;\n\treturn {\n\t\tloader: notPost,\n\t\tasync action({ request, context }) {\n\t\t\tif (request.method !== 'POST') return notPost();\n\t\t\tif (crossSite(request, opts))\n\t\t\t\treturn refusal(\n\t\t\t\t\t403,\n\t\t\t\t\t'RIVA_DATA_CROSS_SITE',\n\t\t\t\t\t'Cross-site requests are refused.',\n\t\t\t\t);\n\t\t\tif (\n\t\t\t\t!/^application\\/json\\s*(;|$)/i.test(\n\t\t\t\t\trequest.headers.get('content-type') ?? '',\n\t\t\t\t)\n\t\t\t)\n\t\t\t\treturn refusal(415, 'RIVA_DATA_MEDIA_TYPE', 'Send application/json.');\n\t\t\tconst text = await readText(request, max);\n\t\t\tif (text === null)\n\t\t\t\treturn refusal(\n\t\t\t\t\t413,\n\t\t\t\t\t'RIVA_DATA_TOO_LARGE',\n\t\t\t\t\t`The body is over ${max} bytes.`,\n\t\t\t\t);\n\t\t\tconst body = parseBody(text);\n\t\t\tif (body instanceof Response) return body;\n\t\t\tlet op: DataOperation | undefined;\n\t\t\tfor (const source of opts.sources) {\n\t\t\t\top = source.find(body.id);\n\t\t\t\tif (op) break;\n\t\t\t}\n\t\t\tif (!op) return refusal(404, 'RIVA_DATA_UNKNOWN', 'Unknown operation.');\n\t\t\ttry {\n\t\t\t\tconst data = await op.run(\n\t\t\t\t\trivaOf(context),\n\t\t\t\t\tbody.variables,\n\t\t\t\t\trequest.signal,\n\t\t\t\t);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{ data: encode(data) },\n\t\t\t\t\t{ headers: { 'cache-control': 'no-store' } },\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn failure(error, request, opts);\n\t\t\t}\n\t\t},\n\t};\n}\n"
7
+ ],
8
+ "mappings": ";;;;;;AAAA;AACA;AAAA;AAAA;AAAA;AAKA;;;ACNA;AAAA;AAAA;AAAA;AAAA;AAOA;AAoCA,IAAM,UAAU,CACf,QACA,MACA,SACA,YAEA,SAAS,KACR,EAAE,OAAO,EAAE,MAAM,SAAS,OAAO,EAAE,GACnC,EAAE,QAAQ,SAAS,EAAE,iBAAiB,eAAe,QAAQ,EAAE,CAChE;AAED,IAAM,UAAU,MACf,QAAQ,KAAK,oBAAoB,aAAa,EAAE,OAAO,OAAO,CAAC;AAGhE,eAAe,QAAQ,CAAC,SAAkB,KAAqC;AAAA,EAC9E,MAAM,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IAAI,QAAQ,IAAI;AAAA;AAAA;",
9
+ "debugId": "75E6AF639ED3E56664756E2164756E21",
10
+ "names": []
11
+ }
package/docs/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # riva-react-router docs
2
+
3
+ The package's [README](../README.md) is the short path. These pages go deeper.
4
+
5
+ ## Guides
6
+
7
+ | Page | Read it when |
8
+ |---|---|
9
+ | [Setup](./guide/setup.md) | You wire the middleware and the provider in the root route. |
10
+ | [The loader pattern](./guide/loader.md) | You fetch in a loader and read in a component, and need to know how hydration works. |
11
+ | [The `/_data` route](./guide/data-route.md) | The browser must run operations through your server (BFF). |
12
+ | [After a write](./guide/after-a-write.md) | An action or a mutation must refresh what is on screen. |
13
+
14
+ ## Also
15
+
16
+ - [Troubleshooting](./troubleshooting.md): every error message and `RIVA_DATA_*` code this package throws, with the fix.
17
+ - [The core guides](../../riva/docs/README.md).
@@ -0,0 +1,68 @@
1
+ # After a write
2
+
3
+ ## What it is for
4
+
5
+ After an action or a mutation, the data on screen must follow. Three tools: write the action's answer into a query, re-run the route loaders, or invalidate on every non-GET settle.
6
+
7
+ ## `useActionResult`
8
+
9
+ `useActionResult(result, { into, vars, select? })` writes an action's result (`useActionData()`, or a fetcher's `data`) into a query's entry, once per result.
10
+
11
+ | Option | Default | Meaning |
12
+ |---|---|---|
13
+ | `into` | required | The query definition whose entry is written. |
14
+ | `vars` | required | The variables of that entry. |
15
+ | `select(result)` | the result itself | Picks the query's data out of the result (required when the types differ). Returning `undefined` (a validation error) writes nothing. |
16
+
17
+ ## `revalidate`
18
+
19
+ `revalidate` is a query: invalidating it re-runs the route loaders through the router's `revalidate()`. Put it in a mutation's `invalidates`, or call `revalidate.invalidate(client)`; invalidations of one tick make one run.
20
+
21
+ ## `invalidateOnAction`
22
+
23
+ `<RivaRouterProvider invalidateOnAction={[patients, revalidate]}>` invalidates that list each time a non-GET navigation or fetcher settles, so a plain `<Form>` keeps the data fresh with no hand-written glue.
24
+
25
+ ## Example
26
+
27
+ ```tsx
28
+ // app/patients.tsx
29
+ import { mutation } from '@softistx/riva-graphql';
30
+ import { useQuery } from '@softistx/riva-react';
31
+ import { revalidate, useActionResult } from '@softistx/riva-react-router';
32
+ import { useActionData } from 'react-router';
33
+ import type { Route } from './+types/patients';
34
+ import { patients } from './patients.queries'; // the query of "The loader pattern"
35
+ import { RENAME_PATIENT_MUTATION } from './graphql'; // schematic: your document
36
+
37
+ // A mutation run in the browser re-runs the route loaders too.
38
+ export const renamePatient = mutation(RENAME_PATIENT_MUTATION, {
39
+ invalidates: [revalidate],
40
+ });
41
+
42
+ // app/root.tsx: a plain <Form> post settles, then these are invalidated.
43
+ // <RivaRouterProvider invalidateOnAction={[patients, revalidate]}>
44
+
45
+ export async function action({ request, context }: Route.ActionArgs) {
46
+ // ...run the write on the server, then answer with the new row
47
+ return { list: { patients: [{ id: '1', name: 'Ada' }] } };
48
+ }
49
+
50
+ export default function Patients({ params }: Route.ComponentProps) {
51
+ const data = useActionData<typeof action>();
52
+ useActionResult(data, {
53
+ into: patients,
54
+ vars: { school: params.school },
55
+ select: (r) => r.list, // the query's data, out of the answer
56
+ });
57
+ const { data: list } = useQuery(patients, { school: params.school });
58
+ return <ul>{list?.patients.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
59
+ }
60
+ ```
61
+
62
+ ## Traps
63
+
64
+ - `revalidate` needs `RivaRouterProvider` above the caller, else it fails with `RIVA_SCOPE`: `revalidate is observed by RivaRouterProvider: render it above the component that invalidates it.`
65
+ - `useActionResult` writes once per result object: a new action answer is a new write.
66
+ - An action that answers a validation error should make `select` return `undefined`, so the entry keeps its last good data.
67
+
68
+ Fixes: [troubleshooting](../troubleshooting.md).
@@ -0,0 +1,63 @@
1
+ # The `/_data` route
2
+
3
+ Entry point: `@softistx/riva-react-router/server`.
4
+
5
+ ## What it is for
6
+
7
+ `dataRoute` lets the browser run allowlisted operations through your server, with the session of the request. Mount it on a route with an action; the browser's `bffTransport` (`@softistx/riva-graphql/bff` or `@softistx/riva-rest/bff`) posts to it.
8
+
9
+ ## GraphQL
10
+
11
+ ```ts
12
+ // app/routes/_data.ts
13
+ import { dataRoute } from '@softistx/riva-react-router/server';
14
+ import { allowlist } from '@softistx/riva-graphql/server';
15
+ import manifest from '../generated/allowlist.json';
16
+
17
+ const route = dataRoute({
18
+ sources: [allowlist(manifest)],
19
+ });
20
+ export const action = route.action;
21
+ export const loader = route.loader; // 405
22
+ ```
23
+
24
+ ## REST, or both
25
+
26
+ ```ts
27
+ import { operations } from '@softistx/riva-rest/server';
28
+
29
+ const route = dataRoute({
30
+ sources: [allowlist(manifest), operations(api)],
31
+ });
32
+ ```
33
+
34
+ ## Options
35
+
36
+ | Option | Default | Meaning |
37
+ |---|---|---|
38
+ | `sources` | required | `DataSource[]`, asked in order: the first that knows the id runs it. |
39
+ | `origin` | the request's own origin | The one allowed origin; set it behind a proxy. |
40
+ | `maxBytes` | `262144` | Largest request body accepted. |
41
+ | `onError(error, request)` | none | What a non-`RivaRequestError` threw, or a network or HTTP failure of the API. The browser only sees a generic answer. |
42
+
43
+ ## Refusals
44
+
45
+ Refusals are `{ error: { code, message, status } }` with `RIVA_DATA_*` codes (the `DataRouteCode` type):
46
+
47
+ | Code | Status | When |
48
+ |---|---|---|
49
+ | `RIVA_DATA_METHOD` | 405 | Not a POST (a GET hits the loader). |
50
+ | `RIVA_DATA_CROSS_SITE` | 403 | The origin is not the allowed one. |
51
+ | `RIVA_DATA_MEDIA_TYPE` | 415 | The body is not JSON. |
52
+ | `RIVA_DATA_TOO_LARGE` | 413 | The body passes `maxBytes`. |
53
+ | `RIVA_DATA_BAD_REQUEST` | 400 | Malformed body, or variables that cannot be decoded. |
54
+ | `RIVA_DATA_UNKNOWN` | 404 | No source knows the id. |
55
+ | `RIVA_DATA_INTERNAL` | 500 | An unexpected failure; see `onError`. |
56
+
57
+ ## Traps
58
+
59
+ - The manifest imports as plain JSON (`import manifest from "./allowlist.json"`): `allowlist` accepts it as is and refuses an unknown `kind` (rerun the codegen).
60
+ - Behind a proxy the request's origin may differ from the browser's: set `origin`.
61
+ - An unknown id is a 404 even for an operation that exists: the id is the persisted id (GraphQL) or `rest:<operationId>` (REST), regenerate the allowlist after changing a document.
62
+
63
+ Fixes: [troubleshooting](../troubleshooting.md).
@@ -0,0 +1,53 @@
1
+ # The loader pattern
2
+
3
+ ## What it is for
4
+
5
+ Define the query once, read it in the loader and in the component. The loader fetches on the server and hands the snapshot to the browser; the component reads the same entry.
6
+
7
+ ## Example
8
+
9
+ ```tsx
10
+ // app/patients.tsx
11
+ import { query } from '@softistx/riva-graphql';
12
+ import { useQuery } from '@softistx/riva-react';
13
+ import { riva, rivaOf } from '@softistx/riva-react-router';
14
+ import { PATIENTS_QUERY } from './graphql'; // schematic: your document
15
+ import type { Route } from './+types/patients';
16
+
17
+ export const patients = query(PATIENTS_QUERY, { staleTime: '30s' });
18
+
19
+ export async function loader({ context, params }: Route.LoaderArgs) {
20
+ await patients.ensure(rivaOf(context), { school: params.school });
21
+ return riva(context);
22
+ }
23
+
24
+ export default function Patients({ params }: Route.ComponentProps) {
25
+ const { data } = useQuery(patients, { school: params.school });
26
+ return <ul>{data?.patients.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
27
+ }
28
+ ```
29
+
30
+ ## The API
31
+
32
+ | Export | What |
33
+ |---|---|
34
+ | `rivaOf(context)` | The request's client; throws `RivaScopeError` when the middleware did not run. |
35
+ | `riva(context)` | `{ '~riva': Snapshot }`, to return from the loader (or spread into its data). |
36
+ | `rivaContext` | The router context key. |
37
+
38
+ `ContextLike` is what `rivaOf` and `riva` accept (anything with `context.get`).
39
+
40
+ ## How hydration works
41
+
42
+ The provider hydrates each match's `~riva` once. The first render is seeded before its children read, so the server markup and the browser's first render agree and fresh data is not fetched again. On a navigation or revalidation, entries something observes (and entries with a cache policy) are applied in a layout effect, never during a render. Named signals that travel (`ssr: true`) are seeded once; a signal the browser already holds, and every local signal, keeps its value.
43
+
44
+ `Snapshot` keeps its brand through `useLoaderData`, so `data['~riva']` can be handed to `hydrate` by hand.
45
+
46
+ ## Traps
47
+
48
+ - `rivaOf` and `riva` are for server loaders and actions only; `clientLoader` is not supported.
49
+ - Every `riva(context)` call dehydrates the whole request client: return it from one loader per request (usually the root's), and let the others only `ensure` their data.
50
+ - Only loaders that return `riva(context)` feed the provider.
51
+ - The ambient scope (`mySignal.get()` resolving to the request's client, also after an `await`) works only inside the `next` that `rivaMiddleware` runs: loaders, actions and the code they call. Outside it (an earlier middleware, a module scope), use `rivaOf(context)`.
52
+ - Errors travel as codes: a failed query rehydrates as its class (`instanceof RivaRequestError` holds) with an empty message.
53
+ - Data that refetches right after hydration: see [troubleshooting](../troubleshooting.md).
@@ -0,0 +1,89 @@
1
+ # Setup
2
+
3
+ ## What it is for
4
+
5
+ One `RivaClient` per request on the server, hydrated in the browser. The middleware creates it, the provider reads it. Built for React Router 8 framework mode (and `@softistx/alxia-react-router`, which hosts the same routes).
6
+
7
+ ## Wire the root
8
+
9
+ `middleware` on a route module needs React Router 8 framework mode. The middleware goes on the root route, the provider in the root component:
10
+
11
+ ```ts
12
+ // app/riva.server.ts: built in a *.server.ts module, so /server stays out of the browser bundle
13
+ import { createGraphQLClient } from '@softistx/graphql-client';
14
+ import { graphqlClientTransport, provideGraphQL } from '@softistx/riva-graphql';
15
+ import { rivaMiddleware } from '@softistx/riva-react-router/server';
16
+
17
+ const API_URL = 'https://api.example.com/graphql'; // schematic: your API
18
+
19
+ export const rivaMw = rivaMiddleware({
20
+ // the caller port of the request: here its session cookie goes to the API
21
+ setup: (client, { request }) =>
22
+ provideGraphQL(
23
+ client,
24
+ graphqlClientTransport(
25
+ createGraphQLClient({
26
+ url: API_URL,
27
+ headers: { cookie: request.headers.get('cookie') ?? '' },
28
+ }),
29
+ ),
30
+ ),
31
+ });
32
+ ```
33
+
34
+ ```tsx
35
+ // app/root.tsx
36
+ import { createGraphQLClient } from '@softistx/graphql-client';
37
+ import { graphqlClientTransport, provideGraphQL } from '@softistx/riva-graphql';
38
+ import { RivaRouterProvider } from '@softistx/riva-react-router';
39
+ import { Outlet } from 'react-router';
40
+ import { rivaMw } from './riva.server';
41
+
42
+ const API_URL = 'https://api.example.com/graphql'; // schematic: your API
43
+
44
+ export const middleware = [rivaMw];
45
+
46
+ export default function Root() {
47
+ return (
48
+ <RivaRouterProvider
49
+ // the client the render and the browser use; the data itself comes from the loaders
50
+ setup={(client) =>
51
+ provideGraphQL(client, graphqlClientTransport(createGraphQLClient({ url: API_URL })))
52
+ }
53
+ >
54
+ <Outlet />
55
+ </RivaRouterProvider>
56
+ );
57
+ }
58
+ ```
59
+
60
+ ## Options
61
+
62
+ `rivaMiddleware(options?)` (from `/server`):
63
+
64
+ | Option | Default | Meaning |
65
+ |---|---|---|
66
+ | `create(args)` | `createRivaClient()` | Makes the request's client. `args` are the middleware's (`request`, `context`, `params`). |
67
+ | `setup(client, { request, context })` | none | Wires the client before the loaders run: the caller port of the request (a transport with the session). May be async. |
68
+
69
+ `<RivaRouterProvider>` props:
70
+
71
+ | Prop | Default | Meaning |
72
+ |---|---|---|
73
+ | `client` | a client made once per mount | The client the render and the browser use. |
74
+ | `setup(client)` | none | Wires it (a browser transport). |
75
+ | `invalidateOnAction` | none | Definitions invalidated each time a non-GET navigation or fetcher settles ([after a write](./after-a-write.md)). |
76
+ | `children` | required | The app. |
77
+
78
+ ## Keep `/server` out of the browser
79
+
80
+ `/server` imports `node:async_hooks`, so it never goes in `app/root.tsx` directly: React Router never bundles a `*.server.ts` module for the browser, and the root imports the middleware from it by path, as above.
81
+
82
+ ## Traps
83
+
84
+ - Declare the middleware once, on the root route: a second run in one request throws `rivaMiddleware ran twice in one request: declare it once, on the root route.`
85
+ - The `client` prop must stay the same object for the lifetime of the mount, and `setup` must be idempotent: React StrictMode runs it twice in development.
86
+ - The ambient scope is one `AsyncLocalStorage` per process, wired by importing `/server` (`setScopeResolver` is one per process: another resolver replaces it).
87
+ - With `@softistx/alxia-react-router`, put `rivaMiddleware` in the root route's `middleware`, beside alxia's own.
88
+
89
+ Fixes: [troubleshooting](../troubleshooting.md).
@@ -0,0 +1,63 @@
1
+ # Troubleshooting
2
+
3
+ Each entry is headed by the message you will see.
4
+
5
+ ## `No RivaClient in this request: add rivaMiddleware() from @softistx/riva-react-router/server to the root route's middleware.`
6
+
7
+ Code: `RIVA_SCOPE` (`RivaScopeError`).
8
+
9
+ **When:** `rivaOf(context)` or `riva(context)` ran in a loader or action of a request where the middleware did not run.
10
+
11
+ **Why:** `rivaOf` and `riva` are for server loaders and actions only (`clientLoader` is not supported), and the request's client is created by the middleware and put in the router context; nothing else makes one.
12
+
13
+ **Fix:** declare it on the root route.
14
+
15
+ ```tsx
16
+ import { rivaMiddleware } from '@softistx/riva-react-router/server';
17
+
18
+ export const middleware = [rivaMiddleware({ setup })];
19
+ ```
20
+
21
+ ## `rivaMiddleware ran twice in one request: declare it once, on the root route.`
22
+
23
+ Code: `RIVA_SCOPE` (`RivaScopeError`).
24
+
25
+ **When:** the middleware is listed on the root route and on a nested route (or twice on one).
26
+
27
+ **Why:** a second run would replace the request's client, and loaders that ran before would have filled another.
28
+
29
+ **Fix:** keep the single declaration on the root route.
30
+
31
+ ## `revalidate is observed by RivaRouterProvider: render it above the component that invalidates it.`
32
+
33
+ Code: `RIVA_SCOPE` (`RivaScopeError`).
34
+
35
+ **When:** `revalidate` was invalidated (a mutation's `invalidates`, `invalidateOnAction`, or `revalidate.invalidate(client)`) on a client no `RivaRouterProvider` renders for.
36
+
37
+ **Why:** the provider leaves the router's `revalidate()` on the client; with no provider there is nothing to call.
38
+
39
+ **Fix:** render `RivaRouterProvider` above the component, with the same `client`.
40
+
41
+ ## `RIVA_DATA_*` refusals from `dataRoute`
42
+
43
+ Codes: `RIVA_DATA_METHOD` (405), `RIVA_DATA_CROSS_SITE` (403), `RIVA_DATA_MEDIA_TYPE` (415), `RIVA_DATA_TOO_LARGE` (413), `RIVA_DATA_BAD_REQUEST` (400, also for variables that cannot be decoded), `RIVA_DATA_UNKNOWN` (404) and `RIVA_DATA_INTERNAL` (500), typed as `DataRouteCode`.
44
+
45
+ **When:** the browser's call to the `/_data` route is refused.
46
+
47
+ **Why and fix:** each code's cause and fix is in the [`riva-graphql` table](https://github.com/softistx/riva/blob/develop/packages/riva-graphql/docs/troubleshooting.md#riva_data_-refusals-from-the-_data-route). A network or HTTP failure of the API reaches the browser with its code and the message "The API is unavailable."; the original error goes to `dataRoute`'s `onError`.
48
+
49
+ For REST operations (`operations(api)` from `@softistx/riva-rest/server`, listed in `sources` beside `allowlist(manifest)`), see [BFF mode](https://github.com/softistx/riva/blob/develop/packages/riva-rest/README.md#bff-mode), the [404 on an operation that exists](https://github.com/softistx/riva/blob/develop/packages/riva-rest/docs/troubleshooting.md#riva_data_unknown-404-on-an-operation-that-exists) and the [non-JSON answer](https://github.com/softistx/riva/blob/develop/packages/riva-rest/docs/troubleshooting.md#the-data-route-answered-n-with-a-body-that-is-not-json).
50
+
51
+ ## Data refetches right after hydration
52
+
53
+ **When:** the browser fetches a query it received from the loader.
54
+
55
+ **Why:** the entry's age travels with the snapshot, so its freshness is the definition's `staleTime` minus that age. With the default `staleTime` of 0 the data is stale the moment it lands.
56
+
57
+ **Fix:** give the definition a `staleTime` that covers the navigation.
58
+
59
+ ```ts
60
+ import { query } from '@softistx/riva-graphql';
61
+
62
+ export const patients = query(PATIENTS_QUERY, { staleTime: '30s' });
63
+ ```
package/package.json CHANGED
@@ -1,6 +1,87 @@
1
1
  {
2
- "name": "@softistx/riva-react-router",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@softistx/riva-react-router",
3
+ "version": "0.1.0",
4
+ "description": "React Router host for riva: one RivaClient per request with an ambient scope, SSR dehydrate and hydrate through loader data, and a merge on each navigation.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "sideEffects": [
10
+ "./dist/server/index.js"
11
+ ],
12
+ "files": [
13
+ "dist",
14
+ "docs",
15
+ "README.md",
16
+ "package.json",
17
+ "LICENSE"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js",
23
+ "default": "./dist/index.js"
24
+ },
25
+ "./server": {
26
+ "types": "./dist/server/index.d.ts",
27
+ "import": "./dist/server/index.js",
28
+ "default": "./dist/server/index.js"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "keywords": [
33
+ "state",
34
+ "signals",
35
+ "cache",
36
+ "graphql",
37
+ "rest",
38
+ "ssr"
39
+ ],
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/softistx/riva.git",
43
+ "directory": "packages/riva-react-router"
44
+ },
45
+ "publishConfig": {
46
+ "registry": "https://registry.npmjs.org/",
47
+ "access": "public"
48
+ },
49
+ "scripts": {
50
+ "build": "bun run ../../build.ts",
51
+ "test": "bun test src",
52
+ "typecheck": "bun check"
53
+ },
54
+ "devDependencies": {
55
+ "@graphql-typed-document-node/core": "^3.2.0",
56
+ "@happy-dom/global-registrator": "^20.0.0",
57
+ "@softistx/riva": "0.1.0",
58
+ "@softistx/riva-graphql": "0.1.0",
59
+ "@softistx/riva-react": "0.1.0",
60
+ "@softistx/riva-rest": "0.1.0",
61
+ "@types/bun": "^1.4.5",
62
+ "@types/react": "^19.0.0",
63
+ "@types/react-dom": "^19.0.0",
64
+ "graphql": "^17.0.0",
65
+ "react": "^19.0.0",
66
+ "react-dom": "^19.0.0",
67
+ "react-router": "^8.5.0"
68
+ },
69
+ "peerDependencies": {
70
+ "@softistx/riva": "^0.1.0",
71
+ "@softistx/riva-react": "^0.1.0",
72
+ "react": "^19.0.0",
73
+ "react-router": "^8.0.0",
74
+ "@softistx/alxia-react-router": "^0.83.1"
75
+ },
76
+ "peerDependenciesMeta": {
77
+ "@softistx/alxia-react-router": {
78
+ "optional": true
79
+ }
80
+ },
81
+ "nxgt": {
82
+ "entrypoints": [
83
+ "src/index.ts",
84
+ "src/server/index.ts"
85
+ ]
86
+ }
87
+ }