@softr/sdk 1.4.0-se22529.1 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,10 +1,23 @@
1
1
  # @softr/sdk
2
2
 
3
+ ## 1.4.1
4
+
5
+ ### Patch Changes
6
+
7
+ - The `auth` skill's sign-out snippet redirects to `/login` with `signedOut: true`, so a login page that goes straight to single sign-on does not sign the visitor back in.
8
+ - The `record-queries`, `record-mutations`, `charts-and-metrics` and `current-user` skills teach `filter` on `defineQuery` and `defineMutation` as the way to keep each visitor to their own records, with `user.properties` for the Record ID of a link to Users, one action per role, and the errors a filter can throw.
9
+
3
10
  ## 1.4.0
4
11
 
5
12
  ### Minor Changes
6
13
 
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.
14
+ - 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()`.
15
+
16
+ ## 1.3.2
17
+
18
+ ### Patch Changes
19
+
20
+ - 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
21
 
9
22
  ## 1.3.1
10
23
 
@@ -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.1";
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.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: core
12
12
  library: softr-sdk
13
- library_version: 1.4.0
13
+ library_version: 1.4.1
14
14
  ---
15
15
 
16
16
  # Softr SDK core
@@ -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` |
@@ -13,7 +13,7 @@ description: >-
13
13
  metadata:
14
14
  type: sub-skill
15
15
  library: softr-sdk
16
- library_version: 1.4.0
16
+ library_version: 1.4.1
17
17
  ---
18
18
 
19
19
  **Boundary.** `ai` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineAiAction` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -102,7 +102,7 @@ const summarize = createServerFn({ method: 'POST' })
102
102
  })
103
103
  ```
104
104
 
105
- The record id comes from the browser, so it can name any deal. The read of `dealQuery` takes the table's scope, like every other read of the table. Where reps see only their own deals, a read without it briefs anyone on any deal: see [record-queries](../record-queries/SKILL.md#keep-each-visitor-to-their-own-records).
105
+ The record id comes from the browser, so it can name any deal. `dealQuery` takes the table's `filter`, like every other query of the table. Where reps see only their own deals, a query without it briefs anyone on any deal: see [record-queries](../record-queries/SKILL.md#keep-each-visitor-to-their-own-records).
106
106
 
107
107
  ## Extraction: an answer that is data
108
108
 
@@ -4,12 +4,13 @@ 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
12
- library_version: 1.4.0
13
+ library_version: 1.4.1
13
14
  ---
14
15
 
15
16
  **Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
@@ -337,11 +338,13 @@ Say "check your email" after `requestPasswordReset` either way, and never branch
337
338
  ```ts
338
339
  const signOut = createServerFn({ method: 'POST' }).handler(async () => {
339
340
  await auth.signOut()
340
- throw redirect({ to: '/login' })
341
+ throw redirect({ to: '/login', search: { signedOut: true } })
341
342
  })
342
343
  ```
343
344
 
344
- 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
+ `signedOut` keeps a login page that sends visitors straight to single sign-on from signing them back in at once: see [references/single-sign-on.md](./references/single-sign-on.md). If the redirect fails the type check with `'signedOut' does not exist`, the app's login route does not declare it yet. Add `signedOut: z.boolean().optional().catch(undefined)` to that route's `validateSearch`. Never remove `signedOut` from the redirect to pass the check.
346
+
347
+ 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. 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.
345
348
 
346
349
  ### Sign up, in two steps
347
350
 
@@ -3,13 +3,14 @@ name: charts-and-metrics
3
3
  description: >-
4
4
  Aggregate records in a server function: ds.chart with groupBy, metrics, where,
5
5
  orderBy and date buckets for chart rows, ds.metric for one number, and
6
- distinct values for filter controls, scoped to the records the visitor may
7
- read. Use for a chart, a stat tile or any counted, summed or averaged number,
8
- or when a chart comes back wrong. Single records are record-queries.
6
+ distinct values for filter controls, through the query's filter that keeps
7
+ them to the records the visitor may read. Use for a chart, a stat tile or any
8
+ counted, summed or averaged number, or when a chart comes back wrong. Single
9
+ records are record-queries.
9
10
  metadata:
10
11
  type: sub-skill
11
12
  library: softr-sdk
12
- library_version: 1.4.0
13
+ library_version: 1.4.1
13
14
  ---
14
15
 
15
16
  **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.
@@ -168,21 +169,26 @@ Each tile and panel is its own request, fired in parallel from one handler.
168
169
 
169
170
  ### Scope a figure like the records behind it
170
171
 
171
- A chart or a metric reads the same records as a list, so it takes the same scope as every read of the table (see [record-queries](../record-queries/SKILL.md#keep-each-visitor-to-their-own-records)). Without it, a "my revenue" tile adds up everyone's sales, and a chart grouped by a person shows the names of people the visitor may not see. Here a rep sees only their own sales, and `usersQuery` is the app's query on the Users table:
172
+ A chart or a metric reads through the `filter` of its query, like `ds.list` (see [record-queries](../record-queries/SKILL.md#keep-each-visitor-to-their-own-records)). So a figure over a filtered query counts only the records its visitor may read. A chart over another query of the same table needs the same filter. Without it, a "my revenue" tile adds up everyone's sales, and a chart grouped by a person shows the names of people the visitor may not see. Here a rep sees only their own sales. `rep` links to Users, and 'Rk2mVx9pQa4Lz7' is the Record ID field of the users table, declared in softr.json under `user.properties`:
172
173
 
173
174
  ```ts
174
- import { auth, ds } from '@softr/sdk/server'
175
-
176
- const myRevenue = createServerFn().handler(async ({ context }) => {
177
- const me = await auth.currentUserRow(context.user, usersQuery, 'email')
178
- if (me === null) return null
179
- const { value } = await ds
180
- .metric(sales, (q) => q.amount.sum)
181
- .where((q) => q.rep.isOneOf([me.id]))
175
+ const mySales = defineQuery({
176
+ id: 'mySales',
177
+ datasourceId: '00000000-0000-0000-0000-000000000000',
178
+ fields: { amount: 'Vk9cXm2pSz6Ld4', closedAt: 'Xp2dLh6vKz9Fa3' },
179
+ filterFields: { rep: 'Gq5wNt8rJy3Hb1' },
180
+ filter: { rep: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } },
181
+ permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
182
+ })
183
+
184
+ const myRevenue = createServerFn().handler(async () => {
185
+ const { value } = await ds.metric(mySales, (q) => q.amount.sum)
182
186
  return value
183
187
  })
184
188
  ```
185
189
 
190
+ A chart can group, aggregate and `where` only on `fields`, not on `filterFields`. For a visitor who is signed out, or who has no value for the token, the chart has no rows, a count is `0` and every other metric is `null`.
191
+
186
192
  ## Order of calls
187
193
 
188
194
  `groupBy` comes first and exactly once; a chart cannot be awaited before it. `metrics` follows, at most once, or not at all for distinct values. `where` can be chained anywhere, repeatedly, and calling it more than once ands the filters together. `orderBy` sorts by the chart's own keys, group and metric alike, and only sees the keys declared so far, so call it last.