@somewhere-cloud/cli 0.38.153 → 0.38.155
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 +11 -0
- package/dist/docs/adopt.md +39 -0
- package/dist/docs/analytics.md +161 -0
- package/dist/docs/api-reference.md +339 -0
- package/dist/docs/api-surface.md +2067 -0
- package/dist/docs/app-mcp.md +162 -0
- package/dist/docs/architecture-patterns.md +334 -0
- package/dist/docs/auth-client.md +531 -0
- package/dist/docs/billing.md +76 -0
- package/dist/docs/browser.md +639 -0
- package/dist/docs/calendar.md +298 -0
- package/dist/docs/changes.md +323 -0
- package/dist/docs/cli.md +407 -0
- package/dist/docs/common-mistakes.md +199 -0
- package/dist/docs/connect-agent.md +72 -0
- package/dist/docs/cors.md +114 -0
- package/dist/docs/cron.md +167 -0
- package/dist/docs/database-engine.md +167 -0
- package/dist/docs/declared-data.md +1656 -0
- package/dist/docs/declared-files.md +475 -0
- package/dist/docs/deploy-intelligence.md +188 -0
- package/dist/docs/deploy.md +733 -0
- package/dist/docs/design-system.md +273 -0
- package/dist/docs/dev-environments.md +496 -0
- package/dist/docs/domain-ownership.md +31 -0
- package/dist/docs/domains.md +370 -0
- package/dist/docs/feedback.md +88 -0
- package/dist/docs/file-tools.md +116 -0
- package/dist/docs/functions.md +489 -0
- package/dist/docs/getting-started.md +238 -0
- package/dist/docs/github.md +95 -0
- package/dist/docs/google-calendar.md +212 -0
- package/dist/docs/groups.md +836 -0
- package/dist/docs/guarantees.md +58 -0
- package/dist/docs/handled-for-you.md +224 -0
- package/dist/docs/inspect.md +171 -0
- package/dist/docs/limits.md +68 -0
- package/dist/docs/live-data.md +197 -0
- package/dist/docs/live.md +92 -0
- package/dist/docs/local-dev.md +30 -0
- package/dist/docs/migration-supabase.md +58 -0
- package/dist/docs/payments.md +1102 -0
- package/dist/docs/portability.md +194 -0
- package/dist/docs/postgres.md +301 -0
- package/dist/docs/pricing-comparison.md +42 -0
- package/dist/docs/pricing.md +39 -0
- package/dist/docs/project-groups.md +107 -0
- package/dist/docs/projects.md +380 -0
- package/dist/docs/recipe-ai-agent.md +112 -0
- package/dist/docs/recipe-ai-features.md +227 -0
- package/dist/docs/recipe-ai-receipts.md +783 -0
- package/dist/docs/recipe-background-jobs.md +369 -0
- package/dist/docs/recipe-booking.md +348 -0
- package/dist/docs/recipe-csv-import.md +390 -0
- package/dist/docs/recipe-ecommerce.md +127 -0
- package/dist/docs/recipe-email.md +282 -0
- package/dist/docs/recipe-escalation.md +133 -0
- package/dist/docs/recipe-file-uploads.md +159 -0
- package/dist/docs/recipe-import-app.md +110 -0
- package/dist/docs/recipe-login.md +457 -0
- package/dist/docs/recipe-multi-chat.md +198 -0
- package/dist/docs/recipe-paid-api.md +161 -0
- package/dist/docs/recipe-pdfs.md +205 -0
- package/dist/docs/recipe-push-notifications.md +107 -0
- package/dist/docs/recipe-seo.md +200 -0
- package/dist/docs/recipe-signed-in-app.md +330 -0
- package/dist/docs/render.md +99 -0
- package/dist/docs/rooms.md +554 -0
- package/dist/docs/sdk.md +287 -0
- package/dist/docs/sdks.md +24 -0
- package/dist/docs/search.md +199 -0
- package/dist/docs/security-model.md +168 -0
- package/dist/docs/setup.md +212 -0
- package/dist/docs/smoke.md +102 -0
- package/dist/docs/speed.md +298 -0
- package/dist/docs/sql-compatibility.md +96 -0
- package/dist/docs/sw.agent.md +248 -0
- package/dist/docs/sw.ai.md +1291 -0
- package/dist/docs/sw.auth.md +1811 -0
- package/dist/docs/sw.billing.md +171 -0
- package/dist/docs/sw.db.md +2128 -0
- package/dist/docs/sw.email.md +661 -0
- package/dist/docs/sw.endpoint.md +187 -0
- package/dist/docs/sw.env.md +303 -0
- package/dist/docs/sw.fetch.md +115 -0
- package/dist/docs/sw.fs.md +424 -0
- package/dist/docs/sw.groups.md +836 -0
- package/dist/docs/sw.image.md +69 -0
- package/dist/docs/sw.jobs.md +520 -0
- package/dist/docs/sw.logs.md +61 -0
- package/dist/docs/sw.mail.md +106 -0
- package/dist/docs/sw.notifications.md +78 -0
- package/dist/docs/sw.push.md +161 -0
- package/dist/docs/sw.rateLimit.md +67 -0
- package/dist/docs/sw.web.md +128 -0
- package/dist/docs/tasks.md +269 -0
- package/dist/docs/test.md +220 -0
- package/dist/docs/tool-reference-account.md +7 -0
- package/dist/docs/tool-reference-ai.md +121 -0
- package/dist/docs/tool-reference-analytics.md +37 -0
- package/dist/docs/tool-reference-api.md +19 -0
- package/dist/docs/tool-reference-artifacts.md +35 -0
- package/dist/docs/tool-reference-auth.md +163 -0
- package/dist/docs/tool-reference-browser.md +114 -0
- package/dist/docs/tool-reference-code.md +26 -0
- package/dist/docs/tool-reference-connect.md +21 -0
- package/dist/docs/tool-reference-cron.md +48 -0
- package/dist/docs/tool-reference-db.md +282 -0
- package/dist/docs/tool-reference-domains.md +107 -0
- package/dist/docs/tool-reference-email.md +55 -0
- package/dist/docs/tool-reference-env.md +19 -0
- package/dist/docs/tool-reference-feedback.md +56 -0
- package/dist/docs/tool-reference-fs.md +265 -0
- package/dist/docs/tool-reference-github.md +57 -0
- package/dist/docs/tool-reference-groups.md +85 -0
- package/dist/docs/tool-reference-help.md +29 -0
- package/dist/docs/tool-reference-jobs.md +39 -0
- package/dist/docs/tool-reference-live.md +48 -0
- package/dist/docs/tool-reference-logs.md +16 -0
- package/dist/docs/tool-reference-payments.md +44 -0
- package/dist/docs/tool-reference-project.md +706 -0
- package/dist/docs/tool-reference-push.md +78 -0
- package/dist/docs/tool-reference-rate-limit.md +18 -0
- package/dist/docs/tool-reference-search.md +68 -0
- package/dist/docs/tool-reference-security.md +42 -0
- package/dist/docs/tool-reference-smoke.md +17 -0
- package/dist/docs/tool-reference-stock-photos.md +20 -0
- package/dist/docs/tool-reference-tasks.md +73 -0
- package/dist/docs/tool-reference-telegram.md +32 -0
- package/dist/docs/tool-reference-usage.md +9 -0
- package/dist/docs/tool-reference-web.md +71 -0
- package/dist/docs/tool-reference-webhooks.md +9 -0
- package/dist/docs/troubleshooting.md +411 -0
- package/dist/docs/typed-functions.md +94 -0
- package/dist/docs/verify-before-deploy.md +67 -0
- package/dist/docs/vs-supabase.md +75 -0
- package/dist/docs/vs-vercel.md +103 -0
- package/dist/lib/bundle.js +303 -221
- package/dist/lib/bundle.js.map +3 -3
- package/dist/types/lib/test-session.d.ts +8 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -2
- package/runtime/DECLARED-DATA-VENDOR.json +5 -5
- package/runtime/PLATFORM-SOURCE.json +1 -1
- package/runtime/SOURCE-LINT-VENDOR.json +2 -2
- package/runtime/declared-data.cjs +37 -19
- package/runtime/source-lint.cjs +1 -1
|
@@ -0,0 +1,1656 @@
|
|
|
1
|
+
# Declared data — the schema file is the contract
|
|
2
|
+
|
|
3
|
+
## Data
|
|
4
|
+
|
|
5
|
+
Application tables are declared in db/schema.ts. sw.db.from reads them with caller-scoped access, and sw.db.server.from reads them once the caller is authorized for server access. The corresponding structured methods, such as sw.db.server.insert, change them. Raw query and batch go to the separate raw SQL database on current projects.
|
|
6
|
+
|
|
7
|
+
Each project has its own managed database. You describe its tables, and who may
|
|
8
|
+
reach each row, in `db/schema.ts`. That file ships with your source, and deploy
|
|
9
|
+
creates or updates the tables to match it. The platform generates a typed
|
|
10
|
+
browser client and applies the same access rules in your functions. Raw SQL
|
|
11
|
+
uses a separate raw database; it never reaches managed tables. To keep an
|
|
12
|
+
existing dataset in Postgres, attach it instead (see `postgres`).
|
|
13
|
+
|
|
14
|
+
A row is private to its owner with `owner()`, as below. To let an owner share
|
|
15
|
+
their existing rows with specific people, use `anyOf(owner(), grant(...))`.
|
|
16
|
+
Every existing caller-scoped read then includes shared rows. For an
|
|
17
|
+
owner-only read, filter by `where: { user_id: me.id }` in a function, using
|
|
18
|
+
the signed-in user's ID. See `per-owner-sharing` for the deploy warning.
|
|
19
|
+
|
|
20
|
+
For one club whose organiser manages the whole app, declare the organiser's
|
|
21
|
+
read/create/update/delete permissions with `appRole()`. For 'my rows or the
|
|
22
|
+
organiser', combine `owner()` and `appRole()` with `anyOf`. `shared()`
|
|
23
|
+
alone keeps writes with each row's creator. See `sw.groups` → `app-wide-roles`
|
|
24
|
+
and `sw.db` → `owner-or-member-and-parent-access`.
|
|
25
|
+
|
|
26
|
+
### Declare a table and use it
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
// db/schema.ts
|
|
30
|
+
import { id, owner, schema, table, text, timestamp } from 'somewhere/db';
|
|
31
|
+
|
|
32
|
+
export default schema({
|
|
33
|
+
notes: table(
|
|
34
|
+
{
|
|
35
|
+
id: id(),
|
|
36
|
+
title: text(),
|
|
37
|
+
body: text({ default: '' }),
|
|
38
|
+
created_at: timestamp({ default: 'now' }),
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
scope: owner(),
|
|
42
|
+
client: {
|
|
43
|
+
read: ['id', 'title', 'body', 'created_at'],
|
|
44
|
+
create: ['title', 'body'],
|
|
45
|
+
update: ['title', 'body'],
|
|
46
|
+
delete: true,
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
),
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`owner()` makes each row belong to the signed-in user who created it. The
|
|
54
|
+
platform adds and fills in the owner column itself. The `client` block is the
|
|
55
|
+
browser's entire grant: these columns can be read, `title` and `body` can be
|
|
56
|
+
set, and rows can be deleted. A table without a `client` block can't be reached
|
|
57
|
+
from the browser at all.
|
|
58
|
+
|
|
59
|
+
`id()` gives a new table a random text key, so `id` is a string. A table
|
|
60
|
+
that already has integer ids keeps them under a bare `id()`: the deploy
|
|
61
|
+
changes neither the table nor its ids. `id({ uuid: false })` declares an
|
|
62
|
+
integer key; the opt-in private-data starter uses it because its safe create retry
|
|
63
|
+
needs one. `id({ uuid: true })` over existing integer ids is refused.
|
|
64
|
+
|
|
65
|
+
Use the generated client from your app:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
// src/services/notes.ts
|
|
69
|
+
import { data, DataError } from 'somewhere:data';
|
|
70
|
+
|
|
71
|
+
export interface Note {
|
|
72
|
+
id: string;
|
|
73
|
+
title: string;
|
|
74
|
+
body: string;
|
|
75
|
+
created_at: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// owner() scopes every call to the signed-in user. Send no user ID or filter.
|
|
79
|
+
export async function listNotes(): Promise<Note[]> {
|
|
80
|
+
const page = await data.notes.list({ limit: 50 });
|
|
81
|
+
return page.data;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function addNote(title: string, body = ''): Promise<Note | null> {
|
|
85
|
+
const created = await data.notes.create({ title: title.trim(), body });
|
|
86
|
+
return created.data;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function updateNote(id: Note['id'], title: string, body: string): Promise<void> {
|
|
90
|
+
await data.notes.update(id, { title: title.trim(), body });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function deleteNote(id: Note['id']): Promise<void> {
|
|
94
|
+
await data.notes.delete(id);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function notesErrorMessage(reason: unknown): string {
|
|
98
|
+
if (reason instanceof DataError) {
|
|
99
|
+
if (reason.code === 'AUTH_REQUIRED') return 'Your session ended. Sign in again.';
|
|
100
|
+
if (reason.code === 'DATA_CONTRACT_MISMATCH') return 'This app was just updated. Reload the page.';
|
|
101
|
+
if (reason.code === 'DATA_NOT_FOUND') return 'That note was not found.';
|
|
102
|
+
}
|
|
103
|
+
return 'Something went wrong. Try again.';
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Run `somewhere typecheck`, then `somewhere deploy`. The deploy creates the
|
|
108
|
+
`notes` table, and `somewhere typecheck` types `somewhere:data` from your
|
|
109
|
+
schema locally. Sign in with two accounts: each one lists, adds, edits and
|
|
110
|
+
deletes only its own notes.
|
|
111
|
+
|
|
112
|
+
What the declaration gives you:
|
|
113
|
+
|
|
114
|
+
- **Ownership comes from the session.** Creates set the owner from the
|
|
115
|
+
verified user, and the browser can't name another owner. List, get, update
|
|
116
|
+
and delete only reach the caller's rows. Updating or deleting someone else's
|
|
117
|
+
note gets the same `DATA_NOT_FOUND` as a missing note, and `get` returns
|
|
118
|
+
`null`.
|
|
119
|
+
- **Only granted operations exist.** An operation or column you didn't grant
|
|
120
|
+
isn't on the client. Direct HTTP to the data endpoint has the same limits.
|
|
121
|
+
Browser calls send your app's origin automatically. A script calling the
|
|
122
|
+
endpoint must set the `Origin` header itself.
|
|
123
|
+
- **Schema changes ship with the source.** Adding tables and columns applies on
|
|
124
|
+
deploy. Production deploys refuse to remove or rename a column that's already
|
|
125
|
+
deployed. After any table change, pages loaded before the deploy get
|
|
126
|
+
`DATA_CONTRACT_MISMATCH` until they reload, which the example handles.
|
|
127
|
+
|
|
128
|
+
## Teams
|
|
129
|
+
|
|
130
|
+
A team people join is a built-in group. Give the team's rows a non-null text
|
|
131
|
+
column holding the group id and scope them with `group()`; the platform keeps
|
|
132
|
+
the team, its invitations, roster and owners. The complete app, with its
|
|
133
|
+
endpoints and spec, is `somewhere docs sw.groups --section team-example`.
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
// db/schema.ts
|
|
137
|
+
import { schema, table, id, text, owner, group, anyOf } from 'somewhere/db';
|
|
138
|
+
export default schema({
|
|
139
|
+
tasks: table({ id: id(), team_id: text(), title: text() }, {
|
|
140
|
+
scope: anyOf(owner(), group({ column: 'team_id', roles: {
|
|
141
|
+
read: ['owner', 'admin', 'member'], create: ['owner', 'admin', 'member'],
|
|
142
|
+
update: ['owner', 'admin', 'member'], delete: ['owner'],
|
|
143
|
+
} })),
|
|
144
|
+
client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },
|
|
145
|
+
}),
|
|
146
|
+
});
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
// src/services/tasks.ts
|
|
151
|
+
import { data } from 'somewhere:data';
|
|
152
|
+
export async function addTask(teamId: string, title: string) {
|
|
153
|
+
return data.tasks.create({ team_id: teamId, title });
|
|
154
|
+
}
|
|
155
|
+
export async function listTasks(teamId: string) {
|
|
156
|
+
return data.tasks.list({ where: { team_id: teamId }, limit: 100 });
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Members read, create and update tasks; the creator or a team owner deletes one,
|
|
161
|
+
and someone removed from the team loses even the tasks they created. Inside
|
|
162
|
+
`anyOf()` an operation left out of `roles` allows no group role, so all four
|
|
163
|
+
are listed. Starting a team needs a signed-in user; joining one needs a
|
|
164
|
+
verified email. For a relationship your app records itself (a booking's
|
|
165
|
+
provider, a class's students), use `member()` over your own table:
|
|
166
|
+
`sw.groups` → `relationships-that-are-not-teams`.
|
|
167
|
+
|
|
168
|
+
## The same table in a function
|
|
169
|
+
|
|
170
|
+
Inside a function, the structured calls `sw.db.from`, `insert`, `update` and
|
|
171
|
+
`remove` act as the calling user and follow the same `owner()` rule. Use a
|
|
172
|
+
function for anything the browser grant can't express. This one searches
|
|
173
|
+
titles:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
// api/notes/search.ts — the signed-in user's notes whose title contains ?q=
|
|
177
|
+
export default async function searchNotes(
|
|
178
|
+
request: Request,
|
|
179
|
+
sw: SomewhereRuntimeContext,
|
|
180
|
+
): Promise<Response> {
|
|
181
|
+
if (request.method !== 'GET') {
|
|
182
|
+
return new Response('Use GET.', { status: 405, headers: { Allow: 'GET' } });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const user = await sw.auth.fromRequest(request);
|
|
186
|
+
if (!user) {
|
|
187
|
+
return Response.json({ error: 'Sign in to search your notes.' }, { status: 401 });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const query = new URL(request.url).searchParams.get('q')?.trim() ?? '';
|
|
191
|
+
if (!query || query.length > 100) {
|
|
192
|
+
return Response.json({ error: 'Search for 1–100 characters.' }, { status: 400 });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// owner() limits this read to the caller's notes.
|
|
196
|
+
const { data } = await sw.db.from('notes', {
|
|
197
|
+
where: { title: { contains: query } },
|
|
198
|
+
columns: ['id', 'title', 'created_at'],
|
|
199
|
+
order: [['created_at', 'desc']],
|
|
200
|
+
limit: 20,
|
|
201
|
+
});
|
|
202
|
+
return Response.json(data);
|
|
203
|
+
}
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
`contains` treats the user's text as data, so `%` and `_` match literally.
|
|
207
|
+
|
|
208
|
+
**Server authority is a separate, explicit path.** `sw.db.server.*` and
|
|
209
|
+
`{ asServer: true }` read or write across all users, and declared row
|
|
210
|
+
permissions don't apply to them. Use them for admin screens, jobs and
|
|
211
|
+
aggregates, and authorize the caller in your function first. Keep the table's
|
|
212
|
+
managed rule: one exceptional write does not require changing every table to
|
|
213
|
+
`serverOnly()`. For an enquiry to a public profile, first use declared
|
|
214
|
+
`client.intake` → `send-an-enquiry-to-a-public-profile` below. For other
|
|
215
|
+
exceptional writes, `recipe-signed-in-app` shows a validated reference,
|
|
216
|
+
abuse protection and an authorized structured server insert.
|
|
217
|
+
|
|
218
|
+
Both `sw.db.query` and `sw.db.server.query` use the separate raw database.
|
|
219
|
+
Neither reads managed tables. Use structured `sw.db.server` calls for authorized
|
|
220
|
+
cross-user work on managed data.
|
|
221
|
+
|
|
222
|
+
### Live lists and search
|
|
223
|
+
|
|
224
|
+
- **A list that updates itself:** declare the read in a function with
|
|
225
|
+
`sw.rooms.live(name, sw.db.from(...))`. The browser gets the rows plus a
|
|
226
|
+
subscription and re-reads through your function when the rows change. See
|
|
227
|
+
`rooms` → `live-lists`.
|
|
228
|
+
- **Matching text in a column:** `contains`, `startsWith` and `endsWith` in a
|
|
229
|
+
function, as above.
|
|
230
|
+
- **Ranked search by meaning over documents or app content:** managed search
|
|
231
|
+
indexes files you add and content you upsert, with no separate vector
|
|
232
|
+
database to run. See `search`.
|
|
233
|
+
- **SQL syntax:** the dialect reference is `sql-compatibility`.
|
|
234
|
+
|
|
235
|
+
### More on data
|
|
236
|
+
|
|
237
|
+
| Need | Where |
|
|
238
|
+
|---|---|
|
|
239
|
+
| Sharing rows with invited people and roles: `group()` | `sw.groups` |
|
|
240
|
+
| Private drafts before sign-up; public enquiry forms | `declared-data` → `keep-a-private-draft-before-sign-up`, `send-an-enquiry-to-a-public-profile` |
|
|
241
|
+
| Read-only or editable links to one private row | `declared-data` → `share-one-row-by-link` |
|
|
242
|
+
| Every scope (`group`, `appRole`, `shared`, `member`, `anyOf`, `parent`, `serverOnly`), public reads, visitors | `declared-data` → `one-table-fully-declared`, `visitors` |
|
|
243
|
+
| Generated client: get, pages (at most 100 rows per call), aggregates, related records, error codes | `declared-data` → `the-generated-client`, `paging-a-list`, `related-records` |
|
|
244
|
+
| Calling the browser data route `POST /__sw/data` from a script or test, and its contract digest | `declared-data` → `calling-the-data-endpoint-directly` |
|
|
245
|
+
| File collections declared in the same schema file | `declared-files` |
|
|
246
|
+
| Table and column names, column types, indexes, composite uniqueness, deploy behavior, removing tables | `sw.db` → `start-with-the-schema-file-dbschemats` |
|
|
247
|
+
| Filters, ordering, joins, aggregates in functions | `sw.db` → `builder-verbs-and-where-shapes`, `related-rows-in-server-functions`, `aggregates-swdbaggregate` |
|
|
248
|
+
| Cross-user reads with server authority | `sw.db` → `cross-user-reads-explicit-server-authority`; `declared-data` → `inside-functions` |
|
|
249
|
+
| All-or-nothing writes | `sw.db` → `swdbtxintents` |
|
|
250
|
+
| Raw SQL, managed-mode rules, migrations | `sw.db` → `managed-mode-what-a-dbschemats-does-to-raw-sql`, `swdbserverquerysql-params-swdbserverbatchstatements` |
|
|
251
|
+
| Large integers, size limits, performance | `sw.db` → `whole-numbers-wider-than-javascript`, `size-boundaries`, `performance-and-query-duration` |
|
|
252
|
+
| Database model and when Postgres fits | `database-engine`, `postgres` |
|
|
253
|
+
| SQL dialect | `sql-compatibility` |
|
|
254
|
+
|
|
255
|
+
## One table, fully declared
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
import { schema, table, id, text, integer, boolean, owner, shared, serverOnly } from 'somewhere/db';
|
|
259
|
+
|
|
260
|
+
export default schema({
|
|
261
|
+
notes: table(
|
|
262
|
+
{ id: id(), title: text(), body: text(), pinned: integer({ default: 0 }) },
|
|
263
|
+
{
|
|
264
|
+
scope: owner(),
|
|
265
|
+
client: {
|
|
266
|
+
read: ['id', 'title', 'body', 'pinned'],
|
|
267
|
+
create: ['title', 'body'],
|
|
268
|
+
update: ['title', 'body', 'pinned'],
|
|
269
|
+
delete: true,
|
|
270
|
+
publicRead: false,
|
|
271
|
+
identity: 'authenticated',
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
),
|
|
275
|
+
posts: table(
|
|
276
|
+
{ id: id(), message: text() },
|
|
277
|
+
{ scope: shared(), client: { read: ['id', 'message'], create: ['message'] } },
|
|
278
|
+
),
|
|
279
|
+
articles: table(
|
|
280
|
+
{ id: id(), title: text(), published: boolean({ default: false }) },
|
|
281
|
+
{
|
|
282
|
+
scope: owner(),
|
|
283
|
+
client: {
|
|
284
|
+
read: ['id', 'title'],
|
|
285
|
+
publicRead: { where: { published: true } },
|
|
286
|
+
create: ['title'],
|
|
287
|
+
update: ['title'],
|
|
288
|
+
},
|
|
289
|
+
},
|
|
290
|
+
),
|
|
291
|
+
// Used by the owner-scoped aggregates example below.
|
|
292
|
+
orders: table(
|
|
293
|
+
{ id: id(), amount: integer(), status: text(), archived: boolean({ default: false }) },
|
|
294
|
+
{ scope: owner(), client: { read: ['id', 'amount', 'status', 'archived'] } },
|
|
295
|
+
),
|
|
296
|
+
ledger: table({ id: id(), amount: integer() }, { scope: serverOnly() }),
|
|
297
|
+
});
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
**scope** says who may access rows:
|
|
301
|
+
|
|
302
|
+
- `owner()` — a signed-in member reads and writes only their own rows. The
|
|
303
|
+
default ownership.
|
|
304
|
+
- `shared()` — every signed-in member reads every row; only its creator
|
|
305
|
+
writes it (others get `DATA_NOT_FOUND`, like a missing row). The author is a
|
|
306
|
+
managed column the browser never sees; rows that predate the declaration have
|
|
307
|
+
no author and cannot be edited from the browser.
|
|
308
|
+
- `group({ column?, roles? })` — the row belongs to one built-in group, named
|
|
309
|
+
by a text column (default `group_id`); members act on it as their current
|
|
310
|
+
role allows. The way to share data in a new app: `sw.groups`.
|
|
311
|
+
- `appRole({ roles })` — access by an app-wide role such as staff, granted
|
|
312
|
+
to people or held by everyone with a verified email at your domain
|
|
313
|
+
(`appRoles: { staff: { emailDomain: 'example.com' } }`):
|
|
314
|
+
`sw.groups` → `app-wide-roles`.
|
|
315
|
+
- `member({ group, membership, member_user, member_group })` — for an app
|
|
316
|
+
that keeps its own membership table. Rows carry a
|
|
317
|
+
group key; members of that group, resolved through the named membership
|
|
318
|
+
table, can read, create, update, and delete them. Moving such an app to
|
|
319
|
+
built-in groups is an explicit mapping, not automatic:
|
|
320
|
+
`sw.groups` → `apps-with-their-own-membership-table`. Use `operations: ['read']`
|
|
321
|
+
inside the member options for read-only membership. The membership table
|
|
322
|
+
itself is never written from the browser.
|
|
323
|
+
**The membership table** is one you declare in the same file, usually
|
|
324
|
+
`serverOnly()`, with one row per group and user: `member_user` names its
|
|
325
|
+
user-id column, `member_group` its group-key column, declared unique
|
|
326
|
+
together. Your functions write it: create a group and its first member in
|
|
327
|
+
one `sw.db.tx` (supply the group id yourself, for example
|
|
328
|
+
`id({ uuid: true })` and `crypto.randomUUID()`), and add a member after
|
|
329
|
+
`sw.auth.getAcceptedInvite`, recording the invitation id in a
|
|
330
|
+
`serverOnly()` table with a unique column in the same transaction so one
|
|
331
|
+
invitation joins once. The invitation steps: `sw.auth` → `invitations`.
|
|
332
|
+
`recipe-login` → `7-team-invites` builds the same team app on built-in
|
|
333
|
+
groups instead.
|
|
334
|
+
- `anyOf(owner(), group({ roles: { read: ['admin'], update: ['admin'] } }))`
|
|
335
|
+
— the owner or a listed role in the row's built-in group. Use
|
|
336
|
+
`appRole({ roles: { read: ['moderator'], update: ['moderator'] } })`
|
|
337
|
+
instead for app-wide moderators. Exactly one owner branch and one
|
|
338
|
+
`group()`, `appRole()`, `member()` or `grant()` branch are supported.
|
|
339
|
+
Each role branch grants only its listed operations. With a `group()` or
|
|
340
|
+
`member()` branch this is a team table: team rows belong to the team, so
|
|
341
|
+
the owner keeps their own rows only while they are in the row's group, and
|
|
342
|
+
removing someone from the group removes their access to its rows, including
|
|
343
|
+
the ones they created (adding them back restores it). A row with no group
|
|
344
|
+
stays with its owner. With an `appRole()` branch the owner always keeps
|
|
345
|
+
their own rows. The platform sets and protects the owner column.
|
|
346
|
+
For a group or member branch, creating a row also requires membership in
|
|
347
|
+
its supplied group. Role lists are exact: include `owner` when group owners
|
|
348
|
+
should have those permissions too. See `sw.db` →
|
|
349
|
+
`owner-or-member-and-parent-access`. A branch may list the columns it
|
|
350
|
+
reads, `owner({ read: ['id', 'subject', 'status'] })`; a branch without
|
|
351
|
+
`read` reads every column. The row a reader gets carries the union of the
|
|
352
|
+
admitting branches' columns, and a column outside them is absent
|
|
353
|
+
(`one-row-two-readers-different-columns`).
|
|
354
|
+
- `allOf(gate, who)` — only the row's current members, AND either its
|
|
355
|
+
author or a permitted role. The gate is `member()`, `group()` or
|
|
356
|
+
`appRole()` with its operations listed; who is `owner()` or
|
|
357
|
+
`anyOf(owner(), …)`. Removing someone from the gate removes their access
|
|
358
|
+
to every row, including the rows they created. See `sw.db` →
|
|
359
|
+
`owner-or-member-and-parent-access`.
|
|
360
|
+
- `parent({ via: 'project_id' })` — access follows the referenced parent's
|
|
361
|
+
private scope. Declare `project_id` with `references: 'projects'`.
|
|
362
|
+
A foreign key or relationship alone never grants this access.
|
|
363
|
+
Creating a child row needs `create` on the parent row for that person: the
|
|
364
|
+
parent's owner, or a role listed under the parent's `create`. Read or update
|
|
365
|
+
alone is not enough: a staff reply to a customer's ticket is refused with 403
|
|
366
|
+
`POLICY_AUTHORITY_REQUIRED` unless the ticket's rule lists `create: ['staff']`.
|
|
367
|
+
- `serverOnly()` — the browser never reaches it; only your functions do.
|
|
368
|
+
|
|
369
|
+
**Who created a row.** `owner()`, including inside `anyOf`, fills the
|
|
370
|
+
owner column from the verified session, and `shared()` records the author in
|
|
371
|
+
a column the browser never sees. Any other column that names a user, such as
|
|
372
|
+
`created_by` or `assigned_to`, is ordinary data: the platform never treats a
|
|
373
|
+
column as identity because of its name, and the browser can write whatever
|
|
374
|
+
`client.create` lists. To record the creator on a `member()` table, keep the
|
|
375
|
+
column out of `client.create` and create rows in a function that sets it from
|
|
376
|
+
`sw.auth.requireUser(req)`: `recipe-login` →
|
|
377
|
+
`who-created-a-task-comes-from-the-session`. A function's own caller-scoped
|
|
378
|
+
`sw.db.insert` stamps the owner the same way and may set any declared column:
|
|
379
|
+
`client.create` limits only the browser's generated client. `sw.db.server.insert`
|
|
380
|
+
stamps nothing; it writes exactly the columns you pass, so name the owner
|
|
381
|
+
column yourself (`docs({ topic: 'sw.db', section: 'start-with-the-schema-file-dbschemats' })`).
|
|
382
|
+
|
|
383
|
+
**client** says what the browser may do, and nothing is exposed until you say
|
|
384
|
+
so. A table without a `client` block is server-only from the browser's point
|
|
385
|
+
of view even when its scope is `owner()`.
|
|
386
|
+
|
|
387
|
+
- `read`: the columns the browser may see (`true` for all of them). The
|
|
388
|
+
owner or author column is never among them; a read asked for `{ can: true }`
|
|
389
|
+
says `mine` on each row instead (`which-rows-belong-to-the-signed-in-user`).
|
|
390
|
+
When the table's `anyOf()` branches list their own columns, the browser gets
|
|
391
|
+
a row's column only when a branch that lists it admits the reader
|
|
392
|
+
(`one-row-two-readers-different-columns`).
|
|
393
|
+
- `create` / `update`: the columns the browser may set; `null` disables the
|
|
394
|
+
operation. Owner and author columns and platform columns are set by the
|
|
395
|
+
platform, never by the browser. A group-key column is supplied on create and
|
|
396
|
+
checked against the caller's membership; it cannot be changed on update.
|
|
397
|
+
Binary columns are never browser-writable.
|
|
398
|
+
- `delete`: whether the browser may delete.
|
|
399
|
+
- `publicRead`: visitors who are not signed in may read the explicit `read`
|
|
400
|
+
columns, and only those. `true` publishes every row; `{ where: {
|
|
401
|
+
published: true } }` publishes only rows matching 1-8 literal equality
|
|
402
|
+
fields. Public access adds to ordinary access: signed-in authors still see
|
|
403
|
+
their own drafts, members see their group rows, and shared-table readers keep
|
|
404
|
+
their signed-in view. A signed-in user with no other access, such as a
|
|
405
|
+
customer without the `staff` role on an `appRole()` table, reads the
|
|
406
|
+
same published rows a signed-out visitor sees.
|
|
407
|
+
List/get filters and cursors narrow that combined view;
|
|
408
|
+
the same explicit read columns apply throughout. Publication
|
|
409
|
+
fields cannot be generic browser create/update fields, and a browser-created
|
|
410
|
+
row must default private. Public never means writable: an authorized server
|
|
411
|
+
handler publishes a row with `sw.db.server.update`. Public live views are unavailable; public list/get calls refresh normally.
|
|
412
|
+
Anonymous public reads can use a cached result for up to
|
|
413
|
+
120 seconds after the database produced it.
|
|
414
|
+
Declared writes invalidate that table's cached results asynchronously; allow
|
|
415
|
+
that full window for an edit, deletion or withdrawal to reach every reader.
|
|
416
|
+
For fresh public pages, use a page handler with `sw.db.server.from`,
|
|
417
|
+
filter for published rows, select only public columns, and return
|
|
418
|
+
`Cache-Control: no-store`.
|
|
419
|
+
Developer SQL writes rely on expiry. Expired results are fetched again;
|
|
420
|
+
a failed refresh returns an error. Each release has its own cache.
|
|
421
|
+
Requests with a session cookie, visitor cookie or `Authorization` header
|
|
422
|
+
bypass this cache. Private, owner and member reads stay live, and the browser
|
|
423
|
+
data client reads live immediately after a write so it sees its own change.
|
|
424
|
+
Whenever a deploy, deploy check or dry run turns `publicRead` on or changes
|
|
425
|
+
it, its warnings carry one line per table naming the columns anyone can
|
|
426
|
+
read, how many rows are readable right now (counting only rows that match
|
|
427
|
+
`where`), and how to narrow it. The line starts `SEVERE: public read`
|
|
428
|
+
when the table was not public in the version it replaces, already has
|
|
429
|
+
rows, or a readable column looks private (email, password, token, secret,
|
|
430
|
+
PIN, phone, address, date of birth); otherwise it starts `Public read:`.
|
|
431
|
+
The same finding appears once in the project's notices and in the security
|
|
432
|
+
review. Redeploying an unchanged `publicRead` stays quiet.
|
|
433
|
+
- `identity`: `'authenticated'`, or `'visitor'` on a table that allows
|
|
434
|
+
visitors (below).
|
|
435
|
+
|
|
436
|
+
## Share one row by link
|
|
437
|
+
|
|
438
|
+
Give someone a read-only or editable link to one row while keeping the table
|
|
439
|
+
private. The platform stores the link secret hashed, checks its permission on
|
|
440
|
+
each request and lets the row owner revoke it. The recipient needs no account;
|
|
441
|
+
the link grants access to that row, without transferring ownership. On a team
|
|
442
|
+
table (`anyOf(owner(), member(...))` or `anyOf(owner(), group(...))`) the
|
|
443
|
+
owner creates and manages links only while in the row's group, and a link
|
|
444
|
+
works only while the person who made it is still in the row's group: removing
|
|
445
|
+
them stops their links, and adding them back restores them.
|
|
446
|
+
|
|
447
|
+
Declare the fields a link may expose in `client.links`:
|
|
448
|
+
|
|
449
|
+
```ts
|
|
450
|
+
import { schema, table, id, text, owner } from 'somewhere/db';
|
|
451
|
+
|
|
452
|
+
export default schema({
|
|
453
|
+
notes: table({ id: id(), title: text(), body: text(), private_note: text() }, {
|
|
454
|
+
scope: owner(),
|
|
455
|
+
client: {
|
|
456
|
+
read: ['id', 'title', 'body', 'private_note'],
|
|
457
|
+
create: ['title', 'body', 'private_note'],
|
|
458
|
+
update: ['title', 'body', 'private_note'],
|
|
459
|
+
links: { read: ['id', 'title', 'body'], edit: ['body'] },
|
|
460
|
+
},
|
|
461
|
+
}),
|
|
462
|
+
});
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
The signed-in owner creates a link in browser code:
|
|
466
|
+
|
|
467
|
+
```ts
|
|
468
|
+
import { data } from 'somewhere:data';
|
|
469
|
+
|
|
470
|
+
export async function shareNote(id: string) {
|
|
471
|
+
const { url } = await data.notes.createLink(id, {
|
|
472
|
+
access: 'edit', returnTo: '/shared',
|
|
473
|
+
});
|
|
474
|
+
return url;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export async function readSharedNote(linkId: string, id: string) {
|
|
478
|
+
return data.linked(linkId).notes.get(id);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
export async function editSharedNote(linkId: string, id: string, body: string) {
|
|
482
|
+
return data.linked(linkId).notes.update(id, { body });
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
export async function stopSharing(id: string, linkId: string) {
|
|
486
|
+
return data.notes.revokeLink(id, linkId);
|
|
487
|
+
}
|
|
488
|
+
```
|
|
489
|
+
|
|
490
|
+
Build the `/shared` screen in your app. Opening the URL first visits the
|
|
491
|
+
platform's link page, which exchanges the secret for an HttpOnly cookie and
|
|
492
|
+
removes the secret before opening your screen. `data.links.sessions()`
|
|
493
|
+
returns the available links with their `link_id`, `table`, `row_id`
|
|
494
|
+
and `access`; use the chosen link ID and row ID for that screen. This schema
|
|
495
|
+
uses numeric IDs, so convert its `row_id` with `Number()`.
|
|
496
|
+
A signed-in recipient's ordinary access is separate from `data.linked(linkId)`.
|
|
497
|
+
|
|
498
|
+
Use `access: 'read'` for a read-only link, `expiresInDays` to choose an
|
|
499
|
+
expiry, and `data.notes.links(id)` to list a row's links. Set
|
|
500
|
+
`client.links.maxDays` to require an expiry within that many days; pass
|
|
501
|
+
`expiresInDays` when creating each link. `data.links.forget(linkId)`
|
|
502
|
+
removes a link from this browser; the owner's `revokeLink` ends it for everyone.
|
|
503
|
+
|
|
504
|
+
A link can also reach the direct `hasMany` relations listed in
|
|
505
|
+
`client.links.children`. Each child table must use `parent({ via })`
|
|
506
|
+
through that relation's foreign key. The linked view can list those children,
|
|
507
|
+
and an edit link can create or update the child fields allowed by its client
|
|
508
|
+
permissions. Links never delete rows, list the whole parent table or claim
|
|
509
|
+
ownership. Refresh a list to see changes made through a link.
|
|
510
|
+
|
|
511
|
+
Share links run on the live app's managed database, with separate raw storage.
|
|
512
|
+
The owner or a creator view can issue them. For a private draft before
|
|
513
|
+
sign-up or a public enquiry form, use the examples below. An unrelated redeploy preserves links. Changing their
|
|
514
|
+
permissions, removing the declaration, deleting the row or changing its key
|
|
515
|
+
or owner ends the affected access. Rollback ends existing links; deploy the
|
|
516
|
+
app's source again before creating new ones. A shared URL grants access to
|
|
517
|
+
whoever receives it, and your own server functions receive the app's cookies.
|
|
518
|
+
|
|
519
|
+
## Keep a private draft before sign-up
|
|
520
|
+
|
|
521
|
+
Let someone start a private note before creating an account, keep its private
|
|
522
|
+
creator link, reopen the note with that link, and claim it after signing in.
|
|
523
|
+
Declare anonymous creation on an `owner()` table:
|
|
524
|
+
|
|
525
|
+
```ts
|
|
526
|
+
// db/schema.ts
|
|
527
|
+
import { schema, table, id, text, owner } from 'somewhere/db';
|
|
528
|
+
|
|
529
|
+
export default schema({
|
|
530
|
+
notes: table({ id: id({ uuid: false }), title: text(), body: text() }, {
|
|
531
|
+
scope: owner(),
|
|
532
|
+
client: {
|
|
533
|
+
read: ['id', 'title', 'body'],
|
|
534
|
+
create: ['title', 'body'],
|
|
535
|
+
update: ['title', 'body'],
|
|
536
|
+
links: { read: true, edit: ['title', 'body'], anonymousCreate: true },
|
|
537
|
+
},
|
|
538
|
+
}),
|
|
539
|
+
});
|
|
540
|
+
```
|
|
541
|
+
|
|
542
|
+
Use the generated browser methods:
|
|
543
|
+
|
|
544
|
+
```ts
|
|
545
|
+
// src/services/drafts.ts
|
|
546
|
+
import { data } from 'somewhere:data';
|
|
547
|
+
|
|
548
|
+
export function startDraft(title: string, body: string) {
|
|
549
|
+
return data.notes.createAnonymous({ title, body });
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
export function retryDraft(created: Awaited<ReturnType<typeof startDraft>>) {
|
|
553
|
+
return created.request.retry(); // Call only when the person chooses Retry.
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
export function readOpenedDraft() {
|
|
557
|
+
const opened = data.creators.opened().find(entry => entry.table === 'notes');
|
|
558
|
+
if (!opened) return null;
|
|
559
|
+
return data.creator(opened.creator_id).notes.get(Number(opened.row_id));
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export function saveOpenedDraft(creatorId: string, id: number, body: string) {
|
|
563
|
+
return data.creator(creatorId).notes.update(id, { body });
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// Sign in through the app's normal sign-in flow before calling this.
|
|
567
|
+
export function claimDraft(creatorId: string, id: number) {
|
|
568
|
+
return data.creator(creatorId).notes.claim(id);
|
|
569
|
+
}
|
|
570
|
+
```
|
|
571
|
+
|
|
572
|
+
`startDraft` returns `data` (the readable row or `null`), `grant`,
|
|
573
|
+
`creator`, `idempotency` and `request`. Offer the person a way to keep
|
|
574
|
+
`created.creator.url` privately and open that URL to continue. Creation does
|
|
575
|
+
not open a creator session by itself. The link first opens the platform's
|
|
576
|
+
creator page, which exchanges its secret for an HttpOnly cookie, removes the
|
|
577
|
+
secret and returns to the app page where creation started. Build that page to
|
|
578
|
+
read `data.creators.opened()` and show the chosen note. Those entries include
|
|
579
|
+
`creator_id`, `table` and `row_id`; `data.creators.sessions()` reads the
|
|
580
|
+
current sessions. `data.creators.forget(creatorId)` removes one from this
|
|
581
|
+
browser.
|
|
582
|
+
|
|
583
|
+
Treat the creator link as a private capability: anyone who receives it can
|
|
584
|
+
read, edit, share and claim this note. Keep its URL and `creator.secret` out
|
|
585
|
+
of logs, analytics, public pages and ordinary share buttons. The capability's
|
|
586
|
+
secret and URL are omitted when the result is JSON-serialized; keeping that
|
|
587
|
+
JSON alone does not save the link.
|
|
588
|
+
|
|
589
|
+
Claim explicitly after sign-in. A successful claim returns `claimed: true`
|
|
590
|
+
and `shares: 'revoked'`, `'kept'` or `'unknown'`; it moves the note to the
|
|
591
|
+
signed-in account and ends creator access. Shares are revoked by default;
|
|
592
|
+
pass `{ keepShares: true }` to preserve existing share links. If a claim's
|
|
593
|
+
reply is lost, use `data.creator(creatorId).notes.claimStatus(id)` to read
|
|
594
|
+
`'claimed_by_you'`, `'not_claimed'` or `'unknown'` before deciding what to
|
|
595
|
+
show. Ordinary read and edit share links never let their recipient claim a
|
|
596
|
+
row.
|
|
597
|
+
|
|
598
|
+
Anonymous creation uses declared create fields on an `id()` table without
|
|
599
|
+
binary columns, with explicit link reads and plain `owner()` ownership.
|
|
600
|
+
It creates a separate private draft even when the browser is signed in.
|
|
601
|
+
Keep the same `request` for an explicit retry; if an error includes `DataError.request`, retain that handle too. The stored outcome lasts 24 hours,
|
|
602
|
+
subject to current access, followed by 7 days of late-retry refusal.
|
|
603
|
+
The handle stays in memory, ends after that period and creates no automatic
|
|
604
|
+
queue. Starting `createAnonymous` again creates a new submission.
|
|
605
|
+
|
|
606
|
+
## Send an enquiry to a public profile
|
|
607
|
+
|
|
608
|
+
Let anyone send a private enquiry to a published consultant by their unique
|
|
609
|
+
public slug. The platform assigns the enquiry to that profile's owner while
|
|
610
|
+
inserting it; the browser supplies only the reference and accepted fields.
|
|
611
|
+
|
|
612
|
+
```ts
|
|
613
|
+
// db/schema.ts
|
|
614
|
+
import { schema, table, id, text, boolean, owner } from 'somewhere/db';
|
|
615
|
+
|
|
616
|
+
export default schema({
|
|
617
|
+
consultants: table({
|
|
618
|
+
id: id(), slug: text({ unique: true }), name: text(),
|
|
619
|
+
published: boolean({ default: false }), accepting: boolean({ default: false }),
|
|
620
|
+
}, {
|
|
621
|
+
scope: owner(),
|
|
622
|
+
client: {
|
|
623
|
+
read: ['id', 'slug', 'name', 'accepting'],
|
|
624
|
+
publicRead: { where: { published: true } },
|
|
625
|
+
},
|
|
626
|
+
}),
|
|
627
|
+
enquiries: table({ id: id({ uuid: false }), message: text(), reply_email: text() }, {
|
|
628
|
+
scope: owner(),
|
|
629
|
+
client: {
|
|
630
|
+
read: ['id', 'message', 'reply_email'],
|
|
631
|
+
intake: {
|
|
632
|
+
target: { table: 'consultants', field: 'slug' },
|
|
633
|
+
fields: ['message', 'reply_email'],
|
|
634
|
+
where: { accepting: true },
|
|
635
|
+
},
|
|
636
|
+
},
|
|
637
|
+
}),
|
|
638
|
+
});
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
Create and publish consultant profiles through an authorized server handler.
|
|
642
|
+
Keep each profile owned by its consultant's account. Use the generated client
|
|
643
|
+
for the public form and the owner's inbox:
|
|
644
|
+
|
|
645
|
+
```ts
|
|
646
|
+
// src/services/enquiries.ts
|
|
647
|
+
import { data } from 'somewhere:data';
|
|
648
|
+
|
|
649
|
+
export function sendEnquiry(slug: string, message: string, reply_email: string) {
|
|
650
|
+
return data.enquiries.intake(slug, { message, reply_email });
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
export function retryEnquiry(submitted: Awaited<ReturnType<typeof sendEnquiry>>) {
|
|
654
|
+
return submitted.request.retry(); // Call only when the person chooses Retry.
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
export function loadMyEnquiries() {
|
|
658
|
+
return data.enquiries.list(); // Normal sign-in required; only this owner's rows.
|
|
659
|
+
}
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
The submission returns `accepted: true`, `idempotency` and `request`.
|
|
663
|
+
It returns no enquiry row, row ID or owner ID. The owner's normal private
|
|
664
|
+
read sees the enquiry. A signed-in sender still submits to the profile's
|
|
665
|
+
owner; supplying an owner, ID or another field is refused.
|
|
666
|
+
|
|
667
|
+
The reference must identify exactly one public, eligible row in this app's
|
|
668
|
+
managed database. It must be a non-null unique text, integer or bigint field included in the
|
|
669
|
+
target's explicit read columns. Both tables use plain `owner()`. Owner-only profiles,
|
|
670
|
+
unpublished or missing references, profiles that are not accepting enquiries
|
|
671
|
+
and unclaimed creator-owned profiles are ineligible. A failed target check
|
|
672
|
+
writes neither an enquiry nor its receipt. Owner selection and the insert
|
|
673
|
+
happen together; changing the profile owner later does not move an enquiry
|
|
674
|
+
already submitted.
|
|
675
|
+
|
|
676
|
+
Use eligibility information that is safe to reveal: success or refusal can
|
|
677
|
+
reveal whether `where` matched, even when that field is not readable. This
|
|
678
|
+
example exposes `accepting` as part of the public profile. Intake permits only
|
|
679
|
+
its declared fields and is not a public update or a way to read the inbox.
|
|
680
|
+
|
|
681
|
+
An explicit retry uses the original handle, reference and values, returning
|
|
682
|
+
the stored acknowledgement for 24 hours while intake remains available under
|
|
683
|
+
the current valid authority. A retry never redirects or inserts the enquiry
|
|
684
|
+
again for a new profile owner. Removing the operation or its current authority
|
|
685
|
+
can refuse the retry. A deploy that changes the app's data contract also
|
|
686
|
+
refuses requests from pages using the old contract. Keep an uncertain
|
|
687
|
+
submission unresolved rather than starting another one. For 7 more days, the platform refuses a late retry
|
|
688
|
+
instead of creating another enquiry; the handle stops sending after that
|
|
689
|
+
period. It stays in memory, survives no reload and never queues or retries
|
|
690
|
+
itself. Calling `intake` again starts a new submission. If a reply is lost,
|
|
691
|
+
retain `DataError.request` rather than calling `intake` again.
|
|
692
|
+
|
|
693
|
+
## Visitors
|
|
694
|
+
|
|
695
|
+
A table can let visitors own rows before they sign in:
|
|
696
|
+
|
|
697
|
+
```ts
|
|
698
|
+
// db/schema.ts
|
|
699
|
+
import { id, owner, schema, table, text } from 'somewhere/db';
|
|
700
|
+
|
|
701
|
+
export default schema({
|
|
702
|
+
cart: table({ id: id({ uuid: false }), sku: text() }, {
|
|
703
|
+
scope: owner({ visitors: true }),
|
|
704
|
+
client: { read: true, create: ['sku'], delete: true, identity: 'visitor' },
|
|
705
|
+
}),
|
|
706
|
+
});
|
|
707
|
+
```
|
|
708
|
+
|
|
709
|
+
The platform gives each visitor a signed session cookie that lasts 30 days.
|
|
710
|
+
Rows the visitor creates belong to that session. When the visitor signs in,
|
|
711
|
+
the platform moves those rows to the account in one step, and that visitor
|
|
712
|
+
session can never hand rows over again, so a later account can never take an earlier
|
|
713
|
+
account's rows. A retry or a second tab is a no-op; logging out issues a fresh
|
|
714
|
+
visitor session. If visitor rows conflict with rows the account already has,
|
|
715
|
+
sign-in still completes and the account's existing data is unaffected; the visitor data stays stored under the visitor session the sign-in replaced and is not merged automatically — the browser cannot reach it again. There is no
|
|
716
|
+
anonymous-session call and no migration step to write.
|
|
717
|
+
|
|
718
|
+
## Retry a create
|
|
719
|
+
|
|
720
|
+
Keep the original request when a save loses its reply. On current managed
|
|
721
|
+
storage, an eligible create returns a `request` handle; errors from that
|
|
722
|
+
request carry the same handle. Offer a Retry button that calls
|
|
723
|
+
`request.retry()`. Calling `create(values)` again starts a new action.
|
|
724
|
+
|
|
725
|
+
The handle sends the same key and values with the browser's current session.
|
|
726
|
+
The platform returns the original result for 24 hours, subject to current
|
|
727
|
+
access. For 7 more days, it refuses the late retry visibly instead of
|
|
728
|
+
creating another row. The handle stops sending after that period. A create
|
|
729
|
+
that affected no rows keeps that result too; retrying does not attempt it again.
|
|
730
|
+
|
|
731
|
+
This applies to a single signed-in or visitor create on an `id()` table
|
|
732
|
+
without a `blob()` column. Deploy the app to receive the generated client.
|
|
733
|
+
A client generated before that deploy, and every other write, has no handle. The handle stays
|
|
734
|
+
in memory; preserve it while the screen offers Retry. It does not survive a
|
|
735
|
+
page reload, repeat itself, or retry email, payments or other function effects.
|
|
736
|
+
|
|
737
|
+
A changed session or request gets `IDEMPOTENCY_CONFLICT`; an expired result
|
|
738
|
+
gets `IDEMPOTENCY_EXPIRED`. A committed result that is no longer
|
|
739
|
+
readable is withheld. Check the error's `outcome` and
|
|
740
|
+
`write_committed` before presenting a save as failed.
|
|
741
|
+
|
|
742
|
+
## The generated client
|
|
743
|
+
|
|
744
|
+
The platform generates a typed client from the declaration at deploy time and
|
|
745
|
+
binds it to that release. Import it in browser code:
|
|
746
|
+
|
|
747
|
+
```ts
|
|
748
|
+
import { data } from 'somewhere:data';
|
|
749
|
+
|
|
750
|
+
// { data: rows, next: cursor or null, has_more }; pass next back as after.
|
|
751
|
+
export function listNotes(after?: string) {
|
|
752
|
+
return data.notes.list({ limit: 20, after });
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
export async function getNote(id: string) {
|
|
756
|
+
const { data: note } = await data.notes.get(id);
|
|
757
|
+
return note; // the row, or null
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
export async function createNote(title: string, body: string) {
|
|
761
|
+
const { data: note } = await data.notes.create({ title, body });
|
|
762
|
+
return note;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
export async function renameNote(id: string, title: string) {
|
|
766
|
+
const { data: note } = await data.notes.update(id, { title });
|
|
767
|
+
return note;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
export async function deleteNote(id: string): Promise<boolean> {
|
|
771
|
+
const { changes } = await data.notes.delete(id);
|
|
772
|
+
return changes === 1;
|
|
773
|
+
}
|
|
774
|
+
```
|
|
775
|
+
|
|
776
|
+
## Which rows belong to the signed-in user
|
|
777
|
+
|
|
778
|
+
The browser never receives the owner or author column, so there is nothing to
|
|
779
|
+
compare. Ask a list or get for row hints with `can: true`; each row then
|
|
780
|
+
carries `mine` and `can`:
|
|
781
|
+
|
|
782
|
+
```ts
|
|
783
|
+
import { data } from 'somewhere:data';
|
|
784
|
+
|
|
785
|
+
export async function commentsForView() {
|
|
786
|
+
const { data: comments } = await data.comments.list({ can: true });
|
|
787
|
+
const view = [];
|
|
788
|
+
for (const comment of comments) {
|
|
789
|
+
// mine: this signed-in user created the row. can: what this user may change, by the write's own rule.
|
|
790
|
+
view.push({ ...comment, author: comment.mine ? 'you' : null, showDelete: comment.can.delete });
|
|
791
|
+
}
|
|
792
|
+
return view;
|
|
793
|
+
}
|
|
794
|
+
```
|
|
795
|
+
|
|
796
|
+
`mine` is true for rows the signed-in user created: the owner column of an
|
|
797
|
+
`owner()` table, including inside `anyOf` and `allOf`, or the author of a
|
|
798
|
+
`shared()` table. A table that records no creator, such as `member()` or
|
|
799
|
+
`group()` alone, answers `false`. `can` and `mine` differ: a group admin
|
|
800
|
+
may delete a member's row that is not `mine`, and a row can be `mine` while
|
|
801
|
+
`can.delete` is false because `client.delete` is off. Rows read without
|
|
802
|
+
`can: true` carry neither field, so a row spread back into `create` or
|
|
803
|
+
`update` stays clean. Hints need a signed-in request and inform the UI; the
|
|
804
|
+
write still enforces the rule. Inside a function, `sw.db.from(table, { can:
|
|
805
|
+
true })` returns the same fields. `client.read` cannot list the owner or
|
|
806
|
+
author column; the deploy refuses it and names this read. The names `can` and
|
|
807
|
+
`mine` belong to these hints; a column cannot be declared with either name.
|
|
808
|
+
|
|
809
|
+
## Rows for the app's owner
|
|
810
|
+
|
|
811
|
+
`appOwner()` admits the app's owner: the signed-in user whose email the app
|
|
812
|
+
has verified and equals the email of the Somewhere account that owns the
|
|
813
|
+
project. Use it instead of writing an owner's email into code. It goes
|
|
814
|
+
wherever `appRole()` goes: a table's own scope, `anyOf(owner(), appOwner())`
|
|
815
|
+
for "my rows, or the owner sees every row", under `parent()`, and in `allOf`.
|
|
816
|
+
|
|
817
|
+
```ts
|
|
818
|
+
import { anyOf, appOwner, id, owner, schema, table, text } from 'somewhere/db';
|
|
819
|
+
|
|
820
|
+
export default schema({
|
|
821
|
+
// Only the app's owner reads, creates, updates and deletes these rows.
|
|
822
|
+
settings: table({ id: id(), name: text(), value: text() }, {
|
|
823
|
+
scope: appOwner(),
|
|
824
|
+
client: { read: true, create: ['name', 'value'], update: ['value'], delete: true },
|
|
825
|
+
}),
|
|
826
|
+
// Each person keeps their own feedback; the owner reads and moderates all of it.
|
|
827
|
+
feedback: table({ id: id(), body: text() }, {
|
|
828
|
+
scope: anyOf(owner(), appOwner()),
|
|
829
|
+
client: { read: true, create: ['body'], update: ['body'], delete: true },
|
|
830
|
+
}),
|
|
831
|
+
});
|
|
832
|
+
```
|
|
833
|
+
|
|
834
|
+
It is decided on every request (the owner's email is re-read at least once a
|
|
835
|
+
minute), so a project hand-over moves it to the new owner and previews
|
|
836
|
+
behave the same way. In a preview, anyone working on the project can act as the app's owner. It is false when:
|
|
837
|
+
|
|
838
|
+
- the user's email was typed at sign-up and never verified. Users who sign in
|
|
839
|
+
with an emailed code or link, or with a provider that confirms the address
|
|
840
|
+
(Google, GitHub, Discord), are verified. If your app never verifies emails,
|
|
841
|
+
`appOwner()` admits nobody;
|
|
842
|
+
- the user changed their email and has not verified the new one;
|
|
843
|
+
- the email differs other than by upper or lower case (A to Z):
|
|
844
|
+
`owner+app@example.com` and `o.wner@example.com` are other addresses, and an
|
|
845
|
+
address with any character outside plain ASCII is never the owner;
|
|
846
|
+
- the user is an editor or another collaborator on the project, not its owner;
|
|
847
|
+
- the owner's Somewhere account email is not verified.
|
|
848
|
+
|
|
849
|
+
`appOwner()` is the built-in app role `app_owner`. It cannot be declared in
|
|
850
|
+
`appRoles`, granted, or named in `grantableBy`. In a function, the same
|
|
851
|
+
answer is `user.is_owner` (see `sw.auth` → `the-apps-owner`).
|
|
852
|
+
|
|
853
|
+
## One row, two readers, different columns
|
|
854
|
+
|
|
855
|
+
A ticket is read by the customer who opened it and by staff; a booked slot by
|
|
856
|
+
the provider and by the booker. When each reader may see different columns of
|
|
857
|
+
the same row, list the columns on the `anyOf()` branch. A branch without
|
|
858
|
+
`read` reads every column:
|
|
859
|
+
|
|
860
|
+
```ts
|
|
861
|
+
import { schema, table, id, text, owner, appRole, anyOf } from 'somewhere/db';
|
|
862
|
+
|
|
863
|
+
export default schema({
|
|
864
|
+
tickets: table({ id: id(), subject: text(), status: text({ default: 'open' }), customer_email: text(), assignee_email: text({ nullable: true }) }, {
|
|
865
|
+
scope: anyOf(owner({ read: ['id', 'subject', 'status'] }), appRole({ roles: { read: ['staff'], update: ['staff'] } })),
|
|
866
|
+
client: { read: ['id', 'subject', 'status', 'customer_email', 'assignee_email'], create: ['subject', 'customer_email'], update: ['status', 'assignee_email'] },
|
|
867
|
+
}),
|
|
868
|
+
}, { appRoles: { staff: { grantableBy: [] } } });
|
|
869
|
+
```
|
|
870
|
+
|
|
871
|
+
The customer's row carries `id`, `subject` and `status`; a staff reader's row
|
|
872
|
+
carries every column; a staff member reading their own ticket gets the union.
|
|
873
|
+
A column outside the reader's branches is absent from the row, not `null`,
|
|
874
|
+
through the generated client, `sw.db.from` in a function and related reads
|
|
875
|
+
alike, and it never leaves the platform. The generated types mark such a
|
|
876
|
+
column optional. Because a column some branch leaves out reaches a reader only
|
|
877
|
+
through a branch that lists it, no filter, ordering, grouping or aggregate may
|
|
878
|
+
name it: the browser client refuses with `DATA_INPUT_INVALID`, a function read
|
|
879
|
+
with a validation error; filter on the columns every branch reads instead. A
|
|
880
|
+
write's returned row carries the columns every branch reads. A column in no
|
|
881
|
+
branch's list reaches server functions only (`sw.db.server`). Public reads
|
|
882
|
+
(`client.publicRead`) grant the columns every branch reads. Each list must
|
|
883
|
+
name the table's id column. The deploy report names each branch's columns.
|
|
884
|
+
Per-branch columns need the project's separate managed database, which every
|
|
885
|
+
new project has.
|
|
886
|
+
|
|
887
|
+
## A column only some roles may write
|
|
888
|
+
|
|
889
|
+
A customer edits their ticket's subject, but only staff move its status. List
|
|
890
|
+
the column under `columns` with the app roles that may write it:
|
|
891
|
+
|
|
892
|
+
```ts
|
|
893
|
+
import { schema, table, id, text, owner, appRole, anyOf } from 'somewhere/db';
|
|
894
|
+
|
|
895
|
+
export default schema({
|
|
896
|
+
tickets: table({ id: id(), subject: text(), status: text({ default: 'open' }) }, {
|
|
897
|
+
scope: anyOf(owner(), appRole({ roles: { read: ['staff'], update: ['staff'] } })),
|
|
898
|
+
client: { read: ['id', 'subject', 'status'], create: ['subject'], update: ['subject', 'status'] },
|
|
899
|
+
columns: { status: { write: ['staff'] } },
|
|
900
|
+
}),
|
|
901
|
+
}, { appRoles: { staff: { grantableBy: ['staff'] } } });
|
|
902
|
+
```
|
|
903
|
+
|
|
904
|
+
A write that sets `status` succeeds only when the caller holds one of the
|
|
905
|
+
listed app roles now, checked in the same database statement. Otherwise it is
|
|
906
|
+
refused whole with 403 `COLUMN_ROLE_REQUIRED`, naming the column, and nothing
|
|
907
|
+
in the statement or its transaction is written. This applies to every write
|
|
908
|
+
made as the caller: the generated client's create and update, a function's
|
|
909
|
+
`sw.db` writes (insert, update, increment, both outcomes of an upsert, a multi-row
|
|
910
|
+
update, every step of `sw.db.tx`), and an app MCP tool. Setting the column to
|
|
911
|
+
the value it already has is still a write of that column. A create that leaves
|
|
912
|
+
the column out takes its declared default. An insert that explicitly supplies
|
|
913
|
+
the default value is still a write: a caller without one of the column's
|
|
914
|
+
roles must omit that column, even when supplying the same declared default
|
|
915
|
+
would leave the stored value unchanged. Reads are unchanged, and
|
|
916
|
+
`sw.db.server` writes the column as before.
|
|
917
|
+
|
|
918
|
+
The rule adds a condition; it never grants anything. The caller still needs the
|
|
919
|
+
table's rule (`scope`) and, in the browser, the column in `client.create` or
|
|
920
|
+
`client.update`. The roles must be declared in `appRoles`; a team role, the
|
|
921
|
+
owner column, a column the table's rule reads (a group, membership or parent
|
|
922
|
+
key), a room's save column and a `serverOnly()` table are refused at deploy.
|
|
923
|
+
Adding, changing or removing the rule on a table that already exists is
|
|
924
|
+
refused at deploy for now; a new table can declare it.
|
|
925
|
+
|
|
926
|
+
## A user who must belong to the row's team
|
|
927
|
+
|
|
928
|
+
A task's assignee must be someone on the task's team. Name the team column
|
|
929
|
+
with `memberOf`:
|
|
930
|
+
|
|
931
|
+
```ts
|
|
932
|
+
import { schema, table, id, text, owner, group, anyOf } from 'somewhere/db';
|
|
933
|
+
|
|
934
|
+
export default schema({
|
|
935
|
+
tasks: table({ id: id(), team_id: text(), title: text(), assignee_id: text({ nullable: true }) }, {
|
|
936
|
+
scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['admin', 'member'], create: ['admin', 'member'], update: ['admin', 'member'] } })),
|
|
937
|
+
client: { read: true, create: ['team_id', 'title', 'assignee_id'], update: ['title', 'assignee_id'] },
|
|
938
|
+
columns: { assignee_id: { memberOf: 'team_id' } },
|
|
939
|
+
}),
|
|
940
|
+
});
|
|
941
|
+
```
|
|
942
|
+
|
|
943
|
+
A write that sets `assignee_id` to a user id succeeds only when that user is
|
|
944
|
+
a current member, in any role, of the row's team: the `team_id` of a new row,
|
|
945
|
+
or the stored `team_id` of an updated one. The check runs in the same database
|
|
946
|
+
statement. Otherwise the write is refused whole with 403
|
|
947
|
+
`MEMBER_OF_REQUIRED`, naming the column, and nothing in the statement or its
|
|
948
|
+
transaction is written. `null` is allowed when the column is nullable. A default
|
|
949
|
+
user id on such a column is refused at deploy (a nullable column may default
|
|
950
|
+
to `null`). The rule applies to every write, including `sw.db.server`. It is checked at write
|
|
951
|
+
only: removing someone from the team later leaves rows assigned to them as
|
|
952
|
+
they are.
|
|
953
|
+
|
|
954
|
+
The team column of such a table is fixed for the row's life: an update that
|
|
955
|
+
names it is refused, and so is an upsert (`onConflict: 'update'`, server
|
|
956
|
+
authority included) that would move the stored row to another team. A caller the table's rule does not admit is refused by
|
|
957
|
+
that rule first, so the answer never says whether a user is on the team.
|
|
958
|
+
`memberOf` names this table's own `group()` column: a root `group()`, the
|
|
959
|
+
`group()` branch of `anyOf(owner(), group())`, or an `allOf()` `group()`
|
|
960
|
+
gate. A team inherited through `parent()` is refused at deploy for now, and so
|
|
961
|
+
are adding, changing or removing the rule on a table that already exists.
|
|
962
|
+
|
|
963
|
+
## Teams without email verification
|
|
964
|
+
|
|
965
|
+
The Team Board uses app-user IDs in a server-only roster. Team members can
|
|
966
|
+
read, create and edit tasks. Team owners can delete tasks and their comments.
|
|
967
|
+
Members can also edit and delete their own comments while they belong to the team.
|
|
968
|
+
|
|
969
|
+
```ts
|
|
970
|
+
// db/schema.ts
|
|
971
|
+
import { schema, table, id, text, serverOnly, member, parent } from 'somewhere/db';
|
|
972
|
+
|
|
973
|
+
export default schema({
|
|
974
|
+
teams: table({ id: id(), name: text() }, { scope: serverOnly() }),
|
|
975
|
+
team_members: table({
|
|
976
|
+
id: id(), team_id: text({ references: 'teams' }), user_id: text(), role: text(),
|
|
977
|
+
}, {
|
|
978
|
+
scope: serverOnly(), unique: [['team_id', 'user_id']],
|
|
979
|
+
}),
|
|
980
|
+
tasks: table({ id: id(), team_id: text({ references: 'teams' }), title: text() }, {
|
|
981
|
+
scope: member({
|
|
982
|
+
group: 'team_id', membership: 'team_members', member_user: 'user_id',
|
|
983
|
+
member_group: 'team_id', deleteWhere: { role: 'owner' },
|
|
984
|
+
}),
|
|
985
|
+
client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'],
|
|
986
|
+
update: ['title'], delete: true },
|
|
987
|
+
}),
|
|
988
|
+
comments: table({
|
|
989
|
+
id: id(), task_id: text({ references: 'tasks', onDelete: 'cascade' }),
|
|
990
|
+
author_id: text({ nullable: true }), body: text(),
|
|
991
|
+
}, {
|
|
992
|
+
scope: parent({
|
|
993
|
+
via: 'task_id', author: 'author_id', update: ['author'], delete: ['author', 'parent'],
|
|
994
|
+
}),
|
|
995
|
+
client: { read: ['id', 'task_id', 'author_id', 'body'], create: ['task_id', 'body'],
|
|
996
|
+
update: ['body'], delete: true },
|
|
997
|
+
}),
|
|
998
|
+
});
|
|
999
|
+
```
|
|
1000
|
+
|
|
1001
|
+
Create the first owner's roster row using their signed-in ID. Authorize
|
|
1002
|
+
later roster changes in a function before writing with `sw.db.server`.
|
|
1003
|
+
`deleteWhere` belongs on a standalone table `member()` rule. It matches one
|
|
1004
|
+
declared text column on the caller's roster row against a string or a list
|
|
1005
|
+
of strings. Use `where` by itself to apply a filter to every enabled operation.
|
|
1006
|
+
|
|
1007
|
+
Comments follow the task for reads and creates. The platform stamps the
|
|
1008
|
+
comment author. The `'parent'` delete branch uses the task's delete rule, and
|
|
1009
|
+
deleting a task also deletes its comments through the foreign key. The
|
|
1010
|
+
access map shows the delete-only filter on the task and in the comment's
|
|
1011
|
+
inherited policy.
|
|
1012
|
+
|
|
1013
|
+
## Comments that their author may edit
|
|
1014
|
+
|
|
1015
|
+
A comment on a task inherits the task's rule through `parent()`. To let a
|
|
1016
|
+
comment's author edit or delete it, name the author column and who may act:
|
|
1017
|
+
|
|
1018
|
+
```ts
|
|
1019
|
+
import { schema, table, id, text, integer, owner, group, anyOf, parent } from 'somewhere/db';
|
|
1020
|
+
|
|
1021
|
+
export default schema({
|
|
1022
|
+
tasks: table({ id: id({ uuid: false }), team_id: text(), title: text() }, {
|
|
1023
|
+
scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['admin', 'member'], create: ['admin', 'member'], update: ['admin'], delete: ['admin'] } })),
|
|
1024
|
+
}),
|
|
1025
|
+
comments: table({ id: id(), task_id: integer({ references: 'tasks' }), body: text(), author_id: text({ nullable: true }) }, {
|
|
1026
|
+
scope: parent({ via: 'task_id', author: 'author_id', update: ['author'], delete: ['author', 'parent'] }),
|
|
1027
|
+
client: { read: true, create: ['task_id', 'body'], update: ['body'], delete: true },
|
|
1028
|
+
}),
|
|
1029
|
+
});
|
|
1030
|
+
```
|
|
1031
|
+
|
|
1032
|
+
- `author` is a `text({ nullable: true })` column the platform fills with the
|
|
1033
|
+
signed-in creator on every create made as the caller. A value supplied for
|
|
1034
|
+
it on a create or update is refused, and an upsert that updates keeps the
|
|
1035
|
+
stored author. `sw.db.server` may set it.
|
|
1036
|
+
- `update` and `delete` list who may act: `'author'` (the row's author) and
|
|
1037
|
+
`'parent'` (whoever may do that operation on the parent, today's meaning).
|
|
1038
|
+
An operation you leave out keeps today's rule, `['parent']`. Above,
|
|
1039
|
+
`delete: ['author', 'parent']` lets the comment's author, or anyone who may
|
|
1040
|
+
delete the task (its creator, a team admin), delete the comment.
|
|
1041
|
+
- Update and delete also always need the caller to read the parent now: an
|
|
1042
|
+
author removed from the team loses the right to edit their comments, and a
|
|
1043
|
+
comment whose task is gone grants its author nothing. A row with no author
|
|
1044
|
+
grants the author action to nobody.
|
|
1045
|
+
- Reading and creating still follow the parent. Files attached to the row and
|
|
1046
|
+
room write tickets follow the row's update rule, so an author who may update
|
|
1047
|
+
may change those too; deleting alone grants neither.
|
|
1048
|
+
- `can` hints on reads say what the caller may update or delete under this
|
|
1049
|
+
rule.
|
|
1050
|
+
|
|
1051
|
+
A table that inherits from a table with `author` is refused at deploy for
|
|
1052
|
+
now. So is adding, changing or removing `author` on a table that already
|
|
1053
|
+
exists, and naming an existing table's column as the author.
|
|
1054
|
+
|
|
1055
|
+
## Paging a list
|
|
1056
|
+
|
|
1057
|
+
Generated `data.<table>.list()` and related-record `list()` calls accept an
|
|
1058
|
+
integer `limit` from 1 to 100; the default is 25. One call never returns
|
|
1059
|
+
more than 100 rows: read more with `after`, below. A literal `limit` outside
|
|
1060
|
+
1 to 100 is a type error, which tsc reports only as `TS2769 No overload matches
|
|
1061
|
+
this call` with `limit?: undefined` in its detail; `somewhere typecheck` adds
|
|
1062
|
+
the rule to that line. At runtime a larger value is refused with
|
|
1063
|
+
`DATA_INPUT_INVALID` (`limit must be an integer from 1 to 100`), not clamped.
|
|
1064
|
+
A page size computed at runtime is a plain `number`, so check it before
|
|
1065
|
+
calling.
|
|
1066
|
+
|
|
1067
|
+
Each page returns `data`, `next` and `has_more`. Pass `page.next` as
|
|
1068
|
+
`after` for the next page, keeping the same filters. Stop when
|
|
1069
|
+
`has_more` is false or `next` is null. Pages follow primary-key order;
|
|
1070
|
+
concurrent row changes can affect later pages, so this is not a frozen snapshot.
|
|
1071
|
+
For a list sorted by another column, serve it from an app endpoint with
|
|
1072
|
+
`sw.db.from('notes', { order: [['created_at', 'desc'], ['id', 'desc']], limit: 25 })`.
|
|
1073
|
+
Use the same order for every page and include the primary key as a tie-breaker.
|
|
1074
|
+
Sorting each page from `data.<table>.list()` can put rows in the wrong order
|
|
1075
|
+
across pages.
|
|
1076
|
+
|
|
1077
|
+
```ts
|
|
1078
|
+
// src/services/note-pages.ts
|
|
1079
|
+
import { data } from 'somewhere:data';
|
|
1080
|
+
|
|
1081
|
+
// Fetch at most ten pages; a UI can instead load one page per "Load more" click.
|
|
1082
|
+
export async function loadNotesBatch() {
|
|
1083
|
+
let page = await data.notes.list({ limit: 100 });
|
|
1084
|
+
const notes = [...page.data];
|
|
1085
|
+
for (let pageNumber = 1; pageNumber < 10 && page.has_more && page.next !== null; pageNumber++) {
|
|
1086
|
+
page = await data.notes.list({ limit: 100, after: page.next });
|
|
1087
|
+
notes.push(...page.data);
|
|
1088
|
+
}
|
|
1089
|
+
return { data: notes, next: page.next, has_more: page.has_more };
|
|
1090
|
+
}
|
|
1091
|
+
```
|
|
1092
|
+
|
|
1093
|
+
If `has_more` is still true after this bounded batch, use its `next` cursor
|
|
1094
|
+
to continue rather than increasing `limit`. Related-record lists use the
|
|
1095
|
+
same paging fields while keeping the same parent ID.
|
|
1096
|
+
|
|
1097
|
+
A `read` grant also gives the client `aggregate`: count, sum, avg, min
|
|
1098
|
+
and max over the readable fields, optionally grouped, with the same row
|
|
1099
|
+
permissions composed into the question — the numbers describe only rows this
|
|
1100
|
+
caller may read, and on a table with `publicRead` an anonymous call
|
|
1101
|
+
summarises the published rows only.
|
|
1102
|
+
|
|
1103
|
+
The `orders` table in the schema above grants reads of the fields used below.
|
|
1104
|
+
Its `owner()` scope keeps each aggregate within the signed-in user's orders.
|
|
1105
|
+
|
|
1106
|
+
```ts
|
|
1107
|
+
const totals = await data.orders.aggregate({ count: true, sum: 'amount' });
|
|
1108
|
+
// totals.data: exactly one row — [{ count: 12, sum_amount: 4800 }]
|
|
1109
|
+
const byStatus = await data.orders.aggregate({
|
|
1110
|
+
count: true, avg: 'amount', groupBy: ['status'],
|
|
1111
|
+
where: { archived: false }, having: { count: { gte: 2 } },
|
|
1112
|
+
order: [['count', 'desc']], limit: 20,
|
|
1113
|
+
});
|
|
1114
|
+
// byStatus.data: one row per group — [{ status: 'paid', count: 9, avg_amount: 410 }, …]
|
|
1115
|
+
// byStatus.has_more: true when more groups exist than the limit allowed
|
|
1116
|
+
```
|
|
1117
|
+
|
|
1118
|
+
`sum` and `avg` accept only readable fields declared `integer` or
|
|
1119
|
+
`number`; `min`, `max` and `groupBy` accept any readable field
|
|
1120
|
+
except `json` and `blob`. Result keys are composed by the platform:
|
|
1121
|
+
`count`, `sum_<field>`, `avg_<field>`, `min_<field>`,
|
|
1122
|
+
`max_<field>`. `where` takes the same equality filters as `list`;
|
|
1123
|
+
`having` filters result keys with one of `eq`, `ne`, `lt`,
|
|
1124
|
+
`lte`, `gt`, `gte`; `order` may name only a `groupBy` field
|
|
1125
|
+
or a result key. A grouped call returns at most `limit` groups (1–100,
|
|
1126
|
+
default 100) and reports `has_more`; an ungrouped call is always exactly
|
|
1127
|
+
one row and carries no `has_more`.
|
|
1128
|
+
|
|
1129
|
+
Only the operations you enabled exist on the client; a disabled one is absent,
|
|
1130
|
+
not a runtime error. Every call carries the digest of the whole declaration it was generated
|
|
1131
|
+
from. After a deploy that changes any table declaration, calls from pages
|
|
1132
|
+
loaded before it are refused with `DATA_CONTRACT_MISMATCH` (409, "Reload
|
|
1133
|
+
the app") until the page reloads; the client does not retry or negotiate.
|
|
1134
|
+
Deploys that leave the declaration unchanged keep serving open pages. Every request to
|
|
1135
|
+
`/__sw/data` is a POST and must include the app's own `Origin` header,
|
|
1136
|
+
including list/get reads and calls with an app-user Bearer token. Browser
|
|
1137
|
+
fetch sends it automatically; a script must set it explicitly. Missing or
|
|
1138
|
+
wrong Origin returns `ORIGIN_REQUIRED`, `ORIGIN_NOT_ALLOWED` or
|
|
1139
|
+
`DATA_ORIGIN_FORBIDDEN`. A foreign origin can be rejected before the data
|
|
1140
|
+
handler runs. Errors are thrown as
|
|
1141
|
+
`DataError` with `status` and `code`:
|
|
1142
|
+
`AUTH_REQUIRED`, `DATA_ACCESS_DENIED`, `DATA_CONTRACT_MISMATCH`,
|
|
1143
|
+
`DATA_IDENTITY_MISMATCH`, `DATA_INPUT_INVALID`, `DATA_INPUT_TOO_LARGE`,
|
|
1144
|
+
`DATA_OPERATION_INVALID`, `DATA_VALUE_INVALID`, `DATA_CONFLICT`.
|
|
1145
|
+
An update or delete by ID that matches no accessible record throws
|
|
1146
|
+
`DataError` with status 404 and code `DATA_NOT_FOUND` ("Record not found.").
|
|
1147
|
+
Missing records and records outside your write permissions return the same error.
|
|
1148
|
+
A `get` of a record that does not exist or is not yours is not an error: over HTTP
|
|
1149
|
+
it answers 200 with `data: null`, while an update or delete by ID answers 404
|
|
1150
|
+
`DATA_NOT_FOUND`, so neither reveals whether the record exists and a write never
|
|
1151
|
+
reports false success.
|
|
1152
|
+
Successful writes report `changes`; a same-value update to your own record succeeds.
|
|
1153
|
+
For these calls `changes` is the number of records the write matched: child rows removed by
|
|
1154
|
+
`onDelete: 'cascade'` are not counted, so deleting one record reports 1 even when its
|
|
1155
|
+
children go with it. Raw SQL reports a different count (docs({ topic: 'sw.db' })).
|
|
1156
|
+
A standalone caller `sw.db.update` with only a primary-key equality filter also
|
|
1157
|
+
throws `DATA_NOT_FOUND` when it changes no accessible row. A caller `sw.db.remove`
|
|
1158
|
+
that matches no accessible row returns `{ data: [], count: 0, changes: 0 }` instead,
|
|
1159
|
+
the same for a missing row and one outside your access, so a repeated delete needs no
|
|
1160
|
+
special case. Bulk writes, additional conditions, server-authority writes and
|
|
1161
|
+
transactions keep their zero-change result.
|
|
1162
|
+
|
|
1163
|
+
A create or update that conflicts with a declared unique value returns
|
|
1164
|
+
`DataError` with status 409 and code `DATA_CONFLICT`. Map that code to your
|
|
1165
|
+
app's duplicate-value message; retrying the same values will not fix it.
|
|
1166
|
+
The error does not identify the existing row or disclose its fields.
|
|
1167
|
+
|
|
1168
|
+
Direct HTTP to the data endpoint enforces the same restrictions. Updating
|
|
1169
|
+
or deleting an inaccessible or missing ID returns HTTP 404 `DATA_NOT_FOUND`.
|
|
1170
|
+
An operation the table does not expose can be refused before it reads a row.
|
|
1171
|
+
|
|
1172
|
+
## Read-only sharing without email verification
|
|
1173
|
+
|
|
1174
|
+
Give the owner a recipient already identified by an app-user ID, such as
|
|
1175
|
+
another member of a team your app manages. Identifying an account by an
|
|
1176
|
+
unverified email address cannot establish who controls the mailbox.
|
|
1177
|
+
|
|
1178
|
+
```ts
|
|
1179
|
+
// db/schema.ts
|
|
1180
|
+
import { schema, table, id, text, owner, anyOf, grant } from 'somewhere/db';
|
|
1181
|
+
|
|
1182
|
+
export default schema({
|
|
1183
|
+
note_shares: table({
|
|
1184
|
+
id: id(), recipient_id: text(),
|
|
1185
|
+
note_id: text({ references: 'notes', onDelete: 'cascade' }),
|
|
1186
|
+
}, {
|
|
1187
|
+
scope: owner(), unique: [['note_id', 'recipient_id']],
|
|
1188
|
+
}),
|
|
1189
|
+
notes: table({ id: id(), title: text() }, {
|
|
1190
|
+
scope: anyOf(owner(), grant({
|
|
1191
|
+
table: 'note_shares', grantee: 'recipient_id', row: 'note_id', operations: ['read'],
|
|
1192
|
+
})),
|
|
1193
|
+
client: { read: true, create: ['title'], update: ['title'], delete: true },
|
|
1194
|
+
}),
|
|
1195
|
+
});
|
|
1196
|
+
```
|
|
1197
|
+
|
|
1198
|
+
```ts
|
|
1199
|
+
// api/notes/share.ts — POST { noteId, recipientId } with a known app-user ID
|
|
1200
|
+
export default sw.endpoint({
|
|
1201
|
+
auth: 'required',
|
|
1202
|
+
body: { noteId: 'string', recipientId: 'string' },
|
|
1203
|
+
rateLimit: '30/minute',
|
|
1204
|
+
handler: async ({ body }, sw) => {
|
|
1205
|
+
await sw.db.insert('note_shares', {
|
|
1206
|
+
note_id: body.noteId, recipient_id: body.recipientId,
|
|
1207
|
+
}, { onConflict: 'ignore' });
|
|
1208
|
+
return { ok: true };
|
|
1209
|
+
},
|
|
1210
|
+
});
|
|
1211
|
+
```
|
|
1212
|
+
|
|
1213
|
+
The platform checks that the caller owns the note. If the app limits
|
|
1214
|
+
recipients to a roster, check the recipient against that roster in the
|
|
1215
|
+
handler before inserting. The recipient can read the named note through
|
|
1216
|
+
`data.notes.list()` and `data.notes.get(id)`. They cannot edit, delete or
|
|
1217
|
+
share it. Removing the grant with caller-scoped `sw.db.remove` on the ledger
|
|
1218
|
+
revokes access. Deleting the note cascades to its grants.
|
|
1219
|
+
|
|
1220
|
+
**When you add `anyOf(owner(), grant(...))`**, every existing caller-scoped
|
|
1221
|
+
read also includes rows shared with the caller. To keep a list owner-only,
|
|
1222
|
+
use `sw.db.from('notes', { where: { user_id: me.id } })` in a function after
|
|
1223
|
+
`sw.auth.requireUser(req)`. The deploy warning and browser behavior are
|
|
1224
|
+
described under **Per-owner sharing**.
|
|
1225
|
+
|
|
1226
|
+
## Per-owner sharing
|
|
1227
|
+
|
|
1228
|
+
Use `grant()` when someone shares **their own existing rows** with specific
|
|
1229
|
+
signed-in people. There is no group key to add to those rows and the owner
|
|
1230
|
+
does not need to invite themselves. The owner always keeps access.
|
|
1231
|
+
|
|
1232
|
+
For a contacts app with read-only sharing:
|
|
1233
|
+
|
|
1234
|
+
```ts
|
|
1235
|
+
import { schema, table, id, text, owner, anyOf, grant } from 'somewhere/db';
|
|
1236
|
+
|
|
1237
|
+
export default schema({
|
|
1238
|
+
shares: table({ id: id(), grantee_id: text() }, {
|
|
1239
|
+
scope: owner(),
|
|
1240
|
+
indexes: [['grantee_id']],
|
|
1241
|
+
unique: [['user_id', 'grantee_id']],
|
|
1242
|
+
}),
|
|
1243
|
+
contacts: table({ id: id(), name: text(), email: text() }, {
|
|
1244
|
+
scope: anyOf(owner(), grant({
|
|
1245
|
+
table: 'shares', grantee: 'grantee_id', operations: ['read'],
|
|
1246
|
+
})),
|
|
1247
|
+
client: { read: true, create: ['name', 'email'], update: ['name', 'email'], delete: true },
|
|
1248
|
+
}),
|
|
1249
|
+
});
|
|
1250
|
+
```
|
|
1251
|
+
|
|
1252
|
+
Create a `shares` row with the recipient's authenticated app-user ID in
|
|
1253
|
+
`grantee_id`. The platform stamps the signed-in owner's `user_id`; never
|
|
1254
|
+
send or declare that column yourself. A share authorizes that recipient to
|
|
1255
|
+
read all of this owner's contacts. Other owners' rows stay private. Only
|
|
1256
|
+
the owner can create, change or delete their shares. Recipients cannot create
|
|
1257
|
+
a share for someone else's rows. Manage shares through caller-scoped sw.db in
|
|
1258
|
+
an endpoint; keep browser writes to the ledger closed. The generated browser
|
|
1259
|
+
client still reads/writes contacts under the declared rule.
|
|
1260
|
+
|
|
1261
|
+
**Keep My contacts and duplicate checks owner-only.** Before the edit, the
|
|
1262
|
+
contacts table uses `scope: owner()`. Its list calls `data.contacts.list()`
|
|
1263
|
+
and its duplicate check calls `sw.db.count('contacts', { where: { email } })`.
|
|
1264
|
+
After changing the schema above, run `somewhere deploy --dry-run`. It reports
|
|
1265
|
+
that existing caller reads may widen and points to the queries it finds.
|
|
1266
|
+
|
|
1267
|
+
```text
|
|
1268
|
+
Database schema: caller-scoped reads of "contacts" may return more rows under the new access rule. The report lists reads it can identify statically.
|
|
1269
|
+
src/Contacts.tsx:12:21: Use { ownerOnly: true } as argument 1 to read only your own "contacts" rows. Leave the call as written to include newly readable rows.
|
|
1270
|
+
api/contacts/import.ts:8:22: Add ownerOnly: true to argument 2 to read only your own "contacts" rows. Leave the call as written to include newly readable rows.
|
|
1271
|
+
```
|
|
1272
|
+
|
|
1273
|
+
In the browser, keep My contacts scoped to its owner and use the ordinary list
|
|
1274
|
+
for All contacts I can see:
|
|
1275
|
+
|
|
1276
|
+
```ts
|
|
1277
|
+
// src/services/contacts.ts
|
|
1278
|
+
import { data } from 'somewhere:data';
|
|
1279
|
+
|
|
1280
|
+
const mine = await data.contacts.list({ ownerOnly: true });
|
|
1281
|
+
const readable = await data.contacts.list();
|
|
1282
|
+
```
|
|
1283
|
+
|
|
1284
|
+
In a signed-in function, apply the same option to the owner-only list and
|
|
1285
|
+
to the duplicate check used before an import:
|
|
1286
|
+
|
|
1287
|
+
```ts
|
|
1288
|
+
// api/contacts.ts
|
|
1289
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
1290
|
+
await sw.auth.requireUser(req);
|
|
1291
|
+
const { data } = await sw.db.from('contacts', { ownerOnly: true, order: [['name', 'asc']], limit: 100 });
|
|
1292
|
+
return Response.json(data);
|
|
1293
|
+
}
|
|
1294
|
+
```
|
|
1295
|
+
|
|
1296
|
+
```ts
|
|
1297
|
+
// api/contacts/import.ts
|
|
1298
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
1299
|
+
await sw.auth.requireUser(req);
|
|
1300
|
+
const email = new URL(req.url).searchParams.get('email') ?? '';
|
|
1301
|
+
const { data: matches } = await sw.db.count('contacts', { where: { email }, ownerOnly: true });
|
|
1302
|
+
return Response.json({ duplicate: matches > 0 });
|
|
1303
|
+
}
|
|
1304
|
+
```
|
|
1305
|
+
|
|
1306
|
+
Use `ownerOnly: true` on private browser `list`, `get` and `aggregate` reads
|
|
1307
|
+
and on caller-scoped `sw.db.from`, `count` and `aggregate`. The platform applies
|
|
1308
|
+
the ownership filter along with the declared access rule before paging or
|
|
1309
|
+
counting. Review queries that select tables dynamically alongside the listed
|
|
1310
|
+
call sites. Deploy the schema and query edits together. Check that an owner
|
|
1311
|
+
sees their own rows, a recipient can read shared contacts through All contacts
|
|
1312
|
+
I can see, and a third account cannot read them. The recipient's My contacts
|
|
1313
|
+
list and duplicate check still use their own rows.
|
|
1314
|
+
|
|
1315
|
+
For an app without email verification, choose a known app-user ID from your
|
|
1316
|
+
app's roster and follow [read-only sharing without email verification](#read-only-sharing-without-email-verification).
|
|
1317
|
+
For sharing by verified email, require a signed-in caller and resolve the
|
|
1318
|
+
address in a deployed function with `sw.auth.server.listUsers({ emails: [address] })`.
|
|
1319
|
+
Use only a match with `email_verified: true`, then insert the share with
|
|
1320
|
+
caller-scoped `sw.db.insert` to stamp the owner. Email verification proves
|
|
1321
|
+
control of the mailbox. Give specific feedback for an invalid address or the
|
|
1322
|
+
owner's own address. For every other address, use the same reply whether a
|
|
1323
|
+
verified account matched or not, so the form keeps account membership private.
|
|
1324
|
+
A deployed preview resolves only its own users. See
|
|
1325
|
+
`somewhere docs sw.auth --section member-contacts`.
|
|
1326
|
+
|
|
1327
|
+
```ts
|
|
1328
|
+
// api/contacts/share.ts — POST { email }: share my contacts with the person at this address
|
|
1329
|
+
export default async function (req: Request, sw: SomewhereRuntimeContext) {
|
|
1330
|
+
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
1331
|
+
const me = await sw.auth.requireUser(req);
|
|
1332
|
+
const body = (await req.json().catch(() => null)) as { email?: unknown } | null;
|
|
1333
|
+
const email = typeof body?.email === 'string' ? body.email.trim() : '';
|
|
1334
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || email.length > 254) {
|
|
1335
|
+
return Response.json({ error: 'Enter the email address of the person to share with.' }, { status: 400 });
|
|
1336
|
+
}
|
|
1337
|
+
if (email.toLowerCase() === me.email.toLowerCase()) {
|
|
1338
|
+
return Response.json({ error: 'That is your own address; you already see your contacts.' }, { status: 400 });
|
|
1339
|
+
}
|
|
1340
|
+
const found = await sw.auth.server.listUsers({ emails: [email] });
|
|
1341
|
+
const recipient = found.users.find((user) => user.email_verified);
|
|
1342
|
+
if (recipient) {
|
|
1343
|
+
await sw.db.insert('shares', { grantee_id: recipient.id }, { onConflict: 'ignore' });
|
|
1344
|
+
}
|
|
1345
|
+
// The same reply whether or not the address matched, so the form never reveals who uses the app.
|
|
1346
|
+
return Response.json({
|
|
1347
|
+
message: `If ${email} belongs to someone who uses this app and has verified it, they can now see your contacts. `
|
|
1348
|
+
+ 'If not, they need to sign up with that address and verify it; then share again.',
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
```
|
|
1352
|
+
|
|
1353
|
+
To share one row instead of all of them, such as inviting coauthors to a
|
|
1354
|
+
single article, add `row`: the shares column holding that row's `id()`.
|
|
1355
|
+
|
|
1356
|
+
```ts
|
|
1357
|
+
import { schema, table, id, text, owner, anyOf, grant } from 'somewhere/db';
|
|
1358
|
+
|
|
1359
|
+
export default schema({
|
|
1360
|
+
article_shares: table({
|
|
1361
|
+
id: id(), grantee_id: text(),
|
|
1362
|
+
article_id: text({ references: 'articles', onDelete: 'cascade' }),
|
|
1363
|
+
}, {
|
|
1364
|
+
scope: owner(),
|
|
1365
|
+
indexes: [['grantee_id']],
|
|
1366
|
+
unique: [['article_id', 'grantee_id']],
|
|
1367
|
+
}),
|
|
1368
|
+
articles: table({ id: id(), title: text(), body: text() }, {
|
|
1369
|
+
scope: anyOf(owner(), grant({
|
|
1370
|
+
table: 'article_shares', grantee: 'grantee_id', row: 'article_id',
|
|
1371
|
+
operations: ['read', 'update'],
|
|
1372
|
+
})),
|
|
1373
|
+
client: { read: true, create: ['title', 'body'], update: ['title', 'body'], delete: true },
|
|
1374
|
+
}),
|
|
1375
|
+
});
|
|
1376
|
+
```
|
|
1377
|
+
|
|
1378
|
+
A share opens only the article it names; the author's other articles stay
|
|
1379
|
+
private. Only an article's owner can share it: a share naming an article the
|
|
1380
|
+
signed-in user does not own, or one that does not exist, is refused with 403
|
|
1381
|
+
`POLICY_AUTHORITY_REQUIRED`, and inside `sw.db.tx` it rolls the whole
|
|
1382
|
+
transaction back. The row column is required, typed like the key (`text()`
|
|
1383
|
+
for `id()`, `integer()` for `id({ uuid: false })`), references the shared
|
|
1384
|
+
table with `onDelete: 'cascade'` and no default, and cannot be in
|
|
1385
|
+
`client.update`. A share names one row for its life: to move it, delete it
|
|
1386
|
+
and create another. The shared table's `id` cannot change either. Deleting an
|
|
1387
|
+
article deletes its shares in the same statement, so an article later created
|
|
1388
|
+
with the same id is not shared. A per-row shares table serves exactly one
|
|
1389
|
+
`grant()` rule and keeps that form: switching it to per-owner sharing, or the
|
|
1390
|
+
reverse, needs a new shares table.
|
|
1391
|
+
|
|
1392
|
+
Coauthors may edit the `client.update` fields of the article shared with them,
|
|
1393
|
+
but cannot transfer ownership, create articles for the owner, delete the
|
|
1394
|
+
article, or share it on. New articles belong to the person creating them.
|
|
1395
|
+
|
|
1396
|
+
A recipient with `update` may also edit a shared row's `parent()` child rows
|
|
1397
|
+
and files in place, but never move them. Moving a child to another parent, or
|
|
1398
|
+
a file to another row, needs the owner branch on both the current and the new
|
|
1399
|
+
parent; a recipient's move, in either form of `grant()`, is refused with 403
|
|
1400
|
+
`POLICY_AUTHORITY_REQUIRED`.
|
|
1401
|
+
|
|
1402
|
+
Server code (`sw.db.server`) that writes a per-row share names its owner in
|
|
1403
|
+
`user_id`, and that owner must own the named row; any other share is refused
|
|
1404
|
+
with 403 `POLICY_AUTHORITY_REQUIRED`, as it is for signed-in callers. An update
|
|
1405
|
+
cannot change a share's row or owner. Raw SQL (`sw.db.server.query`) is not
|
|
1406
|
+
checked. For
|
|
1407
|
+
separate contact readers and article coauthors, declare separate owner-scoped
|
|
1408
|
+
grant tables. Operations are explicit per rule: `['read']` or
|
|
1409
|
+
`['read', 'update']`; `update` without `read` is not supported.
|
|
1410
|
+
|
|
1411
|
+
Functions apply the same rule. Caller-scoped `sw.db` and `sw.db.tx` stamp
|
|
1412
|
+
every insert with the caller as owner, and updates reach the caller's own rows
|
|
1413
|
+
plus the rows a `['read', 'update']` grant opens. In a transaction, an update
|
|
1414
|
+
outside those matches nothing (`changes: 0`) without rolling back the other
|
|
1415
|
+
intents, and an intent that names `user_id` refuses the whole transaction
|
|
1416
|
+
before anything runs. An `onConflict` upsert on the protected table updates
|
|
1417
|
+
an existing row only when the caller may update it (their own, or one a
|
|
1418
|
+
`['read', 'update']` grant shares) and otherwise refuses with 403
|
|
1419
|
+
`POLICY_AUTHORITY_REQUIRED`. The shares table is plain `owner()`, so
|
|
1420
|
+
`onConflict: 'ignore'` with its `unique: [['user_id', 'grantee_id']]` makes a
|
|
1421
|
+
repeated share a no-op. For background work on a shared row, a row-bound job
|
|
1422
|
+
(`docs({ topic: 'sw.jobs', section: 'act-on-one-row-for-the-signed-in-user' })`)
|
|
1423
|
+
acts on that one row as the user who started it, with their current access,
|
|
1424
|
+
so a recipient's job changes nothing once the share is deleted. Work with no
|
|
1425
|
+
signed-in user behind it (cron, webhooks) uses `sw.db.server`, which bypasses
|
|
1426
|
+
the rule: check the share yourself.
|
|
1427
|
+
|
|
1428
|
+
Changing an existing `owner()` table to this rule is an in-place access edit:
|
|
1429
|
+
existing rows retain their IDs, owners and contents. The shares table must
|
|
1430
|
+
be newly declared when first used for grants and use plain authenticated
|
|
1431
|
+
`owner()` with managed `user_id`; public intake and row links on it are not
|
|
1432
|
+
supported. A table already admitted as a grant table can be reused when editing
|
|
1433
|
+
operations. Older ordinary owner tables and restored tables lack verified
|
|
1434
|
+
lifetime grant history, so use a new shares table rather than adopting their
|
|
1435
|
+
existing rows as grants. The grant table and protected rows must be in
|
|
1436
|
+
the same project's declared schema; production, development and draft data
|
|
1437
|
+
remain separate.
|
|
1438
|
+
|
|
1439
|
+
To revoke access, delete the owner's share rows naming that recipient (one
|
|
1440
|
+
row, with the recipe's `unique` rule). Once the delete succeeds, the
|
|
1441
|
+
recipient's next request no longer reaches the row, its `parent()` children
|
|
1442
|
+
or their files: `get` returns `null`, `list` leaves the row out, and an
|
|
1443
|
+
update answers 404 `DATA_NOT_FOUND` (inside `sw.db.tx` it matches nothing,
|
|
1444
|
+
`changes: 0`). Every read and write checks the share in the same
|
|
1445
|
+
database statement as the row, so the generated client and caller-scoped
|
|
1446
|
+
`sw.db` need no extra check; `sw.db.server` bypasses the rule, as above.
|
|
1447
|
+
Data already delivered cannot be recalled: a page keeps a row it loaded
|
|
1448
|
+
until it reads again, and a browser may keep a file it downloaded.
|
|
1449
|
+
`sw.rooms.live` subscriptions over `anyOf` policies are currently unsupported
|
|
1450
|
+
and fail at deploy; use ordinary reads/refetches.
|
|
1451
|
+
|
|
1452
|
+
## Calling the data endpoint directly
|
|
1453
|
+
|
|
1454
|
+
Use the CLI's `data` command for a one-off probe as a signed-in app user and `app.data()`
|
|
1455
|
+
or the `data()` test fixture for scripts. They fill in the app's Origin and
|
|
1456
|
+
contract. See `somewhere docs test --section testing-access-rules`.
|
|
1457
|
+
|
|
1458
|
+
Every generated-client call is a `POST /__sw/data` on the app's own address.
|
|
1459
|
+
For a raw call, send this JSON body:
|
|
1460
|
+
|
|
1461
|
+
| Field | When | Value |
|
|
1462
|
+
|---|---|---|
|
|
1463
|
+
| `contract` | always | The digest of the deployed declaration (below). |
|
|
1464
|
+
| `table` | always | A declared table with client permissions. |
|
|
1465
|
+
| `operation` | always | `list`, `get`, `create`, `update`, `delete`, `aggregate` or `relation_list`. |
|
|
1466
|
+
| `id` | `get`, `update`, `delete` | The row's primary key. |
|
|
1467
|
+
| `values` | `create`, `update` | Only the columns in `client.create` / `client.update`. |
|
|
1468
|
+
| `idempotency_key` | `create` | Optional, 32 lowercase hex: a same-key retry returns the first result. |
|
|
1469
|
+
| `limit`, `after`, `where` | `list` | Page size 1 to 100 (default 25), the previous page's `next`, equality filters. |
|
|
1470
|
+
| `relation`, `parent_id` | `relation_list` | Plus `limit`, `after`, `where`. |
|
|
1471
|
+
| `count`, `sum`, `avg`, `min`, `max`, `groupBy`, `having`, `order` | `aggregate` | As in the generated client, plus `where` and `limit`. |
|
|
1472
|
+
|
|
1473
|
+
Any other field is refused with `DATA_INPUT_INVALID`. Answers: `list` →
|
|
1474
|
+
`{ data, next, has_more }`; `get` → `{ data }` (`null` when not
|
|
1475
|
+
readable); `create`, `update`, `delete` → `{ data, count, changes }`;
|
|
1476
|
+
a refusal → `{ error, message }` with its status.
|
|
1477
|
+
|
|
1478
|
+
The app user's session goes in a `__Host-token` cookie or an
|
|
1479
|
+
`Authorization: Bearer` header, and the `Origin` header must be the app's
|
|
1480
|
+
own address. The digest is `browser_data.contract_digest` in
|
|
1481
|
+
`GET /v1/db/access-map`: HTTP wraps it in `{ ok, data }`, `somewhere api`
|
|
1482
|
+
prints `data`, the MCP `api` tool returns `[{ status, ok, data: <HTTP body> }]`:
|
|
1483
|
+
|
|
1484
|
+
```bash
|
|
1485
|
+
somewhere api GET '/v1/db/access-map?project_id=<project>' | jq '.browser_data'
|
|
1486
|
+
somewhere call api '{"calls":[{"method":"GET","path":"/v1/db/access-map?project_id=<project>"}]}' | jq '.[0].data.data.browser_data'
|
|
1487
|
+
```
|
|
1488
|
+
|
|
1489
|
+
`browser_data` lists tables with and without browser access. If the app grants
|
|
1490
|
+
no browser access, its digest is null and every valid data operation is refused
|
|
1491
|
+
with 403 `DATA_ACCESS_DENIED`.
|
|
1492
|
+
|
|
1493
|
+
- **400 `DATA_CONTRACT_MISSING`** means the request omitted the digest.
|
|
1494
|
+
- **409 `DATA_CONTRACT_MISMATCH`** means the supplied digest did not match.
|
|
1495
|
+
With a verified session for this app the error includes
|
|
1496
|
+
`current_contract_digest`. Use it as `contract` for the next request. The
|
|
1497
|
+
digest fingerprints the deployed browser declaration and contains no row or
|
|
1498
|
+
session data.
|
|
1499
|
+
- Both `DATA_CONTRACT_*` errors stop before the operation and prove nothing about access.
|
|
1500
|
+
- **200 with `access: { filtered: true }`** means a caller-scoped rule
|
|
1501
|
+
constrains the list or get. The metadata is the same whether any rows matched,
|
|
1502
|
+
including for a missing or hidden row. Public-read and link reads omit it.
|
|
1503
|
+
- **404 `DATA_NOT_FOUND`** on update or delete means no writable row matched.
|
|
1504
|
+
Missing and inaccessible rows return the same status and code so a caller
|
|
1505
|
+
cannot use a write to find out whether a hidden row exists.
|
|
1506
|
+
|
|
1507
|
+
On a `member()` table, a signed-in user outside the group gets `list` →
|
|
1508
|
+
`[]`, `get` → `null`, `update` and `delete` → 404 `DATA_NOT_FOUND`,
|
|
1509
|
+
and `create` in that group → 403 `MEMBERSHIP_REQUIRED`. When `member()` sits
|
|
1510
|
+
inside `anyOf()` or `allOf()` (for example `anyOf(owner(), member(...))`), the
|
|
1511
|
+
same refused create is 403 `POLICY_AUTHORITY_REQUIRED`: the composed rule, not
|
|
1512
|
+
one branch, decides.
|
|
1513
|
+
|
|
1514
|
+
## Related records
|
|
1515
|
+
|
|
1516
|
+
Declare a relationship alongside the table, for example
|
|
1517
|
+
`relations: { tasks: hasMany('tasks', 'project_id') }` on `projects`.
|
|
1518
|
+
The child `project_id` column must declare `references: 'projects'`.
|
|
1519
|
+
When both tables grant client reads, the generated client exposes:
|
|
1520
|
+
|
|
1521
|
+
```ts
|
|
1522
|
+
const page = await data.projects.relations.tasks.list(projectId, { limit: 20 });
|
|
1523
|
+
// page.data, page.next, page.has_more — same page shape as an ordinary list.
|
|
1524
|
+
```
|
|
1525
|
+
|
|
1526
|
+
Each side keeps its own permissions. Reading a project does not grant access
|
|
1527
|
+
to its tasks: inaccessible children are omitted, and an inaccessible or missing
|
|
1528
|
+
parent produces an empty page. Sign-in requirements still apply. Each returned
|
|
1529
|
+
child contains only its declared readable fields; a hidden linking column is
|
|
1530
|
+
not added to the result. Filters use readable child fields, and `after` is a
|
|
1531
|
+
child-row cursor. This is one relationship at a time, with up to 100 rows per
|
|
1532
|
+
page. Parent and child reads are separate, so the result is not an atomic
|
|
1533
|
+
snapshot. Relation writes, nested relationships and automatic inheritance of
|
|
1534
|
+
parent permissions are not part of this operation.
|
|
1535
|
+
|
|
1536
|
+
The inverse direction is `belongsTo`: declare
|
|
1537
|
+
`relations: { project: belongsTo('projects', 'project_id') }` on `tasks`,
|
|
1538
|
+
the table that holds the key. The generated client adds no method for it — a
|
|
1539
|
+
task's readable `project_id` is already on the row, and the parent is an
|
|
1540
|
+
ordinary `data.projects.get(task.project_id)` under the parent's own read
|
|
1541
|
+
grant. In a server function, `sw.db.from('tasks', { include: ['project'] })`
|
|
1542
|
+
nests the parent row on each task, or `null` when the caller may not read it
|
|
1543
|
+
(`docs({ topic: 'sw.db' })`).
|
|
1544
|
+
|
|
1545
|
+
Local `somewhere typecheck` and `somewhere dev` resolve `somewhere:data` with
|
|
1546
|
+
the current CLI (`npm i -g @somewhere-cloud/cli@latest` if yours predates this
|
|
1547
|
+
contract); `somewhere deploy-check` compiles on the platform regardless.
|
|
1548
|
+
|
|
1549
|
+
## Inside functions
|
|
1550
|
+
|
|
1551
|
+
Keep the table's managed access rule when adding a function. For a public
|
|
1552
|
+
enquiry to a published profile, use declared `client.intake`
|
|
1553
|
+
(`declared-data` → `send-an-enquiry-to-a-public-profile`). Use a function
|
|
1554
|
+
for an authorized write the declaration cannot express or for a side effect;
|
|
1555
|
+
`recipe-signed-in-app` shows validation, abuse protection and email. The
|
|
1556
|
+
rest of the app continues using the generated client.
|
|
1557
|
+
|
|
1558
|
+
- Default: `sw.db.from / insert / update / remove` run as the calling member
|
|
1559
|
+
and the same ownership rule applies. `owner()` tables need no auth guard.
|
|
1560
|
+
- `sw.db.aggregate(table, { count, sum, avg, min, max, groupBy, where,
|
|
1561
|
+
having, order, limit })` composes count / sum / avg / min / max with the
|
|
1562
|
+
same row permissions; `include` and `has` on `sw.db.from` compose
|
|
1563
|
+
declared `hasMany` / `belongsTo` relations. The contract is in
|
|
1564
|
+
`docs({ topic: 'sw.db' })`.
|
|
1565
|
+
- Intentional cross-user reads (admin screens, aggregates, background jobs):
|
|
1566
|
+
pass `{ asServer: true }` to `sw.db.from`, `sw.db.count` or
|
|
1567
|
+
`sw.db.aggregate`, or use `sw.db.server.from / count / aggregate`.
|
|
1568
|
+
- Intentional cross-user writes: authorize the caller yourself, then use
|
|
1569
|
+
`sw.db.server.insert / update / remove`, or `sw.db.server.tx` for a closed
|
|
1570
|
+
batch applied atomically. `sw.db.tx` checks membership inside the batch;
|
|
1571
|
+
`sw.db.server.tx` writes membership-scoped tables with server authority.
|
|
1572
|
+
A caller's `onConflict` insert into a membership-scoped table is checked
|
|
1573
|
+
like any insert, and its update like any update (`sw.db` → Upserts). Every
|
|
1574
|
+
server-mode call is recorded in the query log with authority `server`.
|
|
1575
|
+
- Raw `query` and `batch` on current projects reach only the separate SQL
|
|
1576
|
+
database. Use the structured methods above for declared tables. Older
|
|
1577
|
+
projects with a shared managed database support explicit read-only raw access
|
|
1578
|
+
through `sw.db.server.query` and `sw.db.server.batch` after caller authorization.
|
|
1579
|
+
|
|
1580
|
+
## Server-only fallback when a rule cannot be declared
|
|
1581
|
+
|
|
1582
|
+
Do not mark data people read or change through your app serverOnly() and
|
|
1583
|
+
hand-write its access checks. Declare who may read and write it; the platform
|
|
1584
|
+
enforces that for you.
|
|
1585
|
+
|
|
1586
|
+
Server-only is right for:
|
|
1587
|
+
- Tables only server code touches: job state, import staging, audit records, counters.
|
|
1588
|
+
- Membership/grant ledgers: never grant browser writes. grant() ledgers retain the
|
|
1589
|
+
owner() scope required by that policy, with no client write grants.
|
|
1590
|
+
- A rule the declarations cannot express; keep other operations declared:
|
|
1591
|
+
- Arbitrary predicates (such as checking the current time): use a checked endpoint.
|
|
1592
|
+
- Different writable fields by role on one table: split tables or check that write.
|
|
1593
|
+
Server-assigned roles and role-filtered member() operations are declarable; they
|
|
1594
|
+
are not reasons to make app data server-only.
|
|
1595
|
+
|
|
1596
|
+
An unverified email suffix is not a declared identity rule; use verified identity
|
|
1597
|
+
or trusted role assignment, not server-only tables for the whole app.
|
|
1598
|
+
|
|
1599
|
+
Start with owner() for personal rows or group() over built-in groups for team
|
|
1600
|
+
rows (`sw.groups` → `team-example`). Keep declared access when
|
|
1601
|
+
only one operation needs a checked endpoint. Use the server-only fallback only
|
|
1602
|
+
when every operation needs a rule the declarations cannot express.
|
|
1603
|
+
|
|
1604
|
+
For the complete signup schema and validated public signup/count handlers, read
|
|
1605
|
+
`docs({ topic: 'architecture-patterns', section: 'minimal-server-only-app' })`.
|
|
1606
|
+
The table uses `serverOnly()`; functions explicitly authorize public or private
|
|
1607
|
+
operations before using `sw.db.server`.
|
|
1608
|
+
|
|
1609
|
+
## Restore and existing databases
|
|
1610
|
+
|
|
1611
|
+
Restoring a project database in place is not available: the request is
|
|
1612
|
+
refused with `DATABASE_RESTORE_UNAVAILABLE` before anything changes. Downloads
|
|
1613
|
+
and exports work as documented.
|
|
1614
|
+
|
|
1615
|
+
A project created now starts in managed mode: its database is shaped only
|
|
1616
|
+
by the schema file you deploy, and you can add that file on any later deploy.
|
|
1617
|
+
A project from before managed mode (one whose database was built with SQL
|
|
1618
|
+
migrations) keeps working as it does today; moving it onto a declaration is
|
|
1619
|
+
an explicit migration step you request, not something the platform performs
|
|
1620
|
+
on your next deploy.
|
|
1621
|
+
|
|
1622
|
+
## Server roles and membership restrictions
|
|
1623
|
+
|
|
1624
|
+
Use `emailDomain` when staff are people at your domain: the role holds once the person verifies that address, with no grant code. Use `assignedBy: 'server'` when your app decides, such as an admin promotion, payment, or an invitation it issued. Require mailbox verification when grant eligibility depends on an email domain. Validate the caller and target before granting from browser input.
|
|
1625
|
+
|
|
1626
|
+
```ts
|
|
1627
|
+
// Help Desk: db/schema.ts
|
|
1628
|
+
import { schema, table, id, text, owner, anyOf, appRole, parent } from 'somewhere/db';
|
|
1629
|
+
export default schema({
|
|
1630
|
+
tickets: table({ id: id(), subject: text() }, {
|
|
1631
|
+
scope: anyOf(owner({ column: 'customer_id' }), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),
|
|
1632
|
+
}),
|
|
1633
|
+
replies: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, { scope: parent({ via: 'ticket_id' }) }),
|
|
1634
|
+
internal_notes: table({ id: id(), body: text() }, { scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }) }),
|
|
1635
|
+
}, { appRoles: { staff: { emailDomain: 'staff.example' } } });
|
|
1636
|
+
```
|
|
1637
|
+
|
|
1638
|
+
Staff reply by creating `replies` rows, and creating a `parent()` child needs
|
|
1639
|
+
`create` on the parent for that person. That is why `tickets` lists
|
|
1640
|
+
`create: ['staff']`: with only `read` and `update`, every staff reply is refused
|
|
1641
|
+
with 403 `POLICY_AUTHORITY_REQUIRED`. It also lets staff open tickets.
|
|
1642
|
+
|
|
1643
|
+
Here staff are the people who verify an address at `staff.example`: no grant
|
|
1644
|
+
code runs, and the role holds on their first request after verification. When
|
|
1645
|
+
staff must hold the role before verifying, grant it inside the sign-up route
|
|
1646
|
+
from an invitation your app issued, never from the address alone:
|
|
1647
|
+
`somewhere docs sw.auth --section server-assigned-app-roles-setroles`.
|
|
1648
|
+
|
|
1649
|
+
A later promotion runs in a POST handler that authorizes the caller first (for
|
|
1650
|
+
example `sw.auth.requireUser(request, { role: 'admin' })`), never a GET: role
|
|
1651
|
+
assignment changes authentication state, so a cookie session cannot perform it
|
|
1652
|
+
through a safe HTTP method.
|
|
1653
|
+
|
|
1654
|
+
After your endpoint validates who may promote the target, call `await sw.auth.server.setRoles(userId, { add: ['staff'] })`; remove with `{ remove: ['staff'] }`. These methods run only in deployed functions, including verified non-row-bound background deliveries; in a preview they act on the preview's own users and its copy of the data, never the live app's; dev, run_code, and app MCP functions cannot use them. A rooms referee must await sw.rooms.event(req) before trusting event input. Developer and app-admin grants remain available. Server-assigned roles cannot delegate other roles. Revoke explicit grants before changing a role's acquisition mode.
|
|
1655
|
+
|
|
1656
|
+
Committed role changes affect subsequent fresh policy evaluations; existing room authorization lasts at most the remaining five-minute ticket, and live subscriptions use the existing close mechanism with a bounded fallback. Already fetched data cannot be recalled.
|