@softr/sdk 1.4.0-se22529.1 → 1.4.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 CHANGED
@@ -4,7 +4,13 @@
4
4
 
5
5
  ### Minor Changes
6
6
 
7
- - `softr-sdk generate` no longer fails when a registered datasource's table no longer exists. It leaves that datasource out of `softr-env.d.ts` and the docs, and lists it under `datasourcesWithoutTable` in the `--json` report. Action: remove such a datasource from the app, or point it at another table.
7
+ - Add `useIdleTimeout()`, which signs the visitor out of this browser after the idle time set in Studio's "End session if idle", and sends them to `/`. Action: call it once in the root route's document component, next to `useUserTimezone()`.
8
+
9
+ ## 1.3.2
10
+
11
+ ### Patch Changes
12
+
13
+ - The current-user skill says `avatarUrl` is the only source of the visitor's photo: the picture column the app's users connection maps, set in Studio's users settings, never the visitor's row in the Users table.
8
14
 
9
15
  ## 1.3.1
10
16
 
@@ -0,0 +1,161 @@
1
+ //#region src/auth/idle-clock.ts
2
+ const KEY_LAST_ACTIVITY = "softr.idle.v1.lastActivity";
3
+ const KEY_SIGNED_OUT = "softr.idle.v1.signedOutAt";
4
+ /** Shared clock writes at most this often, so a mousemove is not a storage write in every tab. */
5
+ const WRITE_EVERY_MS = 5e3;
6
+ /**
7
+ * Activity events, listened for on the document in the capture phase. `scroll`
8
+ * does not bubble, and capture still sees events a handler stops.
9
+ */
10
+ const ACTIVITY_EVENTS = [
11
+ "pointerdown",
12
+ "pointermove",
13
+ "mousedown",
14
+ "mousemove",
15
+ "wheel",
16
+ "keydown",
17
+ "touchstart",
18
+ "touchmove",
19
+ "scroll",
20
+ "click",
21
+ "input",
22
+ "focusin",
23
+ "submit"
24
+ ];
25
+ /**
26
+ * Starts the idle clock and returns what stops it.
27
+ *
28
+ * Idle time is checked against the wall clock on a tick, not with one long
29
+ * timeout. Browsers delay timers in background tabs, and a laptop that wakes
30
+ * from sleep resumes a pending timeout with its full delay left.
31
+ *
32
+ * `signOut` clears this browser's session. It is the `endIdleSession` server
33
+ * function, passed in so a test can run the clock without a server.
34
+ *
35
+ * `sessionStartedAt` is when the visitor signed in. Activity saved in this
36
+ * browser before that belongs to an earlier session and is ignored, so a
37
+ * fresh sign-in is never signed straight out. `null` when it is not known.
38
+ */
39
+ function startIdleClock(idleMs, signOut, sessionStartedAt) {
40
+ const tickMs = Math.min(15e3, Math.max(2e3, Math.floor(idleMs / 30)));
41
+ const graceCapMs = idleMs;
42
+ let localLast = Date.now();
43
+ let lastWrite = 0;
44
+ let graceUsed = 0;
45
+ let ending = false;
46
+ let expired = false;
47
+ let finished = false;
48
+ const listeners = new AbortController();
49
+ function mark(now) {
50
+ if (now > localLast) localLast = now;
51
+ if (now - lastWrite >= WRITE_EVERY_MS) {
52
+ lastWrite = now;
53
+ writeStorage(KEY_LAST_ACTIVITY, String(now));
54
+ }
55
+ }
56
+ function onActivity() {
57
+ if (expired) return;
58
+ if (Date.now() - localLast >= idleMs) {
59
+ tick();
60
+ if (finished || expired) return;
61
+ }
62
+ graceUsed = 0;
63
+ mark(Date.now());
64
+ }
65
+ function stop() {
66
+ finished = true;
67
+ clearInterval(ticker);
68
+ listeners.abort();
69
+ }
70
+ function leave() {
71
+ if (finished) return;
72
+ stop();
73
+ window.location.replace("/");
74
+ }
75
+ async function endSession() {
76
+ if (ending) return;
77
+ ending = true;
78
+ try {
79
+ await signOut();
80
+ } catch {
81
+ ending = false;
82
+ return;
83
+ }
84
+ writeStorage(KEY_SIGNED_OUT, String(Date.now()));
85
+ removeStorage(KEY_LAST_ACTIVITY);
86
+ leave();
87
+ }
88
+ function tick() {
89
+ if (finished) return;
90
+ if (readStorage(KEY_SIGNED_OUT)) {
91
+ leave();
92
+ return;
93
+ }
94
+ if (!expired) {
95
+ const now = Date.now();
96
+ const shared = Number(readStorage(KEY_LAST_ACTIVITY));
97
+ const last = Number.isFinite(shared) && shared > localLast ? shared : localLast;
98
+ if (now - last < idleMs) return;
99
+ const active = document.activeElement;
100
+ if (active !== null && active.tagName === "IFRAME" && document.hasFocus() && graceUsed < graceCapMs && now - last < idleMs + graceCapMs) {
101
+ graceUsed += now - last;
102
+ mark(now);
103
+ return;
104
+ }
105
+ expired = true;
106
+ }
107
+ endSession();
108
+ }
109
+ removeStorage(KEY_SIGNED_OUT);
110
+ const saved = Number(readStorage(KEY_LAST_ACTIVITY));
111
+ if (sessionStartedAt !== null && Number.isFinite(saved) && saved >= sessionStartedAt && Date.now() - saved >= idleMs) expired = true;
112
+ else mark(Date.now());
113
+ const ticker = setInterval(tick, tickMs);
114
+ const { signal } = listeners;
115
+ for (const event of ACTIVITY_EVENTS) document.addEventListener(event, onActivity, {
116
+ capture: true,
117
+ passive: true,
118
+ signal
119
+ });
120
+ window.addEventListener("focus", onActivity, {
121
+ capture: true,
122
+ signal
123
+ });
124
+ document.addEventListener("visibilitychange", () => {
125
+ if (document.visibilityState !== "visible") return;
126
+ tick();
127
+ if (!finished && !expired) onActivity();
128
+ }, { signal });
129
+ window.addEventListener("storage", (event) => {
130
+ if (event.key === KEY_SIGNED_OUT && event.newValue) {
131
+ leave();
132
+ return;
133
+ }
134
+ if (event.key === KEY_LAST_ACTIVITY && event.newValue) {
135
+ const shared = Number(event.newValue);
136
+ if (Number.isFinite(shared) && shared > localLast) localLast = shared;
137
+ }
138
+ }, { signal });
139
+ if (expired) endSession();
140
+ return stop;
141
+ }
142
+ function readStorage(key) {
143
+ try {
144
+ return window.localStorage.getItem(key);
145
+ } catch {
146
+ return null;
147
+ }
148
+ }
149
+ function writeStorage(key, value) {
150
+ try {
151
+ window.localStorage.setItem(key, value);
152
+ } catch {}
153
+ }
154
+ function removeStorage(key) {
155
+ try {
156
+ window.localStorage.removeItem(key);
157
+ } catch {}
158
+ }
159
+
160
+ //#endregion
161
+ export { startIdleClock };
@@ -0,0 +1,17 @@
1
+ //#region src/auth/idle-timeout.d.ts
2
+ /**
3
+ * Signs the visitor out of this browser after the idle time set in Studio's
4
+ * "End session if idle", and sends them to `/`. Activity in any tab of the app
5
+ * keeps the session alive. Does nothing for anonymous visitors.
6
+ *
7
+ * Call it once, in the root route's document component.
8
+ *
9
+ * @example
10
+ * function RootDocument({ children }: { children: React.ReactNode }) {
11
+ * useIdleTimeout()
12
+ * // ...
13
+ * }
14
+ */
15
+ declare function useIdleTimeout(): void;
16
+ //#endregion
17
+ export { useIdleTimeout };
@@ -0,0 +1,85 @@
1
+ import { clearSession, readSessionToken } from "./session.js";
2
+ import { readSoftrContext } from "./context.js";
3
+ import { settings } from "./methods/settings.js";
4
+ import { useCurrentUser } from "./isomorphic.js";
5
+ import { startIdleClock } from "./idle-clock.js";
6
+ import { z } from "zod";
7
+ import { useEffect } from "react";
8
+ import { createServerFn } from "@tanstack/react-start";
9
+
10
+ //#region src/auth/idle-timeout.ts
11
+ /**
12
+ * The "End session if idle" setting from Studio, with when this session began.
13
+ * `null` when it does not apply: nobody is signed in, it is set to never, or
14
+ * this is not a production build. Preview runs on a dev server and is the
15
+ * owner's own session.
16
+ */
17
+ const readIdleTimeout = createServerFn({ method: "GET" }).handler(async () => {
18
+ if (process.env.NODE_ENV !== "production") return null;
19
+ if (readSoftrContext().user === null) return null;
20
+ const minutes = (await settings()).inactivityTimeoutMinutes;
21
+ if (minutes === null) return null;
22
+ return {
23
+ idleMs: minutes * 6e4,
24
+ sessionStartedAt: sessionStartedAt()
25
+ };
26
+ });
27
+ const tokenClaims = z.object({ iat: z.number() });
28
+ /** The platform signs its token with the sign-in time, in seconds. */
29
+ function sessionStartedAt() {
30
+ const payload = readSessionToken()?.split(".")[1];
31
+ if (payload === void 0) return null;
32
+ try {
33
+ const claims = tokenClaims.safeParse(JSON.parse(Buffer.from(payload, "base64url").toString()));
34
+ return claims.success ? claims.data.iat * 1e3 : null;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+ /**
40
+ * Signs this browser out and nothing else. Unlike `auth.signOut()`, the user's
41
+ * other devices stay signed in.
42
+ */
43
+ const endIdleSession = createServerFn({ method: "POST" }).handler(() => {
44
+ clearSession();
45
+ });
46
+ /**
47
+ * Signs the visitor out of this browser after the idle time set in Studio's
48
+ * "End session if idle", and sends them to `/`. Activity in any tab of the app
49
+ * keeps the session alive. Does nothing for anonymous visitors.
50
+ *
51
+ * Call it once, in the root route's document component.
52
+ *
53
+ * @example
54
+ * function RootDocument({ children }: { children: React.ReactNode }) {
55
+ * useIdleTimeout()
56
+ * // ...
57
+ * }
58
+ */
59
+ function useIdleTimeout() {
60
+ const signedIn = useCurrentUser() !== null;
61
+ useEffect(() => {
62
+ if (!signedIn) return;
63
+ let stop = null;
64
+ let retry;
65
+ let unmounted = false;
66
+ function read() {
67
+ readIdleTimeout().then((timeout) => {
68
+ if (unmounted || timeout === null) return;
69
+ stop = startIdleClock(timeout.idleMs, endIdleSession, timeout.sessionStartedAt);
70
+ }, () => {
71
+ if (!unmounted) retry = setTimeout(read, READ_RETRY_MS);
72
+ });
73
+ }
74
+ read();
75
+ return () => {
76
+ unmounted = true;
77
+ clearTimeout(retry);
78
+ stop?.();
79
+ };
80
+ }, [signedIn]);
81
+ }
82
+ const READ_RETRY_MS = 6e4;
83
+
84
+ //#endregion
85
+ export { useIdleTimeout };
package/dist/cli.js CHANGED
@@ -23,10 +23,7 @@ async function generate({ json }) {
23
23
  if (json) console.info = console.error;
24
24
  const input = await fetchSoftrEnvInput(metadataSourceFromEnv(), loadSoftrConfig(process.cwd()).user?.properties ?? {});
25
25
  writeFileSync(path.resolve(process.cwd(), OUTPUT), renderSoftrEnv(input, version), "utf8");
26
- const report = {
27
- ...writeDocs(input),
28
- datasourcesWithoutTable: input.datasourcesWithoutTable
29
- };
26
+ const report = writeDocs(input);
30
27
  report.docs.push({
31
28
  subject: "field shapes",
32
29
  path: FIELDS_OUTPUT,
@@ -77,7 +74,6 @@ function printReport(report) {
77
74
  console.log(`[softr] ${state} ${doc.path} for ${doc.subject}`);
78
75
  }
79
76
  for (const datasource of report.datasources) console.log(`[softr] wrote ${datasource.doc} for ${datasource.name} (${datasource.id})`);
80
- for (const datasource of report.datasourcesWithoutTable) console.log(`[softr] left out ${datasource.name} (${datasource.id}): its table no longer exists`);
81
77
  }
82
78
  const { positionals, values } = parseArgs({
83
79
  allowPositionals: true,
@@ -21,21 +21,15 @@ function metadataSourceFromEnv(env = process.env) {
21
21
  async function fetchSoftrEnvInput(source, aliases) {
22
22
  const { studioApiUrl, datasourceApiUrl, applicationId, token } = source;
23
23
  const [registered, userGroups] = await Promise.all([apiFetch(`${studioApiUrl}/v1/applications/${applicationId}/datasources`, token), apiFetch(`${studioApiUrl}/v1/applications/${applicationId}/access-control/user-groups`, token)]);
24
- const fetched = await Promise.all(registered.map(async ({ name, datasource }) => ({
25
- id: datasource.id,
26
- name,
27
- metadata: await fetchMetadata(`${datasourceApiUrl}/v1/datasource/vibe/studio/applications/${applicationId}/datasources/${datasource.id}/metadata`, token)
28
- })));
29
- const datasources = fetched.flatMap(({ id, name, metadata }) => metadata === null ? [] : [{
30
- ...metadata,
31
- id,
32
- tableId: metadata.id,
33
- name
34
- }]);
35
- const datasourcesWithoutTable = fetched.flatMap(({ id, name, metadata }) => metadata === null ? [{
36
- id,
37
- name
38
- }] : []);
24
+ const datasources = await Promise.all(registered.map(async ({ name, datasource }) => {
25
+ const metadata = await apiFetch(`${datasourceApiUrl}/v1/datasource/vibe/studio/applications/${applicationId}/datasources/${datasource.id}/metadata`, token);
26
+ return {
27
+ ...metadata,
28
+ id: datasource.id,
29
+ tableId: metadata.id,
30
+ name
31
+ };
32
+ }));
39
33
  let users = null;
40
34
  if (Object.keys(aliases).length > 0) {
41
35
  const metadata = await apiFetch(`${datasourceApiUrl}/v1/datasource/vibe/studio/applications/${applicationId}/user-connection/metadata`, token);
@@ -52,30 +46,16 @@ async function fetchSoftrEnvInput(source, aliases) {
52
46
  return {
53
47
  datasources,
54
48
  userGroups,
55
- users,
56
- datasourcesWithoutTable
49
+ users
57
50
  };
58
51
  }
59
- /**
60
- * Null when the datasource API answers 404: the registration points at a table that no longer
61
- * exists. One such registration must not stop the types of every other one.
62
- */
63
- async function fetchMetadata(url, token) {
64
- const response = await request(url, token);
65
- if (response.status === 404) return null;
66
- if (!response.ok) panic(`${url} answered ${response.status}`);
67
- return await response.json();
68
- }
69
52
  async function apiFetch(url, token) {
70
- const response = await request(url, token);
71
- if (!response.ok) panic(`${url} answered ${response.status}`);
72
- return await response.json();
73
- }
74
- function request(url, token) {
75
- return fetch(url, { headers: {
53
+ const response = await fetch(url, { headers: {
76
54
  accept: "application/json",
77
55
  Authorization: `Bearer ${token}`
78
56
  } }).catch(() => panic(`Could not reach ${url}`));
57
+ if (!response.ok) panic(`${url} answered ${response.status}`);
58
+ return await response.json();
79
59
  }
80
60
  function withoutTrailingSlash(url) {
81
61
  return url.replace(/\/+$/, "");
@@ -137,7 +137,7 @@ function chart(query) {
137
137
  };
138
138
  return builder;
139
139
  }
140
- function buildChartRequest(state, select, filterCriteria) {
140
+ function buildChartRequest(state, filterCriteria) {
141
141
  const groups = state.groups;
142
142
  assert(groups && groups.length > 0, "a chart needs at least one column to group by");
143
143
  const metrics = state.metrics ?? [];
@@ -192,13 +192,13 @@ function mapChartRows(columns, data) {
192
192
  }
193
193
  async function executeChart(query, state) {
194
194
  const target = resolveTarget(query, "read");
195
- const { actionId, select } = target;
195
+ const { actionId } = target;
196
196
  const filterCriteria = await readFilterCriteria(target, state.filters);
197
197
  if (filterCriteria === null) return {
198
198
  data: [],
199
199
  executionTimestamp: /* @__PURE__ */ new Date()
200
200
  };
201
- const { body, columns } = buildChartRequest(state, select, filterCriteria);
201
+ const { body, columns } = buildChartRequest(state, filterCriteria);
202
202
  const res = await fetch(`${dsUrl(actionId)}/chart/data`, {
203
203
  method: "POST",
204
204
  headers: {
package/dist/index.d.ts CHANGED
@@ -12,6 +12,7 @@ import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedErr
12
12
  import { toReturnPath } from "./auth/returnPath.js";
13
13
  import { SsoError, ssoSignInHref } from "./auth/sso.js";
14
14
  import { AuthOptions, AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
15
+ import { useIdleTimeout } from "./auth/idle-timeout.js";
15
16
  import { softrMcpMiddleware } from "./mcp.js";
16
17
  import { FieldShape, SoftrFieldRegistry, fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
17
18
  import { useOverrides } from "./core/use-overrides.js";
@@ -20,4 +21,4 @@ import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
20
21
  import { PushNotifications, PushPrompt, usePushNotifications } from "./push.js";
21
22
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
22
23
  import { Audience } from "./route/audience.js";
23
- export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, 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 PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, 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, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
24
+ export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, 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 PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, 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, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import { FormattedDate, FormattingScope, formatDate, formatDateTime, formatNumbe
9
9
  import { SoftrPwaHead, usePwaInstall } from "./pwa.js";
10
10
  import { usePushNotifications } from "./push.js";
11
11
  import { AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
12
+ import { useIdleTimeout } from "./auth/idle-timeout.js";
12
13
  import { softrMcpMiddleware } from "./mcp.js";
13
14
  import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
14
15
  import { useOverrides } from "./core/use-overrides.js";
@@ -16,4 +17,4 @@ import { useUserTimezone } from "./timezone.js";
16
17
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
17
18
  import { Audience } from "./route/audience.js";
18
19
 
19
- export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, 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, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
20
+ export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, 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, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.4.0-se22529.1";
2
+ var version = "1.4.0";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "1.4.0-se22529.1",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -33,7 +33,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
33
33
 
34
34
  | Import | Runs | Holds |
35
35
  | --- | --- | --- |
36
- | `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `defineAiAction`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `usePushNotifications`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
36
+ | `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `defineAiAction`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `useIdleTimeout`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `usePushNotifications`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
37
37
  | `@softr/sdk/server` | Server only | `ds`, `auth`, `workflow`, `integration`, `ai` |
38
38
  | `@softr/sdk/client` | Browser only | `useFileUpload` |
39
39
  | `@softr/sdk/vite` | Build | `softr()`, already in `vite.config.ts` |
@@ -4,8 +4,9 @@ description: >-
4
4
  Sign a visitor in, out or up from a server function with auth from
5
5
  @softr/sdk/server: password, code, Google and magic link, sign-up and its
6
6
  confirmation, the emailed-code and authenticator-app steps, password reset
7
- links, updateProfile, and getAuthSettings and useAuthSettings for the methods
8
- the app enables. Covers the Result shape, its error codes, and toReturnPath.
7
+ links, updateProfile, getAuthSettings and useAuthSettings, and
8
+ useIdleTimeout for "End session if idle". Covers the Result shape, its error
9
+ codes, and toReturnPath.
9
10
  metadata:
10
11
  type: sub-skill
11
12
  library: softr-sdk
@@ -343,6 +344,8 @@ const signOut = createServerFn({ method: 'POST' }).handler(async () => {
343
344
 
344
345
  It returns nothing and has no failure the visitor can act on, so send them somewhere and let the redirect re-resolve the context. It ends every session that visitor has in this app, on every device, so a "sign out of this device only" button is not something you can build on it.
345
346
 
347
+ For Studio's "End session if idle", call `useIdleTimeout()` from `@softr/sdk` once in `RootDocument` in `src/routes/__root.tsx`, next to `useUserTimezone()`. It signs out this browser only and sends the visitor to `/`. Don't build your own idle timer.
348
+
346
349
  ### Sign up, in two steps
347
350
 
348
351
  ```ts
@@ -36,6 +36,8 @@ type User = {
36
36
  }
37
37
  ```
38
38
 
39
+ `avatarUrl` is the visitor's picture in the column the app's users connection maps, and the only place their photo comes from. When it is `null`, show initials, and never read the visitor's row in the Users table for a photo instead. `null` is also what a visitor without a photo gets, so it does not say whether a column is mapped; the user maps one in Studio, in the app's users settings, and every place that shows the visitor follows.
40
+
39
41
  ## Core Patterns
40
42
 
41
43
  ### In a component: `useCurrentUser()`