@softr/sdk 0.0.87-alpha.3 → 0.0.87

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.
@@ -73,15 +73,16 @@ function renderUserPropertiesDoc(users, context) {
73
73
  "",
74
74
  "```tsx",
75
75
  "import { createFileRoute, redirect } from '@tanstack/react-router'",
76
- "import { assertRouteAccess, defineVisibility } from '@softr/sdk'",
76
+ "import { assertRouteAccess, definePage, pageHead } from '@softr/sdk'",
77
77
  "",
78
- "const visibility = defineVisibility({ userGroupTypes: ['LOGGED_IN_USERS'] })",
78
+ "const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] }, title: 'Example' })",
79
79
  "",
80
80
  "export const Route = createFileRoute('/example')({",
81
81
  " beforeLoad: (opts) => {",
82
- " assertRouteAccess(visibility, opts)",
82
+ " assertRouteAccess(pageSettings, opts)",
83
83
  ` if (opts.context.user.properties.${first} == null) throw redirect({ to: '/' })`,
84
84
  " },",
85
+ " head: pageHead(pageSettings),",
85
86
  "})",
86
87
  "```",
87
88
  "",
@@ -90,14 +91,19 @@ function renderUserPropertiesDoc(users, context) {
90
91
  "```tsx",
91
92
  "import { createFileRoute } from '@tanstack/react-router'",
92
93
  "import { createServerFn } from '@tanstack/react-start'",
94
+ "import { definePage, guardRoute, pageHead } from '@softr/sdk'",
93
95
  "",
94
96
  `const get${pascalCase(first)} = createServerFn().handler(async ({ context }) => {`,
95
97
  " if (!context.user) throw new Error('Not signed in')",
96
98
  ` return context.user.properties.${first}`,
97
99
  "})",
98
100
  "",
101
+ "const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] }, title: 'Example' })",
102
+ "",
99
103
  "export const Route = createFileRoute('/example')({",
104
+ " beforeLoad: guardRoute(pageSettings),",
100
105
  ` loader: () => get${pascalCase(first)}(),`,
106
+ " head: pageHead(pageSettings),",
101
107
  " component: Example,",
102
108
  "})",
103
109
  "",
@@ -1,4 +1,4 @@
1
- import * as react2 from "react";
1
+ import * as react6 from "react";
2
2
 
3
3
  //#region src/default-error-overlay.d.ts
4
4
  type Props = {
@@ -8,6 +8,6 @@ type Props = {
8
8
  declare function DefaultErrorOverlay({
9
9
  error,
10
10
  reset
11
- }: Props): react2.JSX.Element;
11
+ }: Props): react6.JSX.Element;
12
12
  //#endregion
13
13
  export { DefaultErrorOverlay };
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import * as react3 from "react";
2
+ import * as react0 from "react";
3
3
  import { ReactNode } from "react";
4
4
 
5
5
  //#region src/formatting.d.ts
@@ -94,7 +94,7 @@ declare function FormattingScope({
94
94
  /** A BCP 47 locale, such as `de-DE`. It drops the app's fixed date format inside the scope. */
95
95
  locale?: string;
96
96
  children?: ReactNode;
97
- }): react3.FunctionComponentElement<react3.ProviderProps<Scope>>;
97
+ }): react0.FunctionComponentElement<react0.ProviderProps<Scope>>;
98
98
  /**
99
99
  * A date in the app's format, safe to render on the server. A timestamp whose
100
100
  * zone is not known yet renders `fallback` until the browser supplies it, so
@@ -115,6 +115,6 @@ declare function FormattedDate({
115
115
  time?: boolean;
116
116
  /** What renders while the visitor's zone is unknown. */
117
117
  fallback?: ReactNode;
118
- }): react3.FunctionComponentElement<react3.FragmentProps>;
118
+ }): react0.FunctionComponentElement<react0.FragmentProps>;
119
119
  //#endregion
120
120
  export { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, FormattedDate, Formatting, FormattingScope, WeekDay, formatDate, formatDateTime, formatNumber, useFormatting };
package/dist/index.d.ts CHANGED
@@ -16,7 +16,5 @@ import { useOverrides } from "./core/use-overrides.js";
16
16
  import { useUserTimezone } from "./timezone.js";
17
17
  import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
18
18
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
19
- import { Agent, AgentChatSummary, listAgents } from "./agent/agent-fns.js";
20
- import { AgentBlock, AgentChat, AgentChatOptions, AgentMessage, AgentQuestion, AgentTodo, AgentToolCall, useAgentChat } from "./agent/use-agent-chat.js";
21
19
  import { Audience } from "./route/audience.js";
22
- export { type ActionPermissions, type Agent, type AgentBlock, type AgentChat, type AgentChatOptions, type AgentChatSummary, type AgentMessage, type AgentQuestion, type AgentTodo, type AgentToolCall, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Page, type PageSettings, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type User, type WeekDay, assertRouteAccess, checkAccess, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, listAgents, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAgentChat, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
20
+ export { type ActionPermissions, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Page, type PageSettings, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type User, type WeekDay, assertRouteAccess, checkAccess, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
package/dist/index.js CHANGED
@@ -12,8 +12,6 @@ import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFiel
12
12
  import { useOverrides } from "./core/use-overrides.js";
13
13
  import { useUserTimezone } from "./timezone.js";
14
14
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
15
- import { listAgents } from "./agent/agent-fns.js";
16
- import { useAgentChat } from "./agent/use-agent-chat.js";
17
15
  import { Audience } from "./route/audience.js";
18
16
 
19
- export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, listAgents, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAgentChat, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
17
+ export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
package/dist/mcp.js CHANGED
@@ -385,10 +385,8 @@ async function rpc(request, origin, actions) {
385
385
  const token = bearerToken(request);
386
386
  if (token === null) return unauthorized(origin);
387
387
  const session = await platformSession(token);
388
- let sessionToken;
389
- if (session.ok) sessionToken = session.sessionToken;
390
- else if (session.refused && await resolveUser(token) !== null) sessionToken = token;
391
- else return session.refused ? unauthorized(origin) : unavailable();
388
+ if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
389
+ const { sessionToken } = session;
392
390
  const body = await readJson(request);
393
391
  const message = z.object({
394
392
  id: z.union([z.string(), z.number()]).optional(),
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.0.87-alpha.3";
2
+ var version = "0.0.87";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/pwa.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as react0 from "react";
1
+ import * as react4 from "react";
2
2
  import "@tanstack/react-start";
3
3
 
4
4
  //#region src/pwa.d.ts
@@ -23,7 +23,7 @@ import "@tanstack/react-start";
23
23
  * )
24
24
  * }
25
25
  */
26
- declare function SoftrPwaHead(): react0.FunctionComponentElement<react0.FragmentProps>;
26
+ declare function SoftrPwaHead(): react4.FunctionComponentElement<react4.FragmentProps>;
27
27
  type PwaPlatform = "ios" | "android" | "desktop";
28
28
  type PwaInstall = {
29
29
  available: false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "0.0.87-alpha.3",
3
+ "version": "0.0.87",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -8,7 +8,7 @@ description: >-
8
8
  metadata:
9
9
  type: core
10
10
  library: softr-sdk
11
- library_version: 0.0.87-alpha.3
11
+ library_version: 0.0.87
12
12
  ---
13
13
 
14
14
  # Softr SDK core
@@ -17,7 +17,7 @@ metadata:
17
17
 
18
18
  > **CRITICAL**: The SDK is split across four entrypoints and the split is enforced. `ds` and `auth` exist only on `@softr/sdk/server` and only run inside a `createServerFn` handler. Importing them anywhere else fails the build.
19
19
  >
20
- > **CRITICAL**: Every route file must declare its audience with `defineVisibility` and guard itself with that rule in `beforeLoad`. There is no default and nothing is inherited from a sibling.
20
+ > **CRITICAL**: Every route file must declare its settings with `definePage`, guard itself with them in `beforeLoad` and render them in `head`. There is no default and nothing is inherited from a sibling.
21
21
  >
22
22
  > **CRITICAL**: The app is already wired. `src/start.ts`, `src/router.tsx` and `src/routes/__root.tsx` register `softrAuthMiddleware` and resolve the session. Do not add a second registration of it. `softrMcpMiddleware` is the one thing an app adds to `src/start.ts` itself — load the `softr-sdk/mcp` sub-skill before doing so.
23
23
  >
@@ -29,7 +29,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
29
29
 
30
30
  | Import | Runs | Holds |
31
31
  | --- | --- | --- |
32
- | `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
32
+ | `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
33
33
  | `@softr/sdk/server` | Server only | `ds`, `auth`, `workflow`, `integration` |
34
34
  | `@softr/sdk/client` | Browser only | `useFileUpload` |
35
35
  | `@softr/sdk/vite` | Build | `softr()`, already in `vite.config.ts` |
@@ -48,7 +48,6 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
48
48
  | Sign a visitor in, out, or up | [auth/SKILL.md](./auth/SKILL.md) |
49
49
  | Call a connected third-party API (Slack, Stripe, Gmail, …) | [integrations/SKILL.md](./integrations/SKILL.md) |
50
50
  | Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
51
- | Let visitors chat with a Softr agent | [agent-chat/SKILL.md](./agent-chat/SKILL.md) |
52
51
  | Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
53
52
  | Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
54
53
 
@@ -85,9 +84,6 @@ Calling a connected third-party API (Slack, Stripe, Gmail, Google Calendar, …)
85
84
  Opening the app to an AI assistant over MCP?
86
85
  load softr-sdk/mcp
87
86
 
88
- Adding a chat with one of the app's Softr agents?
89
- load softr-sdk/agent-chat
90
-
91
87
  Adding an install button, or making the app installable?
92
88
  load softr-sdk/pwa
93
89
 
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.3
12
+ library_version: 0.0.87
13
13
  ---
14
14
 
15
15
  **Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.3
12
+ library_version: 0.0.87
13
13
  ---
14
14
 
15
15
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.3
12
+ library_version: 0.0.87
13
13
  ---
14
14
 
15
15
  # The current user
@@ -55,12 +55,16 @@ It returns `User | null` and never suspends or fetches. It selects off root rout
55
55
 
56
56
  ```tsx
57
57
  export const Route = createFileRoute('/_app/invoices')({
58
- beforeLoad: guardRoute(visibility),
59
- loader: ({ context }) => fetchInvoicesFor({ data: { userId: context.user!.id } }),
58
+ beforeLoad: guardRoute(pageSettings),
59
+ loader: (opts) => {
60
+ assertRouteAccess(pageSettings, opts)
61
+ return fetchInvoicesFor({ data: { userId: opts.context.user.id } })
62
+ },
63
+ head: pageHead(pageSettings),
60
64
  })
61
65
  ```
62
66
 
63
- A `guardRoute` in `beforeLoad` guarantees a visitor at runtime, but it does not change what the compiler sees. `context.user` is still `User | null` further down the route. `isAuthorized(visibility, context)` is the check that narrows it, so prefer that over `!`. See [routes-and-visibility](../routes-and-visibility/SKILL.md).
67
+ A `guardRoute` in `beforeLoad` guarantees a visitor at runtime, but it does not change what the compiler sees. `context.user` is still `User | null` in the loader. `assertRouteAccess(pageSettings, opts)` at the top of the loader narrows it there, so prefer that over `!`. Take `opts` whole: a destructured `context` does not narrow. See [routes-and-visibility](../routes-and-visibility/SKILL.md).
64
68
 
65
69
  ### In a server function: `context`
66
70
 
@@ -94,7 +98,7 @@ For every group's name and id, read `docs/user-groups.md`. It lists every group
94
98
 
95
99
  ## References
96
100
 
97
- - [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md): `isAuthorized` narrows `context.user` while applying the route's rule
101
+ - [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md): `assertRouteAccess` narrows `context.user` while applying the route's rule
98
102
  - [region-visibility/SKILL.md](../region-visibility/SKILL.md): rendering a region only to the visitors a rule admits
99
103
  - [record-queries/SKILL.md](../record-queries/SKILL.md): filtering a query by the visitor, and who really authorizes the read
100
104
  - [auth/SKILL.md](../auth/SKILL.md): what changes the value `useCurrentUser` returns
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 0.0.87-alpha.3
10
+ library_version: 0.0.87
11
11
  ---
12
12
 
13
13
  **Boundary.** `upload` lives on `@softr/sdk/server` and runs inside server functions. `useFileUpload` and `FileItem` live on `@softr/sdk` and run in components. `FileAttachment` comes from `@softr/sdk` and can be imported anywhere.
@@ -8,7 +8,7 @@ description: >-
8
8
  metadata:
9
9
  type: sub-skill
10
10
  library: softr-sdk
11
- library_version: 0.0.87-alpha.3
11
+ library_version: 0.0.87
12
12
  ---
13
13
 
14
14
  # Dates, times and numbers
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 0.0.87-alpha.3
10
+ library_version: 0.0.87
11
11
  ---
12
12
 
13
13
  **Boundary.** `integration` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineIntegration` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.3
12
+ library_version: 0.0.87
13
13
  ---
14
14
 
15
15
  **Boundary.** `softrMcpMiddleware` lives on `@softr/sdk` and is registered once, in `src/start.ts`. The actions you hand it are the same `defineQuery` / `defineMutation` values the app's own pages use — declared wherever they already live, not duplicated for MCP.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.3
12
+ library_version: 0.0.87
13
13
  ---
14
14
 
15
15
  # Installing the app
@@ -8,7 +8,7 @@ description: >-
8
8
  metadata:
9
9
  type: sub-skill
10
10
  library: softr-sdk
11
- library_version: 0.0.87-alpha.3
11
+ library_version: 0.0.87
12
12
  ---
13
13
 
14
14
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineMutation` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.3
12
+ library_version: 0.0.87
13
13
  ---
14
14
 
15
15
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. The same holds for any helper that calls `ds`: declare it inside the handler. A function at module level that calls `ds` keeps the server-only import in the browser bundle, and every page stops loading until it moves. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -53,7 +53,7 @@ const publishedPosts = defineQuery({
53
53
  - `{ userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] }`: everyone, signed out included. `customGroups` narrows only the signed-in half.
54
54
  - `{ userGroupTypes: ['NON_LOGGED_IN_USERS'] }`: signed-out visitors only.
55
55
  - `{ userGroupTypes: ['LOGGED_IN_USERS'] }`: any signed-in visitor, narrowed to particular groups with `customGroups: ['00000000-0000-0000-0000-00000000000a']`. `customGroups` is added to `userGroupTypes`, never written in place of it.
56
- - Write each group id as a literal in `permissions`. An id taken from a `const` is a lint error, as it is in a route's visibility.
56
+ - Write each group id as a literal in `permissions`. An id taken from a `const` is a lint error.
57
57
  - Write the object inline in the `defineQuery` call. Passing the declaration or its `fields` through a variable, or spreading one in, widens the field ids to `string` and the types stop checking.
58
58
 
59
59
  A query fixes the table and the columns, not the rows: filters, sorting and paging stay at the call site, because a list screen changes them as the user types. Declare as many queries over one datasource as the app needs, each carrying the fields its own screen touches.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.3
12
+ library_version: 0.0.87
13
13
  ---
14
14
 
15
15
  **Boundary.** `Audience` and `defineVisibility` come from `@softr/sdk` and work anywhere.
@@ -47,11 +47,9 @@ The rules are the same four a route uses, and [routes-and-visibility](../routes-
47
47
 
48
48
  ### Where the rule is declared
49
49
 
50
- A region's rule is an ordinary value. It can sit beside the component, or come from a module the whole app shares so several regions read the same one. A route's rule cannot. Softr reads that one out of the route file, so it has to be declared there.
50
+ A region's rule is an ordinary value. It can sit beside the component, in the route file, or in a module the whole app shares so several regions read the same one.
51
51
 
52
- Two files cannot hold a region's rule. Any declaration in `__root.tsx` is a build error. In the lazy half of a split route, Softr takes the first declaration as the route's own. Put the rule in the component's file or a shared module and import it.
53
-
54
- A route file may declare a region's rule alongside its own. The route's rule is the one `beforeLoad` names.
52
+ It is separate from the route's own rule. That one is the `visibility` of the route's `definePage`, which `beforeLoad` applies: see [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md).
55
53
 
56
54
  ### Hiding a control is not authorization
57
55
 
@@ -1,21 +1,22 @@
1
1
  ---
2
2
  name: routes-and-visibility
3
3
  description: >-
4
- Add a route file and declare who may see it: defineVisibility with
5
- LOGGED_IN_USERS, NON_LOGGED_IN_USERS and customGroups, guardRoute and
6
- assertRouteAccess in a route, isAuthorized and checkAccess anywhere, rendering
7
- an access error, and the lint rule that requires the declaration.
4
+ Add a route file and declare its settings: definePage with its visibility
5
+ (LOGGED_IN_USERS, NON_LOGGED_IN_USERS and customGroups) and its title,
6
+ guardRoute or assertRouteAccess in beforeLoad, pageHead in head,
7
+ isAuthorized and checkAccess anywhere, rendering an access error, and the
8
+ lint rules that require the declaration.
8
9
  metadata:
9
10
  type: sub-skill
10
11
  library: softr-sdk
11
- library_version: 0.0.87-alpha.3
12
+ library_version: 0.0.87
12
13
  ---
13
14
 
14
- **Boundary.** `defineVisibility`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
15
+ **Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
15
16
 
16
17
  # Route visibility
17
18
 
18
- Every route file in a Softr app declares who may see it. Softr reads that declaration out of the source text without executing it and publishes it to Softr Studio, which shows the app owner every route and its audience. That is why the rules below are strict: a rule Softr cannot read is a rule Studio cannot show.
19
+ Every route file in a Softr app declares its settings: who may see it, its title and its SEO tags. Softr reads them out of the source text without executing it and shows them in Softr Studio, where the app owner sees every route and its audience and can change them. That is why the rules below are strict: a setting Softr cannot read is a setting Studio cannot show.
19
20
 
20
21
  ## Setup
21
22
 
@@ -23,12 +24,16 @@ Every route file, without exception, looks like this:
23
24
 
24
25
  ```tsx
25
26
  import { createFileRoute } from '@tanstack/react-router'
26
- import { defineVisibility, guardRoute } from '@softr/sdk'
27
+ import { definePage, guardRoute, pageHead } from '@softr/sdk'
27
28
 
28
- const visibility = defineVisibility({ userGroupTypes: ['LOGGED_IN_USERS'] })
29
+ const pageSettings = definePage({
30
+ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] },
31
+ title: 'Billing',
32
+ })
29
33
 
30
34
  export const Route = createFileRoute('/_app/billing')({
31
- beforeLoad: guardRoute(visibility),
35
+ beforeLoad: guardRoute(pageSettings),
36
+ head: pageHead(pageSettings),
32
37
  component: Billing,
33
38
  })
34
39
 
@@ -37,30 +42,31 @@ function Billing() {
37
42
  }
38
43
  ```
39
44
 
40
- The route's rule is one `defineVisibility` call at module scope, with an inline object literal as its argument.
45
+ The route's settings are one `definePage` call at module scope, with an inline object literal as its argument. It always states `visibility`, and a page states its `title` too. `beforeLoad` applies the visibility, and `head` renders the title and the SEO tags.
41
46
 
42
- Four constraints on that shape, because Softr reads the file rather than running it:
47
+ These constraints hold, because Softr reads the file rather than running it:
43
48
 
44
49
  - The call must initialise a top-level `const`.
45
50
  - The import must be a direct named import from `@softr/sdk`.
46
- - The route guards itself in `beforeLoad`, naming a rule declared in the same file. A rule imported from elsewhere is rejected.
47
- - Every value inside the literal is written there too. A group id taken from a `const`, a spread or an import is rejected, even when two routes share it: repeat the id on each.
48
- - Never declare on `__root.tsx`. The root cannot carry an audience, so a declaration there would gate nothing while looking like it does. Softr rejects it. Put the rule on a layout below the root instead.
51
+ - A route file has one `definePage`. The route names it in `beforeLoad` and in `head`. A page imported from elsewhere is rejected.
52
+ - Every value inside the literal is written there too. A group id taken from a `const`, a spread or an import still type-checks, but Studio can no longer change that setting. Repeat the id on each route, even when two routes share it.
53
+ - A head setting that depends on the route's data is a function of its head context: `title: ({ loaderData }) => loaderData?.name`.
54
+ - Never state `visibility` on `__root.tsx`. The root cannot carry an audience, so a rule there would gate nothing while looking like it does. Its `definePage` holds the app-wide head defaults only. Put the rule on a layout below the root instead.
49
55
 
50
56
  `userGroupTypes` is a set, so a rule names one audience or several:
51
57
 
52
58
  ```ts
53
- defineVisibility({ userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] }) // everyone, signed in or not
54
- defineVisibility({ userGroupTypes: ['NON_LOGGED_IN_USERS'] }) // signed-out only: login, signup
55
- defineVisibility({ userGroupTypes: ['LOGGED_IN_USERS'] }) // any signed-in visitor
56
- defineVisibility({ // those groups only
59
+ visibility: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] } // everyone, signed in or not
60
+ visibility: { userGroupTypes: ['NON_LOGGED_IN_USERS'] } // signed-out only: login, signup
61
+ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] } // any signed-in visitor
62
+ visibility: { // those groups only
57
63
  userGroupTypes: ['LOGGED_IN_USERS'],
58
64
  customGroups: ['00000000-0000-0000-0000-00000000000a'],
59
- })
60
- defineVisibility({ // signed-out visitors AND those groups
65
+ }
66
+ visibility: { // signed-out visitors AND those groups
61
67
  userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'],
62
68
  customGroups: ['00000000-0000-0000-0000-00000000000a'],
63
- })
69
+ }
64
70
  ```
65
71
 
66
72
  Everyone is both audiences, as in the first line above. A set names each audience at most once and is never empty — the type and the build both reject one that does not. `customGroups` never stands alone: it narrows the `LOGGED_IN_USERS` half of the set, so the rule still names that half, and one without `userGroupTypes` is a type error. Absent or empty it means **any** signed-in visitor, not "nobody".
@@ -74,17 +80,20 @@ Take every id in `customGroups` from `docs/user-groups.md`, which lists each gro
74
80
  ```tsx
75
81
  // src/routes/_app.tsx: guards every route under /_app
76
82
  import { Outlet, createFileRoute } from '@tanstack/react-router'
77
- import { defineVisibility, guardRoute } from '@softr/sdk'
83
+ import { definePage, guardRoute, pageHead } from '@softr/sdk'
78
84
 
79
- const visibility = defineVisibility({ userGroupTypes: ['LOGGED_IN_USERS'] })
85
+ const pageSettings = definePage({ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] } })
80
86
 
81
87
  export const Route = createFileRoute('/_app')({
82
- beforeLoad: guardRoute(visibility),
88
+ beforeLoad: guardRoute(pageSettings),
89
+ head: pageHead(pageSettings),
83
90
  component: () => <Outlet />,
84
91
  })
85
92
  ```
86
93
 
87
- The whole match chain runs, so a layout guards everything beneath it. Sibling routes do not guard each other. `/admin/index.tsx` does nothing for `/admin/users.tsx` unless an `admin.tsx` layout exists. A route below a guarded layout declares and guards its own rule too.
94
+ A pathless layout like this one is not a page, so it needs no `title`.
95
+
96
+ The whole match chain runs, so a layout guards everything beneath it. Sibling routes do not guard each other. `/admin/index.tsx` does nothing for `/admin/users.tsx` unless an `admin.tsx` layout exists. A route below a guarded layout declares and guards its own settings too.
88
97
 
89
98
  A thrown error renders in place of the guarded route's component. A shell layout guarded with `LOGGED_IN_USERS`, where `unauthenticated` redirects, sends a signed-out visitor away before anything renders there. A rule that can _throw_ — a `customGroups` rule with `forbidden` set to throw — should not sit on the shell itself, or the error replaces the nav and chrome. Put it on a layout inside the shell, or on the restricted routes, so the error renders inside the chrome.
90
99
 
@@ -93,9 +102,9 @@ A thrown error renders in place of the guarded route's component. A shell layout
93
102
  `guardRoute` takes per-reason overrides as a second argument. A bare string is shorthand for a redirect.
94
103
 
95
104
  ```ts
96
- beforeLoad: guardRoute(visibility, { unauthenticated: '/marketing/sign-up' }),
97
- beforeLoad: guardRoute(visibility, { forbidden: { strategy: 'throw' } }),
98
- beforeLoad: guardRoute(visibility, {
105
+ beforeLoad: guardRoute(pageSettings, { unauthenticated: '/marketing/sign-up' }),
106
+ beforeLoad: guardRoute(pageSettings, { forbidden: { strategy: 'throw' } }),
107
+ beforeLoad: guardRoute(pageSettings, {
99
108
  unauthenticated: { strategy: 'redirect', to: '/marketing/sign-up' },
100
109
  forbidden: { strategy: 'throw' },
101
110
  }),
@@ -142,15 +151,19 @@ That file covers every route at once; a route's own overrides win over it. A rul
142
151
 
143
152
  ```tsx
144
153
  import { createFileRoute } from '@tanstack/react-router'
145
- import { defineVisibility, guardRoute, isAccessError, isForbiddenError } from '@softr/sdk'
154
+ import { definePage, guardRoute, isAccessError, isForbiddenError, pageHead } from '@softr/sdk'
146
155
 
147
- const visibility = defineVisibility({
148
- userGroupTypes: ['LOGGED_IN_USERS'],
149
- customGroups: ['00000000-0000-0000-0000-00000000000a'],
156
+ const pageSettings = definePage({
157
+ visibility: {
158
+ userGroupTypes: ['LOGGED_IN_USERS'],
159
+ customGroups: ['00000000-0000-0000-0000-00000000000a'],
160
+ },
161
+ title: 'Billing',
150
162
  })
151
163
 
152
164
  export const Route = createFileRoute('/_app/billing')({
153
- beforeLoad: guardRoute(visibility),
165
+ beforeLoad: guardRoute(pageSettings),
166
+ head: pageHead(pageSettings),
154
167
  component: Billing,
155
168
  errorComponent: ({ error }: { error: unknown }) => {
156
169
  if (isForbiddenError(error)) return <UpgradePrompt />
@@ -166,25 +179,53 @@ Use the predicates: `isAccessError` for any of the three, and `isUnauthenticated
166
179
 
167
180
  ### Run the check and then keep going
168
181
 
169
- `guardRoute` covers almost everything. When a route needs its own logic afterwards, `assertRouteAccess(visibility, opts)` applies the same rule to the whole `beforeLoad` argument and throws the same access error, using the default behaviour for each reason. It takes no overrides.
182
+ `guardRoute` covers almost everything. When a route needs its own logic afterwards, `assertRouteAccess(pageSettings, opts)` applies the same rule to the whole `beforeLoad` argument and throws the same access error, using the default behaviour for each reason. It takes no overrides.
170
183
 
171
184
  It also narrows `opts.context.user` for the rest of the handler, where the set names one audience and no other: `User` under `['LOGGED_IN_USERS']`, `null` under `['NON_LOGGED_IN_USERS']`. A set naming both admits either kind of visitor, so it narrows to neither. `guardRoute` cannot, because it hands `beforeLoad` a function rather than running inside one.
172
185
 
173
- ```ts
174
- import { redirect } from '@tanstack/react-router'
175
- import { assertRouteAccess } from '@softr/sdk'
186
+ ```tsx
187
+ import { createFileRoute, redirect } from '@tanstack/react-router'
188
+ import { assertRouteAccess, definePage, pageHead } from '@softr/sdk'
189
+
190
+ const pageSettings = definePage({
191
+ visibility: { userGroupTypes: ['LOGGED_IN_USERS'] },
192
+ title: 'Reports',
193
+ })
176
194
 
177
- beforeLoad: (opts) => {
178
- assertRouteAccess(visibility, opts)
179
- if (opts.context.user.email.endsWith('@example.com')) throw redirect({ to: '/internal' })
180
- },
195
+ export const Route = createFileRoute('/_app/reports')({
196
+ beforeLoad: (opts) => {
197
+ assertRouteAccess(pageSettings, opts)
198
+ if (opts.context.user.email.endsWith('@example.com')) throw redirect({ to: '/internal' })
199
+ },
200
+ head: pageHead(pageSettings),
201
+ component: Reports,
202
+ })
181
203
  ```
182
204
 
183
205
  Take `opts` whole. A `context` destructured in the parameter list does not narrow.
184
206
 
185
- Reach for `assertRouteAccess` when the route wants the error thrown for it, `isAuthorized(visibility, context)` when it wants the same narrowing without a throw, and `checkAccess(visibility, context)` when it needs to branch on why. `checkAccess` returns `{ ok: true } | { ok: false, reason }` and throws nothing. All of them are synchronous and make no request.
207
+ `guardRoute` and `assertRouteAccess` throw router redirects, so they belong in a route and nowhere else. That is what `Route` in their names marks.
208
+
209
+ ### Check a rule without a throw
210
+
211
+ `isAuthorized(rule, context)` and `checkAccess(rule, context)` answer the same question and throw nothing, so they work anywhere: in a loader, a component or a server function. They take a rule from `defineVisibility`, not a page. Use `isAuthorized` for the same narrowing of `context.user` as `assertRouteAccess`, and `checkAccess` to branch on why: it returns `{ ok: true } | { ok: false, reason }`. All of them are synchronous and make no request.
212
+
213
+ ```tsx
214
+ import { defineVisibility, isAuthorized, useCurrentUser } from '@softr/sdk'
215
+
216
+ const staffOnly = defineVisibility({
217
+ userGroupTypes: ['LOGGED_IN_USERS'],
218
+ customGroups: ['00000000-0000-0000-0000-00000000000a'],
219
+ })
220
+
221
+ function StaffNote() {
222
+ const context = { user: useCurrentUser() }
223
+ if (!isAuthorized(staffOnly, context)) return null
224
+ return <p>Signed in as staff: {context.user.email}</p>
225
+ }
226
+ ```
186
227
 
187
- `guardRoute` and `assertRouteAccess` throw router redirects, so they belong in a route and nowhere else. That is what `Route` in their names marks. `isAuthorized` and `checkAccess` throw nothing and answer anywhere, in a loader, a component or a server function.
228
+ To show or hide a part of a page, `Audience` is simpler: see [region-visibility/SKILL.md](../region-visibility/SKILL.md).
188
229
 
189
230
  ## References
190
231
 
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.87-alpha.3
12
+ library_version: 0.0.87
13
13
  ---
14
14
 
15
15
  **Boundary.** `workflow` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineWorkflow` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -1,30 +0,0 @@
1
- import { z } from "zod";
2
- import * as _tanstack_react_start7 from "@tanstack/react-start";
3
-
4
- //#region src/agent/agent-fns.d.ts
5
-
6
- declare const agentSchema: z.ZodObject<{
7
- id: z.ZodString;
8
- title: z.ZodString;
9
- avatar: z.ZodOptional<z.ZodNullable<z.ZodString>>;
10
- thumbnail: z.ZodOptional<z.ZodNullable<z.ZodString>>;
11
- }, z.core.$strip>;
12
- /** An agent the visitor may chat with. */
13
- type Agent = z.infer<typeof agentSchema>;
14
- /**
15
- * The agents the visitor may chat with in this app. The builder attaches them
16
- * in Studio, and each one's visibility settings decide who sees it.
17
- */
18
- declare const listAgents: _tanstack_react_start7.OptionalFetcher<undefined, undefined, Promise<{
19
- id: string;
20
- title: string;
21
- avatar?: string | null | undefined;
22
- thumbnail?: string | null | undefined;
23
- }[]>>;
24
- /** One past chat with an agent. */
25
- type AgentChatSummary = {
26
- id: string;
27
- title: string;
28
- };
29
- //#endregion
30
- export { Agent, AgentChatSummary, listAgents };