@softr/sdk 1.13.2-alpha.0 → 1.14.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
@@ -1,10 +1,16 @@
1
1
  # @softr/sdk
2
2
 
3
+ ## 1.14.0
4
+
5
+ ### Minor Changes
6
+
7
+ - `ds.export` reads every record that matches a query, with the same `where` and `orderBy` as `ds.list`, for a file the visitor downloads. It returns `{ records }`. Each call to the datasource reads 1,000 records, and `.pageSize()` sets fewer for a datasource whose API refuses pages that big. `ds.list` still reads at most 100 records a call. The record-queries skill keeps a large table on the server: a list reads one page, and figures come from `ds.metric` and `ds.chart`.
8
+
3
9
  ## 1.13.2
4
10
 
5
11
  ### Patch Changes
6
12
 
7
- - A page that a route guard refuses with the `throw` strategy (`guardRoute`, `assertRouteAccess`) answers 403 instead of 500 when `softrAuthMiddleware` is registered, with an `x-softr-access-denied` header that names the reason. The page still shows the route's `errorComponent`. The guard no longer logs the refusal as an error, on the server or in the browser. No action is needed.
13
+ - A `ds.list` builder reads again after `where`, `orderBy`, `limit` or `offset` changes it. Before, it answered the first page it had read, so a loop that paged with one builder (`await list.offset(page.nextOffset)`) never ended and stopped the app's server. Awaiting an unchanged builder two times still reads one time. No action is needed.
8
14
 
9
15
  ## 1.13.1
10
16
 
@@ -21,7 +21,7 @@ import * as _tanstack_react_start0 from "@tanstack/react-start";
21
21
  * requestMiddleware: [softrAuthMiddleware()],
22
22
  * }))
23
23
  */
24
- declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
24
+ declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
25
25
  user: User | null;
26
26
  permissions: {
27
27
  datasources: {};
@@ -14,7 +14,6 @@ import { pushMiddleware } from "../push.js";
14
14
  import { faviconMiddleware } from "../favicon.js";
15
15
  import { embeddingMiddleware } from "../embedding.js";
16
16
  import { appIdentityMiddleware } from "../app-identity.js";
17
- import { accessDeniedStatusMiddleware } from "../route/access-denied-status.js";
18
17
  import { getRequestHeader } from "@tanstack/react-start/server";
19
18
  import { createContext, useContext } from "react";
20
19
  import { createMiddleware, createServerFn } from "@tanstack/react-start";
@@ -44,8 +43,7 @@ function softrAuthMiddleware() {
44
43
  pwaMiddleware(),
45
44
  pushMiddleware(),
46
45
  faviconMiddleware(),
47
- ssoMiddleware(),
48
- accessDeniedStatusMiddleware()
46
+ ssoMiddleware()
49
47
  ]).server(async ({ next }) => {
50
48
  async function getSession() {
51
49
  const token = readSessionToken();
@@ -1,4 +1,4 @@
1
- import { createRecord, deleteRecord, getRecord, listRecords, updateRecord } from "./record.js";
1
+ import { createRecord, deleteRecord, exportRecords, getRecord, listRecords, updateRecord } from "./record.js";
2
2
  import { listChoices, listOptions } from "../core/options.js";
3
3
  import { chart, metric } from "./chart.js";
4
4
  import "@tanstack/react-start/server-only";
@@ -6,6 +6,7 @@ import "@tanstack/react-start/server-only";
6
6
  //#region src/datasource/datasource.d.ts
7
7
  declare const ds: {
8
8
  list: typeof listRecords;
9
+ export: typeof exportRecords;
9
10
  get: typeof getRecord;
10
11
  create: typeof createRecord;
11
12
  update: typeof updateRecord;
@@ -1,4 +1,4 @@
1
- import { createRecord, deleteRecord, getRecord, listRecords, updateRecord } from "./record.js";
1
+ import { createRecord, deleteRecord, exportRecords, getRecord, listRecords, updateRecord } from "./record.js";
2
2
  import { chart, metric } from "./chart.js";
3
3
  import { listChoices, listOptions } from "../core/options.js";
4
4
  import "@tanstack/react-start/server-only";
@@ -6,6 +6,7 @@ import "@tanstack/react-start/server-only";
6
6
  //#region src/datasource/datasource.ts
7
7
  const ds = {
8
8
  list: listRecords,
9
+ export: exportRecords,
9
10
  get: getRecord,
10
11
  create: createRecord,
11
12
  update: updateRecord,
@@ -46,6 +46,34 @@ type ListBuilder<TShape extends ReadShape> = {
46
46
  */
47
47
  offset(offset: number | string | null): ListBuilder<TShape>;
48
48
  } & Promise<ListResult<SoftrRecord<ActionRecord<TShape>>>>;
49
+ /**
50
+ * Every matching record, read when awaited. There is no `limit` or `offset`: it reads page
51
+ * after page until the last one.
52
+ */
53
+ type ExportBuilder<TShape extends ReadShape> = {
54
+ /**
55
+ * Narrows down which records come back.
56
+ *
57
+ * @example
58
+ * ds.export(posts).where((q) => q.title.contains("cafe"))
59
+ */
60
+ where(build: WhereCallback<TShape>): ExportBuilder<TShape>;
61
+ /**
62
+ * Sorts the records.
63
+ *
64
+ * @example
65
+ * ds.export(posts).orderBy((q) => [q.views.desc, q.publishedAt.asc])
66
+ */
67
+ orderBy(build: OrderByCallback<TShape>): ExportBuilder<TShape>;
68
+ /**
69
+ * How many records each call to the datasource reads, from 1 to 1000. Defaults to 1000.
70
+ * Set it lower for a datasource whose API refuses pages that big.
71
+ *
72
+ * @example
73
+ * ds.export(posts).pageSize(200)
74
+ */
75
+ pageSize(count: number): ExportBuilder<TShape>;
76
+ } & Promise<ExportResult<SoftrRecord<ActionRecord<TShape>>>>;
49
77
  /**
50
78
  * One record, fetched when awaited. There is no `orderBy`, `limit` or `offset`. The record is
51
79
  * picked by id, so there is nothing to order or page through.
@@ -75,6 +103,9 @@ interface ListResult<TRecord extends SoftrRecord = SoftrRecord> {
75
103
  /** A row position, or the datasource's own cursor as a string. `null` on the last page. */
76
104
  nextOffset: number | string | null;
77
105
  }
106
+ interface ExportResult<TRecord extends SoftrRecord = SoftrRecord> {
107
+ records: TRecord[];
108
+ }
78
109
  type GetRecord<TShape extends ReadShape> = SoftrRecord<ActionRecord<TShape>> | null;
79
110
  /**
80
111
  * Queries a list of records from the datasource.
@@ -87,6 +118,18 @@ type GetRecord<TShape extends ReadShape> = SoftrRecord<ActionRecord<TShape>> | n
87
118
  * .limit(50)
88
119
  */
89
120
  declare function listRecords<TShape extends ReadShape>(query: DatasourceAction<TShape>): ListBuilder<TShape>;
121
+ /**
122
+ * Reads every record that matches, for a download or a copy the visitor asks for: a CSV, a
123
+ * JSON file, a spreadsheet. It reads page after page, so it takes as long as all those pages.
124
+ * To show records on a page, use `ds.list`, which reads one page.
125
+ *
126
+ * @example
127
+ * const { records } = await ds
128
+ * .export(posts)
129
+ * .where((q) => q.published.is(true))
130
+ * .orderBy((q) => q.publishedAt.desc)
131
+ */
132
+ declare function exportRecords<TShape extends ReadShape>(query: DatasourceAction<TShape>): ExportBuilder<TShape>;
90
133
  /**
91
134
  * Gets a single record by ID.
92
135
  *
@@ -143,4 +186,4 @@ declare function deleteRecord<TShape extends ActionShape & {
143
186
  id: string;
144
187
  }): Promise<void>;
145
188
  //#endregion
146
- export { GetRecord, WhereCallback, createRecord, deleteRecord, getRecord, listRecords, updateRecord };
189
+ export { GetRecord, WhereCallback, createRecord, deleteRecord, exportRecords, getRecord, listRecords, updateRecord };
@@ -13,6 +13,7 @@ import { getRequestHeader, getRequestUrl } from "@tanstack/react-start/server";
13
13
 
14
14
  //#region src/datasource/record.ts
15
15
  const MAX_RECORD_COUNT = 100;
16
+ const MAX_EXPORT_PAGE_SIZE = 1e3;
16
17
  const dsUrl = (actionId) => {
17
18
  const applicationId = process.env.SOFTR_APPLICATION_ID;
18
19
  if (!applicationId) panic("SOFTR_APPLICATION_ID is not set.");
@@ -55,24 +56,28 @@ function listRecords(query) {
55
56
  orderBy: []
56
57
  };
57
58
  let page;
58
- const run = () => page ??= executeList(query, args);
59
+ const run = () => page ??= executeList(query, args, Math.min(args.limit ?? 20, MAX_RECORD_COUNT), "list");
59
60
  const builder = {
60
61
  [Symbol.toStringTag]: "RecordListing",
61
62
  where(build) {
62
63
  args.filters.push(build(makeFieldSet(aliases)));
64
+ page = void 0;
63
65
  return builder;
64
66
  },
65
67
  orderBy(build) {
66
68
  const sorting = build(makeSortSet(aliases));
67
69
  args.orderBy.push(...Array.isArray(sorting) ? sorting : [sorting]);
70
+ page = void 0;
68
71
  return builder;
69
72
  },
70
73
  limit(count) {
71
74
  args.limit = count;
75
+ page = void 0;
72
76
  return builder;
73
77
  },
74
78
  offset(offset) {
75
79
  args.offset = offset;
80
+ page = void 0;
76
81
  return builder;
77
82
  },
78
83
  then(onfulfilled, onrejected) {
@@ -87,10 +92,74 @@ function listRecords(query) {
87
92
  };
88
93
  return builder;
89
94
  }
90
- async function executeList(query, args) {
95
+ /**
96
+ * Reads every record that matches, for a download or a copy the visitor asks for: a CSV, a
97
+ * JSON file, a spreadsheet. It reads page after page, so it takes as long as all those pages.
98
+ * To show records on a page, use `ds.list`, which reads one page.
99
+ *
100
+ * @example
101
+ * const { records } = await ds
102
+ * .export(posts)
103
+ * .where((q) => q.published.is(true))
104
+ * .orderBy((q) => q.publishedAt.desc)
105
+ */
106
+ function exportRecords(query) {
107
+ const aliases = Object.keys(resolveTarget(query, "read").select);
108
+ const args = {
109
+ filters: [],
110
+ orderBy: []
111
+ };
112
+ let pageSize = MAX_EXPORT_PAGE_SIZE;
113
+ let result;
114
+ const run = () => result ??= executeExport(query, args, pageSize);
115
+ const builder = {
116
+ [Symbol.toStringTag]: "RecordExport",
117
+ where(build) {
118
+ args.filters.push(build(makeFieldSet(aliases)));
119
+ result = void 0;
120
+ return builder;
121
+ },
122
+ orderBy(build) {
123
+ const sorting = build(makeSortSet(aliases));
124
+ args.orderBy.push(...Array.isArray(sorting) ? sorting : [sorting]);
125
+ result = void 0;
126
+ return builder;
127
+ },
128
+ pageSize(count) {
129
+ assert(Number.isInteger(count) && count >= 1 && count <= MAX_EXPORT_PAGE_SIZE, `pageSize takes a whole number from 1 to ${MAX_EXPORT_PAGE_SIZE}, got ${count}`);
130
+ pageSize = count;
131
+ result = void 0;
132
+ return builder;
133
+ },
134
+ then(onfulfilled, onrejected) {
135
+ return run().then(onfulfilled, onrejected);
136
+ },
137
+ catch(onrejected) {
138
+ return run().catch(onrejected);
139
+ },
140
+ finally(onfinally) {
141
+ return run().finally(onfinally);
142
+ }
143
+ };
144
+ return builder;
145
+ }
146
+ async function executeExport(query, args, pageSize) {
147
+ const records = [];
148
+ let offset = null;
149
+ do {
150
+ const page = await executeList(query, {
151
+ ...args,
152
+ offset
153
+ }, pageSize, "export");
154
+ records.push(...page.records);
155
+ if (page.nextOffset !== null && page.nextOffset === offset) throw new Error(`datasource export failed for "${resolveTarget(query, "read").actionId}": the datasource answered the same offset twice`);
156
+ offset = page.records.length > 0 ? page.nextOffset : null;
157
+ } while (offset !== null);
158
+ return { records };
159
+ }
160
+ async function executeList(query, args, count, operation) {
91
161
  const target = resolveTarget(query, "read");
92
162
  const { actionId, select } = target;
93
- const count = Math.min(args.limit ?? 20, MAX_RECORD_COUNT);
94
163
  const offset = args.offset ?? null;
95
164
  const filterCriteria = await readFilterCriteria(target, args.filters);
96
165
  if (filterCriteria === null) return {
@@ -117,7 +186,7 @@ async function executeList(query, args) {
117
186
  }
118
187
  })
119
188
  });
120
- if (!res.ok) throw new Error(`datasource list failed for "${actionId}": ${await describeFailure(res)}`);
189
+ if (!res.ok) throw new Error(`datasource ${operation} failed for "${actionId}": ${await describeFailure(res)}`);
121
190
  const payload = await res.json();
122
191
  let nextOffset = null;
123
192
  if (typeof payload.offset === "string" && !/^\d*$/.test(payload.offset)) {
@@ -390,4 +459,4 @@ function dealiasData(data, select) {
390
459
  }
391
460
 
392
461
  //#endregion
393
- export { createRecord, deleteRecord, describeFailure, dsUrl, getRecord, listRecords, readFilterCriteria, refererHeader, resolveTarget, updateRecord };
462
+ export { createRecord, deleteRecord, describeFailure, dsUrl, exportRecords, getRecord, listRecords, readFilterCriteria, refererHeader, resolveTarget, updateRecord };
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import * as react2 from "react";
2
+ import * as react0 from "react";
3
3
  import { ReactNode } from "react";
4
4
 
5
5
  //#region src/formatting.d.ts
@@ -96,7 +96,7 @@ declare function FormattingScope({
96
96
  /** A BCP 47 locale, such as `de-DE`. It drops the app's fixed date format inside the scope. */
97
97
  locale?: string;
98
98
  children?: ReactNode;
99
- }): react2.FunctionComponentElement<react2.ProviderProps<Scope>>;
99
+ }): react0.FunctionComponentElement<react0.ProviderProps<Scope>>;
100
100
  /**
101
101
  * A date in the app's format, in a `<span>`, safe to render on the server. A
102
102
  * timestamp whose zone is not known yet renders `fallback` until the browser
@@ -118,7 +118,7 @@ declare function FormattedDate({
118
118
  time?: boolean;
119
119
  /** What renders while the visitor's zone is unknown. */
120
120
  fallback?: ReactNode;
121
- }): react2.FunctionComponentElement<react2.FragmentProps> | react2.DetailedReactHTMLElement<{
121
+ }): react0.FunctionComponentElement<react0.FragmentProps> | react0.DetailedReactHTMLElement<{
122
122
  suppressHydrationWarning: true;
123
123
  }, HTMLElement> | null;
124
124
  //#endregion
package/dist/mcp.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DatasourceAction } from "./action.js";
2
- import * as _tanstack_react_start11 from "@tanstack/react-start";
2
+ import * as _tanstack_react_start10 from "@tanstack/react-start";
3
3
 
4
4
  //#region src/mcp.d.ts
5
5
 
@@ -31,6 +31,6 @@ type SoftrMcpOptions = {
31
31
  * ],
32
32
  * }))
33
33
  */
34
- declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start11.RequestMiddlewareAfterServer<{}, undefined, undefined>;
34
+ declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start10.RequestMiddlewareAfterServer<{}, undefined, undefined>;
35
35
  //#endregion
36
36
  export { softrMcpMiddleware };
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.13.2-alpha.0";
2
+ var version = "1.14.0";
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 react5 from "react";
2
2
  import "@tanstack/react-start";
3
3
 
4
4
  //#region src/pwa.d.ts
@@ -24,7 +24,7 @@ import "@tanstack/react-start";
24
24
  * )
25
25
  * }
26
26
  */
27
- declare function SoftrPwaHead(): react0.FunctionComponentElement<react0.FragmentProps>;
27
+ declare function SoftrPwaHead(): react5.FunctionComponentElement<react5.FragmentProps>;
28
28
  type PwaPlatform = "ios" | "android" | "desktop";
29
29
  type InstallChoice = "accepted" | "dismissed";
30
30
  type PwaInstall = {
@@ -1,22 +1,10 @@
1
1
  import { panic } from "../assertions.js";
2
+ import { logger } from "../logger.js";
2
3
  import { softrConfig } from "../softr-config.js";
3
4
  import { ACCESS_REASONS, checkRule } from "./visibility.js";
4
- import { setResponseHeader } from "@tanstack/react-start/server";
5
- import { createIsomorphicFn } from "@tanstack/react-start";
6
5
  import { redirect } from "@tanstack/react-router";
7
6
 
8
7
  //#region src/route/route.ts
9
- /**
10
- * Marks the answer of a page a guard refused by throwing, with the reason as its
11
- * value. The pod reads it to tell a refusal from a server error, so its name and
12
- * values stay as they are.
13
- */
14
- const ACCESS_DENIED_HEADER = "x-softr-access-denied";
15
- const markRefused = createIsomorphicFn().server((reason) => {
16
- try {
17
- setResponseHeader(ACCESS_DENIED_HEADER, reason);
18
- } catch {}
19
- });
20
8
  function isAccessReason(value) {
21
9
  return ACCESS_REASONS.some((reason) => reason === value);
22
10
  }
@@ -74,7 +62,7 @@ function thrownFor(reason, overrides, location) {
74
62
  type: "access_error",
75
63
  reason
76
64
  };
77
- markRefused(reason);
65
+ logger.error(/* @__PURE__ */ new Error(`Access to ${location.href} denied: ${ACCESS_DENIED_MESSAGES[reason]}`));
78
66
  return error;
79
67
  }
80
68
  function ruleOf(page) {
@@ -116,4 +104,4 @@ function assertRouteAccess(page, opts) {
116
104
  }
117
105
 
118
106
  //#endregion
119
- export { ACCESS_DENIED_HEADER, ACCESS_DENIED_MESSAGES, assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError };
107
+ export { ACCESS_DENIED_MESSAGES, assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError };
package/package.json CHANGED
@@ -1,42 +1,17 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "1.13.2-alpha.0",
3
+ "version": "1.14.0",
4
4
  "type": "module",
5
5
  "exports": {
6
- ".": {
7
- "types": "./dist/index.d.ts",
8
- "import": "./dist/index.js"
9
- },
10
- "./client": {
11
- "types": "./dist/client.d.ts",
12
- "import": "./dist/client.js"
13
- },
14
- "./server": {
15
- "types": "./dist/server.d.ts",
16
- "import": "./dist/server.js"
17
- },
18
- "./vite": {
19
- "types": "./dist/vite.d.ts",
20
- "import": "./dist/vite.js"
21
- },
22
- "./logo-icon": {
23
- "types": "./dist/logo-icon.d.ts",
24
- "import": "./dist/logo-icon.js"
25
- }
26
- },
27
- "bin": {
28
- "softr-sdk": "./dist/cli.js"
29
- },
30
- "files": [
31
- "dist",
32
- "schema",
33
- "skills",
34
- "!skills/_artifacts",
35
- "CHANGELOG.md"
36
- ],
37
- "publishConfig": {
38
- "access": "public"
39
- },
6
+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
7
+ "./client": { "types": "./dist/client.d.ts", "import": "./dist/client.js" },
8
+ "./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" },
9
+ "./vite": { "types": "./dist/vite.d.ts", "import": "./dist/vite.js" },
10
+ "./logo-icon": { "types": "./dist/logo-icon.d.ts", "import": "./dist/logo-icon.js" }
11
+ },
12
+ "bin": { "softr-sdk": "./dist/cli.js" },
13
+ "files": ["dist", "schema", "skills", "!skills/_artifacts", "CHANGELOG.md"],
14
+ "publishConfig": { "access": "public" },
40
15
  "scripts": {
41
16
  "build": "tsdown",
42
17
  "test": "node --import ./src/test-utils/setup.ts --test",
@@ -68,9 +43,7 @@
68
43
  "optional": true
69
44
  }
70
45
  },
71
- "keywords": [
72
- "tanstack-intent"
73
- ],
46
+ "keywords": ["tanstack-intent"],
74
47
  "intent": {
75
48
  "version": 1,
76
49
  "repo": "@softr/sdk",
@@ -11,7 +11,7 @@ description: >-
11
11
  metadata:
12
12
  type: core
13
13
  library: softr-sdk
14
- library_version: 1.13.2
14
+ library_version: 1.14.0
15
15
  ---
16
16
 
17
17
  # Softr SDK core
@@ -13,7 +13,7 @@ description: >-
13
13
  metadata:
14
14
  type: sub-skill
15
15
  library: softr-sdk
16
- library_version: 1.13.2
16
+ library_version: 1.14.0
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.
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.13.2
13
+ library_version: 1.14.0
14
14
  ---
15
15
 
16
16
  **Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.13.2
13
+ library_version: 1.14.0
14
14
  ---
15
15
 
16
16
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A helper that calls `ds` outside a handler goes in `createServerOnlyFn` from `@tanstack/react-start` (the `record-queries` boundary). `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -19,6 +19,8 @@ metadata:
19
19
 
20
20
  `ds.chart` groups records and aggregates each group into one row: the data behind a bar chart, a line, a pie. `ds.metric` aggregates everything into one value: the number on a stat tile. Both live on `@softr/sdk/server` and run inside a `createServerFn` handler, and both take the same query `ds.list` takes, with the same `where` filters.
21
21
 
22
+ A figure over a list's filters, such as the count and the total above a filtered table, is a `ds.metric` or a `ds.chart` with the list's `where`. It covers every matching record in one request. Records loaded with `ds.list` come 100 at a time, so math over them covers only the pages read. `ds.export` reads every record, but it is for downloads and takes seconds on a large table.
23
+
22
24
  ## Setup
23
25
 
24
26
  ```ts
@@ -11,7 +11,7 @@ description: >-
11
11
  metadata:
12
12
  type: sub-skill
13
13
  library: softr-sdk
14
- library_version: 1.13.2
14
+ library_version: 1.14.0
15
15
  ---
16
16
 
17
17
  # The current user
@@ -12,7 +12,7 @@ description: >-
12
12
  metadata:
13
13
  type: sub-skill
14
14
  library: softr-sdk
15
- library_version: 1.13.2
15
+ library_version: 1.14.0
16
16
  ---
17
17
 
18
18
  **Boundary.** `email` and `EmailError` live on `@softr/sdk/server` and run only inside a `createServerFn` handler — importing them into a component fails the build. `defineEmailAction` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 1.13.2
10
+ library_version: 1.14.0
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: 1.13.2
11
+ library_version: 1.14.0
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: 1.13.2
10
+ library_version: 1.14.0
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: 1.13.2
12
+ library_version: 1.14.0
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: 1.13.2
12
+ library_version: 1.14.0
13
13
  ---
14
14
 
15
15
  # Push notifications
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.13.2
13
+ library_version: 1.14.0
14
14
  ---
15
15
 
16
16
  # Installing the app
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.13.2
13
+ library_version: 1.14.0
14
14
  ---
15
15
 
16
16
  **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.
@@ -1,17 +1,17 @@
1
1
  ---
2
2
  name: record-queries
3
3
  description: >-
4
- Fetch records with defineQuery, ds.list and ds.get: where and orderBy, field
5
- names of your own choosing, pagination and its limits, and the filter that
6
- keeps each visitor to their own records, with one query per role for the
7
- fields that role may see. Use to put records on a page or fill a dropdown, to
8
- write any server function that reads a table, or when a read comes back empty,
9
- unsorted or missing a field. Writes are record-mutations; totals and chart
10
- rows are charts-and-metrics.
4
+ Fetch records with defineQuery, ds.list, ds.get and ds.export: where and
5
+ orderBy, field names of your own choosing, pagination and its limits, and the
6
+ filter that keeps each visitor to their own records, with one query per role
7
+ for the fields that role may see. Use to put records on a page, fill a
8
+ dropdown or export them to a file, to write any server function that reads a
9
+ table, or when a read comes back empty, unsorted or missing a field. Writes
10
+ are record-mutations; totals and chart rows are charts-and-metrics.
11
11
  metadata:
12
12
  type: sub-skill
13
13
  library: softr-sdk
14
- library_version: 1.13.2
14
+ library_version: 1.14.0
15
15
  ---
16
16
 
17
17
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A route `loader` also runs in the browser, so it calls a server function, never `ds`. A helper that calls `ds` outside a handler, in this file or in another one, goes in `createServerOnlyFn` from `@tanstack/react-start`, or inside the handler. An exported helper without it keeps the server-only import in the browser bundle, and every page stops loading until it moves. Do not make such a helper a server function when it takes an id: any visitor can call a server function with any id. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -127,8 +127,64 @@ if (first.nextOffset !== null) {
127
127
 
128
128
  `nextOffset` is `null` when there are no more pages. `total` is the count of all matching records, not the count returned.
129
129
 
130
+ To read every matching record, use `ds.export` (see [Export records](#export-records)), not a loop over `ds.list` pages.
131
+
130
132
  Pass `nextOffset` back unchanged, and type whatever carries it (a validator, a state, a search param) as `number | string | null`. Most datasources answer a number, the row position, and for those a page can also be reached directly, `.offset((page - 1) * PAGE_SIZE)`. Some datasources (BigQuery is one) answer a string, their own cursor: it reads only the page after the one that answered it, with the same `where` and `orderBy`, and a read with a computed number fails. For those, build "Load more" or next-page paging from `nextOffset`, never numbered pages.
131
133
 
134
+ ### Keep a large table on the server
135
+
136
+ A read returns at most 100 records, and a cursor datasource reads a page only after the one before it. A loop over every page makes one request per 100 records, one after another, and the page shows nothing until the last one answers. On a table of thousands of records, that is a long wait each time the page opens.
137
+
138
+ So a list or table page reads one page at a time:
139
+
140
+ - Search, filters and sort go into `where` and `orderBy`, and the server function takes them as input. A change reads the first page again.
141
+ - "Load more" or a next-page button reads the next page from `nextOffset`.
142
+ - Counts, totals, averages, group tables and summary strips come from `ds.metric` and `ds.chart` with the same `where` (see [charts-and-metrics](../charts-and-metrics/SKILL.md)), never from math over loaded records.
143
+ - Every matching record is for a download the visitor starts, and comes from `ds.export` (see [Export records](#export-records)). Never read every record to show a page, unless the user asks for it again (see below).
144
+
145
+ ```ts
146
+ // Wrong: every page before anything shows, then filters and figures in the browser.
147
+ let offset: number | string | null = null
148
+ do {
149
+ const page = await ds.list(customers).limit(100).offset(offset)
150
+ rows.push(...page.records)
151
+ offset = page.nextOffset
152
+ } while (offset !== null)
153
+
154
+ // Right: one page of the records that match the visitor's filters.
155
+ const listCustomers = createServerFn()
156
+ .validator(z.object({ search: z.string().optional(), offset: z.union([z.number(), z.string()]).nullable() }))
157
+ .handler(async ({ data }) => {
158
+ const { search, offset } = data
159
+ let list = ds.list(customers).orderBy((q) => q.signedUpAt.desc).limit(50).offset(offset)
160
+ if (search) list = list.where((q) => q.name.contains(search))
161
+ return await list
162
+ })
163
+ ```
164
+
165
+ A request to load the whole table into the browser, so that filters feel instant, asks for a fast page. Build it as above, and tell the user in your reply why the reads stay on the server. When they ask for it again after that reply, build it as they ask: the page reads its records with `ds.export`. Say in your reply what it costs: the page reads every record each time it opens, so it opens more slowly as the table grows.
166
+
167
+ ### Export records
168
+
169
+ `ds.export` reads every record that matches, for a file the visitor downloads or copies: a CSV, a JSON file, a spreadsheet. It takes the same `where` and `orderBy` as `ds.list`, and no `limit` or `offset`. Give it the list's filters, so the file holds what the visitor sees:
170
+
171
+ ```ts
172
+ const exportCustomers = createServerFn()
173
+ .validator(z.object({ search: z.string().optional() }))
174
+ .handler(async ({ data }) => {
175
+ const { search } = data
176
+ let rows = ds.export(customers).orderBy((q) => q.signedUpAt.desc)
177
+ if (search) rows = rows.where((q) => q.name.contains(search))
178
+ return await rows
179
+ })
180
+ ```
181
+
182
+ - It returns `{ records }`, every matching record. Each record has the same shape as a `ds.list` record.
183
+ - A large table takes seconds. Call it from the button that starts the download, and show that the file is being prepared. Never call it from a loader or when a page opens, unless the user asks again for the whole table in the browser (see above).
184
+ - Each call to the datasource reads 1,000 records. When the datasource's API refuses pages that big, or the user names a page size, set it with `.pageSize(200)`, from 1 to 1,000.
185
+ - Build the file from `records`, in the format the user asked for.
186
+ - Every exported record reaches the visitor, so the query reads through the same `filter` as the list, and declares only the fields the visitor may download.
187
+
132
188
  ### Populate a control from a linked table
133
189
 
134
190
  A `LINKED_RECORD` field on a record answers with `{ id, label }` — the label is the linked record's primary field, and the id is what a write or a `where` filter takes. To fill a filter dropdown or form select with **all** options from the linked table (not just the values already referenced by existing records), query the linked table's own datasource:
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.13.2
12
+ library_version: 1.14.0
13
13
  ---
14
14
 
15
15
  **Boundary.** `Audience` and `defineVisibility` come from `@softr/sdk` and work anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.13.2
12
+ library_version: 1.14.0
13
13
  ---
14
14
 
15
15
  **Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.13.2
12
+ library_version: 1.14.0
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,25 +0,0 @@
1
- import { ACCESS_DENIED_HEADER } from "./route.js";
2
- import { getResponseHeader } from "@tanstack/react-start/server";
3
- import { createMiddleware } from "@tanstack/react-start";
4
-
5
- //#region src/route/access-denied-status.ts
6
- /**
7
- * Answers 403 for a page a guard refused by throwing, with the guard's mark.
8
- * TanStack answers any thrown value with 500, which reads as a server error.
9
- */
10
- function accessDeniedStatusMiddleware() {
11
- return createMiddleware({ type: "request" }).server(async ({ next }) => {
12
- const result = await next();
13
- const reason = getResponseHeader(ACCESS_DENIED_HEADER);
14
- if (result.response.status !== 500 || reason === void 0) return result;
15
- const headers = new Headers(result.response.headers);
16
- headers.set(ACCESS_DENIED_HEADER, reason);
17
- return new Response(result.response.body, {
18
- status: 403,
19
- headers
20
- });
21
- });
22
- }
23
-
24
- //#endregion
25
- export { accessDeniedStatusMiddleware };