@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.
Files changed (147) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/docs/adopt.md +39 -0
  3. package/dist/docs/analytics.md +161 -0
  4. package/dist/docs/api-reference.md +339 -0
  5. package/dist/docs/api-surface.md +2067 -0
  6. package/dist/docs/app-mcp.md +162 -0
  7. package/dist/docs/architecture-patterns.md +334 -0
  8. package/dist/docs/auth-client.md +531 -0
  9. package/dist/docs/billing.md +76 -0
  10. package/dist/docs/browser.md +639 -0
  11. package/dist/docs/calendar.md +298 -0
  12. package/dist/docs/changes.md +323 -0
  13. package/dist/docs/cli.md +407 -0
  14. package/dist/docs/common-mistakes.md +199 -0
  15. package/dist/docs/connect-agent.md +72 -0
  16. package/dist/docs/cors.md +114 -0
  17. package/dist/docs/cron.md +167 -0
  18. package/dist/docs/database-engine.md +167 -0
  19. package/dist/docs/declared-data.md +1656 -0
  20. package/dist/docs/declared-files.md +475 -0
  21. package/dist/docs/deploy-intelligence.md +188 -0
  22. package/dist/docs/deploy.md +733 -0
  23. package/dist/docs/design-system.md +273 -0
  24. package/dist/docs/dev-environments.md +496 -0
  25. package/dist/docs/domain-ownership.md +31 -0
  26. package/dist/docs/domains.md +370 -0
  27. package/dist/docs/feedback.md +88 -0
  28. package/dist/docs/file-tools.md +116 -0
  29. package/dist/docs/functions.md +489 -0
  30. package/dist/docs/getting-started.md +238 -0
  31. package/dist/docs/github.md +95 -0
  32. package/dist/docs/google-calendar.md +212 -0
  33. package/dist/docs/groups.md +836 -0
  34. package/dist/docs/guarantees.md +58 -0
  35. package/dist/docs/handled-for-you.md +224 -0
  36. package/dist/docs/inspect.md +171 -0
  37. package/dist/docs/limits.md +68 -0
  38. package/dist/docs/live-data.md +197 -0
  39. package/dist/docs/live.md +92 -0
  40. package/dist/docs/local-dev.md +30 -0
  41. package/dist/docs/migration-supabase.md +58 -0
  42. package/dist/docs/payments.md +1102 -0
  43. package/dist/docs/portability.md +194 -0
  44. package/dist/docs/postgres.md +301 -0
  45. package/dist/docs/pricing-comparison.md +42 -0
  46. package/dist/docs/pricing.md +39 -0
  47. package/dist/docs/project-groups.md +107 -0
  48. package/dist/docs/projects.md +380 -0
  49. package/dist/docs/recipe-ai-agent.md +112 -0
  50. package/dist/docs/recipe-ai-features.md +227 -0
  51. package/dist/docs/recipe-ai-receipts.md +783 -0
  52. package/dist/docs/recipe-background-jobs.md +369 -0
  53. package/dist/docs/recipe-booking.md +348 -0
  54. package/dist/docs/recipe-csv-import.md +390 -0
  55. package/dist/docs/recipe-ecommerce.md +127 -0
  56. package/dist/docs/recipe-email.md +282 -0
  57. package/dist/docs/recipe-escalation.md +133 -0
  58. package/dist/docs/recipe-file-uploads.md +159 -0
  59. package/dist/docs/recipe-import-app.md +110 -0
  60. package/dist/docs/recipe-login.md +457 -0
  61. package/dist/docs/recipe-multi-chat.md +198 -0
  62. package/dist/docs/recipe-paid-api.md +161 -0
  63. package/dist/docs/recipe-pdfs.md +205 -0
  64. package/dist/docs/recipe-push-notifications.md +107 -0
  65. package/dist/docs/recipe-seo.md +200 -0
  66. package/dist/docs/recipe-signed-in-app.md +330 -0
  67. package/dist/docs/render.md +99 -0
  68. package/dist/docs/rooms.md +554 -0
  69. package/dist/docs/sdk.md +287 -0
  70. package/dist/docs/sdks.md +24 -0
  71. package/dist/docs/search.md +199 -0
  72. package/dist/docs/security-model.md +168 -0
  73. package/dist/docs/setup.md +212 -0
  74. package/dist/docs/smoke.md +102 -0
  75. package/dist/docs/speed.md +298 -0
  76. package/dist/docs/sql-compatibility.md +96 -0
  77. package/dist/docs/sw.agent.md +248 -0
  78. package/dist/docs/sw.ai.md +1291 -0
  79. package/dist/docs/sw.auth.md +1811 -0
  80. package/dist/docs/sw.billing.md +171 -0
  81. package/dist/docs/sw.db.md +2128 -0
  82. package/dist/docs/sw.email.md +661 -0
  83. package/dist/docs/sw.endpoint.md +187 -0
  84. package/dist/docs/sw.env.md +303 -0
  85. package/dist/docs/sw.fetch.md +115 -0
  86. package/dist/docs/sw.fs.md +424 -0
  87. package/dist/docs/sw.groups.md +836 -0
  88. package/dist/docs/sw.image.md +69 -0
  89. package/dist/docs/sw.jobs.md +520 -0
  90. package/dist/docs/sw.logs.md +61 -0
  91. package/dist/docs/sw.mail.md +106 -0
  92. package/dist/docs/sw.notifications.md +78 -0
  93. package/dist/docs/sw.push.md +161 -0
  94. package/dist/docs/sw.rateLimit.md +67 -0
  95. package/dist/docs/sw.web.md +128 -0
  96. package/dist/docs/tasks.md +269 -0
  97. package/dist/docs/test.md +220 -0
  98. package/dist/docs/tool-reference-account.md +7 -0
  99. package/dist/docs/tool-reference-ai.md +121 -0
  100. package/dist/docs/tool-reference-analytics.md +37 -0
  101. package/dist/docs/tool-reference-api.md +19 -0
  102. package/dist/docs/tool-reference-artifacts.md +35 -0
  103. package/dist/docs/tool-reference-auth.md +163 -0
  104. package/dist/docs/tool-reference-browser.md +114 -0
  105. package/dist/docs/tool-reference-code.md +26 -0
  106. package/dist/docs/tool-reference-connect.md +21 -0
  107. package/dist/docs/tool-reference-cron.md +48 -0
  108. package/dist/docs/tool-reference-db.md +282 -0
  109. package/dist/docs/tool-reference-domains.md +107 -0
  110. package/dist/docs/tool-reference-email.md +55 -0
  111. package/dist/docs/tool-reference-env.md +19 -0
  112. package/dist/docs/tool-reference-feedback.md +56 -0
  113. package/dist/docs/tool-reference-fs.md +265 -0
  114. package/dist/docs/tool-reference-github.md +57 -0
  115. package/dist/docs/tool-reference-groups.md +85 -0
  116. package/dist/docs/tool-reference-help.md +29 -0
  117. package/dist/docs/tool-reference-jobs.md +39 -0
  118. package/dist/docs/tool-reference-live.md +48 -0
  119. package/dist/docs/tool-reference-logs.md +16 -0
  120. package/dist/docs/tool-reference-payments.md +44 -0
  121. package/dist/docs/tool-reference-project.md +706 -0
  122. package/dist/docs/tool-reference-push.md +78 -0
  123. package/dist/docs/tool-reference-rate-limit.md +18 -0
  124. package/dist/docs/tool-reference-search.md +68 -0
  125. package/dist/docs/tool-reference-security.md +42 -0
  126. package/dist/docs/tool-reference-smoke.md +17 -0
  127. package/dist/docs/tool-reference-stock-photos.md +20 -0
  128. package/dist/docs/tool-reference-tasks.md +73 -0
  129. package/dist/docs/tool-reference-telegram.md +32 -0
  130. package/dist/docs/tool-reference-usage.md +9 -0
  131. package/dist/docs/tool-reference-web.md +71 -0
  132. package/dist/docs/tool-reference-webhooks.md +9 -0
  133. package/dist/docs/troubleshooting.md +411 -0
  134. package/dist/docs/typed-functions.md +94 -0
  135. package/dist/docs/verify-before-deploy.md +67 -0
  136. package/dist/docs/vs-supabase.md +75 -0
  137. package/dist/docs/vs-vercel.md +103 -0
  138. package/dist/lib/bundle.js +303 -221
  139. package/dist/lib/bundle.js.map +3 -3
  140. package/dist/types/lib/test-session.d.ts +8 -0
  141. package/npm-shrinkwrap.json +2 -2
  142. package/package.json +3 -2
  143. package/runtime/DECLARED-DATA-VENDOR.json +5 -5
  144. package/runtime/PLATFORM-SOURCE.json +1 -1
  145. package/runtime/SOURCE-LINT-VENDOR.json +2 -2
  146. package/runtime/declared-data.cjs +37 -19
  147. package/runtime/source-lint.cjs +1 -1
@@ -0,0 +1,198 @@
1
+ # Recipe — Multi-chat (Claude.ai-style conversation list)
2
+
3
+ End users of your chatbot app keep multiple separate conversations,
4
+ like Claude.ai's sidebar. The conversation infrastructure already
5
+ exists on the platform — `sw.ai.forUser(userId).chat({ conversation_id })`
6
+ scopes history to the subject. This recipe shows the UI pattern that
7
+ wraps it.
8
+
9
+ For one conversation per signed-in user, keep one conversation_id and use
10
+ sw.ai.forUser(user.id).chat with that id. The list and switcher below are
11
+ needed only when a user can keep several conversations.
12
+
13
+ ## Two ids per conversation
14
+
15
+ - `conversation_id` — the id YOUR app picks and passes to `chat`. `chat`
16
+ echoes it back. Use it to continue a conversation.
17
+ - stored `id` — the platform's row id, returned by `conversations.list()`
18
+ (each row also carries `client_conversation_id`, the id you picked).
19
+ `conversations.get(id)` and `conversations.delete(id)` take THIS id —
20
+ passing your own `conversation_id` to them finds nothing.
21
+
22
+ ## Backend — four functions
23
+
24
+ The generated runtime types infer the inputs to each `sw.endpoint` handler.
25
+
26
+ ```ts
27
+ // api/chat/send.ts — POST { conversation_id?, message } → { reply, conversation_id }
28
+ export default sw.endpoint({
29
+ auth: 'required',
30
+ handler: async ({ request: req, user }, sw) => {
31
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
32
+ let body: unknown
33
+ try { body = await req.json() } catch { return new Response('Invalid JSON', { status: 400 }) }
34
+ if (!body || typeof body !== 'object' || Array.isArray(body)
35
+ || !('message' in body) || typeof body.message !== 'string' || !body.message.trim()) {
36
+ return new Response('message required', { status: 400 })
37
+ }
38
+ const conversation_id = 'conversation_id' in body && typeof body.conversation_id === 'string' && body.conversation_id
39
+ ? body.conversation_id
40
+ : crypto.randomUUID()
41
+ const r = await sw.ai.forUser(user.id).chat({
42
+ provider: 'anthropic',
43
+ conversation_id,
44
+ system: 'You are a helpful assistant.',
45
+ messages: [{ role: 'user', content: body.message }],
46
+ })
47
+ return Response.json({ reply: r.text, conversation_id })
48
+ },
49
+ });
50
+ ```
51
+
52
+ ```ts
53
+ // api/chat/list.ts — GET → [{ id, conversation_id, updated_at, message_count }]
54
+ export default sw.endpoint({
55
+ auth: 'required',
56
+ handler: async ({ user }, sw) => {
57
+ const { conversations } = await sw.ai.forUser(user.id).conversations.list({ limit: 50 })
58
+ return Response.json(conversations.map(c => ({
59
+ id: c.id, // stored id → get / delete
60
+ conversation_id: c.client_conversation_id, // your id → send
61
+ updated_at: c.updated_at,
62
+ message_count: c.message_count,
63
+ })))
64
+ },
65
+ });
66
+ ```
67
+
68
+ ```ts
69
+ // api/chat/get.ts — GET ?id=<stored id from list> → { messages }
70
+ export default sw.endpoint({
71
+ auth: 'required',
72
+ handler: async ({ request: req, user }, sw) => {
73
+ const id = new URL(req.url).searchParams.get('id')
74
+ if (!id) return new Response('id required', { status: 400 })
75
+ const conversation = await sw.ai.forUser(user.id).conversations.get(id)
76
+ return Response.json({ messages: conversation.messages.map(m => ({ role: m.role, content: m.content })) })
77
+ },
78
+ });
79
+ ```
80
+
81
+ ```ts
82
+ // api/chat/delete.ts — DELETE ?id=<stored id from list>
83
+ export default sw.endpoint({
84
+ auth: 'required',
85
+ handler: async ({ request: req, user }, sw) => {
86
+ if (req.method !== 'DELETE') return new Response('Method not allowed', { status: 405 })
87
+ const id = new URL(req.url).searchParams.get('id')
88
+ if (!id) return new Response('id required', { status: 400 })
89
+ await sw.ai.forUser(user.id).conversations.delete(id)
90
+ return new Response(null, { status: 204 })
91
+ },
92
+ });
93
+ ```
94
+
95
+ ## Frontend
96
+
97
+ The sidebar keeps both ids per row: `id` to load or delete, `conversation_id`
98
+ to keep chatting. After the first message of a new chat, reload the list to
99
+ pick up its stored id.
100
+
101
+ ```tsx
102
+ // src/ChatApp.tsx
103
+ import { useEffect, useRef, useState } from 'react';
104
+
105
+ type Block = { type: string; text?: string };
106
+ type Message = { role: string; content: string | Block[] };
107
+ type Row = { id: string; conversation_id: string | null; updated_at: string; message_count: number };
108
+
109
+ const text = (content: Message['content']): string =>
110
+ typeof content === 'string' ? content : content.filter((b) => b.type === 'text').map((b) => b.text ?? '').join('');
111
+
112
+ async function getJson<T>(url: string, init?: RequestInit): Promise<T> {
113
+ const res = await fetch(url, init);
114
+ if (!res.ok) throw new Error(`Request failed (${res.status})`);
115
+ return (await res.json()) as T;
116
+ }
117
+
118
+ export function ChatApp() {
119
+ const [conversations, setConversations] = useState<Row[]>([]);
120
+ const [current, setCurrent] = useState<Row | null>(null); // a list row; null = new chat
121
+ const [messages, setMessages] = useState<Message[]>([]);
122
+ const [input, setInput] = useState('');
123
+ const [sending, setSending] = useState(false);
124
+ const [error, setError] = useState<string | null>(null);
125
+ // The conversation on screen right now. A response that arrives after the
126
+ // user switched conversations is dropped instead of overwriting the new one.
127
+ const shown = useRef<string | null>(null);
128
+ const fail = (e: unknown) => setError(e instanceof Error ? e.message : String(e));
129
+
130
+ const refresh = () => getJson<Row[]>('/api/chat/list');
131
+ useEffect(() => { refresh().then(setConversations, fail); }, []);
132
+ useEffect(() => {
133
+ shown.current = current?.id ?? null;
134
+ if (!current) { setMessages([]); return; }
135
+ let stale = false;
136
+ getJson<{ messages: Message[] }>(`/api/chat/get?id=${encodeURIComponent(current.id)}`)
137
+ .then((d) => { if (!stale) setMessages(d.messages); }, (e) => { if (!stale) fail(e); });
138
+ return () => { stale = true; };
139
+ }, [current?.id]);
140
+
141
+ async function send() {
142
+ const message = input.trim();
143
+ if (!message || sending) return; // one send at a time: Enter twice sends once
144
+ const from = current;
145
+ const optimistic: Message[] = [...messages, { role: 'user', content: message }];
146
+ setMessages(optimistic); setInput(''); setError(null); setSending(true);
147
+ try {
148
+ const r = await getJson<{ reply: string; conversation_id: string }>('/api/chat/send', {
149
+ method: 'POST',
150
+ headers: { 'Content-Type': 'application/json' },
151
+ body: JSON.stringify({ conversation_id: from?.conversation_id ?? undefined, message }),
152
+ });
153
+ const rows = await refresh();
154
+ setConversations(rows);
155
+ if (shown.current !== (from?.id ?? null)) return; // the user moved on; the reply is stored server-side
156
+ setMessages([...optimistic, { role: 'assistant', content: r.reply }]);
157
+ if (!from) setCurrent(rows.find((c) => c.conversation_id === r.conversation_id) ?? null);
158
+ } catch (e) {
159
+ if (shown.current === (from?.id ?? null)) fail(e);
160
+ } finally {
161
+ setSending(false);
162
+ }
163
+ }
164
+
165
+ return (
166
+ <div style={{ display: 'flex' }}>
167
+ <aside style={{ width: 240, borderRight: '1px solid #eee' }}>
168
+ <button type="button" onClick={() => setCurrent(null)}>+ New chat</button>
169
+ {conversations.map((c) => (
170
+ <button type="button" key={c.id} onClick={() => setCurrent(c)}
171
+ style={{ display: 'block', padding: 8, background: current?.id === c.id ? '#f0f0f0' : 'transparent' }}>
172
+ {new Date(c.updated_at).toLocaleString()} · {c.message_count} messages
173
+ </button>
174
+ ))}
175
+ </aside>
176
+ <main style={{ flex: 1, padding: 16 }}>
177
+ {messages.map((m, i) => <p key={i}><strong>{m.role}:</strong> {text(m.content)}</p>)}
178
+ {error ? <p role="alert">{error}</p> : null}
179
+ <input value={input} disabled={sending} onChange={(e) => setInput(e.target.value)}
180
+ onKeyDown={(e) => { if (e.key === 'Enter') void send(); }} />
181
+ </main>
182
+ </div>
183
+ );
184
+ }
185
+ ```
186
+
187
+ ## What you get for free
188
+
189
+ - **History server-side.** You never store messages in localStorage —
190
+ reloading the page restores the full transcript via conversations.get.
191
+ - **Subject scoping.** sw.ai.forUser(userId) means conversation_ids are
192
+ isolated per user; a leaked id from user A doesn't load user B's
193
+ history.
194
+ - **Compaction.** Long conversations auto-compact via the
195
+ history_max_messages / history_max_tokens caps; pass
196
+ compaction:'summarize' to fold dropped turns into a rolling summary.
197
+
198
+ Related topics: `sw.ai`, `sw.auth`.
@@ -0,0 +1,161 @@
1
+ # Recipe — Paid and OAuth-protected APIs
2
+
3
+ A function's status code and the headers it sets reach the caller unchanged.
4
+ A `402 Payment Required` or `401 Unauthorized` with its
5
+ `WWW-Authenticate` challenge arrives intact, so the HTTP challenge flows that
6
+ agent payment protocols and OAuth-protected APIs use work from an ordinary
7
+ function in `api/`.
8
+
9
+ ## 1. Answer with a payment challenge
10
+
11
+ ```ts
12
+ // api/report.ts — free to describe, paid to fetch
13
+ import { verifyPayment } from './_lib/payment';
14
+
15
+ const PRICE = { amount: '0.01', currency: 'usd' }; // this example's price
16
+
17
+ export default sw.endpoint({
18
+ auth: 'none', // the handler applies its own access check below
19
+ handler: async ({ request }, sw) => {
20
+ const credential = request.headers.get('authorization')?.match(/^Payment\s+(.+)$/i)?.[1];
21
+ if (!credential) {
22
+ return new Response(JSON.stringify({ error: 'payment_required', price: PRICE }), {
23
+ status: 402,
24
+ headers: {
25
+ 'content-type': 'application/json',
26
+ 'www-authenticate': `Payment realm="reports", amount="${PRICE.amount}", currency="${PRICE.currency}"`,
27
+ },
28
+ });
29
+ }
30
+
31
+ const receipt = await verifyPayment(credential, PRICE, sw);
32
+ if (!receipt) return Response.json({ error: 'payment_invalid' }, { status: 402 });
33
+
34
+ // A receipt pays for one call: the unique receipt_id refuses a replay.
35
+ const saved = await sw.db.server.insert('paid_calls', { receipt_id: receipt.id, path: '/api/report' }, { onConflict: 'ignore' });
36
+ if (saved.changes === 0) return Response.json({ error: 'payment_already_used' }, { status: 402 });
37
+
38
+ return Response.json({ report: 'The paid content.' });
39
+ },
40
+ });
41
+ ```
42
+
43
+ ```ts
44
+ // api/_lib/payment.ts — verifyPayment: the provider's verification call
45
+ export async function verifyPayment(
46
+ credential: string,
47
+ price: { amount: string; currency: string },
48
+ sw: SomewhereRuntimeContext,
49
+ ): Promise<{ id: string } | null> {
50
+ const response = await fetch(sw.env.PAYMENT_VERIFY_URL, {
51
+ method: 'POST',
52
+ headers: { authorization: `Bearer ${sw.env.PAYMENT_SECRET}`, 'content-type': 'application/json' },
53
+ body: JSON.stringify({ credential, ...price }),
54
+ });
55
+ if (!response.ok) return null;
56
+ const result = (await response.json()) as { valid?: boolean; receipt_id?: string };
57
+ return result.valid && result.receipt_id ? { id: result.receipt_id } : null;
58
+ }
59
+ ```
60
+
61
+ ```ts
62
+ // db/schema.ts
63
+ import { id, serverOnly, schema, table, text, timestamp } from 'somewhere/db';
64
+
65
+ export default schema({
66
+ paid_calls: table(
67
+ { id: id(), receipt_id: text({ unique: true }), path: text(), created_at: timestamp({ default: 'now' }) },
68
+ { scope: serverOnly() },
69
+ ),
70
+ });
71
+ ```
72
+
73
+ The agent calls once, reads the challenge, pays, and retries with the
74
+ credential. Your payment provider defines the challenge parameters and the
75
+ verification call, so the `www-authenticate` value and `verifyPayment` are the
76
+ provider-specific parts. Save the secret with
77
+ `somewhere env set PAYMENT_SECRET --stdin`, which keeps it out of your shell
78
+ history, and the URL with `somewhere env set PAYMENT_VERIFY_URL <url>`. Recording each receipt in a
79
+ `serverOnly()` table with a unique column makes a replayed credential a no-op.
80
+
81
+ ## 2. Protect an API with OAuth
82
+
83
+ ```ts
84
+ // api/data.ts — accepts tokens from your OAuth authorization server
85
+ export default async function data(request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
86
+ const origin = new URL(request.url).origin;
87
+ const metadata = `${origin}/api/oauth-protected-resource`;
88
+ const token = request.headers.get('authorization')?.match(/^Bearer\s+(.+)$/i)?.[1];
89
+ const subject = token ? await introspect(token, `${origin}/api/data`, sw) : null;
90
+ if (!subject) {
91
+ return new Response(JSON.stringify({ error: 'invalid_token' }), {
92
+ status: 401,
93
+ headers: { 'content-type': 'application/json', 'www-authenticate': `Bearer resource_metadata="${metadata}"` },
94
+ });
95
+ }
96
+ return Response.json({ subject, items: [] });
97
+ }
98
+
99
+ // RFC 7662 token introspection at your authorization server. Accept only an
100
+ // active token issued for this API: its audience must name this resource.
101
+ async function introspect(token: string, resource: string, sw: SomewhereRuntimeContext): Promise<string | null> {
102
+ const response = await fetch(sw.env.OAUTH_INTROSPECTION_URL, {
103
+ method: 'POST',
104
+ headers: {
105
+ authorization: `Basic ${btoa(`${sw.env.OAUTH_CLIENT_ID}:${sw.env.OAUTH_CLIENT_SECRET}`)}`,
106
+ 'content-type': 'application/x-www-form-urlencoded',
107
+ },
108
+ body: new URLSearchParams({ token }),
109
+ });
110
+ if (!response.ok) return null;
111
+ const result = (await response.json()) as { active?: boolean; sub?: string; aud?: string | string[] };
112
+ const audience = Array.isArray(result.aud) ? result.aud : [result.aud];
113
+ return result.active && result.sub && audience.includes(resource) ? result.sub : null;
114
+ }
115
+ ```
116
+
117
+ ```ts
118
+ // api/oauth-protected-resource.ts — the metadata the 401 points to (RFC 9728)
119
+ export default async function protectedResource(request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
120
+ const origin = new URL(request.url).origin;
121
+ return Response.json({
122
+ resource: `${origin}/api/data`,
123
+ authorization_servers: [sw.env.OAUTH_ISSUER],
124
+ bearer_methods_supported: ['header'],
125
+ });
126
+ }
127
+ ```
128
+
129
+ A client without a token gets the 401, follows `resource_metadata` to learn
130
+ which authorization server issues tokens, signs in there, and retries with
131
+ `Authorization: Bearer <token>`. MCP clients that implement the MCP
132
+ authorization spec take this same path. Functions answer paths under `/api/`,
133
+ so the metadata lives at `/api/oauth-protected-resource` and the challenge
134
+ names that URL. Accept only tokens whose `aud` names this API, so a token
135
+ issued for another API is refused. Register the API's public URL as the token
136
+ audience; the check uses the host the request arrived on. Your authorization server is the one you
137
+ already use; the platform does not issue OAuth tokens for your API.
138
+
139
+ ## Rules that keep the challenge intact
140
+
141
+ - Return the 401 yourself. `sw.auth.requireUser` answers a signed-out caller
142
+ with its own JSON 401, which carries no `WWW-Authenticate` header; use
143
+ `sw.auth.fromRequest`, or your own token check, when a client needs the
144
+ challenge.
145
+ - Agents and servers send no `Origin` header, so browser CORS rules never
146
+ apply to them. A browser app on another origin needs two things: its origin
147
+ on the project's allow-list
148
+ (`somewhere project allowed-origins set`), because the platform refuses a
149
+ request that carries `Authorization` from any other origin before your
150
+ function runs; and your own `Access-Control-Allow-Origin` plus
151
+ `Access-Control-Expose-Headers: WWW-Authenticate` on the response, which
152
+ then replace the platform's CORS headers (`cors`).
153
+
154
+ ## Check it
155
+
156
+ ```bash
157
+ somewhere deploy
158
+ # Set APP_URL to your app's HTTPS origin, without a trailing slash.
159
+ curl -si "$APP_URL/api/report" | grep -iE '^HTTP|^www-authenticate' # 402 and its challenge
160
+ curl -si "$APP_URL/api/data" | grep -iE '^HTTP|^www-authenticate' # 401 and resource_metadata
161
+ ```
@@ -0,0 +1,205 @@
1
+ # Recipe — PDFs
2
+
3
+ Write the document as HTML and CSS, and `sw.render.pdf` prints it in a real
4
+ browser: web fonts, flexbox, tables and page breaks render the way they do on
5
+ screen. This recipe makes an invoice for the signed-in user, stores it as a
6
+ private file, previews it in the page and merges PDFs in a function.
7
+
8
+ ## 1. Generate and store an invoice
9
+
10
+ ```ts
11
+ // db/schema.ts
12
+ import { id, integer, owner, schema, table, text } from 'somewhere/db';
13
+
14
+ export default schema({
15
+ invoices: table(
16
+ { id: id(), number: text(), customer: text(), amount_cents: integer() },
17
+ { scope: owner(), client: { read: ['id', 'number', 'customer', 'amount_cents'] } },
18
+ ),
19
+ });
20
+ ```
21
+
22
+ ```ts
23
+ // api/invoices/[id].ts — POST renders the invoice PDF; GET returns it
24
+ const escape = (value: string) =>
25
+ value.replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[ch]!);
26
+
27
+ export default async function invoicePdf(request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
28
+ const user = await sw.auth.fromRequest(request);
29
+ if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
30
+ const id = new URL(request.url).pathname.split('/').pop() ?? '';
31
+ if (!/^\d+$/.test(id)) return Response.json({ error: 'Unknown invoice.' }, { status: 404 });
32
+ const path = `/invoices/${user.id}/${id}.pdf`;
33
+
34
+ if (request.method === 'GET') {
35
+ try {
36
+ return await sw.fs.server.read(path); // streams the stored PDF with its content type
37
+ } catch (error) {
38
+ if (error instanceof Error && 'status' in error && error.status === 404) {
39
+ return Response.json({ error: 'Generate the PDF first.' }, { status: 404 });
40
+ }
41
+ throw error;
42
+ }
43
+ }
44
+ if (request.method !== 'POST') return new Response('Use GET or POST.', { status: 405, headers: { Allow: 'GET, POST' } });
45
+
46
+ // owner(): only this user's invoice is found.
47
+ const { data } = await sw.db.from('invoices', { where: { id }, limit: 1 });
48
+ const invoice = data[0];
49
+ if (!invoice) return Response.json({ error: 'Unknown invoice.' }, { status: 404 });
50
+
51
+ const html = `<!doctype html><html><head><style>
52
+ body { font-family: system-ui, sans-serif; margin: 48px; }
53
+ h1 { font-size: 24px; } td { padding: 8px 0; }
54
+ </style></head><body>
55
+ <h1>Invoice ${escape(invoice.number)}</h1>
56
+ <table><tr><td>Billed to</td><td>${escape(invoice.customer)}</td></tr>
57
+ <tr><td>Total</td><td>$${(Number(invoice.amount_cents) / 100).toFixed(2)}</td></tr></table>
58
+ </body></html>`;
59
+
60
+ const pdf = await sw.render.pdf({ html, format: 'A4', print_background: true });
61
+ await sw.fs.server.write(path, await pdf.arrayBuffer(), { contentType: 'application/pdf' });
62
+ return Response.json({ path }, { status: 201 });
63
+ }
64
+ ```
65
+
66
+ `sw.render.pdf({ html })` returns the PDF as a `Response`. `sw.fs.server.write`
67
+ stores it as a private file, so only your functions read it. The path holds
68
+ the signed-in user's id, taken from the session, so one user's request can
69
+ never name another user's file. Escape every value you put into the HTML.
70
+ Render once and store the file; serve the stored copy after that.
71
+
72
+ Options: `format` is `'A4'`, `'A3'`, `'Letter'` (the default), `'Legal'` or
73
+ `'Tabloid'`; `landscape: true` rotates the page; `print_background: true`
74
+ prints background colours and images; `wait_for: '<css selector>'` waits up to
75
+ 5 seconds for an element before printing. Pass `url` instead of `html` to
76
+ print a public page. `html` is at most 1,000,000 characters, and the page must
77
+ finish loading within 30 seconds. Renders are metered and charged to the
78
+ account balance.
79
+
80
+ ## 2. Preview it in the page
81
+
82
+ Load the stored PDF from your own function, same origin, and draw it with
83
+ PDF.js. It draws to a canvas, so the preview looks the same on phones and
84
+ desktops.
85
+
86
+ ```tsx
87
+ // src/ui/InvoicePreview.tsx — npm install pdfjs-dist (version 5 or later)
88
+ import { useEffect, useRef, useState } from 'react';
89
+ import * as pdfjs from 'pdfjs-dist';
90
+
91
+ pdfjs.GlobalWorkerOptions.workerSrc = `https://unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
92
+
93
+ export function InvoicePreview({ invoiceId }: { invoiceId: string }) {
94
+ return <InvoicePreviewPage key={invoiceId} invoiceId={invoiceId} />;
95
+ }
96
+
97
+ function InvoicePreviewPage({ invoiceId }: { invoiceId: string }) {
98
+ const canvas = useRef<HTMLCanvasElement>(null);
99
+ const [error, setError] = useState<string | null>(null);
100
+
101
+ useEffect(() => {
102
+ let cancelled = false;
103
+ let renderTask: { cancel(): void } | null = null;
104
+ const loadingTask = pdfjs.getDocument({ url: `/api/invoices/${invoiceId}` });
105
+ (async () => {
106
+ const doc = await loadingTask.promise;
107
+ const page = await doc.getPage(1);
108
+ const target = canvas.current;
109
+ if (cancelled || !target) return;
110
+ const viewport = page.getViewport({ scale: 1.5 });
111
+ target.width = viewport.width;
112
+ target.height = viewport.height;
113
+ const task = page.render({ canvas: target, viewport });
114
+ renderTask = task;
115
+ await task.promise;
116
+ })().catch((reason: unknown) => {
117
+ if (cancelled) return; // a replaced or unmounted preview reports nothing
118
+ setError(reason instanceof Error ? reason.message : 'Could not load the PDF.');
119
+ });
120
+ return () => {
121
+ cancelled = true;
122
+ renderTask?.cancel(); // cancels the previous render
123
+ loadingTask.destroy().catch(() => {}); // releases the loading task and worker
124
+ };
125
+ }, [invoiceId]);
126
+
127
+ return (
128
+ <>
129
+ {error && <p role="alert">{error}</p>}
130
+ <canvas ref={canvas} hidden={error !== null} style={{ maxWidth: '100%' }} />
131
+ </>
132
+ );
133
+ }
134
+ ```
135
+
136
+ The worker script loads from a CDN at the same version as the library you
137
+ installed. To serve it yourself, copy `pdfjs-dist/build/pdf.worker.min.mjs`
138
+ into `public/` and set `workerSrc = '/pdf.worker.min.mjs'`. `react-pdf` works
139
+ the same way: set `pdfjs.GlobalWorkerOptions.workerSrc` as above rather than
140
+ the `new URL(..., import.meta.url)` form from its README.
141
+
142
+ ## 3. Share a download link
143
+
144
+ ```ts
145
+ // in a function, after authorizing the caller
146
+ const link = await sw.fs.server.signedUrl(`/invoices/${user.id}/${id}.pdf`, { expiresIn: 7 * 24 * 3600 });
147
+ // link.url opens the PDF for anyone holding it, until link.expires_at
148
+ ```
149
+
150
+ A signed link is for email, a download button or a new tab. `expiresIn` is
151
+ clamped to between 60 seconds and 7 days (default 1 hour). It is served from the platform's file
152
+ host, so a page's own `fetch` or PDF.js loads the file through your function
153
+ as in step 2, not through the link.
154
+
155
+ ## 4. Merge and split with pdf-lib
156
+
157
+ ```ts
158
+ // api/invoices/merge.ts — POST { ids: [1, 2, 3] } → one PDF of the user's stored invoices
159
+ import { PDFDocument } from 'pdf-lib/dist/pdf-lib.esm.js';
160
+
161
+ export default async function mergeInvoices(request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
162
+ if (request.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
163
+ const user = await sw.auth.fromRequest(request);
164
+ if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
165
+ const input = (await request.json().catch(() => null)) as { ids?: unknown } | null;
166
+ const raw = input?.ids;
167
+ const ids = Array.isArray(raw) ? raw.filter((v): v is number => Number.isInteger(v)) : [];
168
+ if (ids.length < 2 || ids.length > 20) return Response.json({ error: 'Send 2–20 invoice ids.' }, { status: 400 });
169
+
170
+ const merged = await PDFDocument.create();
171
+ for (const id of ids) {
172
+ let file: Response;
173
+ try {
174
+ file = await sw.fs.server.read(`/invoices/${user.id}/${id}.pdf`);
175
+ } catch (error) {
176
+ if (error instanceof Error && 'status' in error && error.status === 404) {
177
+ return Response.json({ error: `Generate invoice ${id} first.` }, { status: 404 });
178
+ }
179
+ throw error;
180
+ }
181
+ const source = await PDFDocument.load(await file.arrayBuffer());
182
+ const pages = await merged.copyPages(source, source.getPageIndices());
183
+ for (const page of pages) merged.addPage(page);
184
+ }
185
+ return new Response(await merged.save(), { headers: { 'content-type': 'application/pdf' } });
186
+ }
187
+ ```
188
+
189
+ In a function, pdf-lib loads from `pdf-lib/dist/pdf-lib.esm.js`; the plain
190
+ `'pdf-lib'` specifier fails to build. To split, copy only the pages you want
191
+ into a new document with `copyPages` and save it. pdf-lib also
192
+ fills form fields, adds pages and stamps text onto existing PDFs. It does not
193
+ open password-protected PDFs: `PDFDocument.load` throws `EncryptedPDFError`.
194
+ `ignoreEncryption: true` loads such a file without decrypting it, so its
195
+ pages stay unreadable.
196
+
197
+ ## Check it
198
+
199
+ ```bash
200
+ somewhere typecheck && somewhere deploy
201
+ ```
202
+
203
+ Create an invoice row, `POST /api/invoices/<id>`, and open the page with
204
+ `<InvoicePreview invoiceId={id} />`. A second user's `GET` of the same id
205
+ returns 404.
@@ -0,0 +1,107 @@
1
+ # Recipe — Push notifications to a signed-in user
2
+
3
+ A signed-in user turns on notifications in their browser, your function
4
+ notifies them, and you check delivery in the send history. The platform
5
+ serves the service worker and the subscribe helper, holds the signing keys
6
+ and encrypts each message, so these two files connect your page and function.
7
+
8
+ ## 1. The page: a button that turns notifications on
9
+
10
+ ```ts
11
+ // src/services/notifications.ts — browser
12
+ import { enablePush, disablePush, pushStatus } from 'somewhere:push'
13
+
14
+ /** Call from a click handler: browsers show the permission prompt only after a user gesture. */
15
+ export async function turnOnNotifications(): Promise<string> {
16
+ try {
17
+ await enablePush()
18
+ return 'Notifications are on for this browser.'
19
+ } catch (error) {
20
+ const code = error instanceof Error && 'code' in error ? String(error.code) : ''
21
+ if (code === 'PUSH_PERMISSION_DENIED') return 'Notifications are blocked in this browser\'s site settings.'
22
+ if (code === 'PUSH_UNSUPPORTED') return 'This browser cannot receive notifications. On iPhone, add the app to the Home Screen first.'
23
+ if (code === 'AUTH_REQUIRED') return 'Sign in first.'
24
+ throw error
25
+ }
26
+ }
27
+
28
+ export async function turnOffNotifications(): Promise<void> {
29
+ await disablePush()
30
+ }
31
+
32
+ export async function notificationsAreOn(): Promise<boolean> {
33
+ return (await pushStatus()).subscribed
34
+ }
35
+ ```
36
+
37
+ `enablePush()` registers this browser for the user of the session cookie.
38
+ Call `turnOffNotifications()` before signing out on a shared computer; if
39
+ another user signs in and turns notifications on, the browser moves to them.
40
+
41
+ ## 2. The function: notify the signed-in user
42
+
43
+ ```ts
44
+ // api/notify.ts — send a test notification to the signed-in user
45
+ export default sw.endpoint({
46
+ auth: 'none', // the handler applies its own access check below
47
+ handler: async ({ request: req }, sw) => {
48
+ if (req.method !== 'POST') return new Response(null, { status: 405, headers: { Allow: 'POST' } })
49
+ const user = await sw.auth.fromRequest(req)
50
+ if (!user) return Response.json({ error: 'Sign in first.' }, { status: 401 })
51
+
52
+ const push = await sw.push.send({
53
+ user_id: user.id,
54
+ payload: { title: 'Notifications are ready', body: 'Your browser is connected.', url: '/' },
55
+ })
56
+ return Response.json({ notified_devices: push.sent + push.captured, push })
57
+ },
58
+ });
59
+ ```
60
+
61
+ `sw.push.send({ user_id })` reaches every browser that user turned on, and
62
+ reports one result per device. A missing or `null` `user_id` is refused, never
63
+ sent to everyone; a broadcast is `audience: 'all'`. To notify a different user (a comment on
64
+ their post, a task assigned to them), the function first checks that the
65
+ signed-in user is allowed to reach that user, then passes that user's id.
66
+
67
+ Tapping the notification opens `url` in your app, or focuses the tab already
68
+ showing it. Only paths on your own origin open; anything else opens `/`.
69
+
70
+ ## 3. Check it
71
+
72
+ ```bash
73
+ somewhere deploy
74
+ ```
75
+
76
+ In a real browser: sign in, press the button, allow notifications, then call
77
+ `/api/notify`. The notification appears even with the tab in the background.
78
+
79
+ In a hosted or headless browser, which cannot reach a push service, use the
80
+ push test inbox. It needs no permission:
81
+
82
+ ```ts
83
+ import { enablePush } from 'somewhere:push'
84
+ await enablePush({ test: true }) // this user's test device
85
+ ```
86
+
87
+ Call `/api/notify`, then read the history from a function or with the
88
+ `push_deliveries` tool:
89
+
90
+ ```ts
91
+ const { deliveries } = await sw.push.deliveries({ user_id: user.id, limit: 5 })
92
+ // [{ outcome: 'captured', platform: 'test', title: 'Notifications are ready', payload: { ... } }]
93
+ ```
94
+
95
+ `captured` with the payload you sent confirms your app sent it to this user’s test inbox. For real devices the same history shows `sent`, `failed` with the
96
+ HTTP status and a reason, or `gone` when the browser revoked the
97
+ device. Reads return the last 7 days.
98
+
99
+ ## 4. Going further
100
+
101
+ | Need | Use |
102
+ |---|---|
103
+ | React to a push or a click inside an open tab | `listenToPush(({ type, payload }) => …)`: `sw.push` → `turn-on-notifications-in-the-page` |
104
+ | A count on the app icon | `badge_count` in the payload: `sw.push` → `send-from-a-function` |
105
+ | Register from your own function instead of the helper | `sw.push.subscribe(subscription)`: `sw.push` → `register-from-a-function-instead` |
106
+ | Alerts to your own browser as the developer | `push_subscribe`, then `send({ audience: 'developer' })`: `sw.push` → `developer-devices` |
107
+ | Bell, push and email in one call | `sw.notifications.send(userId, …)` |