@shivaedev/react 0.50.0 → 0.52.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/CHANGELOG.md +29 -0
- package/README.md +137 -79
- package/dist/adapters/permissionBoundary.d.ts.map +1 -1
- package/dist/adapters/permissionBoundary.js +21 -2
- package/dist/adapters/permissionBoundary.js.map +1 -1
- package/dist/adapters/permissionGuard.d.ts +4 -3
- package/dist/adapters/permissionGuard.d.ts.map +1 -1
- package/dist/adapters/permissionGuard.js +3 -4
- package/dist/adapters/permissionGuard.js.map +1 -1
- package/dist/adapters/signInRedirect.d.ts +4 -0
- package/dist/adapters/signInRedirect.d.ts.map +1 -0
- package/dist/adapters/signInRedirect.js +6 -0
- package/dist/adapters/signInRedirect.js.map +1 -0
- package/dist/client/adapters/SessionGeneration.d.ts +3 -1
- package/dist/client/adapters/SessionGeneration.d.ts.map +1 -1
- package/dist/client/adapters/SessionGeneration.js +4 -1
- package/dist/client/adapters/SessionGeneration.js.map +1 -1
- package/dist/{adapters → client/adapters}/queryRoute.d.ts +12 -5
- package/dist/client/adapters/queryRoute.d.ts.map +1 -0
- package/dist/{adapters → client/adapters}/queryRoute.js +14 -1
- package/dist/client/adapters/queryRoute.js.map +1 -0
- package/dist/client/adapters/useWarmQueries.d.ts +4 -0
- package/dist/client/adapters/useWarmQueries.d.ts.map +1 -0
- package/dist/client/adapters/useWarmQueries.js +36 -0
- package/dist/client/adapters/useWarmQueries.js.map +1 -0
- package/dist/client/authSession.d.ts +10 -2
- package/dist/client/authSession.d.ts.map +1 -1
- package/dist/client/authSession.js +32 -3
- package/dist/client/authSession.js.map +1 -1
- package/dist/client/sessionBoundary.d.ts +2 -1
- package/dist/client/sessionBoundary.d.ts.map +1 -1
- package/dist/client/sessionBoundary.js +2 -1
- package/dist/client/sessionBoundary.js.map +1 -1
- package/dist/client/useDebouncedValue.js +1 -1
- package/dist/client/useDebouncedValue.js.map +1 -1
- package/dist/client/useDelay.js +1 -1
- package/dist/client/useDelay.js.map +1 -1
- package/package.json +7 -7
- package/src/adapters/permissionBoundary.ts +23 -2
- package/src/adapters/permissionGuard.ts +6 -5
- package/src/adapters/signInRedirect.ts +7 -0
- package/src/client/adapters/SessionGeneration.ts +6 -0
- package/src/{adapters → client/adapters}/queryRoute.ts +24 -9
- package/src/client/adapters/useWarmQueries.ts +39 -0
- package/src/client/authSession.ts +57 -4
- package/src/client/sessionBoundary.ts +3 -0
- package/src/client/useDebouncedValue.ts +1 -1
- package/src/client/useDelay.ts +1 -1
- package/dist/adapters/queryRoute.d.ts.map +0 -1
- package/dist/adapters/queryRoute.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.52.0 - 2026-11-20
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `authSession(read, { remember: browserSessionMemory })` answers at once with the remembered session, marked as refreshing, and checks the session in the background, so `SessionBoundary` renders and the live socket opens while the check is on the wire. The same user keeps the generation with refreshed permissions, another user starts a new one, a signed-out answer wipes the memory before the signed-out screen renders, a failed check keeps the remembered session rendering, and past the remembered expiry the launch waits for the check. With `remember`, the session's value is `RememberedSession | null`.
|
|
8
|
+
- with `remember`, the session has `signOut(request)`, which wipes the memory as soon as the sign-out request succeeds, so a relaunch starts without a remembered session even when the session check after the sign-out never answers.
|
|
9
|
+
- `SessionBoundary` takes `warm`, a function of the session's client that returns bound query atoms, such as `warm={(client) => [client.water.day.query({ date }), client.notes.list.query()]}`. Each listed query is mounted in the session's registry when the generation commits and stays subscribed until sign-out, another user or unmount, so a screen that reads it later renders its current value in its first render, also after a long idle stretch. The list is read again on every render and compared by atom identity: a changed payload opens the new query and hands the old one to retention. A warm query that no screen reads does not hold back `useFirstSettled`. Each listed query holds one subscription on the host for the whole session. Delete components that only mounted queries to keep them warm and list those queries instead.
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- `PermissionBoundary` runs the router's guards again when the grants of its session change without a navigation, so a screen that needs a removed grant is replaced by the refusal.
|
|
14
|
+
|
|
15
|
+
## 0.51.0 - 2026-11-20
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- the result of `queryRoute(buildQuery)` has `useQuery(options?)`, which reads the route's query with the current match's params, decoded search, context and loader value, so a route's component no longer names the operation and its arguments again. `useLoaded()` returns the same atom as `query` and the loader value as `loaded`, to spread into a loader-backed `useEditor`. Replace `useLoaderQuery(api.get.query({ id }), route.useLoaderData())` in a route's component with `noteQuery.useQuery()`, keeping the `queryRoute` result as `noteQuery`; `useLoaderQuery` stays for loaders written with `loadQuery`.
|
|
20
|
+
- a query route reads `redirects` from the router context, so `redirects.signedOut` and `redirects.refused` are stated once for every query route. A route's own `queryRoute(buildQuery, { redirects })` still overrides them for its query.
|
|
21
|
+
- `signInRedirect(path)` in `adapters/signInRedirect.ts` builds a signed-out redirect to `path` that carries the requested location in `returnTo`.
|
|
22
|
+
|
|
23
|
+
### Changed
|
|
24
|
+
|
|
25
|
+
- from this version, with the `@shivaedev/quality` release of this change, write a `failures` handler inline in the component: `useEditor(api.retitle, { query, fixed: { id }, failures: { SubtitleRejected: (error) => ({ field: "title", message: error.message }) } })`. The 0.50.0 note said to declare a handler such as `onTitle` or `couldNotRemove` outside the component because Biome's `noNestedComponentDefinitions` read it as a component; that is no longer needed, and the README now shows the inline form.
|
|
26
|
+
|
|
27
|
+
### Breaking
|
|
28
|
+
|
|
29
|
+
- `queryRoute` moves to `client/adapters/queryRoute.ts`, beside the client hooks its `useQuery()` uses. Change `@shivaedev/react/adapters/queryRoute.ts` imports to `@shivaedev/react/client/adapters/queryRoute.ts`.
|
|
30
|
+
- `permissionGuard` takes `signedOut`, the redirect callback, in place of the `signIn` path. Before: `permissionGuard({ session, signIn: "/sign-in" })`. After: put `redirects: { signedOut: signInRedirect("/sign-in") }` in the router context and pass it to the guard: `beforeLoad: ({ context, ...route }) => permissionGuard({ session, signedOut: context.redirects.signedOut })(route)`.
|
|
31
|
+
|
|
3
32
|
## 0.50.0 - 2026-11-20
|
|
4
33
|
|
|
5
34
|
### Added
|
package/README.md
CHANGED
|
@@ -26,7 +26,7 @@ An **editor** joins a query atom, a form field schema and a save Effect. The que
|
|
|
26
26
|
|
|
27
27
|
Use `useConnectionStatus(client)` from `@shivaedev/react/client/adapters/useConnectionStatus.ts` with the client returned by contract's `makeClient`. It returns one `"live" | "reconnecting" | "waiting-for-connection"` value across mounted queries from every binding on that client's `Client` service. Live subscription status changes debounce for 300 ms on the client runtime's Clock. A bound command held for reconnection reports `"waiting-for-connection"` immediately, so the application can show Reconnecting while keeping the action pending. Contract holds unsent commands for up to 10 seconds and returns a typed `RpcClientError` on timeout; commands already sent are never replayed. The default socket probes Ping/Pong on browser or native resume and reconnects after 2.5 seconds without a Pong. A query refusal is separate from connectivity. Visible browser `online` and `visibilitychange` signals interrupt the live retry delay and reconnect immediately with a fresh backoff schedule.
|
|
28
28
|
|
|
29
|
-
Use `useFirstSettled(client)` from `@shivaedev/react/client/adapters/useFirstSettled.ts` with the same client to reveal a session's first screen in one step instead of one loading state per query. It returns `false` until a query mounted on that client has delivered its first success or failure and, with that, no mounted query awaits a first result and no command is in flight. From then on it returns `true` for that client: a later command or a newly mounted query does not turn it back. The signal belongs to the client, so a new session generation whose `connect` makes a new client starts at `false` again. A client whose screen mounts no query stays at `false`; gate only screens that read through the client.
|
|
29
|
+
Use `useFirstSettled(client)` from `@shivaedev/react/client/adapters/useFirstSettled.ts` with the same client to reveal a session's first screen in one step instead of one loading state per query. It returns `false` until a query mounted on that client has delivered its first success or failure and, with that, no mounted query awaits a first result and no command is in flight. From then on it returns `true` for that client: a later command or a newly mounted query does not turn it back. The signal belongs to the client, so a new session generation whose `connect` makes a new client starts at `false` again. A client whose screen mounts no query stays at `false`; gate only screens that read through the client. A query that only the session's [warm list](#keep-queries-warm-for-the-session) mounts does not hold it back while it awaits its first result.
|
|
30
30
|
|
|
31
31
|
A **session generation** is the string returned by `identify(session)`. `SessionBoundary` owns its client, registry and React subtree. Your auth owner supplies the session and decides when to replace or end it. The boundary automatically mounts live connections on bound contract APIs returned by `connect`, directly or as client properties such as `api`. Use a Platform database host and the default shared WebSocket client; the application needs no subscribe handler or `live()` call. The process holding the socket reloads the session and runs the read policy and handler for each subscriber independently. It stores one encoded-result hash per subscribed query in memory and pushes changed values; equal reads acknowledge completion without replacing the screen. Each subscription has at most one rerun in flight and one pending, merging further changes while busy. Other subscriptions run independently in parallel. Backlog overflow triggers a server `Resync`: the server reruns queries itself, and the client sends no follow-up reads. Query results stay in their native registry; RPC declarations and transport stay with native Effect and the application; this package supplies their React state and lifecycle boundary.
|
|
32
32
|
|
|
@@ -88,6 +88,27 @@ Pass the signed-out router as `signedOut` and the requested continuation address
|
|
|
88
88
|
|
|
89
89
|
A query that fails with an `Unauthorized` from `@shivaedev/errors/taxonomy.ts` asks `recheck` to run and keeps its retained data. An action does the same once per failed result, retaining its last successful `data` and the typed failure in `cause`; rerendering that result does not repeat the recheck. A live reconnect requests a check only for a typed `Unauthorized` authentication refusal; dropped sockets and unreachable servers leave the session alone. Pass the auth owner’s session-refresh Effect as `recheck` (for example, `recheck={auth.session.refresh}`). The boundary shares an in-flight check, retries failures after 1, 2, 4 seconds and so on up to 30 seconds, and retries immediately on visible `online` or `visibilitychange` events while a check is pending, restarting an in-flight check too. Session replacement and unmount cancel retries. Supply `runtime` on `SessionBoundary` to run these retries on a native atom runtime, including one carrying a story’s controlled Clock. Existing void callbacks remain supported; they keep their own check and retry policy. Keep retained session data on screen when a refresh exposes a failure, and pass `session={undefined}` only after a definite signed-out answer. The auth owner decides whether the session ends. The boundary also handles React StrictMode's effect replay and preserves component state across hiding and revealing an `<Activity>` subtree, supplying a live registry when revealed.
|
|
90
90
|
|
|
91
|
+
#### Keep queries warm for the session
|
|
92
|
+
|
|
93
|
+
A screen's first visit, and a return after retention let its result go, wait one subscription round trip. Name the queries whose screens should open with current data in `SessionBoundary`'s `warm`, a function of the session's client that returns bound query atoms:
|
|
94
|
+
|
|
95
|
+
```tsx
|
|
96
|
+
<SessionBoundary
|
|
97
|
+
session={session}
|
|
98
|
+
identify={(current) => current.user.id}
|
|
99
|
+
connect={connect}
|
|
100
|
+
recheck={recheck}
|
|
101
|
+
warm={(client) => [client.water.day.query({ date }), client.notes.list.query()]}
|
|
102
|
+
signedOut={<SignIn />}
|
|
103
|
+
>
|
|
104
|
+
{(client) => <Screens client={client} />}
|
|
105
|
+
</SessionBoundary>;
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`connect`, `date`, `SignIn` and `Screens` belong to the application; `date` is its own value, for example derived from `useNow`. The boundary mounts each listed query in the session's registry when the generation commits and keeps it subscribed until the session ends: sign-out, another user or unmount. The host pushes its changes, so a screen that reads it later renders the current value in its first render, with no request of its own. The list is read again on every render and compared by atom identity, and bound query atoms are cached per payload: when `date` changes, the new day's query opens and the previous one is handed to retention like a screen that closed. A warm query that no screen reads does not hold back `useFirstSettled`.
|
|
109
|
+
|
|
110
|
+
Each warm query holds one subscription on the host for the whole session, with its stored result hash and a rerun on each matching change, whether a screen shows it or not. The list must name the payload the screen reads: a query whose payload no screen asks for subscribes for nothing, and that screen stays cold.
|
|
111
|
+
|
|
91
112
|
#### Session-scoped bindings
|
|
92
113
|
|
|
93
114
|
A contract declared with `keyScope: "session"` binds to the registry that owns the session's queries. In the browser, `bind` prefixes every client read and invalidation key of that contract with an opaque id of its registry, so a successful command in one session refreshes none of another session's queries on the page, even when both registries share one runtime. The server adds no prefix: its subscriptions and committed writes use plain keys, and each query's read policy decides what a viewer receives. The [contract guide](https://github.com/ShivaeDev/platform/blob/main/packages/contract/README.md#session-owned-keys) describes the declaration and its handlers. `SessionBoundary` passes that registry to `connect` as its second argument:
|
|
@@ -273,23 +294,16 @@ The hook owns retained display data and the native atom owns execution and cachi
|
|
|
273
294
|
|
|
274
295
|
For both queries and actions, a successful `undefined` is `Option.some(undefined)` in `data`, with `pending` and `refreshing` false. A defect or interruption is available as `Option.some(cause)` in `cause`; they do not request a session recheck, even when the defect has an `Unauthorized` tag.
|
|
275
296
|
|
|
276
|
-
The example's action returns a value; it does not persist the report or invalidate its query. In an application,
|
|
297
|
+
The example's action returns a value; it does not persist the report or invalidate its query. In an application, pass the bound query and command of a module's generated contract instead:
|
|
277
298
|
|
|
278
299
|
```ts
|
|
279
|
-
const notes = useQuery(
|
|
280
|
-
|
|
281
|
-
reactivityKeys: ["notes"],
|
|
282
|
-
}),
|
|
283
|
-
);
|
|
284
|
-
const create = useAction(NotesClient.mutation("CreateNote"));
|
|
300
|
+
const notes = useQuery(api.list.query());
|
|
301
|
+
const add = useAction(api.add);
|
|
285
302
|
|
|
286
|
-
|
|
287
|
-
payload: { title: "Morning walk" },
|
|
288
|
-
reactivityKeys: ["notes"],
|
|
289
|
-
});
|
|
303
|
+
add.dispatch({ title: "Morning walk" });
|
|
290
304
|
```
|
|
291
305
|
|
|
292
|
-
`
|
|
306
|
+
`api` comes from `makeClient` over the module's generated contract, as the [contract guide](https://github.com/ShivaeDev/platform/blob/main/packages/contract/README.md#the-wire-and-the-browsers-contract) describes, with a `list` query and an `add` command that takes `{ title }`. The command's success refreshes the queries that read its keys.
|
|
293
307
|
|
|
294
308
|
An action's `dispatch(input)` returns `void`. Read the atom's latest result from `data`, `cause` or `result`. With the default `Atom.fn` action, a later dispatch interrupts the earlier work and the shared state reports the later result.
|
|
295
309
|
|
|
@@ -456,17 +470,17 @@ A bound command given to `useAction`, `usePendingCommand` or `useUndoableChange`
|
|
|
456
470
|
`failureKind` from `@shivaedev/contract/failureKind.ts` holds that classification, `AppRejection<E>` names the app's own rejections in an error type, and `RequestRejection` and `ServerFailure` in `@shivaedev/errors/taxonomy.ts` name the shared ones.
|
|
457
471
|
|
|
458
472
|
```tsx
|
|
459
|
-
function onTitle(error: SubtitleRejected) {
|
|
460
|
-
return { field: "title" as const, message: error.message };
|
|
461
|
-
}
|
|
462
|
-
|
|
463
473
|
function Retitle({ id }: { readonly id: number }) {
|
|
464
|
-
const editor = useEditor(api.retitle, {
|
|
474
|
+
const editor = useEditor(api.retitle, {
|
|
475
|
+
query: api.get.query({ id }),
|
|
476
|
+
fixed: { id },
|
|
477
|
+
failures: { SubtitleRejected: (error) => ({ field: "title", message: error.message }) },
|
|
478
|
+
});
|
|
465
479
|
return <TitleForm form={editor.form} save={editor.save} />;
|
|
466
480
|
}
|
|
467
481
|
```
|
|
468
482
|
|
|
469
|
-
Here `api.retitle` takes `{ id, title }` and can fail with the app's tagged `SubtitleRejected`, which refers to the server's `subtitle` while the form calls the input `title`; `api`, `SubtitleRejected` and `TitleForm` belong to the application.
|
|
483
|
+
Here `api.retitle` takes `{ id, title }` and can fail with the app's tagged `SubtitleRejected`, which refers to the server's `subtitle` while the form calls the input `title`; `api`, `SubtitleRejected` and `TitleForm` belong to the application. A handler is keyed by the failure's tag and receives the error and the invocation's input, which for a form is its decoded values. It returns a notice descriptor, a field rejection `{ field, message }` naming one of the form's fields (form hooks only), or `"silent"`. In place of a function, `"message"` shows the error's own message as a notice and `"silent"` shows nothing for that tag. A handler may also be given for a shared rejection to word it differently for that call. `silent: true` shows nothing for any failure of the call, which differs from leaving `failures` out: that uses the defaults. The typed failure stays in the hook's `failure` and `cause` in every case.
|
|
470
484
|
|
|
471
485
|
A missing handler is a compile error that names the tag. `useAction(api.retitle)` with no options reports `Property '"failures.SubtitleRejected"' is missing`, followed by `the operation can fail with SubtitleRejected, a rejection the app declared: say what it shows, for example failures: { SubtitleRejected: "message" }`. Options without `failures` report `Property 'failures' is missing` for a type `HandleAppRejections<"SubtitleRejected", …>`, `failures: {}` reports `Property 'SubtitleRejected' is missing`, and a key that is not a failure of the operation is an unknown property. A form's rejection whose `field` can only name a field the form lacks counts as the app's own and needs a handler.
|
|
472
486
|
|
|
@@ -643,7 +657,7 @@ With native `RpcClient.layerProtocolHttp` and `FetchHttpClient.layer` as the bro
|
|
|
643
657
|
|
|
644
658
|
#### Route loaders with TanStack Router
|
|
645
659
|
|
|
646
|
-
TanStack Router owns routes, navigation, search validation, loader data and screen components.
|
|
660
|
+
TanStack Router owns routes, navigation, search validation, loader data and screen components. Declare a route's query once with `queryRoute(buildQuery)` from `@shivaedev/react/client/adapters/queryRoute.ts`, spread the result into `createRoute`, and call its `useQuery()` in the route's component. The spread derives loader dependencies from validated search and loads the contract query atom in the router context’s registry; `useQuery()` reads the same atom, so the component names neither the operation nor its arguments. A `NotFound` instance from `@shivaedev/errors/taxonomy.ts` or a `QueryReadDenied` refusal enters TanStack's not-found handling with the original rejection in the not-found component's `data` prop, preserving its message. One root `notFoundComponent` can show that message for all query routes; a route's own `notFoundComponent` takes precedence. Other typed failures reach `errorComponent` unchanged. The atom runs through its native RPC runtime and shares its execution with React. The factory receives `{ context, params, search }`: `context` is the loader’s router context, including parent `beforeLoad` contributions. Annotate it with `typeof root.types.allContext` (or the parent route’s `types.allContext`) to keep client and viewer access checked against the route’s declaration.
|
|
647
661
|
|
|
648
662
|
This example assumes an application-owned `api.get.query({ id, page })` returning `{ id, title }`, with declared `NotFound` and `NoteMissing` rejections:
|
|
649
663
|
|
|
@@ -655,8 +669,7 @@ import { Effect, Option, Predicate, Schema } from "effect";
|
|
|
655
669
|
import type { ReactNode } from "react";
|
|
656
670
|
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
657
671
|
import { NotFound } from "@shivaedev/errors/taxonomy.ts";
|
|
658
|
-
import { queryRoute } from "@shivaedev/react/adapters/queryRoute.ts";
|
|
659
|
-
import { useLoaderQuery } from "@shivaedev/react/client/useLoaderQuery.ts";
|
|
672
|
+
import { queryRoute } from "@shivaedev/react/client/adapters/queryRoute.ts";
|
|
660
673
|
import { api } from "./notes-client.ts";
|
|
661
674
|
|
|
662
675
|
const registry = AtomRegistry.make();
|
|
@@ -704,7 +717,7 @@ function Shell({ children }: { readonly children: ReactNode }) {
|
|
|
704
717
|
);
|
|
705
718
|
}
|
|
706
719
|
function Note() {
|
|
707
|
-
const query =
|
|
720
|
+
const query = noteQuery.useQuery();
|
|
708
721
|
return <h1>{query.data.title}</h1>;
|
|
709
722
|
}
|
|
710
723
|
function Failure({ error }: ErrorComponentProps) {
|
|
@@ -736,28 +749,40 @@ export function App() {
|
|
|
736
749
|
|
|
737
750
|
Keep the result of `queryRoute` to call its `useRetry()` hook inside that route's error component. The returned callback refreshes the query using the current match's params, decoded search dependencies and context, then invalidates that match. A successful retry renders the route again without replacing the surrounding shell or its draft inputs.
|
|
738
751
|
|
|
739
|
-
|
|
752
|
+
State where a signed-out visitor goes once, as `redirects.signedOut` in the router's context. A query route whose query fails with the shared `Unauthorized` rejection redirects there, and `permissionGuard` takes the same callback. `signInRedirect(path)` from `@shivaedev/react/adapters/signInRedirect.ts` builds it: a TanStack redirect to `path` that carries the requested path, search and fragment in sign-in's `returnTo` search field. `redirects.refused` handles `Forbidden` and `QueryReadDenied` the same way, with a callback that returns TanStack's `redirect`. A route overrides either target for its own query with `queryRoute(buildQuery, { redirects })`, as `memberNote` does here:
|
|
740
753
|
|
|
741
754
|
```ts
|
|
742
|
-
import {
|
|
743
|
-
import
|
|
744
|
-
import {
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
755
|
+
import { createRootRouteWithContext, createRoute, createRouter } from "@tanstack/react-router";
|
|
756
|
+
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
757
|
+
import type { QueryRouteRedirects } from "@shivaedev/react/adapters/queryRouteFailure.ts";
|
|
758
|
+
import { signInRedirect } from "@shivaedev/react/adapters/signInRedirect.ts";
|
|
759
|
+
import { queryRoute } from "@shivaedev/react/client/adapters/queryRoute.ts";
|
|
760
|
+
import { api } from "./notes-client.ts";
|
|
761
|
+
|
|
762
|
+
const registry = AtomRegistry.make();
|
|
763
|
+
const root = createRootRouteWithContext<{ registry: AtomRegistry.AtomRegistry; api: typeof api; redirects: QueryRouteRedirects }>()();
|
|
764
|
+
const memberNote = createRoute({
|
|
765
|
+
getParentRoute: () => root,
|
|
766
|
+
path: "/members/$id",
|
|
767
|
+
...queryRoute(
|
|
768
|
+
({ context, params }: { context: typeof root.types.allContext; params: { id: string }; search: object }) =>
|
|
769
|
+
context.api.get.query({ id: params.id, page: 1 }),
|
|
770
|
+
{ redirects: { signedOut: signInRedirect("/members/sign-in") } },
|
|
771
|
+
),
|
|
772
|
+
});
|
|
773
|
+
const router = createRouter({
|
|
774
|
+
context: { registry, api, redirects: { signedOut: signInRedirect("/sign-in") } },
|
|
775
|
+
routeTree: root.addChildren([memberNote]),
|
|
751
776
|
});
|
|
752
777
|
```
|
|
753
778
|
|
|
754
|
-
Without
|
|
779
|
+
Without a callback at either level, failures keep their normal error or not-found handling. `NotFound` continues to use the not-found screen even when refusal redirects are configured.
|
|
755
780
|
|
|
756
781
|
For a loader that coordinates more work, use `loadQuery(registry, atom, loaderContext)` from `@shivaedev/react/adapters/loadQuery.ts` directly. It reads the atom in the supplied registry and throws typed failures unchanged, including `NotFound`; the loader decides how to handle them.
|
|
757
782
|
|
|
758
783
|
`defaultPendingMs: Infinity` keeps the current route's data visible during navigation; the shell reads TanStack's `isLoading` to display pending state. The new route commits when its loader settles. This is TanStack's pending policy, separate from `useQuery`'s retained display. The loader hands its query over to the route's component: the first render has the loaded value, and the query handler runs once, for a live subscription and for a `live: false` query alike, even when the route mounts after the registry’s idle window.
|
|
759
784
|
|
|
760
|
-
`
|
|
785
|
+
`useQuery()` reads the current match's params, decoded search, context and loader value, and exposes `data` as the query's success type, with no `Option` or Initial result. It takes the options of `useQuery` from `@shivaedev/react/client/resultState.ts`. Call it inside the route's component or a component it renders. Refetches keep the last value visible. `useQuery`, a route's `useQuery()` and a loader-backed editor’s `query` expose `denied: true` for `QueryReadDenied`, alongside the typed `cause`. Use this state to replace retained content with the application’s not-found screen after access is revoked. Refused live queries stay refused through change notifications until their input or viewer changes. For a loader-backed editor, spread the route's `useLoaded()`, which returns its atom as `query` and the loader value as `loaded`: `useEditor(api.save, { ...noteQuery.useLoaded(), fixed: { id } })`. Its form is defined on the first render and `editor.query.data` is the row directly. A loader written with `loadQuery` reads its atom with `useLoaderQuery(atom, route.useLoaderData())` from `@shivaedev/react/client/useLoaderQuery.ts`, which `useQuery()` uses underneath.
|
|
761
786
|
|
|
762
787
|
`loadQuery` mounts its query while the loader runs and, once it succeeds, for a five-second hand-over window measured on the bound query's atom runtime `Clock`. A component that mounts within the window continues the loader's subscription and its first result instead of opening another. A route that is left or never mounts releases the query when the window passes; from then on the bound query uses the same retention policy as component reads, including its expiry, capacity and session ownership. A route that mounts after the window shows that kept value while a new subscription revalidates it. A returning route whose bound query still has a kept result renders it immediately as stale. Readers without data suspend until their active loader completes. Failed loaders also release execution; the route keeps its error visible and Retry starts a new load. Already mounted readers keep their data during refreshes.
|
|
763
788
|
|
|
@@ -767,9 +792,9 @@ For a loader that coordinates more work, use `loadQuery(registry, atom, loaderCo
|
|
|
767
792
|
|
|
768
793
|
Permissions come from the session payload's `user.permissions`, populated by `@shivaedev/access` through the server's role policy. `can(session, permission)` uses access's grant evaluator without making a request: names match exactly, and an `any` grant covers an `own` check for that name. An `own` grant does not cover an `any` check. `useCan()` supplies the same check from the nearest `PermissionBoundary` for component controls. A signed-out session has no grants. These checks control visibility; the server still authorizes every request.
|
|
769
794
|
|
|
770
|
-
Declare a route's requirement in TanStack's native `staticData`: `signedIn: true` admits any signed-in viewer, and `permission` requires a specific grant. Routes that declare neither stay public. Install `permissionGuard` once as the root route's `beforeLoad`; it checks all matched routes before their loaders run, including requirements on parents. Signed-out visitors go to the
|
|
795
|
+
Declare a route's requirement in TanStack's native `staticData`: `signedIn: true` admits any signed-in viewer, and `permission` requires a specific grant. Routes that declare neither stay public. Install `permissionGuard` once as the root route's `beforeLoad`; it checks all matched routes before their loaders run, including requirements on parents. Signed-out visitors go to the guard's `signedOut` redirect; pass it the router's `redirects.signedOut` so the guard and query routes share one target. A signed-in session without a required grant throws the shared `Forbidden` failure. A signed-in-only parent does not bypass a child's permission requirement.
|
|
771
796
|
|
|
772
|
-
Set `permissionGuard({ session,
|
|
797
|
+
Set `permissionGuard({ session, signedOut, hidden: true })` to hide refused routes from signed-in members. The guard throws TanStack's native not-found result, renders the app's `notFoundComponent` at the requested URL and prevents the route's loader from running. Signed-out visitors still go to sign-in with their return location; sessions with the required grant still enter the route.
|
|
773
798
|
|
|
774
799
|
```tsx
|
|
775
800
|
import { RegistryContext } from "@effect/atom-react";
|
|
@@ -779,17 +804,23 @@ import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
|
779
804
|
import { permission } from "@shivaedev/access/permission.ts";
|
|
780
805
|
import { Forbidden } from "@shivaedev/react/adapters/Forbidden.ts";
|
|
781
806
|
import { PermissionBoundary, PermissionBoundaryError, useCan } from "@shivaedev/react/adapters/permissionBoundary.ts";
|
|
782
|
-
import { useLoaderQuery } from "@shivaedev/react/client/useLoaderQuery.ts";
|
|
783
807
|
import { permissionGuard } from "@shivaedev/react/adapters/permissionGuard.ts";
|
|
808
|
+
import type { QueryRouteRedirects } from "@shivaedev/react/adapters/queryRouteFailure.ts";
|
|
809
|
+
import { signInRedirect } from "@shivaedev/react/adapters/signInRedirect.ts";
|
|
784
810
|
import type { PermissionSession } from "@shivaedev/identity/PermissionSession.ts";
|
|
785
811
|
import { can } from "@shivaedev/react/can.ts";
|
|
786
|
-
import { queryRoute } from "@shivaedev/react/adapters/queryRoute.ts";
|
|
812
|
+
import { queryRoute } from "@shivaedev/react/client/adapters/queryRoute.ts";
|
|
787
813
|
import { api, registry } from "./notes-client.ts";
|
|
788
814
|
import { auth, SignIn } from "./auth.tsx";
|
|
789
815
|
|
|
790
816
|
const ReadNotes = permission("notes.read");
|
|
791
|
-
const root = createRootRouteWithContext<{
|
|
792
|
-
|
|
817
|
+
const root = createRootRouteWithContext<{
|
|
818
|
+
registry: AtomRegistry.AtomRegistry;
|
|
819
|
+
api: typeof api;
|
|
820
|
+
redirects: Required<Pick<QueryRouteRedirects, "signedOut">>;
|
|
821
|
+
session: PermissionSession | undefined;
|
|
822
|
+
}>()({
|
|
823
|
+
beforeLoad: ({ context, ...route }) => permissionGuard({ session: () => context.session, signedOut: context.redirects.signedOut })(route),
|
|
793
824
|
});
|
|
794
825
|
const profile = createRoute({
|
|
795
826
|
getParentRoute: () => root,
|
|
@@ -797,15 +828,17 @@ const profile = createRoute({
|
|
|
797
828
|
staticData: { signedIn: true },
|
|
798
829
|
component: () => <h1>Profile</h1>,
|
|
799
830
|
});
|
|
831
|
+
const noteQuery = queryRoute(
|
|
832
|
+
({ context, params }: { context: typeof root.types.allContext; params: { id: string }; search: Record<string, never> }) =>
|
|
833
|
+
context.api.get.query({ id: params.id, page: 1 }),
|
|
834
|
+
);
|
|
800
835
|
const note = createRoute({
|
|
801
836
|
getParentRoute: () => root,
|
|
802
837
|
path: "/notes/$id",
|
|
803
838
|
staticData: { permission: ReadNotes },
|
|
804
|
-
...
|
|
805
|
-
context.api.get.query({ id: params.id, page: 1 }),
|
|
806
|
-
),
|
|
839
|
+
...noteQuery,
|
|
807
840
|
component: () => {
|
|
808
|
-
const query =
|
|
841
|
+
const query = noteQuery.useQuery();
|
|
809
842
|
return <h1>{query.data.title}</h1>;
|
|
810
843
|
},
|
|
811
844
|
});
|
|
@@ -821,7 +854,7 @@ const login = createRoute({
|
|
|
821
854
|
},
|
|
822
855
|
});
|
|
823
856
|
const router = createRouter({
|
|
824
|
-
context: { registry, api, session: auth.session },
|
|
857
|
+
context: { registry, api, redirects: { signedOut: signInRedirect("/login") }, session: auth.session },
|
|
825
858
|
InnerWrap: PermissionShell,
|
|
826
859
|
defaultErrorComponent: PermissionBoundaryError,
|
|
827
860
|
routeTree: root.addChildren([profile, note, login]),
|
|
@@ -833,7 +866,7 @@ function Controls() {
|
|
|
833
866
|
return can(ReadNotes) ? <button type="button">Read notes</button> : null;
|
|
834
867
|
}
|
|
835
868
|
|
|
836
|
-
function PermissionShell({ children }: { readonly children: ReactNode })
|
|
869
|
+
function PermissionShell({ children }: { readonly children: ReactNode }) {
|
|
837
870
|
const session = useRouter<typeof router>().options.context?.session;
|
|
838
871
|
return (
|
|
839
872
|
<PermissionBoundary session={session} fallback={<NoAccess />}>
|
|
@@ -865,7 +898,9 @@ const showNotes = can(auth.session, ReadNotes);
|
|
|
865
898
|
|
|
866
899
|
`auth` owns the current session and passes it to `App`; `SignIn` updates that session before invoking `onSignedIn`. Use the session's registry for router context and React, as with other query routes. Importing `permissionGuard` augments TanStack's `StaticDataRouteOption`; route options and their inference remain native. The guard returns `void` explicitly, so `beforeLoad` needs no return annotation, including when it reads the session from route context.
|
|
867
900
|
|
|
868
|
-
`
|
|
901
|
+
`PermissionBoundary` runs the guards again when the grants of its `session` change without a navigation, such as a remembered session whose check answers with fewer grants, so a screen that needs a removed grant is replaced by the refusal. The application writes nothing for it; the boundary invalidates the router it renders inside.
|
|
902
|
+
|
|
903
|
+
`InnerWrap` puts `PermissionBoundary` inside the router, and the boundary's fallback can render `Link` and read route context. TanStack types `InnerWrap` as a component that returns an element, so `PermissionShell` leaves its return type to inference; annotated as returning `ReactNode`, it does not compile. Set `defaultErrorComponent: PermissionBoundaryError` so route and loader failures reach the boundary's fallback while TanStack keeps its navigation controller mounted. This lets a refused viewer follow the fallback link without reloading the page. Keep `disableGlobalCatchBoundary: true`; other errors propagate to an enclosing application boundary. A route-specific `errorComponent` owns any failures it consumes.
|
|
869
904
|
|
|
870
905
|
`Forbidden` from `@shivaedev/react/adapters/Forbidden.ts` supplies the no-access heading, explanation and a router link. Set `to` to a route the viewer may open. Optional `title`, `children`, `backLabel` and `className` let the application choose wording and layout. The default heading is “Permission denied” and the link says “Go back”.
|
|
871
906
|
|
|
@@ -894,7 +929,7 @@ function SignInButton({ email, password }: { email: string; password: string })
|
|
|
894
929
|
|
|
895
930
|
The example uses `authAction`, identity's `authCall`, `useAction`, `effect/reactivity/AsyncResult` and `effect/Option`, with an application-owned `authClient`. Identity owns the Promise bridge and its typed failures; see [Better Auth client adapters](https://github.com/ShivaeDev/platform/blob/main/packages/identity/README.md#better-auth-client-adapters). For a form's Effect-based `onSubmit`, pass the function returned by `authCall` directly.
|
|
896
931
|
|
|
897
|
-
Use `authSession` from `@shivaedev/react/client/authSession.ts` to wrap identity's session Effect. It returns a native `atom` for `useQuery` and a `refresh` Effect that refreshes that same atom and waits through its loading state. Both expose typed `user.permissions` alongside the provider's existing session and user fields, using the `PermissionSession` schema from `@shivaedev/identity/PermissionSession.ts`. Applications do not decode `get-session` themselves. Missing grants stay optional; malformed grants fail with `AuthUnavailable`. The reader must return a nullable session with a `user` object; use `authQuery` for other payload shapes. Supply Better Auth's public `getSession` call with `disableCookieCache: true` so a mutation reads current user data:
|
|
932
|
+
Use `authSession` from `@shivaedev/react/client/authSession.ts` to wrap identity's session Effect. It returns a native `atom` for `useQuery` and a `refresh` Effect that refreshes that same atom and waits through its loading state. Both expose typed `user.permissions` alongside the provider's existing session and user fields, using the `PermissionSession` schema from `@shivaedev/identity/PermissionSession.ts`. Applications do not decode `get-session` themselves. Missing grants stay optional; malformed grants fail with `AuthUnavailable`. The reader must return a nullable session with a `user` object; use `authQuery` for other payload shapes. Pass `{ remember: browserSessionMemory }` as the second argument to start a returning person's app from the last verified session while the check runs; see [identity's remembered session](https://github.com/ShivaeDev/platform/blob/main/packages/identity/README.md#start-from-the-last-verified-session) for what it keeps and what it means. With `remember`, the session also has `signOut(request)`, which wipes the memory when the sign-out request succeeds. Supply Better Auth's public `getSession` call with `disableCookieCache: true` so a mutation reads current user data:
|
|
898
933
|
|
|
899
934
|
```tsx
|
|
900
935
|
import { Effect } from "effect";
|
|
@@ -930,7 +965,7 @@ For other Better Auth reads, `authQuery` from `@shivaedev/react/client/authQuery
|
|
|
930
965
|
|
|
931
966
|
Pass the auth owner’s sign-out atom to `SessionBoundary` as `signOut={signOut}`. The boundary mounts it in the auth owner’s registry and unmounts the signed-in tree while sign-out is pending, including the following session refetch. A successful action keeps the tree held until the session clears; a failed action releases the hold. Supply an atom for the sign-out request itself, and give `recheck` the auth owner’s session refresh. After the request succeeds, the boundary starts that check and retries failures while holding the tree. A failed session check never releases a successful sign-out’s hold.
|
|
932
967
|
|
|
933
|
-
For an explicit sign-out in a TanStack route, use `useSignOut(signOut, { signIn: "/sign-in" })` from `@shivaedev/react/client/adapters/useSignOut.ts` in place of `useAction`. It exposes the same state and a `dispatch()` handler. The hook records sign-out intent before the request and navigates to sign-in after success. A refused request clears that intent, including when the boundary remounts its route. Repeated clicks while pending share one request and follow-up. Unmounting the component or disposing its registry stops the follow-up navigation. If a session refresh replaces the component before the response, the replacement session’s route policy owns navigation to sign-in. `
|
|
968
|
+
For an explicit sign-out in a TanStack route, use `useSignOut(signOut, { signIn: "/sign-in" })` from `@shivaedev/react/client/adapters/useSignOut.ts` in place of `useAction`. It exposes the same state and a `dispatch()` handler. The hook records sign-out intent before the request and navigates to sign-in after success. A refused request clears that intent, including when the boundary remounts its route. Repeated clicks while pending share one request and follow-up. Unmounting the component or disposing its registry stops the follow-up navigation. If a session refresh replaces the component before the response, the replacement session’s route policy owns navigation to sign-in. `signInRedirect` and `signInSearch(location)` omit `returnTo` for that intent, including when the auth owner's session refresh reruns guards first. Use `signInSearch` for module sign-in links too; ordinary visits retain the full requested location. Applications do not need history markers or Better Auth completion timing hooks.
|
|
934
969
|
|
|
935
970
|
### 3. Every day
|
|
936
971
|
|
|
@@ -1048,22 +1083,49 @@ These lines belong inside a component; `text` and `ClipboardDenied` belong to th
|
|
|
1048
1083
|
|
|
1049
1084
|
#### Render tests in happy-dom
|
|
1050
1085
|
|
|
1051
|
-
Use `@shivaedev/test-story/client/adapters/react.ts` with Vitest's `happy-dom` environment. Install contract and
|
|
1086
|
+
Use `@shivaedev/test-story/client/adapters/react.ts` with Vitest's `happy-dom` environment. Install changes, contract and identity for the module's keys, operations, middleware and client binding, and the testing peers and environment in your app's dev dependencies:
|
|
1052
1087
|
|
|
1053
1088
|
```sh
|
|
1054
|
-
pnpm add @shivaedev/changes @shivaedev/contract
|
|
1089
|
+
pnpm add @shivaedev/changes @shivaedev/contract @shivaedev/identity
|
|
1055
1090
|
pnpm add -D @shivaedev/test-story @effect/platform-node @effect/vitest vitest happy-dom react-dom @types/react-dom
|
|
1056
1091
|
```
|
|
1057
1092
|
|
|
1058
|
-
Configure Vitest with `test: { environment: "happy-dom" }`, or select that environment for your DOM test project.
|
|
1093
|
+
Configure Vitest with `test: { environment: "happy-dom" }`, or select that environment for your DOM test project. The screen below reads a defined `notes` module, whose operations yield a `NoteTitles` service and run behind identity's `Authenticated` middleware:
|
|
1094
|
+
|
|
1095
|
+
```ts
|
|
1096
|
+
import { defineModule } from "@shivaedev/contract/defineModule.ts";
|
|
1097
|
+
import { command, query } from "@shivaedev/contract/operation.ts";
|
|
1098
|
+
import { Authenticated } from "@shivaedev/identity/middleware.ts";
|
|
1099
|
+
import { notesWire } from "#generated/modules/notes/Notes.ts";
|
|
1100
|
+
import { NoteTitle, notes } from "#modules/notes/model.ts";
|
|
1101
|
+
import { NoteTitles } from "#modules/notes/services.ts";
|
|
1102
|
+
|
|
1103
|
+
const List = query("list", {
|
|
1104
|
+
reads: () => [notes.list],
|
|
1105
|
+
*run() {
|
|
1106
|
+
return yield* (yield* NoteTitles).all;
|
|
1107
|
+
},
|
|
1108
|
+
});
|
|
1109
|
+
const Add = command("add", {
|
|
1110
|
+
invalidates: () => [notes.list],
|
|
1111
|
+
payload: NoteTitle,
|
|
1112
|
+
*run({ title }) {
|
|
1113
|
+
yield* (yield* NoteTitles).add(title);
|
|
1114
|
+
},
|
|
1115
|
+
});
|
|
1116
|
+
export const Notes = defineModule({ middleware: Authenticated, name: "notes", operations: [List, Add], wire: notesWire });
|
|
1117
|
+
```
|
|
1118
|
+
|
|
1119
|
+
`model.ts` declares `notes` as `collection("notes", Schema.Number)` and `NoteTitle` as `Schema.Struct({ title: Schema.String })`, and `services.ts` declares `NoteTitles` with an `all` Effect of titles and an `add(title)` method. Keep the engine, rendering and verbs in a story kit under `src/test-support/notesScreen.tsx`. This kit serves the module's own handlers from `moduleHandlers` over native RPC, with an in-memory `NoteTitles` and a fake `Authenticated` that signs alice in, binds the generated contract and gives the screen driver the registry's pending signal:
|
|
1059
1120
|
|
|
1060
1121
|
```tsx
|
|
1061
|
-
import { Effect, Layer, Option, Ref
|
|
1122
|
+
import { Effect, Layer, Option, Ref } from "effect";
|
|
1062
1123
|
import { act, createElement } from "react";
|
|
1063
|
-
import { collection } from "@shivaedev/changes/keys.ts";
|
|
1064
1124
|
import { makeClient } from "@shivaedev/contract/bind.ts";
|
|
1065
|
-
import {
|
|
1066
|
-
import {
|
|
1125
|
+
import { moduleHandlers } from "@shivaedev/contract/moduleHandlers.ts";
|
|
1126
|
+
import { CurrentViewer } from "@shivaedev/contract/readPolicy.ts";
|
|
1127
|
+
import { Identity } from "@shivaedev/identity/identity.ts";
|
|
1128
|
+
import { Authenticated } from "@shivaedev/identity/middleware.ts";
|
|
1067
1129
|
import { layerMemoryProtocol } from "@shivaedev/test-kits/contract/testing.ts";
|
|
1068
1130
|
import { screenPending } from "@shivaedev/react/adapters/screenPending.ts";
|
|
1069
1131
|
import { useAction, useQuery } from "@shivaedev/react/client/resultState.ts";
|
|
@@ -1071,33 +1133,29 @@ import { render } from "@shivaedev/test-story/client/adapters/react.ts";
|
|
|
1071
1133
|
import { screenDriver } from "@shivaedev/test-story/server/screenDriver.ts";
|
|
1072
1134
|
import { storyKit } from "@shivaedev/test-story/server/storyKit.ts";
|
|
1073
1135
|
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
const Add = command("add", { invalidates: () => [notes.list], payload: { title: Schema.String } });
|
|
1078
|
-
const Notes = contract("notes", { commands: [Add], queries: [List] });
|
|
1136
|
+
import { Notes } from "#generated/modules/notes/Notes.ts";
|
|
1137
|
+
import { Notes as NotesModule } from "#modules/notes/Notes.ts";
|
|
1138
|
+
import { NoteTitles } from "#modules/notes/services.ts";
|
|
1079
1139
|
|
|
1080
1140
|
export const notesScreen = storyKit({
|
|
1081
1141
|
*create() {
|
|
1082
|
-
const
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
});
|
|
1090
|
-
}),
|
|
1142
|
+
const stored = yield* Ref.make<readonly string[]>([]);
|
|
1143
|
+
const titles = Layer.succeed(NoteTitles, {
|
|
1144
|
+
add: (title) => Ref.update(stored, (all) => [...all, title]),
|
|
1145
|
+
all: Ref.get(stored),
|
|
1146
|
+
});
|
|
1147
|
+
const signedIn = Layer.succeed(Authenticated, (effect) =>
|
|
1148
|
+
effect.pipe(Effect.provideService(CurrentViewer, Option.some({ id: "alice" })), Effect.provideService(Identity, { id: "alice" })),
|
|
1091
1149
|
);
|
|
1092
|
-
const
|
|
1150
|
+
const handlers = moduleHandlers(NotesModule).pipe(Layer.provide(titles));
|
|
1151
|
+
const { api } = makeClient(Notes, {
|
|
1093
1152
|
live: false,
|
|
1094
|
-
protocol: layerMemoryProtocol(
|
|
1153
|
+
protocol: layerMemoryProtocol(NotesModule.application).pipe(Layer.provide([handlers, signedIn])),
|
|
1095
1154
|
url: "memory://notes",
|
|
1096
1155
|
});
|
|
1097
|
-
const add = Client.runtime.fn(api.add.run);
|
|
1098
1156
|
function NotesView() {
|
|
1099
1157
|
const list = useQuery(api.list.query());
|
|
1100
|
-
const
|
|
1158
|
+
const add = useAction(api.add);
|
|
1101
1159
|
return createElement(
|
|
1102
1160
|
"section",
|
|
1103
1161
|
null,
|
|
@@ -1105,8 +1163,8 @@ export const notesScreen = storyKit({
|
|
|
1105
1163
|
createElement(
|
|
1106
1164
|
"button",
|
|
1107
1165
|
{
|
|
1108
|
-
disabled: list.pending ||
|
|
1109
|
-
onClick: () =>
|
|
1166
|
+
disabled: list.pending || add.pending,
|
|
1167
|
+
onClick: () => add.dispatch({ title: "Morning walk" }),
|
|
1110
1168
|
type: "button",
|
|
1111
1169
|
},
|
|
1112
1170
|
"Add",
|
|
@@ -1160,7 +1218,7 @@ notesScreen.it("a command refetches the rendered notes through native RPC", [],
|
|
|
1160
1218
|
|
|
1161
1219
|
`render(node, options?)` returns the attached `container`, its fresh native `registry`, `render(nextNode)` to update the same root and registry, and `unmount()` to release the root, registry and container. The options are React's own `RootOptions`, passed to `createRoot`, including `onCaughtError`, `onUncaughtError` and `onRecoverableError`. Acquire the view with `Effect.acquireRelease` so its scope releases it on success, failure or interruption. The screen driver's `act` adapter keeps component interactions and settling inside React's `act`. `expectNoReactWarnings()` registers a Vitest hook that fails a test if it logged to `console.error`.
|
|
1162
1220
|
|
|
1163
|
-
The
|
|
1221
|
+
The kit runs the module's real operations, read policies included, and replaces only the service they yield and the session. `moduleHandlers` requires exactly the services the operations yield beyond the middleware, so the compiler names one the kit forgets. The fake middleware provides the viewer the default `signedIn` policy checks and the `Identity` the operations may yield; without a viewer, the list answers `QueryReadDenied`. The starter's [notes screen kit](https://github.com/ShivaeDev/platform/blob/main/examples/starter/src/modules/notes/test-support/client.ts) fakes its middleware the same way. A story about persistence or the real session runs the operations through the application host, as the starter's application kit does.
|
|
1164
1222
|
|
|
1165
1223
|
For a boundary fallback test, keep the warnings guard and declare the caught error inside the test. `expectCaughtError(predicate)` returns an `onCaughtError` handler that accepts matching errors without logging them. The guard fails if the handler receives any other error or the expected error never arrives. Other console errors and React warnings still fail the guard.
|
|
1166
1224
|
|
|
@@ -1217,7 +1275,7 @@ pnpm add @shivaedev/react @effect/atom-react effect react
|
|
|
1217
1275
|
pnpm add @shivaedev/form
|
|
1218
1276
|
```
|
|
1219
1277
|
|
|
1220
|
-
Add the optional router peer when using `queryRoute`, `loadQuery`, `permissionGuard`, `PermissionBoundary`, `PermissionBoundaryError`, `Forbidden` or `useSignOut`:
|
|
1278
|
+
Add the optional router peer when using `queryRoute`, `loadQuery`, `permissionGuard`, `signInRedirect`, `PermissionBoundary`, `PermissionBoundaryError`, `Forbidden` or `useSignOut`:
|
|
1221
1279
|
|
|
1222
1280
|
```sh
|
|
1223
1281
|
pnpm add @tanstack/react-router
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permissionBoundary.d.ts","sourceRoot":"","sources":["../../src/adapters/permissionBoundary.ts"],"names":[],"mappings":"AACA,OAAO,EAAiB,KAAK,SAAS,
|
|
1
|
+
{"version":3,"file":"permissionBoundary.d.ts","sourceRoot":"","sources":["../../src/adapters/permissionBoundary.ts"],"names":[],"mappings":"AACA,OAAO,EAAiB,KAAK,SAAS,EAAiC,MAAM,OAAO,CAAC;AACrF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAElE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAIlF,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC;IAC7B,QAAQ,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,GAAG,SAAS,CAAC;CACvD;AAED,wBAAgB,MAAM,IAAI,CAAC,UAAU,EAAE,UAAU,KAAK,OAAO,CAG5D;AAED,wBAAgB,uBAAuB,CAAC,EAAE,KAAK,EAAE,EAAE;IAAE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAA;CAAE,GAAG,SAAS,CAMzF;AAsBD,wBAAgB,kBAAkB,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,uBAAuB,GAAG,SAAS,CAOtG"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CatchBoundary } from "@tanstack/react-router";
|
|
2
|
-
import { createElement, useContext } from "react";
|
|
1
|
+
import { CatchBoundary, useRouter } from "@tanstack/react-router";
|
|
2
|
+
import { createElement, useContext, useEffect, useRef } from "react";
|
|
3
3
|
import { isForbidden } from "@shivaedev/errors/taxonomy.ts";
|
|
4
4
|
import { PermissionContext } from "#adapters/PermissionContext.ts";
|
|
5
5
|
import { can } from "#can.ts";
|
|
@@ -14,7 +14,26 @@ export function PermissionBoundaryError({ error }) {
|
|
|
14
14
|
}
|
|
15
15
|
return context?.fallback;
|
|
16
16
|
}
|
|
17
|
+
function grantKey(session) {
|
|
18
|
+
return (session?.user.permissions ?? [])
|
|
19
|
+
.map((grant) => `${grant.name}:${grant.strength}`)
|
|
20
|
+
.sort()
|
|
21
|
+
.join(",");
|
|
22
|
+
}
|
|
23
|
+
// Route guards read the session when a navigation loads, so a session refreshed in place reruns them here.
|
|
24
|
+
function useGuardRerun(session) {
|
|
25
|
+
const router = useRouter({ warn: false });
|
|
26
|
+
const grants = grantKey(session);
|
|
27
|
+
const guardedRef = useRef(grants);
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
if (guardedRef.current !== grants) {
|
|
30
|
+
guardedRef.current = grants;
|
|
31
|
+
void router?.invalidate();
|
|
32
|
+
}
|
|
33
|
+
}, [router, grants]);
|
|
34
|
+
}
|
|
17
35
|
export function PermissionBoundary({ children, fallback, session }) {
|
|
36
|
+
useGuardRerun(session);
|
|
18
37
|
return createElement(PermissionContext.Provider, { value: { fallback, session } }, createElement(CatchBoundary, { children, errorComponent: PermissionBoundaryError, getResetKey: () => "permission" }));
|
|
19
38
|
}
|
|
20
39
|
//# sourceMappingURL=permissionBoundary.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permissionBoundary.js","sourceRoot":"","sources":["../../src/adapters/permissionBoundary.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"permissionBoundary.js","sourceRoot":"","sources":["../../src/adapters/permissionBoundary.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,aAAa,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAClF,OAAO,EAAE,aAAa,EAAkB,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAErF,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAE5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAQ9B,MAAM,UAAU,MAAM;IACrB,MAAM,OAAO,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;IAC9C,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;AAC1D,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,EAAE,KAAK,EAA+B;IAC7E,MAAM,OAAO,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;IAC9C,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,KAAK,CAAC;IACb,CAAC;IACD,OAAO,OAAO,EAAE,QAAQ,CAAC;AAC1B,CAAC;AAED,SAAS,QAAQ,CAAC,OAA6C;IAC9D,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC;SACtC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;SACjD,IAAI,EAAE;SACN,IAAI,CAAC,GAAG,CAAC,CAAC;AACb,CAAC;AAED,2GAA2G;AAC3G,SAAS,aAAa,CAAC,OAA6C;IACnE,MAAM,MAAM,GAA0B,SAAS,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IACjE,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC;IACjC,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IAClC,SAAS,CAAC,GAAG,EAAE;QACd,IAAI,UAAU,CAAC,OAAO,KAAK,MAAM,EAAE,CAAC;YACnC,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC;YAC5B,KAAK,MAAM,EAAE,UAAU,EAAE,CAAC;QAC3B,CAAC;IACF,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAA2B;IAC1F,aAAa,CAAC,OAAO,CAAC,CAAC;IACvB,OAAO,aAAa,CACnB,iBAAiB,CAAC,QAAQ,EAC1B,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,EAChC,aAAa,CAAC,aAAa,EAAE,EAAE,QAAQ,EAAE,cAAc,EAAE,uBAAuB,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC,YAAY,EAAE,CAAC,CACpH,CAAC;AACH,CAAC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Permission } from "@shivaedev/access/permission.ts";
|
|
2
2
|
import type { PermissionSession } from "@shivaedev/identity/PermissionSession.ts";
|
|
3
|
-
import {
|
|
3
|
+
import type { QueryRouteRedirect } from "#adapters/queryRouteFailure.ts";
|
|
4
|
+
import type { SignInLocation } from "#signInSearch.ts";
|
|
4
5
|
declare module "@tanstack/react-router" {
|
|
5
6
|
interface StaticDataRouteOption {
|
|
6
7
|
readonly permission?: Permission;
|
|
@@ -10,7 +11,7 @@ declare module "@tanstack/react-router" {
|
|
|
10
11
|
export interface PermissionGuardOptions {
|
|
11
12
|
readonly hidden?: boolean;
|
|
12
13
|
readonly session: () => PermissionSession | null | undefined;
|
|
13
|
-
readonly
|
|
14
|
+
readonly signedOut: (location: SignInLocation) => QueryRouteRedirect;
|
|
14
15
|
}
|
|
15
16
|
export interface PermissionGuardContext {
|
|
16
17
|
readonly location: SignInLocation;
|
|
@@ -21,5 +22,5 @@ export interface PermissionGuardContext {
|
|
|
21
22
|
};
|
|
22
23
|
}[];
|
|
23
24
|
}
|
|
24
|
-
export declare function permissionGuard({ session,
|
|
25
|
+
export declare function permissionGuard({ session, signedOut, hidden }: PermissionGuardOptions): (context: PermissionGuardContext) => void;
|
|
25
26
|
//# sourceMappingURL=permissionGuard.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permissionGuard.d.ts","sourceRoot":"","sources":["../../src/adapters/permissionGuard.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAElE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;
|
|
1
|
+
{"version":3,"file":"permissionGuard.d.ts","sourceRoot":"","sources":["../../src/adapters/permissionGuard.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAElE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0CAA0C,CAAC;AAClF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEzE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD,OAAO,QAAQ,wBAAwB,CAAC;IACvC,UAAU,qBAAqB;QAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;QACjC,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;KAC5B;CACD;AAED,MAAM,WAAW,sBAAsB;IACtC,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,iBAAiB,GAAG,IAAI,GAAG,SAAS,CAAC;IAC7D,QAAQ,CAAC,SAAS,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,kBAAkB,CAAC;CACrE;AAED,MAAM,WAAW,sBAAsB;IACtC,QAAQ,CAAC,QAAQ,EAAE,cAAc,CAAC;IAClC,QAAQ,CAAC,OAAO,EAAE,SAAS;QAAE,QAAQ,CAAC,UAAU,EAAE;YAAE,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;YAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;SAAE,CAAA;KAAE,EAAE,CAAC;CACxH;AAED,wBAAgB,eAAe,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,MAAc,EAAE,EAAE,sBAAsB,GAAG,CAAC,OAAO,EAAE,sBAAsB,KAAK,IAAI,CAgBzI"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { notFound
|
|
1
|
+
import { notFound } from "@tanstack/react-router";
|
|
2
2
|
import { forbidden } from "@shivaedev/access/refusal.ts";
|
|
3
3
|
import { can } from "#can.ts";
|
|
4
|
-
|
|
5
|
-
export function permissionGuard({ session, signIn, hidden = false }) {
|
|
4
|
+
export function permissionGuard({ session, signedOut, hidden = false }) {
|
|
6
5
|
return ({ matches, location }) => {
|
|
7
6
|
const required = matches.flatMap((match) => (match.staticData.permission === undefined ? [] : [match.staticData.permission]));
|
|
8
7
|
if (required.length === 0 && !matches.some((match) => match.staticData.signedIn === true)) {
|
|
@@ -10,7 +9,7 @@ export function permissionGuard({ session, signIn, hidden = false }) {
|
|
|
10
9
|
}
|
|
11
10
|
const current = session();
|
|
12
11
|
if (current === null || current === undefined) {
|
|
13
|
-
throw
|
|
12
|
+
throw signedOut(location);
|
|
14
13
|
}
|
|
15
14
|
for (const permission of required) {
|
|
16
15
|
if (!can(current, permission)) {
|