@somewhere-cloud/cli 0.38.155 → 0.38.156

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 (142) hide show
  1. package/CHANGELOG.md +4 -1
  2. package/dist/commands/docs.js +1 -1
  3. package/dist/lib/bundle.js +276 -188
  4. package/dist/lib/bundle.js.map +3 -3
  5. package/npm-shrinkwrap.json +2 -2
  6. package/package.json +2 -3
  7. package/dist/docs/adopt.md +0 -39
  8. package/dist/docs/analytics.md +0 -161
  9. package/dist/docs/api-reference.md +0 -339
  10. package/dist/docs/api-surface.md +0 -2067
  11. package/dist/docs/app-mcp.md +0 -162
  12. package/dist/docs/architecture-patterns.md +0 -334
  13. package/dist/docs/auth-client.md +0 -531
  14. package/dist/docs/billing.md +0 -76
  15. package/dist/docs/browser.md +0 -639
  16. package/dist/docs/calendar.md +0 -298
  17. package/dist/docs/changes.md +0 -323
  18. package/dist/docs/cli.md +0 -407
  19. package/dist/docs/common-mistakes.md +0 -199
  20. package/dist/docs/connect-agent.md +0 -72
  21. package/dist/docs/cors.md +0 -114
  22. package/dist/docs/cron.md +0 -167
  23. package/dist/docs/database-engine.md +0 -167
  24. package/dist/docs/declared-data.md +0 -1656
  25. package/dist/docs/declared-files.md +0 -475
  26. package/dist/docs/deploy-intelligence.md +0 -188
  27. package/dist/docs/deploy.md +0 -733
  28. package/dist/docs/design-system.md +0 -273
  29. package/dist/docs/dev-environments.md +0 -496
  30. package/dist/docs/domain-ownership.md +0 -31
  31. package/dist/docs/domains.md +0 -370
  32. package/dist/docs/feedback.md +0 -88
  33. package/dist/docs/file-tools.md +0 -116
  34. package/dist/docs/functions.md +0 -489
  35. package/dist/docs/getting-started.md +0 -238
  36. package/dist/docs/github.md +0 -95
  37. package/dist/docs/google-calendar.md +0 -212
  38. package/dist/docs/groups.md +0 -836
  39. package/dist/docs/guarantees.md +0 -58
  40. package/dist/docs/handled-for-you.md +0 -224
  41. package/dist/docs/inspect.md +0 -171
  42. package/dist/docs/limits.md +0 -68
  43. package/dist/docs/live-data.md +0 -197
  44. package/dist/docs/live.md +0 -92
  45. package/dist/docs/local-dev.md +0 -30
  46. package/dist/docs/migration-supabase.md +0 -58
  47. package/dist/docs/payments.md +0 -1102
  48. package/dist/docs/portability.md +0 -194
  49. package/dist/docs/postgres.md +0 -301
  50. package/dist/docs/pricing-comparison.md +0 -42
  51. package/dist/docs/pricing.md +0 -39
  52. package/dist/docs/project-groups.md +0 -107
  53. package/dist/docs/projects.md +0 -380
  54. package/dist/docs/recipe-ai-agent.md +0 -112
  55. package/dist/docs/recipe-ai-features.md +0 -227
  56. package/dist/docs/recipe-ai-receipts.md +0 -783
  57. package/dist/docs/recipe-background-jobs.md +0 -369
  58. package/dist/docs/recipe-booking.md +0 -348
  59. package/dist/docs/recipe-csv-import.md +0 -390
  60. package/dist/docs/recipe-ecommerce.md +0 -127
  61. package/dist/docs/recipe-email.md +0 -282
  62. package/dist/docs/recipe-escalation.md +0 -133
  63. package/dist/docs/recipe-file-uploads.md +0 -159
  64. package/dist/docs/recipe-import-app.md +0 -110
  65. package/dist/docs/recipe-login.md +0 -457
  66. package/dist/docs/recipe-multi-chat.md +0 -198
  67. package/dist/docs/recipe-paid-api.md +0 -161
  68. package/dist/docs/recipe-pdfs.md +0 -205
  69. package/dist/docs/recipe-push-notifications.md +0 -107
  70. package/dist/docs/recipe-seo.md +0 -200
  71. package/dist/docs/recipe-signed-in-app.md +0 -330
  72. package/dist/docs/render.md +0 -99
  73. package/dist/docs/rooms.md +0 -554
  74. package/dist/docs/sdk.md +0 -287
  75. package/dist/docs/sdks.md +0 -24
  76. package/dist/docs/search.md +0 -199
  77. package/dist/docs/security-model.md +0 -168
  78. package/dist/docs/setup.md +0 -212
  79. package/dist/docs/smoke.md +0 -102
  80. package/dist/docs/speed.md +0 -298
  81. package/dist/docs/sql-compatibility.md +0 -96
  82. package/dist/docs/sw.agent.md +0 -248
  83. package/dist/docs/sw.ai.md +0 -1291
  84. package/dist/docs/sw.auth.md +0 -1811
  85. package/dist/docs/sw.billing.md +0 -171
  86. package/dist/docs/sw.db.md +0 -2128
  87. package/dist/docs/sw.email.md +0 -661
  88. package/dist/docs/sw.endpoint.md +0 -187
  89. package/dist/docs/sw.env.md +0 -303
  90. package/dist/docs/sw.fetch.md +0 -115
  91. package/dist/docs/sw.fs.md +0 -424
  92. package/dist/docs/sw.groups.md +0 -836
  93. package/dist/docs/sw.image.md +0 -69
  94. package/dist/docs/sw.jobs.md +0 -520
  95. package/dist/docs/sw.logs.md +0 -61
  96. package/dist/docs/sw.mail.md +0 -106
  97. package/dist/docs/sw.notifications.md +0 -78
  98. package/dist/docs/sw.push.md +0 -161
  99. package/dist/docs/sw.rateLimit.md +0 -67
  100. package/dist/docs/sw.web.md +0 -128
  101. package/dist/docs/tasks.md +0 -269
  102. package/dist/docs/test.md +0 -220
  103. package/dist/docs/tool-reference-account.md +0 -7
  104. package/dist/docs/tool-reference-ai.md +0 -121
  105. package/dist/docs/tool-reference-analytics.md +0 -37
  106. package/dist/docs/tool-reference-api.md +0 -19
  107. package/dist/docs/tool-reference-artifacts.md +0 -35
  108. package/dist/docs/tool-reference-auth.md +0 -163
  109. package/dist/docs/tool-reference-browser.md +0 -114
  110. package/dist/docs/tool-reference-code.md +0 -26
  111. package/dist/docs/tool-reference-connect.md +0 -21
  112. package/dist/docs/tool-reference-cron.md +0 -48
  113. package/dist/docs/tool-reference-db.md +0 -282
  114. package/dist/docs/tool-reference-domains.md +0 -107
  115. package/dist/docs/tool-reference-email.md +0 -55
  116. package/dist/docs/tool-reference-env.md +0 -19
  117. package/dist/docs/tool-reference-feedback.md +0 -56
  118. package/dist/docs/tool-reference-fs.md +0 -265
  119. package/dist/docs/tool-reference-github.md +0 -57
  120. package/dist/docs/tool-reference-groups.md +0 -85
  121. package/dist/docs/tool-reference-help.md +0 -29
  122. package/dist/docs/tool-reference-jobs.md +0 -39
  123. package/dist/docs/tool-reference-live.md +0 -48
  124. package/dist/docs/tool-reference-logs.md +0 -16
  125. package/dist/docs/tool-reference-payments.md +0 -44
  126. package/dist/docs/tool-reference-project.md +0 -706
  127. package/dist/docs/tool-reference-push.md +0 -78
  128. package/dist/docs/tool-reference-rate-limit.md +0 -18
  129. package/dist/docs/tool-reference-search.md +0 -68
  130. package/dist/docs/tool-reference-security.md +0 -42
  131. package/dist/docs/tool-reference-smoke.md +0 -17
  132. package/dist/docs/tool-reference-stock-photos.md +0 -20
  133. package/dist/docs/tool-reference-tasks.md +0 -73
  134. package/dist/docs/tool-reference-telegram.md +0 -32
  135. package/dist/docs/tool-reference-usage.md +0 -9
  136. package/dist/docs/tool-reference-web.md +0 -71
  137. package/dist/docs/tool-reference-webhooks.md +0 -9
  138. package/dist/docs/troubleshooting.md +0 -411
  139. package/dist/docs/typed-functions.md +0 -94
  140. package/dist/docs/verify-before-deploy.md +0 -67
  141. package/dist/docs/vs-supabase.md +0 -75
  142. package/dist/docs/vs-vercel.md +0 -103
@@ -1,187 +0,0 @@
1
- # sw.endpoint — declarative endpoint wrapper
2
-
3
- `sw.endpoint` wraps a server function with auth, body validation, rate
4
- limiting, error formatting, and CORS so you only write business logic. It is the
5
- ordinary way to write a JSON endpoint. Set `auth` on every endpoint:
6
- `'required'` unless it is public on purpose, then `'none'`. `body` and
7
- `rateLimit` apply only when declared.
8
-
9
- The starter's AGENTS.md has the ordinary endpoint shapes; read further for
10
- validation, rate limits and other options. Endpoint files are routes:
11
- api/items.ts → /api/items, api/items/[id].ts → params.id, and
12
- api/items/[id]/sub.ts → /api/items/:id/sub; underscore-prefixed files are helpers.
13
- GET/DELETE are named exports; POST with a JSON body uses the default export.
14
- handler receives { user, params, body, request } and a second sw runtime argument;
15
- auth: 'required' supplies user.id and user.email (string); declare body fields first.
16
-
17
- With a rate limit configured, each endpoint path gets its own counter per
18
- signed-in user, or per client IP when no user is resolved. A dynamic route
19
- counts each concrete request path separately: `/api/notes/1` and
20
- `/api/notes/2` have separate counters.
21
-
22
- ```ts
23
- // db/schema.ts — owner() stamps each note with the signed-in user
24
- import { schema, table, id, text, owner } from 'somewhere/db'
25
- export default schema({
26
- notes: table({ id: id(), title: text(), note: text({ nullable: true }) }, { scope: owner() }),
27
- })
28
- ```
29
-
30
- ```ts
31
- // api/notes.ts
32
- export default sw.endpoint({
33
- auth: 'required',
34
- body: { title: 'string', note: 'string?' },
35
- rateLimit: '30/minute',
36
- cors: 'same-origin',
37
- handler: async ({ body, user }, sw) => {
38
- const made = await sw.db.insert('notes', { title: body.title, note: body.note ?? null });
39
- return { ok: true, note: made.data[0], by: user.id };
40
- }
41
- });
42
- ```
43
-
44
- Sign-in itself is not an endpoint you write: the SDK's packaged handler serves
45
- `/api/auth/*` (`docs({ topic: 'auth-client' })`).
46
-
47
- ## What the platform handles before your handler runs
48
-
49
- - **auth** — exactly three modes (there is no `'public'`; a public endpoint for anonymous visitors is `'none'`):
50
- - `'required'` — calls `sw.auth.requireUser(request)` and returns
51
- 401 `AUTH_REQUIRED` if the request isn't signed in. Use this for
52
- every signed-in endpoint.
53
- - `'optional'` — `user` when the caller is signed in, otherwise `null`.
54
- - `'none'` — public; no sign-in check. Write it for an endpoint that is
55
- public on purpose.
56
-
57
- A config written without `auth` is refused at deploy, patch and
58
- `deploy-check` with 400 `ENDPOINT_AUTH_OMITTED`, naming the file and
59
- line. The check reads the object literal in `sw.endpoint({ ... })`; a
60
- config passed as a variable or built elsewhere is not read, and if it
61
- has no `auth` it still runs as `'none'`. Endpoints already deployed
62
- keep serving as before.
63
-
64
- Any other value (`'user'`, a typo, `true`) is refused at deploy and
65
- by `deploy-check` with 400 `ENDPOINT_AUTH_MODE_INVALID`, naming the
66
- file, line, and value. It is never treated as public.
67
- - **roles** — app roles (declared in `appRoles` in db/schema.ts), any of
68
- which admits the caller: `roles: ['staff']`. Roles imply a signed-in
69
- caller, so `auth` is `'required'` or left out. The caller's roles are read
70
- fresh on every request (grants, and roles held by verified email domain),
71
- before the body is read or your handler runs: signed out is 401
72
- `AUTH_REQUIRED`, signed in without a listed role is 403
73
- `APP_ROLE_REQUIRED`, and a read that fails is 503 `APP_ROLES_UNAVAILABLE`
74
- (never treated as "holds no role"). The handler's `user.appRoles` lists the
75
- caller's roles for that request. An empty list, a malformed value, or
76
- `auth: 'optional'`/`'none'` with roles, written as literals in
77
- `sw.endpoint({ ... })`, is refused at deploy with 400
78
- `ENDPOINT_ROLES_INVALID`; so is a role the app does not declare, when the
79
- deploy carries db/schema.ts. A roles list computed in code, and an
80
- undeclared role in a deploy without db/schema.ts, are refused at request
81
- time instead: the endpoint answers 500 `ENDPOINT_ROLES_INVALID` and the
82
- handler never runs. An endpoint that is an
83
- MCP tool (`mcp`) cannot declare roles yet. A revoked role refuses the next
84
- request; a request already admitted finishes.
85
- - **body** — parses JSON, validates against the schema, returns 400
86
- `VALIDATION_ERROR` with a list of field-level messages if anything's
87
- off. Schema types: `'string'`, `'email'`, `'number'`, `'boolean'`,
88
- `'array'`, `'object'`. Suffix `'?'` to make a field optional
89
- (`'string?'`). Nest objects by nesting the schema.
90
- Without `body`, the wrapper does not read the request: `body` is
91
- `null` and the request stays unread for your handler. A handler that reads
92
- `body` with no `body` declared would drop what the caller sent, so it is
93
- refused at deploy, patch and `deploy-check` with 400
94
- `ENDPOINT_BODY_UNDECLARED`, naming the file and line. Declare the fields,
95
- or read the raw request (`await request.json()`, `request.text()`) for a
96
- webhook or form post. The check has the same limits as the `auth` check.
97
- - **rateLimit** — use a string such as `'30/minute'`, `'60/hour'` or `'1000/day'` in `sw.endpoint`. The endpoint option takes the string directly.
98
- With `auth: 'required'` or `'optional'`, the counter uses the resolved
99
- user ID, falling back to client IP when there is no user. With
100
- `auth: 'none'`, it always uses client IP. Each endpoint path has its own counter.
101
- Returns 429 `RATE_LIMITED` + `Retry-After` header.
102
- An invalid limit returns 500 `ENDPOINT_RATE_LIMIT_INVALID` before your handler
103
- runs. Fix the value or remove it for an unlimited endpoint. Existing apps
104
- adopt this validation on their next source deploy.
105
- - **cors** — `'same-origin'` (default; no CORS headers), `'*'` (allow
106
- any), or an allow-list array (`['app.example.com']` — subdomain
107
- matches accepted). Preflight `OPTIONS` is auto-answered with 204.
108
- `'*'` sends no `Access-Control-Allow-Credentials`, so it is for a
109
- public endpoint called without credentials. It does not bypass the
110
- platform's origin check: a browser request from an unapproved origin that
111
- carries a cookie or `Authorization` is refused with 403
112
- `ORIGIN_NOT_ALLOWED` before your handler runs (docs({ topic: 'cors' })).
113
-
114
- ## What your handler receives
115
-
116
- `async ({ body, user, headers, params, request }, sw) => …`
117
-
118
- - `body` — the validated, parsed JSON, or `null` when no schema is
119
- declared.
120
- - `user` — the authed user, or `null` for `auth: 'optional'`/`'none'`. With
121
- `roles`, `user.appRoles` is the caller's own app-role names.
122
- Any endpoint can read them with
123
- `await sw.auth.requireUser(request, { appRoles: true })`, for a page that
124
- shows staff controls (a hint; every action is still checked).
125
- - `headers` — the request `Headers` object.
126
- - `params` — route params (from `api/[id].ts`-style paths).
127
- - `request` — the original `Request` if you need it.
128
- - `sw` — the per-request platform context, same as a plain handler's
129
- second arg.
130
-
131
- Return a plain object → wrapped in `Response.json`. Return a
132
- `Response` → passed through unchanged. Return `null`/`undefined` → 204.
133
-
134
- With a `body` schema declared, the handler always receives a validated
135
- body. GET and HEAD cannot carry one, so after the auth check they are
136
- answered with 405 `METHOD_NOT_ALLOWED` and an
137
- `Allow: POST, PUT, PATCH, DELETE, OPTIONS` header, and your handler does
138
- not run. POST, PUT, PATCH and DELETE must send valid JSON: a missing or
139
- malformed body is 400 `INVALID_JSON`.
140
-
141
- To serve GET from the same path, export it separately. The platform calls
142
- the export named after the request method before the default export:
143
-
144
- ```ts
145
- // api/inbox.ts
146
- export const GET = sw.endpoint({
147
- auth: 'required',
148
- handler: async (_input, sw) => ({ notes: (await sw.db.from('notes', { limit: 20 })).data }),
149
- });
150
-
151
- export default sw.endpoint({
152
- auth: 'required',
153
- body: { title: 'string' },
154
- handler: async ({ body }, sw) => (await sw.db.insert('notes', { title: body.title })).data[0],
155
- });
156
- ```
157
-
158
-
159
- ## Errors
160
-
161
- Throw anywhere in your handler and the wrapper formats it. A thrown error
162
- with a 4xx `.status` keeps that status and its `.code` (capital letters,
163
- digits and underscores), but not its message: the wrapper cannot tell your
164
- text from an internal error's. Platform errors marked safe for callers, such as
165
- `AUTH_REQUIRED`, keep their message. Everything else is a 500
166
- `HANDLER_ERROR`. Errors that are not shown to the caller are written to your
167
- function logs. To answer with
168
- your own message, return it, for example
169
- `return Response.json({ error: 'INSUFFICIENT_FUNDS', message: 'Not enough credit.' }, { status: 402 })`.
170
-
171
- An endpoint whose `auth` is set at runtime to anything other than
172
- `'required'`, `'optional'`, or `'none'` answers every request with
173
- 500 `ENDPOINT_AUTH_MODE_INVALID` and never runs your handler.
174
-
175
- ## MCP tools for Claude
176
-
177
- Endpoints can also be tools that Claude, or any MCP client, calls as the
178
- person signed in to your app (a preview feature). The full steps, examples and
179
- current limits are in one place: `somewhere docs app-mcp`.
180
-
181
- ## When NOT to use it
182
-
183
- Write a plain `async (req, sw) => …` handler when you want to parse the
184
- request, check sign-in and build error responses yourself: read the body from
185
- `req`, call `sw.auth.requireUser(req)`, and return your own `Response`.
186
-
187
- Related topics: `sw.auth`, `sw.rateLimit`.
@@ -1,303 +0,0 @@
1
- # sw.env — Environment Variables (inside deployed functions)
2
-
3
- ## Env vars and secrets
4
-
5
- Keep API keys and other configuration in the project's settings and read them
6
- in a function through `sw.env`. Values are private to your functions unless you
7
- publish one on purpose. They're encrypted at rest, and management reads list
8
- names, never values. After a save, ordinary requests see the change within
9
- 60 seconds, usually in a few seconds. Background runs
10
- and cron see it within 5 seconds. Both
11
- update without another deploy. If the save response
12
- says `requires_deploy: true`, deploy your app's raw source once to enable
13
- these updates.
14
-
15
- Built-in services (database, auth, files, AI and email) need no keys. Use
16
- `sw.env` for the outside services your app calls.
17
-
18
- ### Store a key and use it
19
-
20
- Save the value from a file outside the project, so it stays out of your shell
21
- history and your source:
22
-
23
- ```bash
24
- somewhere env set FEEDBACK_WEBHOOK_URL --stdin < ~/secrets/feedback-webhook-url
25
- somewhere deploy
26
- ```
27
-
28
- Deploy a new app as shown above. For an existing app, deploy its raw source
29
- once if the save response says `requires_deploy: true`. After that,
30
- `env set`, rotation and `env delete` take effect without another deploy.
31
-
32
- Read the value inside the handler, on each request:
33
-
34
- ```ts
35
- // api/team-feedback.ts — forwards a signed-in user's feedback to your team chat
36
- export default sw.endpoint({
37
- auth: 'none', // the handler applies its own access check below
38
- handler: async ({ request }, sw) => {
39
- if (request.method !== 'POST') {
40
- return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
41
- }
42
-
43
- const user = await sw.auth.fromRequest(request);
44
- if (!user) {
45
- return Response.json({ error: 'Sign in to send feedback.' }, { status: 401 });
46
- }
47
-
48
- const input: unknown = await request.json().catch(() => null);
49
- const message =
50
- typeof input === 'object' && input !== null && 'message' in input ? input.message : undefined;
51
- if (typeof message !== 'string' || !message.trim() || message.length > 2000) {
52
- return Response.json({ error: 'Feedback must be 1–2,000 characters.' }, { status: 400 });
53
- }
54
-
55
- // Limit each user before any outside call, so one account can't flood the service.
56
- const allowance = await sw.rateLimit.check(`team-feedback:${user.id}`, 5, 3600);
57
- if (!allowance.allowed) {
58
- const retryAfter =
59
- allowance.retry_after ?? Math.max(1, allowance.reset - Math.floor(Date.now() / 1000));
60
- return Response.json(
61
- { error: 'You have sent a lot of feedback. Try again later.' },
62
- { status: 429, headers: { 'Retry-After': String(retryAfter) } },
63
- );
64
- }
65
-
66
- // Read the secret here, not at module level, so a rotated value is used.
67
- const webhookUrl = sw.env.FEEDBACK_WEBHOOK_URL;
68
- if (!webhookUrl) {
69
- return Response.json({ error: 'Feedback is not configured yet.' }, { status: 503 });
70
- }
71
-
72
- const delivered = await fetch(webhookUrl, {
73
- method: 'POST',
74
- headers: { 'Content-Type': 'application/json' },
75
- body: JSON.stringify({ text: `Feedback from ${user.email}: ${message.trim()}` }),
76
- });
77
- if (!delivered.ok) {
78
- return Response.json({ error: 'Could not deliver feedback.' }, { status: 502 });
79
- }
80
- return Response.json({ sent: true });
81
- },
82
- });
83
- ```
84
-
85
- This assumes a chat service whose incoming webhook accepts JSON `{ text }`.
86
- Match the body to your service. The function sends the message only to the
87
- stored URL, and the browser can't choose where it goes. The response tells the
88
- browser only whether delivery worked; the webhook URL is never returned to it.
89
- The per-user allowance runs before the outside call, as in **Functions**.
90
-
91
- ### How changes reach your function
92
-
93
- - **Read inside the handler.** `sw.env` gives each request the current
94
- production values. A module-level constant such as
95
- `const key = process.env.KEY`, or an SDK client created once at module level,
96
- keeps the value it captured, and rotation doesn't replace it. Create clients
97
- that hold a key inside the handler.
98
- - **New invocations.** Ordinary HTTP requests pick up saved values within
99
- 60 seconds. Manual and scheduled cron, background
100
- jobs, queues, and Somewhere webhook deliveries pick them up within
101
- 5 seconds. An invocation already running finishes
102
- with the values it started with. If the current configuration can't be
103
- loaded after that window, the request fails rather than run with an older
104
- value.
105
- - **Scopes.** `--scope prod` applies to production, `--scope dev` to previews,
106
- and `all` (the default) to both. A preview keeps the values it captured when
107
- it was created.
108
-
109
- ### Keep secrets on the server
110
-
111
- - Never return a secret from a function or put one in browser source. Deploy
112
- refuses recognized secret literals in source with `SECRET_IN_SOURCE`.
113
- - A value for browser code (for example, a map's publishable key) needs a
114
- `VITE_` or `REACT_APP_` name and an explicit `--public`. Every visitor can
115
- read it. Deploy refuses a browser reference to a server-only value and refuses
116
- to publish a recognized server credential.
117
- - If a key leaks, rotate it at the provider as well as here.
118
-
119
- ### Limits
120
-
121
- All of a project's values share one budget of 5,120 bytes, names included.
122
- For a large credential such as a service-account JSON, store it as a private
123
- file and keep only its path in an env value.
124
-
125
- ### More on configuration
126
-
127
- | Need | Where |
128
- |---|---|
129
- | Adoption, rotation timing and failure behavior | `sw.env` → `timing` |
130
- | Public browser values, `--public`/`--private`, labels, REST and MCP forms | `sw.env` → `server-keys-and-browser-keys` |
131
- | Size budget errors and the private-file pattern | `sw.env` → `size-limit` |
132
- | Reading a value in a function | `sw.env` → `access` |
133
- | Preview environments | `dev-environments` |
134
- | CLI flags (`env list`, `set`, `delete`) | `cli` |
135
-
136
- ## Access
137
- Read `sw.env.YOUR_KEY` inside the function handling the request, as in
138
- `store-a-key-and-use-it` above. Keep the value on the server; return only
139
- the result your page needs.
140
-
141
- ## Timing
142
- The save and delete responses tell you what to do. If `requires_deploy`
143
- is `true`, deploy the app's raw source once to enable live updates. When
144
- it is `false`, setting, rotating, changing visibility or deleting a
145
- production value takes effect without a deploy.
146
-
147
- Server functions read the current production values through `sw.env` for
148
- each request. A change reaches ordinary requests within 60 seconds. New
149
- background runs and cron see it within 5 seconds. If the
150
- platform cannot load the current configuration after that window, the request
151
- fails instead of using an older value. A request already in flight may finish
152
- with the values it started with.
153
-
154
- Read the key inside the handler and create any integration client that stores
155
- it there. A module-level constant such as `const key = process.env.KEY` or
156
- a cached SDK client keeps its captured value; rotation does not recreate it.
157
-
158
- ```ts
159
- // api/admin/stripe-balance.ts — admins only; the key never leaves the server
160
- import Stripe from 'stripe';
161
-
162
- export default async function stripeBalance(
163
- request: Request,
164
- sw: SomewhereRuntimeContext,
165
- ): Promise<Response> {
166
- await sw.auth.requireUser(request, { role: 'admin' });
167
- const key = sw.env.STRIPE_SECRET_KEY;
168
- if (!key) return Response.json({ error: 'Stripe is not configured yet.' }, { status: 503 });
169
-
170
- // Create per request instead of retaining the old key in a cached client.
171
- const stripe = new Stripe(key);
172
- const balance = await stripe.balance.retrieve();
173
- return Response.json({ available: balance.available });
174
- }
175
- ```
176
-
177
- ## Size limit
178
- All of a project's environment values share one budget of 5,120 bytes, names
179
- included, measured as the JSON of every name and value together (a newline in
180
- a PEM key counts as two bytes, `\n`). It is not a per-value limit: a 3 KB
181
- value can be refused when other values are already set. The budget is counted
182
- per environment (live, and preview when enabled); a value with scope `all`
183
- counts in both.
184
-
185
- - `ENV_VALUE_TOO_LARGE` (413) — this one value is larger than the whole
186
- budget, so it can never fit.
187
- - `ENV_VALUES_TOO_LARGE` (413) — saving it would bring the combined values
188
- over the budget. The message names the largest values.
189
-
190
- Keep large content — a service-account JSON, a certificate — in a private file
191
- and put only its path in an environment value:
192
-
193
- ```ts
194
- // api/_lib/service-account.ts
195
- // Once, from your machine:
196
- // somewhere fs put ./service-account.json /secrets/service-account.json
197
- // somewhere env set SERVICE_ACCOUNT_PATH /secrets/service-account.json
198
- export async function readServiceAccount(sw: SomewhereRuntimeContext): Promise<unknown> {
199
- const path = sw.env.SERVICE_ACCOUNT_PATH;
200
- if (!path) throw new Error('SERVICE_ACCOUNT_PATH is not set.');
201
- // Project authority over files: call this only from a handler that has
202
- // already authorized the request.
203
- const file = await sw.fs.server.read(path);
204
- return file.json();
205
- }
206
- ```
207
-
208
- Or delete values you no longer need (`somewhere env delete NAME`), then set
209
- the value again. An existing project needs its one-time adoption deploy before
210
- changes can take effect without another deploy.
211
-
212
- ## Server keys and browser keys
213
-
214
- Keep service secrets in a server function. Feed `--stdin` from your credential
215
- tool or a private file outside the project, for example
216
- `somewhere env set SERVICE_KEY --stdin --scope prod < /secure/service-key`.
217
- It accepts piped or redirected input, not an interactive paste. The value stays
218
- out of the command arguments. Then read it inside a function:
219
-
220
- ```ts
221
- // api/service-status.ts
222
- export default async function serviceStatus(
223
- request: Request,
224
- sw: SomewhereRuntimeContext,
225
- ): Promise<Response> {
226
- await sw.auth.requireUser(request); // only signed-in users can spend the key
227
- const key = sw.env.SERVICE_KEY;
228
- if (!key) return Response.json({ error: 'The service is not configured yet.' }, { status: 503 });
229
-
230
- const upstream = await fetch('https://service.example/v1/status', {
231
- headers: { Authorization: `Bearer ${key}` },
232
- });
233
- // Return only the result the page needs, never the key or the raw response.
234
- return Response.json({ ok: upstream.ok });
235
- }
236
- ```
237
-
238
- For a browser SDK's publishable key, save a separate value with
239
- `somewhere env set VITE_MAP_PUBLIC_KEY --stdin --public < /secure/map-public-key` and read it as
240
- `import.meta.env.VITE_MAP_PUBLIC_KEY` in browser code. The equivalent
241
- `REACT_APP_` convention is `process.env.REACT_APP_NAME`. A public value
242
- is visible to every visitor. After adoption, new page loads get a changed value
243
- within 60 seconds without a new deploy, and making it private again stops new
244
- page loads from receiving it within the same window.
245
- Both explicit `public: true` and an uppercase `VITE_` or `REACT_APP_` name are
246
- needed for that browser reference. A prefix alone never grants publication.
247
- Browser names use uppercase letters, digits, and underscores; server names may
248
- also contain lowercase letters.
249
- For example, the MCP call is `env({ project_id, key:
250
- 'VITE_MAP_PUBLIC_KEY', value: '<publishable key>', public: true })`.
251
-
252
- A browser reference to a stored server-only value fails deploy with
253
- `BROWSER_ENV_PRIVATE_REF` (400). An attempt to publish a recognized server
254
- credential, including a test credential, fails with `BROWSER_ENV_SECRET`
255
- (400), whether or not its name has a browser prefix. The same check runs again
256
- when browser code is compiled. No rejected value is published. A public key
257
- without a browser prefix can be stored, but needs a separately created
258
- prefixed name for browser code; the platform never renames it automatically.
259
- The checks recognize known credential patterns, not every possible secret.
260
- A recognized secret literal in page or function source, including a test-mode
261
- secret, is refused separately with `SECRET_IN_SOURCE`. Never put a secret in
262
- browser source or return one from your function.
263
-
264
- `somewhere env list` and MCP `env({ project_id })` show names, scope,
265
- visibility, optional labels and reference guidance, without values. Scope is
266
- `all` (both), `dev` (previews), or `prod` (production). Set it with CLI
267
- `--scope` or MCP `scope`. Use CLI `--public` or `--private` (one at a
268
- time), or MCP `public: true` / `public: false`. Omit the public choice
269
- when rotating a value in the same scope to keep its existing visibility; an
270
- explicit private choice withdraws browser publication on new production page
271
- loads after adoption. Before adoption, it takes effect on the next deploy.
272
- Optional `--provider` / `--purpose` (MCP `provider` / `purpose`) are
273
- non-secret labels to help you identify a key. Visibility and credential checks
274
- control publication independently of these labels.
275
-
276
- The REST equivalent is `POST /v1/env` with `{ project_id, key, value,
277
- scope?, public?, provider?, purpose? }`; `GET /v1/env?project_id=...`
278
- lists the saved configuration. The save response has effective `scope` and
279
- `visibility`, optional `provider` / `purpose`, `server_reference`,
280
- optional `browser_reference`,
281
- `browser_guidance`, and `requires_deploy`, which is false after adoption and
282
- true before it. `browser_exposed` and `exposure_eligible` describe whether
283
- the saved value qualifies for browser publication. A page already open keeps
284
- the values it loaded; reload it to read the current public configuration.
285
- Omitting provider or purpose during a rotation retains it; an empty string
286
- clears it. These fields cannot contain a recognized secret.
287
-
288
- After adoption, production browser references read the current public values
289
- when a new page loads. Explicitly public values are visible to every visitor;
290
- use them only for publishable configuration. Production changes do not change
291
- an already loaded page. A customer Service Worker may serve an offline or
292
- older page or configuration response; freshness applies to requests that reach
293
- the platform. A browser asset that is already published keeps the values it
294
- was built with: changing visibility or rotating a key does not recall it.
295
-
296
- Previews capture `dev` + `all` values when their snapshot is created.
297
- Production changes do not update an existing preview; create a new preview
298
- snapshot for changed development values. A code rollback between adopted
299
- releases continues to use current production configuration. The platform
300
- refuses rollback to a release from before adoption because it contains older
301
- embedded values.
302
- If a published credential is compromised, rotate it at its provider as well.
303
- The platform does not extract keys from source or create a proxy automatically.
@@ -1,115 +0,0 @@
1
- # sw.fetch — outbound HTTP fetch from a function
2
-
3
- Call public HTTP and HTTPS APIs from server code with the standard global
4
- `fetch`. In a deployed function the runtime wraps it with the platform's
5
- outbound protections, and it returns a standard `Response`. `sw.fetch` is the
6
- same function under a second name: same arguments, same `Response`.
7
- Preview functions block outbound requests. Browser calls to your own functions
8
- use same-origin `fetch('/api/...')`.
9
-
10
- ```ts
11
- // api/weather.ts
12
- export default async function (_req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
13
- // The warning is awaited so it is sent before the function returns. A refused
14
- // log write throws (the daily log quota, for example); report that on the
15
- // console instead of letting it turn this 502 into a 500.
16
- const unavailable = async (message: string, data: Record<string, unknown>): Promise<Response> => {
17
- try {
18
- await sw.logs.warn(message, data);
19
- } catch (logError) {
20
- console.error('Weather warning was not logged', logError);
21
- }
22
- return Response.json({ error: 'Weather is temporarily unavailable' }, { status: 502 });
23
- };
24
-
25
- let response: Response;
26
- try {
27
- response = await fetch('https://api.example.com/weather?city=Oakland', {
28
- headers: { Authorization: `Bearer ${sw.env.WEATHER_API_KEY}` },
29
- signal: AbortSignal.timeout(8_000), // this call's own limit
30
- });
31
- } catch (err) {
32
- // No response at all: a refused destination, a failed lookup, a timeout or a network error.
33
- return unavailable('Weather request failed', { error: err instanceof Error ? err.message : String(err) });
34
- }
35
-
36
- if (!response.ok) {
37
- return unavailable('Weather provider refused', { status: response.status });
38
- }
39
-
40
- let weather: unknown;
41
- try {
42
- weather = await response.json();
43
- } catch {
44
- return unavailable('Weather provider returned a body that is not JSON', { status: response.status });
45
- }
46
- return Response.json({ weather });
47
- }
48
- ```
49
-
50
- ## What a call returns
51
-
52
- - A standard `Response`. A 4xx or 5xx answer is still a `Response`: check
53
- `response.ok` or `response.status`, then read the body once with
54
- `response.json()` or `response.text()`.
55
- - The call rejects only when there is no response to return. Platform refusals
56
- carry an `error.code`, for example `SSRF_BLOCKED`, `DNS_LOOKUP_FAILED`,
57
- `FETCH_TIMEOUT` or `DRAFT_EGRESS_DENIED`. Redirect failures and other
58
- network failures reject with a `TypeError`. Aborting your own `signal`
59
- rejects with its reason.
60
- - Nothing is retried automatically. Retry only a request that is safe to
61
- repeat, for example one the upstream deduplicates with an idempotency key.
62
-
63
- The rest of this topic describes deployed functions. `run_code` returns a
64
- standard `Response` too, through its own guarded fetch.
65
-
66
- ## Time limits and cancellation
67
-
68
- - The runtime rejects a call with `FETCH_TIMEOUT` when the response headers
69
- do not arrive within 120 seconds. That limit ends when the headers
70
- arrive; it never cuts off a response body you are still reading.
71
- - Pass your own `signal` for a shorter limit or to cancel a call. Aborting
72
- it after the headers arrive also cancels reading the body.
73
- - A hostname lookup that exceeds 3 seconds rejects with `DNS_LOOKUP_FAILED`.
74
-
75
- ## Destination safety
76
-
77
- Before sending, the runtime refuses a private, loopback, link-local or
78
- cloud-metadata address, and a reserved name such as `localhost` or a
79
- `.local` or `.internal` host (`SSRF_BLOCKED`). It resolves any other
80
- hostname and refuses it with `SSRF_BLOCKED` when an address it resolves to
81
- is in a blocked range; a name that does not resolve to a public address
82
- rejects with `DNS_LOOKUP_FAILED`. The connection then goes to an address the
83
- platform checked, so a DNS change after the check cannot redirect it.
84
- Resolution is checked per request, not continuously. A preview function cannot
85
- make outbound requests at all (`DRAFT_EGRESS_DENIED`).
86
-
87
- Behind the runtime, the platform's outbound guard refuses a request that
88
- reaches it with a literal blocked target — a non-public address or internal
89
- hostname, a URL with embedded `user:password`, a scheme other than
90
- `http:`/`https:`, or a port other than 80, 443 or 1024 and above — with
91
- a 403 carrying `x-sw-outbound-error`, before it leaves the platform. A
92
- request the guard allows passes through unchanged. The guard classifies the
93
- URL as written; it does not resolve names. Put credentials in an
94
- `Authorization` header, never in the URL.
95
-
96
- ## Redirects
97
-
98
- - By default (`redirect: 'follow'`) a 301, 302, 303, 307 or 308 is followed,
99
- and each new destination is checked exactly like the first, up to the
100
- limit of 20 redirects. Past the limit the call rejects with a
101
- `TypeError`.
102
- - A hop to another origin drops the `Authorization`, `Cookie` and
103
- `Proxy-Authorization` headers.
104
- - A 303 after any method other than GET or HEAD, and a 301 or 302 after a
105
- POST, continue as a GET without the body. Other redirects resend the body;
106
- a streaming (`ReadableStream`) body cannot be resent, so the call rejects
107
- with a `TypeError`.
108
- - `redirect: 'manual'` returns the 3xx `Response` to you;
109
- `redirect: 'error'` rejects with a `TypeError`.
110
-
111
- ## Telemetry
112
-
113
- The runtime sends a record to project logs with the method, host, status or
114
- error code, duration and redirect count. It leaves out the full URL, headers
115
- and body. Logging failures do not block the request.