@somewhere-cloud/cli 0.38.155 → 0.38.157
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 +8 -1
- package/dist/commands/docs.js +1 -1
- package/dist/lib/bundle.js +286 -188
- package/dist/lib/bundle.js.map +3 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -3
- package/dist/docs/adopt.md +0 -39
- package/dist/docs/analytics.md +0 -161
- package/dist/docs/api-reference.md +0 -339
- package/dist/docs/api-surface.md +0 -2067
- package/dist/docs/app-mcp.md +0 -162
- package/dist/docs/architecture-patterns.md +0 -334
- package/dist/docs/auth-client.md +0 -531
- package/dist/docs/billing.md +0 -76
- package/dist/docs/browser.md +0 -639
- package/dist/docs/calendar.md +0 -298
- package/dist/docs/changes.md +0 -323
- package/dist/docs/cli.md +0 -407
- package/dist/docs/common-mistakes.md +0 -199
- package/dist/docs/connect-agent.md +0 -72
- package/dist/docs/cors.md +0 -114
- package/dist/docs/cron.md +0 -167
- package/dist/docs/database-engine.md +0 -167
- package/dist/docs/declared-data.md +0 -1656
- package/dist/docs/declared-files.md +0 -475
- package/dist/docs/deploy-intelligence.md +0 -188
- package/dist/docs/deploy.md +0 -733
- package/dist/docs/design-system.md +0 -273
- package/dist/docs/dev-environments.md +0 -496
- package/dist/docs/domain-ownership.md +0 -31
- package/dist/docs/domains.md +0 -370
- package/dist/docs/feedback.md +0 -88
- package/dist/docs/file-tools.md +0 -116
- package/dist/docs/functions.md +0 -489
- package/dist/docs/getting-started.md +0 -238
- package/dist/docs/github.md +0 -95
- package/dist/docs/google-calendar.md +0 -212
- package/dist/docs/groups.md +0 -836
- package/dist/docs/guarantees.md +0 -58
- package/dist/docs/handled-for-you.md +0 -224
- package/dist/docs/inspect.md +0 -171
- package/dist/docs/limits.md +0 -68
- package/dist/docs/live-data.md +0 -197
- package/dist/docs/live.md +0 -92
- package/dist/docs/local-dev.md +0 -30
- package/dist/docs/migration-supabase.md +0 -58
- package/dist/docs/payments.md +0 -1102
- package/dist/docs/portability.md +0 -194
- package/dist/docs/postgres.md +0 -301
- package/dist/docs/pricing-comparison.md +0 -42
- package/dist/docs/pricing.md +0 -39
- package/dist/docs/project-groups.md +0 -107
- package/dist/docs/projects.md +0 -380
- package/dist/docs/recipe-ai-agent.md +0 -112
- package/dist/docs/recipe-ai-features.md +0 -227
- package/dist/docs/recipe-ai-receipts.md +0 -783
- package/dist/docs/recipe-background-jobs.md +0 -369
- package/dist/docs/recipe-booking.md +0 -348
- package/dist/docs/recipe-csv-import.md +0 -390
- package/dist/docs/recipe-ecommerce.md +0 -127
- package/dist/docs/recipe-email.md +0 -282
- package/dist/docs/recipe-escalation.md +0 -133
- package/dist/docs/recipe-file-uploads.md +0 -159
- package/dist/docs/recipe-import-app.md +0 -110
- package/dist/docs/recipe-login.md +0 -457
- package/dist/docs/recipe-multi-chat.md +0 -198
- package/dist/docs/recipe-paid-api.md +0 -161
- package/dist/docs/recipe-pdfs.md +0 -205
- package/dist/docs/recipe-push-notifications.md +0 -107
- package/dist/docs/recipe-seo.md +0 -200
- package/dist/docs/recipe-signed-in-app.md +0 -330
- package/dist/docs/render.md +0 -99
- package/dist/docs/rooms.md +0 -554
- package/dist/docs/sdk.md +0 -287
- package/dist/docs/sdks.md +0 -24
- package/dist/docs/search.md +0 -199
- package/dist/docs/security-model.md +0 -168
- package/dist/docs/setup.md +0 -212
- package/dist/docs/smoke.md +0 -102
- package/dist/docs/speed.md +0 -298
- package/dist/docs/sql-compatibility.md +0 -96
- package/dist/docs/sw.agent.md +0 -248
- package/dist/docs/sw.ai.md +0 -1291
- package/dist/docs/sw.auth.md +0 -1811
- package/dist/docs/sw.billing.md +0 -171
- package/dist/docs/sw.db.md +0 -2128
- package/dist/docs/sw.email.md +0 -661
- package/dist/docs/sw.endpoint.md +0 -187
- package/dist/docs/sw.env.md +0 -303
- package/dist/docs/sw.fetch.md +0 -115
- package/dist/docs/sw.fs.md +0 -424
- package/dist/docs/sw.groups.md +0 -836
- package/dist/docs/sw.image.md +0 -69
- package/dist/docs/sw.jobs.md +0 -520
- package/dist/docs/sw.logs.md +0 -61
- package/dist/docs/sw.mail.md +0 -106
- package/dist/docs/sw.notifications.md +0 -78
- package/dist/docs/sw.push.md +0 -161
- package/dist/docs/sw.rateLimit.md +0 -67
- package/dist/docs/sw.web.md +0 -128
- package/dist/docs/tasks.md +0 -269
- package/dist/docs/test.md +0 -220
- package/dist/docs/tool-reference-account.md +0 -7
- package/dist/docs/tool-reference-ai.md +0 -121
- package/dist/docs/tool-reference-analytics.md +0 -37
- package/dist/docs/tool-reference-api.md +0 -19
- package/dist/docs/tool-reference-artifacts.md +0 -35
- package/dist/docs/tool-reference-auth.md +0 -163
- package/dist/docs/tool-reference-browser.md +0 -114
- package/dist/docs/tool-reference-code.md +0 -26
- package/dist/docs/tool-reference-connect.md +0 -21
- package/dist/docs/tool-reference-cron.md +0 -48
- package/dist/docs/tool-reference-db.md +0 -282
- package/dist/docs/tool-reference-domains.md +0 -107
- package/dist/docs/tool-reference-email.md +0 -55
- package/dist/docs/tool-reference-env.md +0 -19
- package/dist/docs/tool-reference-feedback.md +0 -56
- package/dist/docs/tool-reference-fs.md +0 -265
- package/dist/docs/tool-reference-github.md +0 -57
- package/dist/docs/tool-reference-groups.md +0 -85
- package/dist/docs/tool-reference-help.md +0 -29
- package/dist/docs/tool-reference-jobs.md +0 -39
- package/dist/docs/tool-reference-live.md +0 -48
- package/dist/docs/tool-reference-logs.md +0 -16
- package/dist/docs/tool-reference-payments.md +0 -44
- package/dist/docs/tool-reference-project.md +0 -706
- package/dist/docs/tool-reference-push.md +0 -78
- package/dist/docs/tool-reference-rate-limit.md +0 -18
- package/dist/docs/tool-reference-search.md +0 -68
- package/dist/docs/tool-reference-security.md +0 -42
- package/dist/docs/tool-reference-smoke.md +0 -17
- package/dist/docs/tool-reference-stock-photos.md +0 -20
- package/dist/docs/tool-reference-tasks.md +0 -73
- package/dist/docs/tool-reference-telegram.md +0 -32
- package/dist/docs/tool-reference-usage.md +0 -9
- package/dist/docs/tool-reference-web.md +0 -71
- package/dist/docs/tool-reference-webhooks.md +0 -9
- package/dist/docs/troubleshooting.md +0 -411
- package/dist/docs/typed-functions.md +0 -94
- package/dist/docs/verify-before-deploy.md +0 -67
- package/dist/docs/vs-supabase.md +0 -75
- package/dist/docs/vs-vercel.md +0 -103
|
@@ -1,282 +0,0 @@
|
|
|
1
|
-
# Recipe — Email the signed-in user
|
|
2
|
-
|
|
3
|
-
A signed-in user asks for an email, your function sends it to their own
|
|
4
|
-
address once they have verified it, and the page shows what the platform
|
|
5
|
-
answered. No sender account or domain is needed to start. Then add your own
|
|
6
|
-
sender domain, receiving, bounces or many recipients when the app needs them.
|
|
7
|
-
|
|
8
|
-
## 1. The function: verified recipient, one send per action
|
|
9
|
-
|
|
10
|
-
A password sign-up can name any address. This function sends custom content
|
|
11
|
-
only after the account's owner has verified that address: it checks that
|
|
12
|
-
`user.email_verified` is true, which a sign-in link or the verification
|
|
13
|
-
code sets (`sw.auth` → `email-verification`, `magic-links`).
|
|
14
|
-
|
|
15
|
-
```ts
|
|
16
|
-
// api/email-me.ts — POST { title, body, request_id }
|
|
17
|
-
export default sw.endpoint({
|
|
18
|
-
auth: 'none', // the handler applies its own access check below
|
|
19
|
-
handler: async ({ request }, sw) => {
|
|
20
|
-
if (request.method !== 'POST') {
|
|
21
|
-
return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
22
|
-
}
|
|
23
|
-
const refuse = (error: string, status: number, code?: string) =>
|
|
24
|
-
Response.json({ outcome: 'request-refused', error, code }, { status });
|
|
25
|
-
|
|
26
|
-
const user = await sw.auth.fromRequest(request);
|
|
27
|
-
if (!user) return refuse('Sign in to email yourself.', 401);
|
|
28
|
-
if (user.email_verified !== true) return refuse('Verify your email address first.', 403);
|
|
29
|
-
|
|
30
|
-
const input: unknown = await request.json().catch(() => null);
|
|
31
|
-
const fields = typeof input === 'object' && input !== null ? input : {};
|
|
32
|
-
const title = 'title' in fields ? fields.title : undefined;
|
|
33
|
-
const body = 'body' in fields ? fields.body : undefined;
|
|
34
|
-
const requestId = 'request_id' in fields ? fields.request_id : undefined;
|
|
35
|
-
if (typeof title !== 'string' || !title.trim() || title.length > 120
|
|
36
|
-
|| typeof body !== 'string' || body.length > 10000
|
|
37
|
-
|| typeof requestId !== 'string' || !/^[\w-]{8,64}$/.test(requestId)) {
|
|
38
|
-
return refuse('Send a title, a body and a request_id.', 400);
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// 10 per hour per user is this example's choice.
|
|
42
|
-
const allowance = await sw.rateLimit.check(`email-me:${user.id}`, 10, 3600);
|
|
43
|
-
if (!allowance.allowed) return refuse('Too many requests. Try again later.', 429);
|
|
44
|
-
|
|
45
|
-
try {
|
|
46
|
-
const sent = await sw.email.send({
|
|
47
|
-
to: user.email,
|
|
48
|
-
subject: `Your note: ${title.trim()}`,
|
|
49
|
-
text: body,
|
|
50
|
-
// Reuse this key when checking the outcome of the same action.
|
|
51
|
-
idempotency_key: `email-me:${user.id}:${requestId}`,
|
|
52
|
-
});
|
|
53
|
-
return Response.json({ id: sent.id, status: sent.status });
|
|
54
|
-
} catch (error) {
|
|
55
|
-
const code = error instanceof Error && 'code' in error ? String(error.code) : 'EMAIL_FAILED';
|
|
56
|
-
const status = error instanceof Error && 'status' in error ? Number(error.status) : 0;
|
|
57
|
-
// The email service refused this request (422 or 429). Anything else is unconfirmed.
|
|
58
|
-
if (status === 422 || status === 429) return refuse('The email service refused this request.', status, code);
|
|
59
|
-
return Response.json({ outcome: 'unconfirmed', error: 'Could not confirm the email.', code }, { status: 502 });
|
|
60
|
-
}
|
|
61
|
-
},
|
|
62
|
-
});
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
The recipient is the session's own address, never one from the request body,
|
|
66
|
-
and the checks run before the send. Every refusal says only that this request
|
|
67
|
-
was refused; it says nothing about an earlier request with the same
|
|
68
|
-
`request_id`.
|
|
69
|
-
|
|
70
|
-
## 2. Call it from the page
|
|
71
|
-
|
|
72
|
-
```ts
|
|
73
|
-
// src/services/email-me.ts
|
|
74
|
-
import { auth } from './auth';
|
|
75
|
-
|
|
76
|
-
export type EmailResult =
|
|
77
|
-
| { kind: 'status'; status: string } // the platform's state for this message
|
|
78
|
-
| { kind: 'request-refused'; error: string } // this request was refused
|
|
79
|
-
| { kind: 'unconfirmed' }; // nothing settled the outcome
|
|
80
|
-
|
|
81
|
-
/** One request_id per user action. Check again with the same id, title and body. */
|
|
82
|
-
export async function emailMe(title: string, body: string, requestId: string): Promise<EmailResult> {
|
|
83
|
-
let response: Response;
|
|
84
|
-
try {
|
|
85
|
-
response = await auth.fetch('/api/email-me', {
|
|
86
|
-
method: 'POST',
|
|
87
|
-
headers: { 'content-type': 'application/json' },
|
|
88
|
-
body: JSON.stringify({ title, body, request_id: requestId }),
|
|
89
|
-
});
|
|
90
|
-
} catch {
|
|
91
|
-
return { kind: 'unconfirmed' }; // the request may have arrived
|
|
92
|
-
}
|
|
93
|
-
const result: unknown = await response.json().catch(() => null);
|
|
94
|
-
const fields = typeof result === 'object' && result !== null ? result : {};
|
|
95
|
-
if (response.ok && 'status' in fields && typeof fields.status === 'string') {
|
|
96
|
-
return { kind: 'status', status: fields.status };
|
|
97
|
-
}
|
|
98
|
-
if ('outcome' in fields && fields.outcome === 'request-refused') {
|
|
99
|
-
const error = 'error' in fields && typeof fields.error === 'string' ? fields.error : 'This request was refused.';
|
|
100
|
-
return { kind: 'request-refused', error };
|
|
101
|
-
}
|
|
102
|
-
return { kind: 'unconfirmed' };
|
|
103
|
-
}
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
Create the id when the user acts, for example
|
|
107
|
-
`const requestId = crypto.randomUUID()`, and keep it with that action's title
|
|
108
|
-
and body. Reuse that id to check the same message; create a new id for a
|
|
109
|
-
new note.
|
|
110
|
-
|
|
111
|
-
- **`status`**: show it. `sent` means the provider accepted the message,
|
|
112
|
-
and `captured` that it is in the test inbox, not delivered. A repeat
|
|
113
|
-
shows the message's later state: `delivered`, `opened` or `clicked`
|
|
114
|
-
happened. `bounced` reports a delivery failure; `complained` reports
|
|
115
|
-
a spam complaint. `suppressed`, `preference_blocked` and `failed`
|
|
116
|
-
report that the send was blocked or failed. `pending`,
|
|
117
|
-
`claimed` or `delivery_unknown` mean the platform could not confirm it
|
|
118
|
-
yet.
|
|
119
|
-
- **`request-refused`**: show "This request was refused" and the error. It
|
|
120
|
-
covers this request only; a repeat keeps the same `request_id`.
|
|
121
|
-
- **`unconfirmed`**: show "We couldn't confirm the email" and offer **Check
|
|
122
|
-
again**, which calls `emailMe` with the same `requestId`, title and body.
|
|
123
|
-
Nothing is sent automatically. A check can stay unconfirmed; `sw.email` →
|
|
124
|
-
`result-and-errors` explains the states.
|
|
125
|
-
|
|
126
|
-
## 3. Check it with the test inbox
|
|
127
|
-
|
|
128
|
-
```bash
|
|
129
|
-
somewhere deploy
|
|
130
|
-
# Replace my-app with your app's subdomain.
|
|
131
|
-
somewhere email test-inbox ana@my-app.test.somewhere.site
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
Sign in to your app with a sign-in link sent to
|
|
135
|
-
`ana@<project>.test.somewhere.site` (`sw.auth` → `magic-links`): run the
|
|
136
|
-
second command, open the link it prints, and the account's address is
|
|
137
|
-
verified. Then send yourself a note and run the command again: it prints the
|
|
138
|
-
captured message, and the page shows `captured`. An account that signed up
|
|
139
|
-
with a password and never verified gets 403 from the function. Test-inbox
|
|
140
|
-
messages are never delivered and don't count toward your email allowance.
|
|
141
|
-
|
|
142
|
-
## 4. Going further
|
|
143
|
-
|
|
144
|
-
| Need | Section |
|
|
145
|
-
|---|---|
|
|
146
|
-
| Invite someone who isn't a user yet, into a team | `recipe-login` → `7-team-invites` |
|
|
147
|
-
| Mail to people who aren't your users, from your own address | **Your own sender domain** below |
|
|
148
|
-
| Receive mail and act on it | **Receive email** below |
|
|
149
|
-
| Know whether a message arrived; bounces and complaints | **Delivery status and bounces** below |
|
|
150
|
-
| One message to many users | **Send to a list** below |
|
|
151
|
-
| Every result state and error code | `sw.email` → `result-and-errors` |
|
|
152
|
-
|
|
153
|
-
Your plan's email allowance and send rate are in `pricing`.
|
|
154
|
-
|
|
155
|
-
## Your own sender domain
|
|
156
|
-
|
|
157
|
-
The platform's sender reaches this project's users and its owner. To email
|
|
158
|
-
anyone else, or to send from your own address, pass `from` on a verified
|
|
159
|
-
sender domain of the project:
|
|
160
|
-
|
|
161
|
-
```ts
|
|
162
|
-
// Fragment, inside a function, once the domain is verified.
|
|
163
|
-
await sw.email.send({ to: 'alice@example.com', from: 'hello@yourapp.com', subject: 'Welcome', text: 'Thanks for joining.' });
|
|
164
|
-
```
|
|
165
|
-
|
|
166
|
-
- A domain bought through the platform is set up for sending automatically.
|
|
167
|
-
- For a domain registered elsewhere, [add and verify a sender domain](https://somewhere.cloud/docs/sw.email.txt#your-own-sender-domain).
|
|
168
|
-
Sender domains need a paid plan. On Free the call answers `UPGRADE_REQUIRED` (402).
|
|
169
|
-
- A send with that `from` returns `SENDER_DOMAIN_NOT_FOUND` if the
|
|
170
|
-
domain has not been added, or `SENDER_DOMAIN_NOT_VERIFIED` while verification
|
|
171
|
-
is pending. Once verified, sign-in emails use your domain too.
|
|
172
|
-
|
|
173
|
-
## Receive email
|
|
174
|
-
|
|
175
|
-
Mail arrives at addresses on a custom domain of the project:
|
|
176
|
-
|
|
177
|
-
1. Turn on inbound mail for a domain claimed on the project:
|
|
178
|
-
`domain_enable_email({ id })`, with the domain id from `domain_owned`. Its
|
|
179
|
-
`receiving_host` is the domain itself, or reply.<domain> when the domain
|
|
180
|
-
already has a mail provider (whose records stay unchanged).
|
|
181
|
-
2. Register addresses on that `receiving_host` and read the mail they
|
|
182
|
-
receive through the mail API (`/v1/mail`).
|
|
183
|
-
|
|
184
|
-
Inbound addresses need a custom domain; the test inbox captures mail your
|
|
185
|
-
project sends and receives no outside mail.
|
|
186
|
-
|
|
187
|
-
## A follow-up that sends once and stops on reply
|
|
188
|
-
|
|
189
|
-
A day-two nudge takes a schedule, a query on your own data, and two options on
|
|
190
|
-
`sw.mail.project.send`. It needs no workflow engine.
|
|
191
|
-
|
|
192
|
-
- **`once: '<step>'`** sends this step to this person at most once. A second
|
|
193
|
-
call for the same step and recipient returns the first result with
|
|
194
|
-
`duplicate: true` and sends nothing, so a schedule that runs twice is safe.
|
|
195
|
-
The first attempt counts whatever its outcome: a refused or waiting first
|
|
196
|
-
attempt is not retried for that person. `once` needs exactly one address in
|
|
197
|
-
`to`.
|
|
198
|
-
- **`unless_replied: true`** sends nothing to someone the project mailbox has
|
|
199
|
-
already received mail from. The answer is then `status: 'skipped'` with
|
|
200
|
-
`skipped: 'replied'`.
|
|
201
|
-
|
|
202
|
-
A reply already recorded stops the next nudge. A reply still in transit while
|
|
203
|
-
the nudge goes out cannot stop it.
|
|
204
|
-
|
|
205
|
-
```ts
|
|
206
|
-
// api/jobs/day-two.ts: runs daily and nudges people who signed up the day before yesterday
|
|
207
|
-
export default sw.endpoint({
|
|
208
|
-
auth: 'none', // The platform invocation signature authorizes this route.
|
|
209
|
-
handler: async ({ request: req }, sw) => {
|
|
210
|
-
if (!(await sw.jobs.verifyInvocation(req))) return new Response('forbidden', { status: 403 });
|
|
211
|
-
const day = 24 * 60 * 60 * 1000;
|
|
212
|
-
const { data } = await sw.db.server.from('signups', {
|
|
213
|
-
where: { created_at: [{ gte: new Date(Date.now() - 3 * day).toISOString() }, { lt: new Date(Date.now() - 2 * day).toISOString() }] },
|
|
214
|
-
limit: 500,
|
|
215
|
-
});
|
|
216
|
-
let sent = 0;
|
|
217
|
-
for (const person of data) {
|
|
218
|
-
const r = await sw.mail.project.send({
|
|
219
|
-
from: 'hello@example.com', // an address of this project on a verified sending domain
|
|
220
|
-
to: String(person.email),
|
|
221
|
-
subject: 'Did it work for you?',
|
|
222
|
-
text: 'If anything got in the way, reply to this email and I will help.',
|
|
223
|
-
once: 'day-two',
|
|
224
|
-
unless_replied: true,
|
|
225
|
-
});
|
|
226
|
-
if (r.status !== 'skipped' && !r.duplicate) sent += 1;
|
|
227
|
-
}
|
|
228
|
-
return { sent };
|
|
229
|
-
},
|
|
230
|
-
});
|
|
231
|
-
```
|
|
232
|
-
|
|
233
|
-
```bash
|
|
234
|
-
somewhere deploy
|
|
235
|
-
somewhere cron create "0 16 * * *" /api/jobs/day-two --project <project> --name day-two
|
|
236
|
-
somewhere cron run day-two --project <project> --wait # run it once now
|
|
237
|
-
```
|
|
238
|
-
|
|
239
|
-
The sending address must be on a domain the project has verified for
|
|
240
|
-
sending. Replies come back to the same address and are recorded in the
|
|
241
|
-
project mailbox, which is what `unless_replied` reads.
|
|
242
|
-
|
|
243
|
-
## Delivery status and bounces
|
|
244
|
-
|
|
245
|
-
`status: 'sent'` means the provider accepted the message. What happened next
|
|
246
|
-
is on the message:
|
|
247
|
-
|
|
248
|
-
- `sw.email.status(id)` returns one message's timeline: delivered, opened,
|
|
249
|
-
clicked, bounced or complained.
|
|
250
|
-
- A permanent bounce pauses that address for 30 days, a temporary one for
|
|
251
|
-
24 hours, and a spam complaint permanently. Sends to a paused address throw
|
|
252
|
-
`EMAIL_SUPPRESSED` before anything is sent.
|
|
253
|
-
- `sw.email.checkSuppression(address)` checks one address before you send;
|
|
254
|
-
`sw.email.bounces({ days })` returns the list to skip for a mailing.
|
|
255
|
-
- A project whose mail bounces or draws complaints too often is paused for
|
|
256
|
-
every send until the rate recovers: `sw.email` → `sending-reputation`.
|
|
257
|
-
|
|
258
|
-
## Send to a list
|
|
259
|
-
|
|
260
|
-
There is no batch send call: each recipient is one `sw.email.send`. These
|
|
261
|
-
rules keep a mailing fast, repeat-safe and out of spam folders:
|
|
262
|
-
|
|
263
|
-
- **Start sends together in small groups, never one awaited send after
|
|
264
|
-
another.** Each send waits for the provider, so a loop of awaited sends
|
|
265
|
-
takes as many round trips as there are recipients.
|
|
266
|
-
- **One `idempotency_key` per recipient per mailing**, such as
|
|
267
|
-
`` `digest-${digestId}-${user.id}` ``, so a retried batch never emails
|
|
268
|
-
anyone twice.
|
|
269
|
-
- **Skip bounced and opted-out addresses first.** Remove
|
|
270
|
-
`sw.email.bounces()` addresses, and keep an opt-out column of your own that
|
|
271
|
-
a link in every mailing sets.
|
|
272
|
-
- **Escape every value you put into `html`.** A user's name is user input.
|
|
273
|
-
- **Stay under the send rate.** It's counted per account across its
|
|
274
|
-
projects; above it a send throws `RATE_LIMITED` (429). For a list longer
|
|
275
|
-
than one minute's worth, create one job per batch, each with a later
|
|
276
|
-
`run_at`, and send that batch in its handler
|
|
277
|
-
(`recipe-background-jobs` → `8-work-that-starts-later`).
|
|
278
|
-
- **Use your own sender domain for newsletters and announcements.** The
|
|
279
|
-
platform's sender is for transactional mail.
|
|
280
|
-
|
|
281
|
-
The send-rate number and a grouped-send example: `sw.email` →
|
|
282
|
-
`sending-to-many-recipients`.
|
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
# Recipe — Cheap model escalates to smart model when stuck
|
|
2
|
-
|
|
3
|
-
Run your chatbot on a cheap fast model (Haiku, GPT-4o-mini) for the
|
|
4
|
-
90% of turns that are easy — navigation, simple lookups, short
|
|
5
|
-
answers. When a turn is actually hard (a real bug, architecture
|
|
6
|
-
advice, a code review), the cheap model hands the hard question, restated with the code, errors
|
|
7
|
-
and constraints it needs, to a smarter model in one call. The application receives the final
|
|
8
|
-
answer from the same agent run.
|
|
9
|
-
|
|
10
|
-
## The pattern
|
|
11
|
-
|
|
12
|
-
Add one tool — `ask_expert` — to a `sw.agent.run` call. The cheap model
|
|
13
|
-
calls it with the question restated in full; the tool sends that to the
|
|
14
|
-
smart model in one `sw.ai.chat` call and returns the answer as the tool
|
|
15
|
-
result. The cheap model relays it. The run's conversation is stored for the
|
|
16
|
-
signed-in user automatically, so the next request continues it with the same
|
|
17
|
-
`conversation_id`.
|
|
18
|
-
|
|
19
|
-
## Code
|
|
20
|
-
|
|
21
|
-
`SomewhereRuntimeContext` is supplied by the current generated runtime types.
|
|
22
|
-
|
|
23
|
-
```ts
|
|
24
|
-
// api/chat.ts — POST { message, conversation_id? } → { reply, conversation_id }
|
|
25
|
-
export default async (req: Request, sw: SomewhereRuntimeContext): Promise<Response> => {
|
|
26
|
-
if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
|
|
27
|
-
const user = await sw.auth.requireUser(req)
|
|
28
|
-
// Every message is a paid model call, so throttle each verified user before
|
|
29
|
-
// the run starts. Sample policy: 20 messages per hour.
|
|
30
|
-
const turns = await sw.rateLimit.check(`chat:${user.id}`, 20, 3600)
|
|
31
|
-
if (!turns.allowed) {
|
|
32
|
-
return Response.json({ error: 'rate_limited', retry_at: turns.reset }, { status: 429 })
|
|
33
|
-
}
|
|
34
|
-
let body: unknown
|
|
35
|
-
try { body = await req.json() } catch { return new Response('Invalid JSON', { status: 400 }) }
|
|
36
|
-
if (!body || typeof body !== 'object' || Array.isArray(body)
|
|
37
|
-
|| !('message' in body) || typeof body.message !== 'string' || !body.message.trim()) {
|
|
38
|
-
return new Response('message required', { status: 400 })
|
|
39
|
-
}
|
|
40
|
-
const message = body.message
|
|
41
|
-
const conversation_id = 'conversation_id' in body && typeof body.conversation_id === 'string' && body.conversation_id
|
|
42
|
-
? body.conversation_id
|
|
43
|
-
: crypto.randomUUID()
|
|
44
|
-
|
|
45
|
-
const askExpert = {
|
|
46
|
-
name: 'ask_expert',
|
|
47
|
-
description: 'Ask a more capable model. Use for real debugging help (stack traces, "why does this fail"), architecture advice, code review and genuine unknowns. Do NOT use for simple lookups, navigation or status questions.',
|
|
48
|
-
input_schema: {
|
|
49
|
-
type: 'object',
|
|
50
|
-
properties: {
|
|
51
|
-
question: { type: 'string', description: 'The question restated in full, with the code, errors and constraints the expert needs.' },
|
|
52
|
-
},
|
|
53
|
-
required: ['question'],
|
|
54
|
-
},
|
|
55
|
-
execute: async (input: { [key: string]: unknown }) => {
|
|
56
|
-
// Throttle escalations per user before calling the smart model. The
|
|
57
|
-
// count is approximate under concurrency, not a spend guarantee.
|
|
58
|
-
const quota = await sw.rateLimit.check(`escalate:${user.id}`, 3, 86400)
|
|
59
|
-
if (!quota.allowed) return 'Expert limit reached for this 24-hour window.'
|
|
60
|
-
const question = typeof input.question === 'string' && input.question.trim() ? input.question : message
|
|
61
|
-
const expert = await sw.ai.chat({
|
|
62
|
-
provider: 'anthropic',
|
|
63
|
-
model: 'claude-sonnet-4-6',
|
|
64
|
-
system: 'You are an expert assistant. Be precise and thorough.',
|
|
65
|
-
messages: [{ role: 'user', content: question }],
|
|
66
|
-
})
|
|
67
|
-
return expert.text
|
|
68
|
-
},
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const r = await sw.agent.run({
|
|
72
|
-
provider: 'anthropic',
|
|
73
|
-
model: 'claude-haiku-4-5',
|
|
74
|
-
conversation_id,
|
|
75
|
-
system: 'You are a helpful assistant. When a user asks for real debugging help, architecture advice or a code review, call ask_expert with the full question. Otherwise answer directly.',
|
|
76
|
-
messages: [{ role: 'user', content: message }],
|
|
77
|
-
tools: [askExpert],
|
|
78
|
-
})
|
|
79
|
-
return Response.json({ reply: r.text, conversation_id })
|
|
80
|
-
}
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
Two per-user limits run before paid calls: 20 messages an hour for the
|
|
84
|
-
cheap model, then 3 escalations a day for the smart one. Over the first, the
|
|
85
|
-
request answers 429 with `retry_at`. Both are sample values. `sw.rateLimit`
|
|
86
|
-
is a request throttle: concurrent requests can pass slightly more than the
|
|
87
|
-
limit, so it is not exact spend accounting. To bound what one run may spend,
|
|
88
|
-
set `maxSpendCents` on `sw.agent.run` (`docs({ topic: 'sw.agent' })`).
|
|
89
|
-
|
|
90
|
-
## When the cheap model should escalate
|
|
91
|
-
|
|
92
|
-
Four typical escalation signals:
|
|
93
|
-
|
|
94
|
-
- **Debugging** — user pastes a stack trace, error, or asks "why
|
|
95
|
-
doesn't X work?". The cheap model is usually wrong on these; the
|
|
96
|
-
smart model spots the missing `await` / wrong destructure / off-by-
|
|
97
|
-
one.
|
|
98
|
-
- **Architecture / design advice** — "how should I structure my
|
|
99
|
-
database for…", "where should this logic live…". The cheap model
|
|
100
|
-
picks one option confidently; the smart model weighs trade-offs.
|
|
101
|
-
- **Code review** — user pastes 30+ lines of code asking for feedback.
|
|
102
|
-
- **Genuine unknown** — the user is asking about a domain the cheap
|
|
103
|
-
model hasn't been taught (your product, a niche library).
|
|
104
|
-
|
|
105
|
-
Typical non-escalation signals:
|
|
106
|
-
- Navigation ("where do I find X?").
|
|
107
|
-
- Project status ("am I healthy?", "what's my usage?").
|
|
108
|
-
- Simple how-to questions answered in your existing system prompt.
|
|
109
|
-
|
|
110
|
-
## Cost math
|
|
111
|
-
|
|
112
|
-
See /v1/pricing for current per-model rates. Cheap and smart models
|
|
113
|
-
typically differ by an order of magnitude or more on per-turn cost.
|
|
114
|
-
|
|
115
|
-
If 10% of turns escalate, your blended cost is roughly 6× the
|
|
116
|
-
cheap-model-only rate — but your bot now gets the hard questions right.
|
|
117
|
-
Cheap-everywhere costs less per turn and gets half the hard answers wrong.
|
|
118
|
-
|
|
119
|
-
## Tier gating
|
|
120
|
-
|
|
121
|
-
Don't expose the same cap to every user. Pick the limits passed to
|
|
122
|
-
`sw.rateLimit.check` from the plan you store for the user. These are
|
|
123
|
-
approximate throttles, not billing limits. A reasonable starting shape for
|
|
124
|
-
escalations:
|
|
125
|
-
|
|
126
|
-
- **Free** — 3 escalations / day.
|
|
127
|
-
- **Paid** — 20 / day.
|
|
128
|
-
- **Top tier** — unlimited.
|
|
129
|
-
|
|
130
|
-
When the cap is hit, the tool result reports that the daily expert quota was
|
|
131
|
-
reached. The application retains authority over how that state is presented.
|
|
132
|
-
|
|
133
|
-
Related topics: `sw.ai`, `recipe-ai-agent`, `recipe-multi-chat`.
|
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
# Recipe — File uploads: each user's own files
|
|
2
|
-
|
|
3
|
-
Users upload, list, open and delete their own files from the page. Declare a
|
|
4
|
-
file collection; the generated `somewhere:files` client sends each file
|
|
5
|
-
straight from the browser to storage, and the platform checks your rules on
|
|
6
|
-
every request. You write no upload endpoint.
|
|
7
|
-
|
|
8
|
-
## 1. Declare the collection
|
|
9
|
-
|
|
10
|
-
```ts
|
|
11
|
-
// db/schema.ts
|
|
12
|
-
import { files, owner, schema } from 'somewhere/db';
|
|
13
|
-
|
|
14
|
-
export default schema({}, {
|
|
15
|
-
files: {
|
|
16
|
-
uploads: files({
|
|
17
|
-
path: '/uploads',
|
|
18
|
-
scope: owner(),
|
|
19
|
-
client: { read: true, upload: true, delete: true },
|
|
20
|
-
limits: { maxSize: '20MB', types: ['image/*', 'application/pdf', 'text/plain'] },
|
|
21
|
-
}),
|
|
22
|
-
},
|
|
23
|
-
});
|
|
24
|
-
```
|
|
25
|
-
|
|
26
|
-
`owner()` gives each signed-in user their own files. `'20MB'` and the type
|
|
27
|
-
list are this example's choices; the client checks them before sending and the
|
|
28
|
-
platform enforces them. Your plan's per-file ceiling is in `limits`. If the
|
|
29
|
-
schema already declares tables, keep them in the first argument.
|
|
30
|
-
|
|
31
|
-
## 2. Upload, list and delete from the page
|
|
32
|
-
|
|
33
|
-
```tsx
|
|
34
|
-
// src/ui/Uploads.tsx — the signed-in user's own files
|
|
35
|
-
import { useEffect, useState, type ChangeEvent } from 'react';
|
|
36
|
-
import { files, type FileMeta } from 'somewhere:files';
|
|
37
|
-
|
|
38
|
-
type Listing = { status: 'loading' } | { status: 'error'; message: string } | { status: 'ready'; items: FileMeta[]; more: boolean };
|
|
39
|
-
|
|
40
|
-
export function Uploads() {
|
|
41
|
-
const [listing, setListing] = useState<Listing>({ status: 'loading' });
|
|
42
|
-
const [actionError, setActionError] = useState<string | null>(null);
|
|
43
|
-
const [busy, setBusy] = useState(false);
|
|
44
|
-
|
|
45
|
-
async function refresh() {
|
|
46
|
-
// The first 50 files; has_more says whether there are more to page through.
|
|
47
|
-
const { data, error } = await files.uploads.list({ limit: 50 });
|
|
48
|
-
setListing(error ? { status: 'error', message: error.message } : { status: 'ready', items: data.items, more: data.has_more });
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
useEffect(() => { void refresh(); }, []);
|
|
52
|
-
|
|
53
|
-
async function onPick(event: ChangeEvent<HTMLInputElement>) {
|
|
54
|
-
const file = event.target.files?.[0];
|
|
55
|
-
event.target.value = '';
|
|
56
|
-
if (!file) return;
|
|
57
|
-
setBusy(true);
|
|
58
|
-
setActionError(null);
|
|
59
|
-
const { error } = await files.uploads.upload(file);
|
|
60
|
-
setBusy(false);
|
|
61
|
-
if (error) return setActionError(error.message);
|
|
62
|
-
await refresh();
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
async function remove(id: string) {
|
|
66
|
-
const { error } = await files.uploads.delete(id);
|
|
67
|
-
if (error) return setActionError(error.message);
|
|
68
|
-
await refresh();
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
return (
|
|
72
|
-
<section className="panel">
|
|
73
|
-
<label htmlFor="upload-file">Add a file</label>
|
|
74
|
-
<input id="upload-file" type="file" onChange={(event) => void onPick(event)} disabled={busy} />
|
|
75
|
-
{actionError ? <p className="error" role="alert">{actionError}</p> : null}
|
|
76
|
-
{listing.status === 'loading' ? <p role="status">Loading your files…</p> : null}
|
|
77
|
-
{listing.status === 'error' ? (
|
|
78
|
-
<p className="error" role="alert">
|
|
79
|
-
{listing.message} <button type="button" className="button button--quiet" onClick={() => void refresh()}>Try again</button>
|
|
80
|
-
</p>
|
|
81
|
-
) : null}
|
|
82
|
-
{listing.status === 'ready' && listing.items.length === 0 ? <p id="uploads-empty">No files yet.</p> : null}
|
|
83
|
-
{listing.status === 'ready' && listing.items.length > 0 ? (
|
|
84
|
-
<ul>
|
|
85
|
-
{listing.items.map((item) => (
|
|
86
|
-
<li key={item.id}>
|
|
87
|
-
<a className="upload__name" href={files.uploads.url(item.id)}>{item.name}</a>
|
|
88
|
-
<button type="button" className="button button--quiet" onClick={() => void remove(item.id)}>Delete</button>
|
|
89
|
-
</li>
|
|
90
|
-
))}
|
|
91
|
-
</ul>
|
|
92
|
-
) : null}
|
|
93
|
-
{listing.status === 'ready' && listing.more ? <p className="hint">Showing your first 50 files.</p> : null}
|
|
94
|
-
</section>
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
Render `<Uploads />` on a signed-in page, such as the starter's
|
|
100
|
-
`src/pages/HomePage.tsx`. "No files yet." appears only after the list has
|
|
101
|
-
loaded successfully; while it loads or after a failed list, the page says so
|
|
102
|
-
instead. The list shows the first 50 files (`has_more` tells you there are
|
|
103
|
-
more; pass its `next` as `cursor` to page). Every call resolves to
|
|
104
|
-
`{ data, error }` and none throws for a refusal: a type outside `limits`, a file that is too large, a
|
|
105
|
-
signed-out caller or a lost connection (`NETWORK_ERROR`) arrives in `error`
|
|
106
|
-
with a `code`, `status` and `message`. `url(id)` is checked against the session
|
|
107
|
-
on every request, so a link only opens for its owner. Large files are sent in
|
|
108
|
-
parts by the same `upload` call; pass `onProgress` to show progress.
|
|
109
|
-
|
|
110
|
-
## 3. Check it with two users
|
|
111
|
-
|
|
112
|
-
```bash
|
|
113
|
-
somewhere typecheck && somewhere deploy
|
|
114
|
-
somewhere verify --project <project> --flow uploads-flow.json
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
```json
|
|
118
|
-
{
|
|
119
|
-
"actors": { "alice": {}, "bob": {} },
|
|
120
|
-
"journey": [
|
|
121
|
-
{ "as": "alice", "path": "/", "actions": [
|
|
122
|
-
{ "fill": "#auth-email", "value": "alice@<project>.test.somewhere.site" },
|
|
123
|
-
{ "fill": "#auth-password", "value": "alice-password-1" },
|
|
124
|
-
{ "click": "[data-sw-auth='sign-up']" },
|
|
125
|
-
{ "wait": "#upload-file" },
|
|
126
|
-
{ "upload": "#upload-file", "file": "data:text/plain;base64,aGVsbG8=", "name": "alice.txt" },
|
|
127
|
-
{ "expect": { "selector": ".upload__name", "text": "alice.txt" } }
|
|
128
|
-
] },
|
|
129
|
-
{ "as": "bob", "path": "/", "actions": [
|
|
130
|
-
{ "fill": "#auth-email", "value": "bob@<project>.test.somewhere.site" },
|
|
131
|
-
{ "fill": "#auth-password", "value": "bob-password-1" },
|
|
132
|
-
{ "click": "[data-sw-auth='sign-up']" },
|
|
133
|
-
{ "expect": { "selector": "#uploads-empty", "text": "No files yet." } }
|
|
134
|
-
] }
|
|
135
|
-
]
|
|
136
|
-
}
|
|
137
|
-
```
|
|
138
|
-
|
|
139
|
-
Alice uploads a file and sees it; Bob signs up and sees none of hers. Bob's
|
|
140
|
-
check passes only on the loaded, empty list, never on the loading message.
|
|
141
|
-
`upload` puts a file into a file input from a local path, data URL or base64,
|
|
142
|
-
or from a stored project file with `fs_path` (up to 50 MB per call);
|
|
143
|
-
`somewhere verify --schema` lists every action. A journey needs a claimed
|
|
144
|
-
account and a CLI login for all your projects: `browser` →
|
|
145
|
-
`several-users-in-one-run`.
|
|
146
|
-
|
|
147
|
-
## 4. Other file jobs
|
|
148
|
-
|
|
149
|
-
| Need | Use |
|
|
150
|
-
|---|---|
|
|
151
|
-
| Teams, shared files, public images, replace, share links | `declared-files` → `declare`, `share-links` |
|
|
152
|
-
| A file your function creates, such as an export | `sw.fs.server.write`, then `sw.fs.server.signedUrl(path, { expiresIn })` (`declared-files` → `files-outside-a-collection`) |
|
|
153
|
-
| A large upload to a path your function chooses | `sw.fs` → `swfsuploadurl-path-maxsize-contenttype-expiresin-` |
|
|
154
|
-
| Reading files in a function | `sw.fs` acts as the signed-in caller under the same rules (`declared-files` → `in-your-functions`) |
|
|
155
|
-
|
|
156
|
-
`sw.fs.server` has your project's authority over every file. Authorize the
|
|
157
|
-
caller in your function before using it. Developer tools such as
|
|
158
|
-
`sw.fs.dev.*` and the integrity check are for agents and scripts, not app code:
|
|
159
|
-
`sw.fs` → `swfsdev-project-wide-file-view-runcode-only`.
|