@softr/sdk 1.0.1-alpha.0 → 1.1.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 +3 -3
- package/dist/action.d.ts +34 -2
- package/dist/action.js +9 -2
- package/dist/auth/context.js +13 -0
- package/dist/auth/isomorphic.js +6 -9
- package/dist/auth/methods/authenticator.js +1 -1
- package/dist/auth/methods/code.js +1 -1
- package/dist/auth/methods/emailCode2fa.js +1 -1
- package/dist/auth/methods/magicLink.js +1 -1
- package/dist/auth/methods/password.js +1 -1
- package/dist/auth/methods/passwordLink.js +1 -1
- package/dist/auth/methods/profile.js +1 -1
- package/dist/auth/methods/signup.js +1 -1
- package/dist/auth/methods/social.js +1 -1
- package/dist/auth/session.js +19 -6
- package/dist/datasource/chart.d.ts +1 -1
- package/dist/datasource/chart.js +27 -19
- package/dist/datasource/enforced-filter.d.ts +56 -0
- package/dist/datasource/enforced-filter.js +127 -0
- package/dist/datasource/fields.d.ts +2 -2
- package/dist/datasource/filter.d.ts +9 -2
- package/dist/datasource/filter.js +17 -1
- package/dist/datasource/record.d.ts +1 -1
- package/dist/datasource/record.js +58 -10
- package/dist/default-error-overlay.d.ts +2 -2
- package/dist/fetch.js +1 -15
- package/dist/formatting.d.ts +3 -3
- package/dist/mcp.js +1 -1
- package/dist/package.js +1 -1
- package/dist/pwa.d.ts +2 -2
- package/package.json +1 -1
- package/skills/softr-sdk/SKILL.md +1 -1
- package/skills/softr-sdk/ai/SKILL.md +1 -1
- package/skills/softr-sdk/auth/SKILL.md +1 -1
- package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
- package/skills/softr-sdk/current-user/SKILL.md +1 -1
- package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
- package/skills/softr-sdk/formatting/SKILL.md +1 -1
- package/skills/softr-sdk/integrations/SKILL.md +1 -1
- package/skills/softr-sdk/mcp/SKILL.md +1 -1
- package/skills/softr-sdk/push-notifications/SKILL.md +1 -1
- package/skills/softr-sdk/pwa/SKILL.md +1 -1
- package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
- package/skills/softr-sdk/record-queries/SKILL.md +1 -1
- package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/workflows/SKILL.md +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# @softr/sdk
|
|
2
2
|
|
|
3
|
-
## 1.0
|
|
3
|
+
## 1.1.0
|
|
4
4
|
|
|
5
|
-
###
|
|
5
|
+
### Minor Changes
|
|
6
6
|
|
|
7
|
-
-
|
|
7
|
+
- `defineQuery` takes an optional `filter` with its `filterFields`. Every read of the query, with `ds.list`, `ds.get`, `chart` and `metric`, returns only the records that match the filter. A read returns only `fields`, not `filterFields`.
|
|
8
8
|
|
|
9
9
|
## 1.0.0
|
|
10
10
|
|
package/dist/action.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { SoftrUserGroupId } from "./auth/user.js";
|
|
2
|
+
import { FilterCriteria } from "./datasource/filter.js";
|
|
3
|
+
import { EnforcedFilter } from "./datasource/enforced-filter.js";
|
|
2
4
|
|
|
3
5
|
//#region src/action.d.ts
|
|
4
6
|
type ActionOperation = "read" | "create" | "update" | "delete";
|
|
@@ -69,6 +71,10 @@ type DatasourceResource = {
|
|
|
69
71
|
datasourceId: SoftrDatasourceId;
|
|
70
72
|
operation: ActionOperation;
|
|
71
73
|
fields?: Record<string, string>;
|
|
74
|
+
/** The fields that the filter reads, by alias. A read returns only `fields`. */
|
|
75
|
+
filterFields?: Record<string, string>;
|
|
76
|
+
/** The enforced filter, keyed by alias, with its tokens unresolved. */
|
|
77
|
+
filter?: FilterCriteria;
|
|
72
78
|
};
|
|
73
79
|
/**
|
|
74
80
|
* A datasource-backed action (query or mutation). The `TShape` brand carries field and
|
|
@@ -85,11 +91,19 @@ type WriteDeclaration<TId extends string, TDatasource$1, TOperation$1, TFields$1
|
|
|
85
91
|
fields: TFields$1;
|
|
86
92
|
permissions: ActionPermissions;
|
|
87
93
|
};
|
|
88
|
-
type ReadDeclaration<TId extends string, TDatasource$1, TFields$1
|
|
94
|
+
type ReadDeclaration<TId extends string, TDatasource$1 extends SoftrDatasourceId, TFields$1 extends Record<string, string>, TFilterFields extends Record<string, string>> = {
|
|
89
95
|
id: TId;
|
|
90
96
|
datasourceId: TDatasource$1;
|
|
91
97
|
fields: TFields$1;
|
|
92
98
|
permissions: ActionPermissions;
|
|
99
|
+
/** The fields that `filter` reads, by alias. A read returns only `fields`. */
|
|
100
|
+
filterFields?: TFilterFields;
|
|
101
|
+
filter?: EnforcedFilter<{
|
|
102
|
+
id: TId;
|
|
103
|
+
datasourceId: TDatasource$1;
|
|
104
|
+
operation: "read";
|
|
105
|
+
fields: NoInfer<TFilterFields>;
|
|
106
|
+
}>;
|
|
93
107
|
};
|
|
94
108
|
type DeleteDeclaration<TId extends string, TDatasource$1> = {
|
|
95
109
|
id: TId;
|
|
@@ -103,6 +117,14 @@ type DeleteDeclaration<TId extends string, TDatasource$1> = {
|
|
|
103
117
|
*
|
|
104
118
|
* The argument must be a static object.
|
|
105
119
|
*
|
|
120
|
+
* `filter` limits every read of the query to the rows that match it, and a `where` cannot widen
|
|
121
|
+
* it. Write a filter on the visitor with a user token. A condition on a user token matches no rows
|
|
122
|
+
* for a visitor who is signed out. A filter has at most 4 group levels.
|
|
123
|
+
*
|
|
124
|
+
* The keys of `filter` are aliases of `filterFields`. A read returns only `fields`, so a field
|
|
125
|
+
* that only the filter needs, such as the owner's email, stays hidden. A field that the read
|
|
126
|
+
* returns and the filter reads goes in both.
|
|
127
|
+
*
|
|
106
128
|
* @example
|
|
107
129
|
* const publishedPosts = defineQuery({
|
|
108
130
|
* id: "publishedPosts",
|
|
@@ -115,8 +137,18 @@ type DeleteDeclaration<TId extends string, TDatasource$1> = {
|
|
|
115
137
|
* .list(publishedPosts)
|
|
116
138
|
* .where((q) => q.publishedAt.lte(today))
|
|
117
139
|
* .orderBy((q) => q.publishedAt.desc)
|
|
140
|
+
*
|
|
141
|
+
* @example
|
|
142
|
+
* const myRequests = defineQuery({
|
|
143
|
+
* id: "myRequests",
|
|
144
|
+
* datasourceId: "8f14e45f-ceea-467a-9d0b-2c1a0e3b5d77",
|
|
145
|
+
* fields: { title: "V1StGXR8", dueAt: "Xp2dLh6v" },
|
|
146
|
+
* filterFields: { requesterEmail: "Z7pQm4Kd" },
|
|
147
|
+
* permissions: { userGroupTypes: ["LOGGED_IN_USERS"] },
|
|
148
|
+
* filter: { requesterEmail: { is: "{USER:::EMAIL}" }, dueAt: { gte: "FIXED_DATE:DAYS_AGO:7" } },
|
|
149
|
+
* })
|
|
118
150
|
*/
|
|
119
|
-
declare function defineQuery<const TId extends string, const TDatasource$1 extends SoftrDatasourceId, const TFields$1 extends Record<string, ReadFieldIdOf<TDatasource$1
|
|
151
|
+
declare function defineQuery<const TId extends string, const TDatasource$1 extends SoftrDatasourceId, const TFields$1 extends Record<string, ReadFieldIdOf<TDatasource$1>>, const TFilterFields extends Record<string, ReadFieldIdOf<TDatasource$1>> = Record<never, never>>(definition: ReadDeclaration<TId, TDatasource$1, TFields$1, TFilterFields>): DatasourceAction<{
|
|
120
152
|
id: TId;
|
|
121
153
|
datasourceId: TDatasource$1;
|
|
122
154
|
operation: "read";
|
package/dist/action.js
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
|
+
import { assert } from "./assertions.js";
|
|
2
|
+
import { buildEnforcedFilter } from "./datasource/enforced-filter.js";
|
|
3
|
+
|
|
1
4
|
//#region src/action.ts
|
|
2
5
|
function defineQuery(definition) {
|
|
6
|
+
const { id, filterFields, filter } = definition;
|
|
7
|
+
assert(filter === void 0 === (filterFields === void 0), () => `defineQuery "${id}": declare filter and filterFields together. The filter names aliases of filterFields.`);
|
|
3
8
|
return {
|
|
4
|
-
id
|
|
9
|
+
id,
|
|
5
10
|
resource: {
|
|
6
11
|
type: "DATASOURCE",
|
|
7
12
|
datasourceId: definition.datasourceId,
|
|
8
13
|
operation: "read",
|
|
9
|
-
fields: definition.fields
|
|
14
|
+
fields: definition.fields,
|
|
15
|
+
filterFields,
|
|
16
|
+
filter: filter === void 0 ? void 0 : buildEnforcedFilter(filter, Object.keys(filterFields ?? {}))
|
|
10
17
|
},
|
|
11
18
|
permissions: definition.permissions
|
|
12
19
|
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { assert } from "../assertions.js";
|
|
2
|
+
import { getGlobalStartContext } from "@tanstack/react-start";
|
|
3
|
+
|
|
4
|
+
//#region src/auth/context.ts
|
|
5
|
+
/** The context that `softrAuthMiddleware` resolved for this request. Server only. */
|
|
6
|
+
function readSoftrContext() {
|
|
7
|
+
const context = getGlobalStartContext();
|
|
8
|
+
assert(typeof context === "object" && context !== null && "user" in context && "permissions" in context && "formatting" in context, "softrAuthMiddleware has not run: the Start global context carries no session. Register it as a global request middleware, e.g. createStart(() => ({ requestMiddleware: [softrAuthMiddleware()] })).");
|
|
9
|
+
return context;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
//#endregion
|
|
13
|
+
export { readSoftrContext };
|
package/dist/auth/isomorphic.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { panic, requireDefined } from "../assertions.js";
|
|
2
2
|
import { readUserTimezone, writeCookies } from "../cookies.js";
|
|
3
3
|
import { sessionConfig } from "./config.js";
|
|
4
|
+
import { makePlatform } from "./platform.js";
|
|
4
5
|
import { clearSession, makeSessionDataCookie, readSessionData, readSessionToken } from "./session.js";
|
|
6
|
+
import { readSoftrContext } from "./context.js";
|
|
5
7
|
import { defaultFormatting, resolveFormatting } from "../formatting.js";
|
|
6
8
|
import { readLocaleSettings } from "../locale-settings.js";
|
|
7
|
-
import { makePlatform } from "./platform.js";
|
|
8
9
|
import { settings } from "./methods/settings.js";
|
|
9
10
|
import { bootErrorMiddleware } from "../boot-error.js";
|
|
10
11
|
import { pwaMiddleware } from "../pwa.js";
|
|
@@ -12,9 +13,9 @@ import { pushMiddleware } from "../push.js";
|
|
|
12
13
|
import { faviconMiddleware } from "../favicon.js";
|
|
13
14
|
import { embeddingMiddleware } from "../embedding.js";
|
|
14
15
|
import { appIdentityMiddleware } from "../app-identity.js";
|
|
15
|
-
import { getRequestHeader } from "@tanstack/react-start/server";
|
|
16
16
|
import { createContext, useContext } from "react";
|
|
17
|
-
import { createMiddleware, createServerFn
|
|
17
|
+
import { createMiddleware, createServerFn } from "@tanstack/react-start";
|
|
18
|
+
import { getRequestHeader } from "@tanstack/react-start/server";
|
|
18
19
|
import { rootRouteId, useRouteContext } from "@tanstack/react-router";
|
|
19
20
|
import { jsx } from "react/jsx-runtime";
|
|
20
21
|
|
|
@@ -76,11 +77,7 @@ function softrAuthMiddleware() {
|
|
|
76
77
|
* beforeLoad: async () => await getSoftrContext(),
|
|
77
78
|
* })
|
|
78
79
|
*/
|
|
79
|
-
const getSoftrContext = createServerFn({ method: "GET" }).handler(async () =>
|
|
80
|
-
const context = getGlobalStartContext();
|
|
81
|
-
assert(typeof context === "object" && context !== null && "user" in context && "permissions" in context && "formatting" in context, "softrAuthMiddleware has not run: the Start global context carries no session. Register it as a global request middleware, e.g. createStart(() => ({ requestMiddleware: [softrAuthMiddleware()] })).");
|
|
82
|
-
return context;
|
|
83
|
-
});
|
|
80
|
+
const getSoftrContext = createServerFn({ method: "GET" }).handler(async () => readSoftrContext());
|
|
84
81
|
/**
|
|
85
82
|
* The context to hand `createRouter`, before any request has resolved one.
|
|
86
83
|
*
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../../assertions.js";
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
|
-
import { clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js";
|
|
5
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
+
import { clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/authenticator.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../../assertions.js";
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
+
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/code.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../../assertions.js";
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js";
|
|
5
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
+
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/emailCode2fa.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../../assertions.js";
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
|
-
import { makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
+
import { makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/magicLink.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic, softAssert } from "../../assertions.js";
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
|
-
import { clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readSessionToken } from "../session.js";
|
|
5
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
+
import { clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readSessionToken } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/password.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../../assertions.js";
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
+
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/passwordLink.ts
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { assert, panic } from "../../assertions.js";
|
|
2
2
|
import { sessionConfig } from "../config.js";
|
|
3
|
-
import { clearSessionData, readSessionToken } from "../session.js";
|
|
4
3
|
import { makePlatform } from "../platform.js";
|
|
4
|
+
import { clearSessionData, readSessionToken } from "../session.js";
|
|
5
5
|
import { authError } from "./utils.js";
|
|
6
6
|
|
|
7
7
|
//#region src/auth/methods/profile.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../../assertions.js";
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
+
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/signup.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../../assertions.js";
|
|
2
2
|
import { writeCookies } from "../../cookies.js";
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
|
-
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
5
4
|
import { makePlatform } from "../platform.js";
|
|
5
|
+
import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
6
|
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/social.ts
|
package/dist/auth/session.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { panic } from "../assertions.js";
|
|
1
2
|
import { expireCookie, expireOtherCopy, readRequestCookies, serializeCookie, writeCookies } from "../cookies.js";
|
|
2
3
|
import { sessionConfig } from "./config.js";
|
|
4
|
+
import { makePlatform } from "./platform.js";
|
|
3
5
|
import { userSchema } from "./user.js";
|
|
4
|
-
import { getRequestProtocol } from "@tanstack/react-start/server";
|
|
5
6
|
import { z } from "zod";
|
|
6
7
|
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
|
7
8
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
+
import { getRequestProtocol } from "@tanstack/react-start/server";
|
|
8
10
|
|
|
9
11
|
//#region src/auth/session.ts
|
|
10
12
|
const SESSION_TOKEN = "session_token";
|
|
@@ -43,12 +45,23 @@ function sessionCookie(base) {
|
|
|
43
45
|
* call authenticates with a bearer token and has no cookie at all.
|
|
44
46
|
*/
|
|
45
47
|
function withSessionToken(token, fn) {
|
|
46
|
-
return
|
|
48
|
+
return standIn.run({ token }, fn);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The visitor of the token that {@link withSessionToken} stands in, fetched once
|
|
52
|
+
* per scope. `undefined` outside one, where the request middleware has already
|
|
53
|
+
* resolved the visitor.
|
|
54
|
+
*/
|
|
55
|
+
function readStandInUser() {
|
|
56
|
+
const scope = standIn.getStore();
|
|
57
|
+
if (scope === void 0) return void 0;
|
|
58
|
+
scope.user ??= makePlatform(sessionConfig().applicationId).session(scope.token).then((result) => result.ok ? result.data.user : panic(result.message));
|
|
59
|
+
return scope.user;
|
|
47
60
|
}
|
|
48
61
|
/** The platform token this request carries, or `null`. */
|
|
49
62
|
function readSessionToken() {
|
|
50
|
-
const
|
|
51
|
-
if (
|
|
63
|
+
const scope = standIn.getStore();
|
|
64
|
+
if (scope !== void 0) return scope.token;
|
|
52
65
|
const { name } = sessionCookie(SESSION_TOKEN);
|
|
53
66
|
return openEnvelope(readRequestCookies()[name], SESSION_TOKEN);
|
|
54
67
|
}
|
|
@@ -127,7 +140,7 @@ function clearSession() {
|
|
|
127
140
|
function clearSessionData() {
|
|
128
141
|
clearCookies([SESSION_DATA]);
|
|
129
142
|
}
|
|
130
|
-
const
|
|
143
|
+
const standIn = new AsyncLocalStorage();
|
|
131
144
|
const sessionDataSchema = z.object({
|
|
132
145
|
user: userSchema.nullable(),
|
|
133
146
|
exp: z.number(),
|
|
@@ -215,4 +228,4 @@ function openEnvelope(raw, purpose) {
|
|
|
215
228
|
}
|
|
216
229
|
|
|
217
230
|
//#endregion
|
|
218
|
-
export { clearPendingAuth, clearSession, clearSessionData, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionData, readSessionToken, withSessionToken };
|
|
231
|
+
export { clearPendingAuth, clearSession, clearSessionData, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionData, readSessionToken, readStandInUser, withSessionToken };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { DatasourceAction, FieldTypeOf, ReadShape, SoftrDatasources } from "../action.js";
|
|
2
1
|
import { ConstructableOrderBy } from "./filter.js";
|
|
3
2
|
import { DateFieldType, NumberFieldType, SortSet } from "./fields.js";
|
|
3
|
+
import { DatasourceAction, FieldTypeOf, ReadShape, SoftrDatasources } from "../action.js";
|
|
4
4
|
import { WhereCallback } from "./record.js";
|
|
5
5
|
|
|
6
6
|
//#region src/datasource/chart.d.ts
|
package/dist/datasource/chart.js
CHANGED
|
@@ -2,9 +2,9 @@ import { assert, panic } from "../assertions.js";
|
|
|
2
2
|
import { fetch } from "../fetch.js";
|
|
3
3
|
import { readUserTimezone } from "../cookies.js";
|
|
4
4
|
import { readSessionToken } from "../auth/session.js";
|
|
5
|
-
import { INTERNAL_KIND,
|
|
6
|
-
import {
|
|
7
|
-
import { describeFailure, dsUrl, refererHeader, resolveTarget } from "./record.js";
|
|
5
|
+
import { INTERNAL_KIND, buildOrderBy } from "./filter.js";
|
|
6
|
+
import { makeFieldSet, makeSortSet } from "./fields.js";
|
|
7
|
+
import { describeFailure, dsUrl, readFilterCriteria, refererHeader, resolveTarget } from "./record.js";
|
|
8
8
|
|
|
9
9
|
//#region src/datasource/chart.ts
|
|
10
10
|
const COUNT_CNT = "COUNT_CNT";
|
|
@@ -137,7 +137,7 @@ function chart(query) {
|
|
|
137
137
|
};
|
|
138
138
|
return builder;
|
|
139
139
|
}
|
|
140
|
-
function buildChartRequest(state, select) {
|
|
140
|
+
function buildChartRequest(state, select, 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 ?? [];
|
|
@@ -161,14 +161,13 @@ function buildChartRequest(state, select) {
|
|
|
161
161
|
}];
|
|
162
162
|
}
|
|
163
163
|
const responseKeyOf = new Map(columns.map((column) => [column.key, column.responseKey]));
|
|
164
|
-
const sortingOptions = orderBys.map((orderBy) => ({
|
|
165
|
-
sortingField: responseKeyOf.get(orderBy.sortingField) ?? panic(() => `"${orderBy.sortingField}" is not a column of this chart`),
|
|
166
|
-
sortType: orderBy.sortType
|
|
167
|
-
}));
|
|
168
164
|
return {
|
|
169
165
|
body: {
|
|
170
|
-
filterCriteria
|
|
171
|
-
sortingOptions
|
|
166
|
+
filterCriteria,
|
|
167
|
+
sortingOptions: orderBys.map((orderBy) => ({
|
|
168
|
+
sortingField: responseKeyOf.get(orderBy.sortingField) ?? panic(() => `"${orderBy.sortingField}" is not a column of this chart`),
|
|
169
|
+
sortType: orderBy.sortType
|
|
170
|
+
})),
|
|
172
171
|
groupBy: groups.map(([, handle]) => handle.options ? {
|
|
173
172
|
field: handle.fieldId,
|
|
174
173
|
options: handle.options
|
|
@@ -192,8 +191,14 @@ function mapChartRows(columns, data) {
|
|
|
192
191
|
});
|
|
193
192
|
}
|
|
194
193
|
async function executeChart(query, state) {
|
|
195
|
-
const
|
|
196
|
-
const {
|
|
194
|
+
const target = resolveTarget(query, "read");
|
|
195
|
+
const { actionId, select } = target;
|
|
196
|
+
const filterCriteria = await readFilterCriteria(target, state.filters);
|
|
197
|
+
if (filterCriteria === null) return {
|
|
198
|
+
data: [],
|
|
199
|
+
executionTimestamp: /* @__PURE__ */ new Date()
|
|
200
|
+
};
|
|
201
|
+
const { body, columns } = buildChartRequest(state, select, filterCriteria);
|
|
197
202
|
const res = await fetch(`${dsUrl(actionId)}/chart/data`, {
|
|
198
203
|
method: "POST",
|
|
199
204
|
headers: {
|
|
@@ -247,7 +252,7 @@ function metric(query, pick) {
|
|
|
247
252
|
};
|
|
248
253
|
return builder;
|
|
249
254
|
}
|
|
250
|
-
function buildMetricRequest(handle,
|
|
255
|
+
function buildMetricRequest(handle, filterCriteria) {
|
|
251
256
|
return {
|
|
252
257
|
body: {
|
|
253
258
|
groupBy: [],
|
|
@@ -255,7 +260,7 @@ function buildMetricRequest(handle, filters, select) {
|
|
|
255
260
|
field: handle.fieldId ?? void 0,
|
|
256
261
|
aggregation: handle.aggregation
|
|
257
262
|
}],
|
|
258
|
-
filterCriteria
|
|
263
|
+
filterCriteria
|
|
259
264
|
},
|
|
260
265
|
responseKey: handle.aggregation === "COUNT" && !handle.fieldId ? COUNT_CNT : handle.fieldId
|
|
261
266
|
};
|
|
@@ -266,8 +271,14 @@ function readMetricValue(responseKey, data) {
|
|
|
266
271
|
return row[responseKey];
|
|
267
272
|
}
|
|
268
273
|
async function executeMetric(query, handle, filters) {
|
|
269
|
-
const
|
|
270
|
-
const
|
|
274
|
+
const target = resolveTarget(query, "read");
|
|
275
|
+
const filterCriteria = await readFilterCriteria(target, filters);
|
|
276
|
+
if (filterCriteria === null) return {
|
|
277
|
+
value: handle.aggregation === "COUNT" || handle.aggregation === "DISTINCT" ? 0 : null,
|
|
278
|
+
executionTimestamp: /* @__PURE__ */ new Date()
|
|
279
|
+
};
|
|
280
|
+
const { actionId } = target;
|
|
281
|
+
const { body, responseKey } = buildMetricRequest(handle, filterCriteria);
|
|
271
282
|
const res = await fetch(`${dsUrl(actionId)}/chart/data`, {
|
|
272
283
|
method: "POST",
|
|
273
284
|
headers: {
|
|
@@ -285,9 +296,6 @@ async function executeMetric(query, handle, filters) {
|
|
|
285
296
|
executionTimestamp: /* @__PURE__ */ new Date(payload.executionTimestamp * 1e3)
|
|
286
297
|
};
|
|
287
298
|
}
|
|
288
|
-
function toFilterCriteria(filters, select) {
|
|
289
|
-
return filters.length ? dealiasFilterCriteria(buildFilterCriteria(andAll(filters)), select) : {};
|
|
290
|
-
}
|
|
291
299
|
|
|
292
300
|
//#endregion
|
|
293
301
|
export { chart, metric };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { AnyChain, ChainFor } from "./fields.js";
|
|
2
|
+
import { FieldTypeOf, ReadOf, ReadShape, SoftrDatasources } from "../action.js";
|
|
3
|
+
|
|
4
|
+
//#region src/datasource/enforced-filter.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The operators of one alias, each written as the value its `where` method takes. An operator
|
|
8
|
+
* with no value takes `true`, and a range takes a pair.
|
|
9
|
+
*/
|
|
10
|
+
type Conditions<TChain> = { [Operator in keyof TChain]?: TChain[Operator] extends ((...args: infer TArgs) => unknown) ? TArgs extends [] ? true : TArgs extends [infer TValue] ? TValue : TArgs extends [infer TStart, infer TEnd] ? [TStart, TEnd] : never : never };
|
|
11
|
+
type Junctions<TShape extends ReadShape> = {
|
|
12
|
+
$and?: Array<EnforcedFilter<TShape>>;
|
|
13
|
+
$or?: Array<EnforcedFilter<TShape>>;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* The filter a query enforces on every read. Each key is an alias of the query's `filterFields`,
|
|
17
|
+
* with the same operators as `where`. `$and` and `$or` nest more filters. The keys of one object
|
|
18
|
+
* combine with AND.
|
|
19
|
+
*
|
|
20
|
+
* A read returns `fields`, not `filterFields`. So a field that the visitor must not see can be in
|
|
21
|
+
* `filterFields` only. The datasource refuses a read that filters on a field a data restriction
|
|
22
|
+
* hides, even when it hides the field on some records only.
|
|
23
|
+
*
|
|
24
|
+
* A token stands for a value of the visitor or for a day. Write it in the form that the Studio
|
|
25
|
+
* condition builder stores:
|
|
26
|
+
* - `{USER:::EMAIL}` and `{USER:::EMAIL_DOMAIN}`: the visitor's email and its domain.
|
|
27
|
+
* - `USER:::<field id>`: a field of the visitor's row in the users table. softr.json must declare
|
|
28
|
+
* it under `user.properties`. For the id of that row, declare a Record ID field.
|
|
29
|
+
* - `PREDEFINED:TODAY`, `PREDEFINED:YESTERDAY`, `PREDEFINED:TOMORROW`,
|
|
30
|
+
* `FIXED_DATE:DAYS_AGO:<n>` and `FIXED_DATE:DAYS_FROM_NOW:<n>`: a day relative to today.
|
|
31
|
+
*
|
|
32
|
+
* The datasource resolves the tokens on each read. It resolves a day in the app's time zone. A
|
|
33
|
+
* condition on a user token matches no rows for a visitor who is signed out or has no value for
|
|
34
|
+
* it. In an `$or`, the other branches still match.
|
|
35
|
+
*
|
|
36
|
+
* Compare a field of the visitor that can hold several values, such as a link to their teams,
|
|
37
|
+
* with `isOneOf`. With a scalar `is`, a visitor who holds more than one value reads no rows.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* // "7fMhE" is a Record ID field of the users table, declared under `user.properties`.
|
|
41
|
+
* filter: { assignee: { isOneOf: ["USER:::7fMhE"] } }
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* // `requesterEmail` is in `filterFields`, so public rows do not show it.
|
|
45
|
+
* filter: {
|
|
46
|
+
* $or: [
|
|
47
|
+
* { requesterEmail: { is: "{USER:::EMAIL}" } },
|
|
48
|
+
* { visibility: { is: "public" }, publishedAt: { lte: "PREDEFINED:TODAY" } },
|
|
49
|
+
* ],
|
|
50
|
+
* }
|
|
51
|
+
*/
|
|
52
|
+
type EnforcedFilter<TShape extends ReadShape> = keyof SoftrDatasources extends never ? {
|
|
53
|
+
[key: string]: Conditions<AnyChain> | Array<EnforcedFilter<TShape>>;
|
|
54
|
+
} : { [Alias in keyof TShape["fields"]]?: Conditions<ChainFor<FieldTypeOf<TShape["datasourceId"], TShape["fields"][Alias]>, NonNullable<ReadOf<TShape["datasourceId"]>[TShape["fields"][Alias] & keyof ReadOf<TShape["datasourceId"]>]>>> } & Junctions<TShape>;
|
|
55
|
+
//#endregion
|
|
56
|
+
export { EnforcedFilter };
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { assert, requireDefined } from "../assertions.js";
|
|
2
|
+
import { softrConfig } from "../softr-config.js";
|
|
3
|
+
import { INTERNAL_KIND, buildFilterCriteria } from "./filter.js";
|
|
4
|
+
import { makeChain } from "./fields.js";
|
|
5
|
+
|
|
6
|
+
//#region src/datasource/enforced-filter.ts
|
|
7
|
+
/** The group levels Studio can show and edit. The root group is level 1. */
|
|
8
|
+
const MAX_LEVELS = 4;
|
|
9
|
+
const USER_TOKEN = /^(?:\{USER:::(EMAIL|EMAIL_DOMAIN)\}|USER:::(.+))$/;
|
|
10
|
+
const DATE_TOKEN = /^(?:PREDEFINED:(?:TODAY|YESTERDAY|TOMORROW)|FIXED_DATE:(?:DAYS_AGO|DAYS_FROM_NOW):\d+)$/;
|
|
11
|
+
/** Anything in the token namespaces. A value here that is no known token is a typo, not data. */
|
|
12
|
+
const TOKEN_LIKE = /^\{?(?:USER|PREDEFINED|FIXED_DATE):/;
|
|
13
|
+
/**
|
|
14
|
+
* Builds the filter that a query declares into the shape a read sends. Subjects stay aliases and
|
|
15
|
+
* tokens stay unresolved: the datasource resolves them on each read.
|
|
16
|
+
*/
|
|
17
|
+
function buildEnforcedFilter(declared, aliases) {
|
|
18
|
+
const root = requireDefined(buildFilterCriteria(toConstructable(declared)).filterConditionGroup);
|
|
19
|
+
const levels = levelsOf(root);
|
|
20
|
+
assert(levels <= MAX_LEVELS, () => `the filter has ${levels} group levels, and Studio shows at most ${MAX_LEVELS}`);
|
|
21
|
+
return { filterConditionGroup: root };
|
|
22
|
+
function toConstructable(node) {
|
|
23
|
+
assert(isObject(node) && Object.keys(node).length > 0, "a filter must be an object with at least one key");
|
|
24
|
+
const members = [];
|
|
25
|
+
for (const [key, value] of Object.entries(node)) if (key === "$and") members.push(...junction(key, value).flatMap((member) => membersOf(member, "AND")));
|
|
26
|
+
else if (key === "$or") members.push(group("OR", junction(key, value).flatMap((member) => membersOf(member, "OR"))));
|
|
27
|
+
else members.push(...conditions(key, value));
|
|
28
|
+
return members.length === 1 ? members[0] : group("AND", members);
|
|
29
|
+
}
|
|
30
|
+
function junction(key, value) {
|
|
31
|
+
assert(Array.isArray(value) && value.length > 0, () => `${key} must be a list of at least one filter`);
|
|
32
|
+
return value.map(toConstructable);
|
|
33
|
+
}
|
|
34
|
+
function conditions(alias, value) {
|
|
35
|
+
assert(aliases.includes(alias), () => `the filter names "${alias}", which is not one of the query's filterFields`);
|
|
36
|
+
assert(isObject(value) && Object.keys(value).length > 0, () => `"${alias}" in the filter needs at least one operator`);
|
|
37
|
+
const chain = makeChain(alias);
|
|
38
|
+
return Object.entries(value).map(([operator, argument]) => {
|
|
39
|
+
assert(Object.hasOwn(chain, operator), () => `"${operator}" on "${alias}" is not a filter operator`);
|
|
40
|
+
const build = chain[operator];
|
|
41
|
+
let values$1 = [argument];
|
|
42
|
+
if (build.length === 0) {
|
|
43
|
+
assert(argument === true, () => `"${operator}" on "${alias}" takes true`);
|
|
44
|
+
values$1 = [];
|
|
45
|
+
} else if (build.length === 2) {
|
|
46
|
+
assert(Array.isArray(argument) && argument.length === 2, () => `"${operator}" on "${alias}" takes a pair`);
|
|
47
|
+
values$1 = argument;
|
|
48
|
+
}
|
|
49
|
+
for (const token of values$1.flat()) {
|
|
50
|
+
const unbraced = typeof token === "string" ? /^\{(USER:::.+)\}$/.exec(token)?.[1] : void 0;
|
|
51
|
+
assert(typeof token !== "string" || !TOKEN_LIKE.test(token) || USER_TOKEN.test(token) || DATE_TOKEN.test(token), () => `"${token}" on "${alias}" is not a known token` + (unbraced === void 0 ? "" : `. Write a field of the visitor without braces: "${unbraced}"`));
|
|
52
|
+
const key = typeof token === "string" ? USER_TOKEN.exec(token)?.[2] : void 0;
|
|
53
|
+
assert(key === void 0 || Object.values(softrConfig().user?.properties ?? {}).includes(key), () => `"${token}" on "${alias}" names a field that softr.json does not declare under user.properties`);
|
|
54
|
+
}
|
|
55
|
+
return build(...values$1);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Whether the filter reads a value of the visitor, so a read has to know who the visitor is. */
|
|
60
|
+
function readsVisitor(group$1) {
|
|
61
|
+
return values(group$1).some((value) => typeof value === "string" && USER_TOKEN.test(value));
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The part of the filter that can match rows for this visitor, or `null` when no part can.
|
|
65
|
+
*
|
|
66
|
+
* The datasource resolves each user token from the session. For a visitor with no value, it
|
|
67
|
+
* compares with an empty value, and that matches the wrong rows. So a condition whose user token
|
|
68
|
+
* has no value never goes out. The visitor is signed out, or their row holds nothing there.
|
|
69
|
+
*
|
|
70
|
+
* In an AND group, such a condition makes the group match nothing. In an OR group, only that
|
|
71
|
+
* branch drops out. Either way the visitor reads fewer rows, never more.
|
|
72
|
+
*/
|
|
73
|
+
function filterForVisitor(group$1, visitor) {
|
|
74
|
+
const filters = group$1.filters.filter(filterCanMatch);
|
|
75
|
+
const filterGroups = group$1.filterGroups.flatMap((nested) => filterForVisitor(nested, visitor) ?? []);
|
|
76
|
+
const kept = filters.length + filterGroups.length;
|
|
77
|
+
return (group$1.logicalOperator === "AND" ? kept === group$1.filters.length + group$1.filterGroups.length : kept > 0) ? {
|
|
78
|
+
...group$1,
|
|
79
|
+
filters,
|
|
80
|
+
filterGroups
|
|
81
|
+
} : null;
|
|
82
|
+
function filterCanMatch(filter) {
|
|
83
|
+
if (Array.isArray(filter.value)) return filter.value.every((value) => valueCount(value) > 0);
|
|
84
|
+
return valueCount(filter.value) === 1;
|
|
85
|
+
}
|
|
86
|
+
function valueCount(value) {
|
|
87
|
+
const user = typeof value === "string" ? USER_TOKEN.exec(value) : null;
|
|
88
|
+
if (user === null) return 1;
|
|
89
|
+
return visitor === null ? 0 : userValues(visitor, user[1], user[2]).length;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** `property` is EMAIL or EMAIL_DOMAIN for the braced tokens, and `key` is set for the others. */
|
|
93
|
+
function userValues(visitor, property, key) {
|
|
94
|
+
if (property === "EMAIL") return [visitor.email];
|
|
95
|
+
if (property === "EMAIL_DOMAIN") {
|
|
96
|
+
const domain = visitor.email.slice(visitor.email.indexOf("@") + 1);
|
|
97
|
+
return visitor.email.includes("@") && domain !== "" ? [domain] : [];
|
|
98
|
+
}
|
|
99
|
+
const raw = visitor.field(requireDefined(key));
|
|
100
|
+
return (Array.isArray(raw) ? raw : [raw]).filter((item) => item !== null && item !== void 0 && item !== "");
|
|
101
|
+
}
|
|
102
|
+
function levelsOf(group$1) {
|
|
103
|
+
return 1 + Math.max(0, ...group$1.filterGroups.map(levelsOf));
|
|
104
|
+
}
|
|
105
|
+
function values(group$1) {
|
|
106
|
+
return [...group$1.filters.flatMap((filter) => Array.isArray(filter.value) ? filter.value : [filter.value]), ...group$1.filterGroups.flatMap(values)];
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* A member that is itself a group of `logicalOperator` gives its members. So the filter stays as
|
|
110
|
+
* shallow as written.
|
|
111
|
+
*/
|
|
112
|
+
function membersOf(member, logicalOperator) {
|
|
113
|
+
return member[INTERNAL_KIND] === "LOGICAL_GROUP" && member.logicalOperator === logicalOperator ? member.filters : [member];
|
|
114
|
+
}
|
|
115
|
+
function group(logicalOperator, filters) {
|
|
116
|
+
return {
|
|
117
|
+
logicalOperator,
|
|
118
|
+
filters,
|
|
119
|
+
[INTERNAL_KIND]: "LOGICAL_GROUP"
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function isObject(value) {
|
|
123
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
//#endregion
|
|
127
|
+
export { buildEnforcedFilter, filterForVisitor, readsVisitor };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { FieldTypeOf, ReadOf, ReadShape, SoftrDatasources } from "../action.js";
|
|
2
1
|
import { AnyConstructable, ConstructableFilter, ConstructableFilterGroup, ConstructableOrderBy } from "./filter.js";
|
|
2
|
+
import { FieldTypeOf, ReadOf, ReadShape, SoftrDatasources } from "../action.js";
|
|
3
3
|
|
|
4
4
|
//#region src/datasource/fields.d.ts
|
|
5
5
|
type EmptyChain = {
|
|
@@ -111,4 +111,4 @@ type SortSet<TRecord> = { [K in keyof TRecord]: {
|
|
|
111
111
|
readonly desc: ConstructableOrderBy;
|
|
112
112
|
} };
|
|
113
113
|
//#endregion
|
|
114
|
-
export { DateFieldType, FieldSet, NumberFieldType, SortSet };
|
|
114
|
+
export { AnyChain, ChainFor, DateFieldType, FieldSet, NumberFieldType, SortSet };
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
//#region src/datasource/filter.d.ts
|
|
2
|
-
|
|
2
|
+
interface FilterCriteria {
|
|
3
|
+
filterConditionGroup?: FilterConditionGroup;
|
|
4
|
+
}
|
|
5
|
+
interface FilterConditionGroup {
|
|
6
|
+
logicalOperator: LogicalOperator;
|
|
7
|
+
filters: Filter[];
|
|
8
|
+
filterGroups: FilterConditionGroup[];
|
|
9
|
+
}
|
|
3
10
|
type LogicalOperator = "AND" | "OR";
|
|
4
11
|
type FilterOperator = "IS" | "IS_NOT" | "EQUAL" | "NOT_EQUAL" | "IS_EMPTY" | "IS_NOT_EMPTY" | "IS_ONE_OF" | "IS_NONE_OF" | "HAS_ALL_OF" | "CONTAINS" | "INLINE_CONTAINS" | "GT" | "LT" | "GTE" | "LTE" | "BETWEEN" | "IS_NOT_BETWEEN" | "DOES_NOT_CONTAINS" | "STARTS_WITH" | "ENDS_WITH";
|
|
5
12
|
type ConditionFieldType = "TEXT" | "BOOLEAN" | "NUMERIC" | "ARRAY" | "DATE";
|
|
@@ -27,4 +34,4 @@ type ConstructableOrderBy = SortingOptionItem & {
|
|
|
27
34
|
type AnyConstructable = ConstructableFilter | ConstructableFilterGroup;
|
|
28
35
|
declare const INTERNAL_KIND: unique symbol;
|
|
29
36
|
//#endregion
|
|
30
|
-
export { AnyConstructable, ConstructableFilter, ConstructableFilterGroup, ConstructableOrderBy };
|
|
37
|
+
export { AnyConstructable, ConstructableFilter, ConstructableFilterGroup, ConstructableOrderBy, FilterCriteria };
|
|
@@ -49,6 +49,22 @@ function buildFilterGroup(logicalOperator, members) {
|
|
|
49
49
|
};
|
|
50
50
|
}
|
|
51
51
|
/**
|
|
52
|
+
* Joins groups with AND. An AND group gives its conditions and groups to the join rather than
|
|
53
|
+
* nesting in it, so the join is at most one level deeper than its deepest member.
|
|
54
|
+
*/
|
|
55
|
+
function andGroups(groups) {
|
|
56
|
+
const joined = {
|
|
57
|
+
logicalOperator: "AND",
|
|
58
|
+
filters: [],
|
|
59
|
+
filterGroups: []
|
|
60
|
+
};
|
|
61
|
+
for (const group of groups) if (group.logicalOperator === "AND") {
|
|
62
|
+
joined.filters.push(...group.filters);
|
|
63
|
+
joined.filterGroups.push(...group.filterGroups);
|
|
64
|
+
} else joined.filterGroups.push(group);
|
|
65
|
+
return joined;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
52
68
|
* Converts order-by utility conditions to a format our backend supports
|
|
53
69
|
*
|
|
54
70
|
* @example
|
|
@@ -130,4 +146,4 @@ function isFilter(item) {
|
|
|
130
146
|
}
|
|
131
147
|
|
|
132
148
|
//#endregion
|
|
133
|
-
export { INTERNAL_KIND, buildFilterCriteria, buildOrderBy, dealiasFilterCriteria, dealiasOrderBy };
|
|
149
|
+
export { INTERNAL_KIND, andGroups, buildFilterCriteria, buildOrderBy, dealiasFilterCriteria, dealiasOrderBy };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { ActionData, ActionRecord, ActionShape, DatasourceAction, ReadShape } from "../action.js";
|
|
2
1
|
import { AnyConstructable, ConstructableOrderBy } from "./filter.js";
|
|
3
2
|
import { FieldSet, SortSet } from "./fields.js";
|
|
3
|
+
import { ActionData, ActionRecord, ActionShape, DatasourceAction, ReadShape } from "../action.js";
|
|
4
4
|
|
|
5
5
|
//#region src/datasource/record.d.ts
|
|
6
6
|
type GetOptions = {
|
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
import { assert, panic } from "../assertions.js";
|
|
1
|
+
import { assert, panic, requireDefined } from "../assertions.js";
|
|
2
2
|
import { softrApiUrl } from "../softr-api.js";
|
|
3
3
|
import { fetch } from "../fetch.js";
|
|
4
|
+
import { softrConfig } from "../softr-config.js";
|
|
4
5
|
import { readUserTimezone } from "../cookies.js";
|
|
5
|
-
import { readSessionToken } from "../auth/session.js";
|
|
6
|
-
import {
|
|
7
|
-
import { buildFilterCriteria, buildOrderBy, dealiasFilterCriteria, dealiasOrderBy } from "./filter.js";
|
|
6
|
+
import { readSessionToken, readStandInUser } from "../auth/session.js";
|
|
7
|
+
import { andGroups, buildFilterCriteria, buildOrderBy, dealiasFilterCriteria, dealiasOrderBy } from "./filter.js";
|
|
8
8
|
import { andAll, makeFieldSet, makeSortSet } from "./fields.js";
|
|
9
|
+
import { filterForVisitor, readsVisitor } from "./enforced-filter.js";
|
|
10
|
+
import { isDatasourceAction } from "../action.js";
|
|
11
|
+
import { readSoftrContext } from "../auth/context.js";
|
|
9
12
|
import { getRequestHeader, getRequestUrl } from "@tanstack/react-start/server";
|
|
10
13
|
|
|
11
14
|
//#region src/datasource/record.ts
|
|
@@ -85,10 +88,16 @@ function listRecords(query) {
|
|
|
85
88
|
return builder;
|
|
86
89
|
}
|
|
87
90
|
async function executeList(query, args) {
|
|
88
|
-
const
|
|
91
|
+
const target = resolveTarget(query, "read");
|
|
92
|
+
const { actionId, select } = target;
|
|
89
93
|
const count = Math.min(args.limit ?? 20, MAX_RECORD_COUNT);
|
|
90
94
|
const offset = args.offset ?? null;
|
|
91
|
-
const filterCriteria =
|
|
95
|
+
const filterCriteria = await readFilterCriteria(target, args.filters);
|
|
96
|
+
if (filterCriteria === null) return {
|
|
97
|
+
records: [],
|
|
98
|
+
total: 0,
|
|
99
|
+
nextOffset: null
|
|
100
|
+
};
|
|
92
101
|
const sortingOption = args.orderBy.length ? dealiasOrderBy(buildOrderBy(args.orderBy), select) : void 0;
|
|
93
102
|
const res = await fetch(`${dsUrl(actionId)}/records`, {
|
|
94
103
|
method: "POST",
|
|
@@ -160,8 +169,10 @@ function getRecord(query, options) {
|
|
|
160
169
|
}
|
|
161
170
|
async function executeGet(query, id, filters) {
|
|
162
171
|
assert(id, "a record id must not be empty");
|
|
163
|
-
const
|
|
164
|
-
const
|
|
172
|
+
const target = resolveTarget(query, "read");
|
|
173
|
+
const { actionId, select } = target;
|
|
174
|
+
const filterCriteria = await readFilterCriteria(target, filters);
|
|
175
|
+
if (filterCriteria === null) return null;
|
|
165
176
|
const res = await fetch(`${dsUrl(actionId)}/records/${id}`, {
|
|
166
177
|
method: "POST",
|
|
167
178
|
headers: {
|
|
@@ -266,7 +277,44 @@ function resolveTarget(subject, operation) {
|
|
|
266
277
|
assert(action.resource.operation === operation, () => `action "${action.id}" is declared as ${action.resource.operation}, not ${operation}`);
|
|
267
278
|
return {
|
|
268
279
|
actionId: action.id,
|
|
269
|
-
select: action.resource.fields ?? {}
|
|
280
|
+
select: action.resource.fields ?? {},
|
|
281
|
+
filterFields: action.resource.filterFields,
|
|
282
|
+
filter: action.resource.filter
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* The filter a read sends: the query's enforced filter, with its tokens, AND the `where`
|
|
287
|
+
* filters. `null` when the enforced filter matches no rows for this visitor. The read then sends
|
|
288
|
+
* no request and returns nothing.
|
|
289
|
+
*/
|
|
290
|
+
async function readFilterCriteria(target, filters) {
|
|
291
|
+
const groups = [];
|
|
292
|
+
const enforced = target.filter?.filterConditionGroup;
|
|
293
|
+
if (enforced !== void 0) {
|
|
294
|
+
const forVisitor = readsVisitor(enforced) ? filterForVisitor(enforced, await readVisitor()) : enforced;
|
|
295
|
+
if (forVisitor === null) return null;
|
|
296
|
+
groups.push(dealias(forVisitor, requireDefined(target.filterFields, "defineQuery declares filterFields with a filter")));
|
|
297
|
+
}
|
|
298
|
+
const requested = filters.length ? buildFilterCriteria(andAll(filters)).filterConditionGroup : void 0;
|
|
299
|
+
if (requested !== void 0) groups.push(dealias(requested, target.select));
|
|
300
|
+
if (groups.length === 0) return {};
|
|
301
|
+
return { filterConditionGroup: groups.length === 1 ? groups[0] : andGroups(groups) };
|
|
302
|
+
function dealias(group, aliases) {
|
|
303
|
+
return requireDefined(dealiasFilterCriteria({ filterConditionGroup: group }, aliases).filterConditionGroup);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async function readVisitor() {
|
|
307
|
+
const user = await (readStandInUser() ?? readSoftrContext().user);
|
|
308
|
+
if (user === null) return null;
|
|
309
|
+
const properties = user.properties;
|
|
310
|
+
const aliasOf = new Map(Object.entries(softrConfig().user?.properties ?? {}).map(([alias, fieldId]) => [fieldId, alias]));
|
|
311
|
+
return {
|
|
312
|
+
email: user.email,
|
|
313
|
+
field(key) {
|
|
314
|
+
const alias = aliasOf.get(key);
|
|
315
|
+
assert(alias !== void 0, () => `the enforced filter reads USER:::${key}, a field that softr.json does not declare under user.properties`);
|
|
316
|
+
return properties[alias];
|
|
317
|
+
}
|
|
270
318
|
};
|
|
271
319
|
}
|
|
272
320
|
function aliasFields(fields, aliases) {
|
|
@@ -281,4 +329,4 @@ function dealiasData(data, select) {
|
|
|
281
329
|
}
|
|
282
330
|
|
|
283
331
|
//#endregion
|
|
284
|
-
export { createRecord, deleteRecord, describeFailure, dsUrl, getRecord, listRecords, refererHeader, resolveTarget, updateRecord };
|
|
332
|
+
export { createRecord, deleteRecord, describeFailure, dsUrl, getRecord, listRecords, readFilterCriteria, refererHeader, resolveTarget, updateRecord };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react6 from "react";
|
|
2
2
|
|
|
3
3
|
//#region src/default-error-overlay.d.ts
|
|
4
4
|
type Props = {
|
|
@@ -8,6 +8,6 @@ type Props = {
|
|
|
8
8
|
declare function DefaultErrorOverlay({
|
|
9
9
|
error,
|
|
10
10
|
reset
|
|
11
|
-
}: Props):
|
|
11
|
+
}: Props): react6.JSX.Element;
|
|
12
12
|
//#endregion
|
|
13
13
|
export { DefaultErrorOverlay };
|
package/dist/fetch.js
CHANGED
|
@@ -2,10 +2,8 @@ import { version } from "./package.js";
|
|
|
2
2
|
import { assert, requireDefined } from "./assertions.js";
|
|
3
3
|
import { logger } from "./logger.js";
|
|
4
4
|
import { softrApiUrl } from "./softr-api.js";
|
|
5
|
-
import { getRequestHeader } from "@tanstack/react-start/server";
|
|
6
5
|
|
|
7
6
|
//#region src/fetch.ts
|
|
8
|
-
const CLIENT_IP_HEADER = "x-softr-client-ip";
|
|
9
7
|
const fetch = async (input, init) => {
|
|
10
8
|
const url = input instanceof Request ? input.url : String(input);
|
|
11
9
|
if ([
|
|
@@ -15,10 +13,6 @@ const fetch = async (input, init) => {
|
|
|
15
13
|
].some((base) => url.startsWith(`${base}/`))) {
|
|
16
14
|
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
|
|
17
15
|
headers.set("user-agent", `softr-sdk/${version}`);
|
|
18
|
-
headers.delete(CLIENT_IP_HEADER);
|
|
19
|
-
const clientIp = readClientIp();
|
|
20
|
-
const isPlatformCall = url.startsWith(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/`);
|
|
21
|
-
if (clientIp && isPlatformCall) headers.set(CLIENT_IP_HEADER, clientIp);
|
|
22
16
|
init = {
|
|
23
17
|
...init,
|
|
24
18
|
headers
|
|
@@ -48,7 +42,7 @@ const fetch = async (input, init) => {
|
|
|
48
42
|
* id (`<environment>/<applicationId>/<master number>`) is copied into the signature as is so the verifier can
|
|
49
43
|
* derive the same key.
|
|
50
44
|
*
|
|
51
|
-
* The signature covers the method, authority, path, query and, when sent, the Authorization
|
|
45
|
+
* The signature covers the method, authority, path, query and, when sent, the Authorization header. The body is
|
|
52
46
|
* not covered: TLS protects it in transit, and signing is there to tell the app's own server from anyone holding a
|
|
53
47
|
* user token, which needs no body coverage. So nothing is buffered here and the body streams through as given.
|
|
54
48
|
*/
|
|
@@ -69,7 +63,6 @@ async function sign(input, init) {
|
|
|
69
63
|
};
|
|
70
64
|
const fields = Object.keys(derived);
|
|
71
65
|
if (headers.has("authorization")) fields.push("authorization");
|
|
72
|
-
if (headers.has(CLIENT_IP_HEADER)) fields.push(CLIENT_IP_HEADER);
|
|
73
66
|
const created = Math.floor(Date.now() / 1e3);
|
|
74
67
|
const params = `(${fields.map((field) => `"${field}"`).join(" ")});created=${created};keyid="${keyId}";tag="softr-code-app"`;
|
|
75
68
|
const base = [...fields.map((field) => `"${field}": ${derived[field] ?? requireDefined(headers.get(field), field)}`), `"@signature-params": ${params}`].join("\n");
|
|
@@ -82,13 +75,6 @@ async function sign(input, init) {
|
|
|
82
75
|
headers.set("signature", `softr=:${signature}:`);
|
|
83
76
|
return new Request(request, { headers });
|
|
84
77
|
}
|
|
85
|
-
function readClientIp() {
|
|
86
|
-
try {
|
|
87
|
-
return getRequestHeader("cf-connecting-ip");
|
|
88
|
-
} catch {
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
78
|
function base64(bytes) {
|
|
93
79
|
return btoa(String.fromCharCode(...new Uint8Array(bytes)));
|
|
94
80
|
}
|
package/dist/formatting.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import * as
|
|
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
|
-
}):
|
|
99
|
+
}): react0.FunctionComponentElement<react0.ProviderProps<Scope>>;
|
|
100
100
|
/**
|
|
101
101
|
* A date in the app's format, safe to render on the server. A timestamp whose
|
|
102
102
|
* zone is not known yet renders `fallback` until the browser supplies it, so
|
|
@@ -118,6 +118,6 @@ declare function FormattedDate({
|
|
|
118
118
|
time?: boolean;
|
|
119
119
|
/** What renders while the visitor's zone is unknown. */
|
|
120
120
|
fallback?: ReactNode;
|
|
121
|
-
}):
|
|
121
|
+
}): react0.FunctionComponentElement<react0.FragmentProps> | null;
|
|
122
122
|
//#endregion
|
|
123
123
|
export { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, FormattedDate, Formatting, FormattingScope, WeekDay, formatDate, formatDateTime, formatNumber, useFormatting };
|
package/dist/mcp.js
CHANGED
|
@@ -3,9 +3,9 @@ import { softrApiUrl } from "./softr-api.js";
|
|
|
3
3
|
import { fetch } from "./fetch.js";
|
|
4
4
|
import { softrConfig } from "./softr-config.js";
|
|
5
5
|
import { sessionConfig } from "./auth/config.js";
|
|
6
|
+
import { makePlatform } from "./auth/platform.js";
|
|
6
7
|
import { readSessionToken, withSessionToken } from "./auth/session.js";
|
|
7
8
|
import { isDatasourceAction } from "./action.js";
|
|
8
|
-
import { makePlatform } from "./auth/platform.js";
|
|
9
9
|
import { ds } from "./datasource/datasource.js";
|
|
10
10
|
import { z } from "zod";
|
|
11
11
|
import { createMiddleware } from "@tanstack/react-start";
|
package/dist/package.js
CHANGED
package/dist/pwa.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react4 from "react";
|
|
2
2
|
import "@tanstack/react-start";
|
|
3
3
|
|
|
4
4
|
//#region src/pwa.d.ts
|
|
@@ -23,7 +23,7 @@ import "@tanstack/react-start";
|
|
|
23
23
|
* )
|
|
24
24
|
* }
|
|
25
25
|
*/
|
|
26
|
-
declare function SoftrPwaHead():
|
|
26
|
+
declare function SoftrPwaHead(): react4.FunctionComponentElement<react4.FragmentProps>;
|
|
27
27
|
type PwaPlatform = "ios" | "android" | "desktop";
|
|
28
28
|
type PwaInstall = {
|
|
29
29
|
available: false;
|
package/package.json
CHANGED
|
@@ -13,7 +13,7 @@ description: >-
|
|
|
13
13
|
metadata:
|
|
14
14
|
type: sub-skill
|
|
15
15
|
library: softr-sdk
|
|
16
|
-
library_version: 1.
|
|
16
|
+
library_version: 1.1.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.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 1.
|
|
12
|
+
library_version: 1.1.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 1.
|
|
12
|
+
library_version: 1.1.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 1.
|
|
10
|
+
library_version: 1.1.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.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 1.
|
|
10
|
+
library_version: 1.1.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.
|
|
12
|
+
library_version: 1.1.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.
|
|
12
|
+
library_version: 1.1.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**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.
|
|
@@ -10,7 +10,7 @@ description: >-
|
|
|
10
10
|
metadata:
|
|
11
11
|
type: sub-skill
|
|
12
12
|
library: softr-sdk
|
|
13
|
-
library_version: 1.
|
|
13
|
+
library_version: 1.1.0
|
|
14
14
|
---
|
|
15
15
|
|
|
16
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. The same holds for any helper that calls `ds`: declare it inside the handler. A function at module level that calls `ds` keeps the server-only import in the browser bundle, and every page stops loading until it moves. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 1.
|
|
12
|
+
library_version: 1.1.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.
|
|
12
|
+
library_version: 1.1.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.
|