@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,212 +0,0 @@
1
- # Setup — Use the CLI, or connect MCP without a shell
2
-
3
- Install the CLI and sign in through your browser, or connect MCP from chat.
4
-
5
- ## Connecting from a terminal
6
-
7
- For an agent with a terminal, the Somewhere CLI is the better way to deploy:
8
- `somewhere deploy` reads files from disk without putting their contents in
9
- conversation tool arguments. The default auth/styled starter avoids about
10
- 28,734 tokens of inline deploy arguments (114,934 UTF-8 JSON bytes, estimated
11
- at four bytes per token). Sign in with `somewhere login`: browser sign-in
12
- gives a full CLI session that renews itself.
13
- Beyond the connector's named tool list, the CLI covers project lifecycle and
14
- collaborators, database import and export, file history, jobs and cron,
15
- search indexes, push notifications, payment administration and PostgreSQL
16
- migration. Many of these operations are also reachable through the connector's
17
- `api_read`, `api_write` and `run_code` tools.
18
-
19
- `auth_cli_pair` links a CLI inside a sandbox or container with no browser; it
20
- keeps the connector's limits: AI image, audio and video generation and financial
21
- asset transfers are unavailable, domain purchases happen in the dashboard, and
22
- generic API access cannot reach credential, OAuth, CLI, code-runner, admin,
23
- internal or system endpoints.
24
-
25
- ## 1. Install the CLI
26
-
27
- Ask before destructive or paid actions unless the user already authorized them.
28
-
29
- ```bash
30
- npm i -g @somewhere-cloud/cli
31
- ```
32
-
33
- The package is `@somewhere-cloud/cli`. The binary is `somewhere`.
34
-
35
- Requires Node.js 22.19.0 or newer. The CLI works on macOS, Linux, and Windows (via WSL or PowerShell).
36
-
37
- ## 2. Log in (browser-based, no key paste)
38
-
39
- ```bash
40
- somewhere auth login
41
- ```
42
-
43
- The command prints an eight-character code and a sign-in link, opens a
44
- browser if the machine has one, and waits. A human approves that code in their
45
- own browser; the session then lands in `~/.somewhere/config.json`. Same flow as
46
- `gh auth login`. The code is good for ten minutes.
47
-
48
- To keep a separate CLI login, set `SOMEWHERE_CONFIG_DIR` to a directory: the
49
- CLI keeps its login, temporary-project session, device id and caches there
50
- instead of `~/.somewhere`, and `HOME` is unchanged. An empty directory starts
51
- signed out, so a test or a second identity never touches your own login.
52
- `somewhere mcp` passes the same value to the MCP server it registers; files
53
- other tools keep in your home directory (such as `~/.claude.json`) stay there.
54
-
55
- **What the CLI sends about this machine.** Device-code sign-in (`somewhere auth
56
- login`) and the first signed-out deploy of a project, which registers its claim
57
- link, send a device label, `CLI · <host name> · <8 characters of a random device
58
- id>`, and the machine's host name, CLI version, Node.js version, operating
59
- system and release, and CPU architecture. The platform stores these with the
60
- CLI session, together with the request's IP address and approximate city,
61
- region and country. Browser sign-in sends only the device label, which names
62
- the key it creates. The device id is random,
63
- created on first use and kept in `device.json` in the config directory.
64
- Open [Connected agents](https://somewhere.cloud/app/agents) to find the CLI
65
- by its device label and disconnect it.
66
-
67
- Nothing has to open a browser on the machine running the command, so this is
68
- also the login path on a hosted VM (ChatGPT Work, Claude Work), a remote
69
- container, or any SSH session — the terminal and the browser can be different
70
- devices. Signing an account in is the account owner's decision: confirm consent
71
- before starting the flow, show the code and the link exactly as printed, and
72
- leave the approval to the person in the browser. A code should only ever be
73
- approved if it matches the one on that person's own terminal.
74
-
75
- The session persists on that machine: every later command and shell reuses it. The access credential lasts 24 hours and the CLI renews it silently;
76
- the renewal right lasts 30 days and resets each time it is used, so a machine
77
- touched at least monthly stays signed in. A sign-out, or approving the same
78
- device name again, ends the old session.
79
-
80
- After this you can run `somewhere deploy`, `somewhere logs`, and
81
- the MCP bridge — all read the same config file. For a human setup flow, use
82
- `somewhere auth login` instead of putting a developer key in the config file.
83
- Developer keys serve CI and server-to-server calls. For a disposable shell
84
- already connected through MCP, use the pairing flow below.
85
-
86
- ## 3. Optionally connect MCP to Claude Code
87
-
88
- The Somewhere CLI includes the MCP bridge. Register it with Claude Code:
89
-
90
- ```bash
91
- somewhere mcp install claude-code
92
- # reload Claude Code
93
- ```
94
-
95
- After reload, the Somewhere MCP tools are available in context. The bridge uses
96
- the CLI session, so you don't paste a key. This step is optional when the agent
97
- has a shell — the CLI needs no MCP setup: routine work uses first-class CLI
98
- commands, `somewhere call <tool> '<json>'` covers the full tool catalog, and
99
- `somewhere run <script>` executes code against the live project. The bridge
100
- shares the CLI login; a separately connected Claude.ai or ChatGPT uses its own
101
- OAuth session. Connected clients without a shell use MCP directly, where
102
- `run_code` is the same capability (the directory connector's runs cannot
103
- generate AI media or move money; an independently signed-in full CLI has the broader catalog).
104
-
105
- ## 4. Deploy something
106
-
107
- For an existing Somewhere app, start with `somewhere pull <app>` in a fresh
108
- folder. In a connected chat, start with `project_export` and use
109
- `project_patch` for selected file changes.
110
-
111
- A real React + function example — the platform compiles the JSX and
112
- the server-side TypeScript automatically at deploy time. No build
113
- step.
114
-
115
- ```bash
116
- mkdir hello && cd hello
117
- ```
118
-
119
- `index.html` — entry point:
120
-
121
- ```html
122
- <!doctype html>
123
- <html><head><title>hello</title></head>
124
- <body>
125
- <div id="root"></div>
126
- <script type="module" src="/src/main.tsx"></script>
127
- </body></html>
128
- ```
129
-
130
- `src/main.tsx` — React app (raw TSX, deployed as-is):
131
-
132
- ```tsx
133
- import { createRoot } from 'react-dom/client';
134
- import { useEffect, useState } from 'react';
135
-
136
- function App() {
137
- const [msg, setMsg] = useState('loading...');
138
- useEffect(() => {
139
- fetch('/api/hello').then(r => r.json()).then(d => setMsg(d.message));
140
- }, []);
141
- return <h1>{msg}</h1>;
142
- }
143
-
144
- createRoot(document.getElementById('root')!).render(<App />);
145
- ```
146
-
147
- `api/hello.ts` — server function (raw TS, deployed as-is):
148
-
149
- ```ts
150
- export default sw.endpoint({
151
- auth: 'none',
152
- handler: async () => ({ message: 'hello from a function' }),
153
- });
154
- ```
155
-
156
- Now deploy:
157
-
158
- ```bash
159
- somewhere deploy
160
- ```
161
-
162
- The CLI uploads the source files. The platform's compiler bundles
163
- `src/main.tsx` into a hashed JS chunk under `/_compiled/`, rewrites
164
- `index.html` to load it, and compiles `api/hello.ts` into a function
165
- the runtime can execute. The public URL serves that live deploy.
166
-
167
- (For just-a-static-page, you can ship a single `index.html` with
168
- plain HTML — the JSX/TSX compiler only runs on files that need it.)
169
-
170
- ## Common follow-up commands
171
-
172
- ```bash
173
- somewhere logs # tail recent function logs
174
- somewhere deploy # redeploy current directory
175
- somewhere mcp # raw stdio MCP bridge (for hosts you wire by hand)
176
- somewhere auth status # show current login
177
- ```
178
-
179
- For everything else (custom domains, project rename, env vars, billing), run
180
- `somewhere call --list` and invoke the matching platform tool, or use the
181
- dashboard at https://somewhere.cloud. Without a shell, use the matching MCP tool.
182
-
183
- ## Ephemeral environments (Claude Code Web, sandboxes, containers)
184
-
185
- This is for a machine whose home directory does NOT survive (Claude Code Web, a
186
- fresh CI container, a sandboxed runner). A hosted VM with a lasting home
187
- directory does not need it — use `somewhere auth login` above, which stays signed in
188
- across sessions.
189
-
190
- Where the home directory is discarded, the browser-based `somewhere auth login`
191
- won't survive the session — but the MCP connection already has an authenticated
192
- session. Pair the CLI to that session:
193
-
194
- ```text
195
- 1. npm i -g @somewhere-cloud/cli
196
- 2. Call MCP tool auth_cli_pair # returns { key, expires_at }
197
- 3. Put the returned key in the command environment as SOMEWHERE_TOKEN.
198
- 4. somewhere auth set # reads SOMEWHERE_TOKEN
199
- 5. somewhere whoami # confirm identity
200
- 6. somewhere deploy
201
- ```
202
-
203
- `auth_cli_pair` mints a short-lived `smt_` key (kind='cli_pair', 24h
204
- TTL) scoped to the same user as the MCP session. `somewhere auth set` stores
205
- this pairing key in the CLI config, using the identity already verified by MCP.
206
- The key auto-expires; revoke early with `DELETE /v1/keys/<id>` if you
207
- need to.
208
-
209
- Pure-MCP path (Claude.ai connector, no shell at all): skip the CLI entirely and
210
- use the platform tools directly. With a shell, `somewhere call` invokes those
211
- same tools without requiring an MCP client, while first-class commands handle
212
- the routine workflows.
@@ -1,102 +0,0 @@
1
- # Smoke tests — deploy and recurring checks
2
-
3
- Smoke checks request your homepage, custom domains and the paths you
4
- choose, then report which checks passed. Use them to catch a broken page,
5
- an unexpected status or missing data after a deploy. Authenticated probes
6
- use a fresh session for your designated test user. Check the HTTP status,
7
- that fields are present in its JSON, and that its text contains or omits
8
- what you expect.
9
-
10
- Run `site_check({ project_id: "my-app" })`. If the result is still
11
- `running`, read `site_check_status({ project_id: "my-app" })` for the
12
- finished checks. Manual and deploy-triggered checks are available on every
13
- plan. Recurring checks run on Builder and higher. Read the current interval
14
- from your plan's `smoke_cadence_minutes` in `GET /v1/pricing` → `plans`.
15
-
16
- Status per run: `pass` / `partial` / `fail`. A fail-after-pass
17
- transition is detected and alerted automatically, debounced by
18
- `alert_cooldown_seconds` (default 3600).
19
-
20
- ## MCP
21
-
22
- site_check_status({ project_id })
23
- → { latest: SmokeRun, history: SmokeRun[] }
24
-
25
- site_check({ project_id })
26
- → { run: SmokeRun } // may return status: "running"; read status next
27
-
28
- smoke_config_get({ project_id })
29
- smoke_config_update({ project_id, enabled?, test_auth_flow?, alert_cooldown_seconds?, extra_checks?, test_user_email?, canary_enabled? })
30
-
31
- `extra_checks` is an array of additional URL probes:
32
- [ { name: "users-list", path: "/api/users", expect_status: 200 }, ... ]
33
-
34
- ## Probe fields
35
-
36
- Each probe accepts:
37
-
38
- - `path` (required) — must start with `/`.
39
- - `method` — default `GET`.
40
- - `name` — label in run results (max 80 chars); auto-generated if omitted.
41
- - `expect_status` — exact HTTP status. Without it, anything below 500
42
- passes — useful for "POST /api/login with no body should be 4xx, not
43
- 500" and similar contract checks.
44
- - `headers` — extra request headers (max 10 per probe).
45
- - `body` — request body. An object is sent as JSON (Content-Type set
46
- for you); a string is sent raw. Max 8 KB.
47
- - `auth: "test_user"` — the probe runs authenticated: the platform
48
- mints a fresh session for the project's designated test user at probe
49
- time. Set the test user first with
50
- `smoke_config_update({ project_id, test_user_email })` — it must be an existing
51
- app user of the project (create one via signup). No credentials are
52
- ever stored in the manifest. When `auth` is set, the Authorization
53
- header can't be overridden via `headers`.
54
- - `expect_json_path` — dot-path (or array of them, max 10) that must
55
- resolve to a non-null value in the JSON response, e.g.
56
- `"data.reply"` or `"choices.0.message"`.
57
- - `expect_contains` / `expect_not_contains` — substrings the response
58
- text must / must not contain (string or array, max 10 each).
59
- - `expect_max_ms` — fail the probe if it takes longer than this, even
60
- on HTTP 200.
61
-
62
- ## 15-minute canary (opt-in)
63
-
64
- smoke_config_update({ project_id, canary_enabled: true })
65
-
66
- Runs the full check set (homepage + custom domains + extra_checks +
67
- `/_smoke_tests.json`) every 15 minutes, on top of the regular
68
- plan cadence. Off by default. A fail-after-pass transition alerts the
69
- project owner (debounced by `alert_cooldown_seconds`).
70
-
71
- ## Auto-detected: `/_smoke_tests.json`
72
-
73
- Deploy a JSON file at `/_smoke_tests.json` in your project and the
74
- cron picks up the entries automatically — same shape as
75
- `extra_checks`, no config call needed. Up to 20 entries per project.
76
- Useful when you want the smoke contract to ship with the code, not
77
- sit in the dashboard. With the CLI, publish the root file explicitly:
78
-
79
- somewhere deploy --include _smoke_tests.json
80
-
81
- Manifest contents:
82
-
83
- ```json
84
- [
85
- { "name": "homepage", "path": "/", "expect_status": 200 },
86
- { "name": "auth-page", "path": "/login", "expect_status": 200 },
87
- { "name": "api-list-no-auth", "path": "/api/users", "method": "GET", "expect_status": 401 }
88
- ]
89
- ```
90
-
91
- If both `extra_checks` and `/_smoke_tests.json` are present, both
92
- run — they're additive.
93
-
94
- ## Opt out
95
-
96
- smoke_config_update({ project_id: '...', enabled: false })
97
-
98
- Disabling checks stops manual runs as well as automatic checks. While
99
- disabled, `site_check` returns `400 NO_TARGETS`; set `enabled: true`
100
- before running it again. For a private app,
101
- configure authenticated probes or explicit expected status codes instead
102
- of turning checks off.
@@ -1,298 +0,0 @@
1
- # Speed
2
-
3
- Paint the screen first, start independent reads together, and measure the
4
- requests your visitor waits for. Somewhere compiles your source, delivers
5
- static assets close to visitors, and batches production reads started together:
6
-
7
- ```ts
8
- const [posts, tags] = await Promise.all([
9
- sw.db.from('posts', { where: { published: true }, order: [['created_at', 'desc']], limit: 20 }),
10
- sw.db.from('tags'),
11
- ]);
12
- ```
13
-
14
- In production, these independent reads share a database round trip. Preview
15
- and development runs send each read separately. Awaiting the first before
16
- starting the second adds another trip. Keep dependent work sequential; use
17
- `sw.db.tx` when several writes must succeed or fail together.
18
-
19
- Measure cold and warm loads in the regions your visitors use. The sections
20
- below explain page delivery, data reads, and the tools for finding slow work.
21
-
22
- ## Pages and assets
23
-
24
- Deployed source is compiled for you. The browser bundle is minified, ships no
25
- source maps, and declares its chunks up front so they load alongside the page
26
- instead of after it. Compiled assets are content-addressed: a browser and the
27
- edge can both hold one indefinitely, and a deploy produces new addresses rather
28
- than changing old ones.
29
-
30
- On your project host and on a custom domain, an ELIGIBLE public request — a
31
- `GET` or `HEAD` for a page, a compiled asset or a public file, answered from
32
- a route this location has already resolved recently — runs the routing check
33
- behind the response instead of in front of it. The trade is bounded and
34
- deliberate: for up to 60 seconds after a deploy, a location that missed the
35
- update can still answer with the previous release. Past that window, and
36
- whenever this location has no recent route to go on, the request is exact.
37
-
38
- Not every request takes that path, and none of them are slower for it: anything
39
- that is not a plain `GET`/`HEAD`, a preview or development address, a
40
- group or platform-overlay surface, and the platform's own addresses
41
- all resolve the route before answering. Those confirm the
42
- routing decision first, which is a different guarantee from being instantly
43
- consistent everywhere — a deploy still propagates.
44
-
45
- Separately from routing: eligible static pages and single-page app routes can
46
- reuse the release's stored HTML. The shared copy contains only the base page.
47
- User-specific prefetched data is added afterwards for each request, using that
48
- request's identity and the current release's function. That personalized
49
- response is private and must not be cached. Preview, development, grouped and
50
- overlay views keep their existing serving path.
51
-
52
- ## Choosing whether to use shared copies
53
-
54
- Control shared copies of pages, static assets and eligible public-data
55
- responses through `PATCH /v1/projects/:id`. Set `edge_cache_disabled: true` to
56
- turn shared caching off. Set it to `false` to restore the default. This uses the existing project editor
57
- permission. The saved boolean is returned by the project API.
58
-
59
- Turning shared caching off starts clearing existing copies; it is not an instant global
60
- flush. Copies can remain for up to about an hour if clearing fails. Browser
61
- copies already downloaded are separate and are not removed by this setting.
62
- Authenticated page data still uses the requesting visitor's identity; this
63
- switch does not grant access to private data.
64
-
65
- ## Deploy performance hints
66
-
67
- A deploy can return a small number of warnings about absolute stylesheet
68
- references, large images referenced by source, or repeated awaited raw SQL
69
- calls. Each names the source location and the bytes or calls observed, with
70
- an action to consider. These are warnings, never deploy refusals or measured
71
- latency claims. The scan is bounded: it flags recognizable shapes and does not
72
- inspect every possible execution path. For visitor performance, with or
73
- without warnings, measure the real page's cold and warm loads and its request
74
- waterfall.
75
-
76
- ## Server-rendered pages and the SPA
77
-
78
- A function can return HTML rendered on the server. Declare a root
79
- `[...path].ts` route for document paths, including `/`, `/articles/example`
80
- and `/sitemap.xml`. This is explicit Request/Response code, not automatic
81
- framework rendering or deploy-time pre-rendering. See `functions` →
82
- `server-rendered-pages-alongside-the-spa` for a complete route.
83
-
84
- Keep the SPA shell in `index.html`. The catch-all can decline `/` with
85
- `Response.json({ error: 'FUNCTION_NOT_FOUND' }, { status: 404 })`; the
86
- platform then serves the normal static/SPA path at the same URL. An HTML 404
87
- from the function remains a 404. A database read before returning HTML adds
88
- its latency to the first paint; use server rendering when the initial document
89
- needs that content, and browser fetching for data that can arrive afterwards.
90
-
91
- ## Page data with the document
92
-
93
- This is opt-in. It runs only for a release whose own JavaScript reads
94
- `window.__PREFETCH`; the starter and the SDK do not read it. For such a
95
- release, a page request carrying a session cookie or bearer token makes the
96
- platform try the matching `/api/<path>` function with those same
97
- credentials. The function verifies the caller and decides what data to
98
- return. This applies to `GET` requests for page paths other than `/` and
99
- `/api/*` when the project has functions.
100
-
101
- A `200` JSON answer is added as `window.__PREFETCH`, with
102
- `window.__PREFETCH_PATH` naming its source. The headers and body share a
103
- 1-second deadline and a 100 KiB body
104
- limit. A missing route, error, invalid JSON, or exceeded limit leaves the
105
- original page unchanged. Check for the global and fetch normally when absent.
106
-
107
- The personalized response is private and cannot be stored in shared caches.
108
- The platform stores only the base HTML and adds this data for each request.
109
-
110
- ## What a database call costs
111
-
112
- Your function runs close to the visitor, and reaching the database is a
113
- network round trip. Writes reach the database primary; eligible reads may be
114
- served closer to the reader. Either way, sequential database calls can still
115
- incur separate round trips — and a round trip carries a BATCH of statements,
116
- not one statement, so statements your handler sends together share one while
117
- statements it awaits one after another each pay their own.
118
-
119
- For an ordinary indexed read of a modest number of rows, the crossing is
120
- usually the larger share of the time and the distance to the database is the
121
- term that moves it most. That is not universal — a wide scan, a big sort, an
122
- unindexed filter or an aggregate over a large table can spend more time in the
123
- query engine than on the wire, and no amount of batching helps with that. The
124
- two problems look identical from the outside and have opposite fixes, so
125
- measure (last section) before deciding which one you have.
126
-
127
- The habit that follows: count the ROUND TRIPS a handler makes, then check
128
- whether any single statement is doing too much work.
129
-
130
- Composed calls — `sw.db.from` / `count` / `aggregate` / `insert` /
131
- `update` / `remove` / `tx` — run on the project's own database connection.
132
- That is the ordinary path and the fast one. Start there.
133
-
134
- ## Reads issued together travel together
135
-
136
- The `Promise.all` example above starts both reads before awaiting either.
137
- Production reads through the project database connection are batched automatically;
138
- preview and development reads are sent separately. Each awaited write is its
139
- own trip; `sw.db.tx([...])` sends its steps in one atomic request, one
140
- `insert` step per row (`recipe-csv-import`). Raw `batch` never writes
141
- declared tables.
142
-
143
- ## Dependent reads: bound the number of round trips
144
-
145
- The expensive shape is a read per row — fetch 50 tasks, then fetch each task's
146
- project. Declaring the relationship replaces that with a fixed cost:
147
-
148
- ```ts
149
- // a declared belongsTo relation
150
- const tasks = await sw.db.from('tasks', { include: ['project'], limit: 50 });
151
- ```
152
-
153
- `include` reads the root rows, then reads the related rows in bounded
154
- batches rather than one query per row. The number of database round trips
155
- grows with the relations you include and with the number of key batches, not
156
- with the rows themselves. It is the fix for the read-per-row loop, not a way to
157
- reach one round trip, and it is deliberately not a single snapshot.
158
-
159
- `sw.db.aggregate` genuinely is one statement, and it is the right answer
160
- whenever you were about to read rows only to count, total or group them:
161
-
162
- ```ts
163
- const byStatus = await sw.db.aggregate('orders', { count: true, groupBy: ['status'] });
164
- ```
165
-
166
- `include`, `has` and `sw.db.aggregate` all carry the caller's row
167
- permissions into the question the platform composes; `docs({ topic: 'sw.db' })`
168
- has their full contracts. When a read genuinely cannot be expressed this way it
169
- stays sequential. That is a correct program, just a slower one.
170
-
171
- ## What raw server SQL costs
172
-
173
- On a project with a declared schema, ordinary `sw.db.query` and
174
- `sw.db.batch` are refused. The escape hatch is `sw.db.server.query` /
175
- `sw.db.server.batch`. They also do not apply declared row permissions —
176
- authorize the caller yourself before calling them.
177
-
178
- Where the extra cost comes from: a declared structured operation can run on
179
- the project's own database connection, while an explicit server statement goes
180
- as a separate platform request that then reaches the database through the
181
- provider's authorized read-only API. That is more network requests per
182
- statement, and more requests can add latency. How much, and whether it matters
183
- for a given statement, depends on your workload and where things sit — so
184
- measure your own app rather than budgeting from a figure.
185
-
186
- So, in order:
187
-
188
- 1. Try to express it as a composed call. An `include`, a `has` filter or an
189
- `aggregate` usually covers what the raw read was for, on the faster route
190
- and with permissions already applied.
191
- 2. If you do need raw reads and they are independent of each other, send them
192
- in ONE call rather than awaiting several:
193
-
194
- ```ts
195
- // Server authority reads ACROSS users. Authorize the caller first — the
196
- // platform applies no row permissions to these statements.
197
- const actor = await sw.auth.fromRequest(req);
198
- if (!actor || actor.role !== 'admin') return new Response('Forbidden', { status: 403 });
199
-
200
- const since = new Date(Date.now() - 7 * 86_400_000).toISOString(); // last 7 days
201
- const [recent, totals] = await sw.db.server.batch([
202
- { sql: 'SELECT id, email FROM users WHERE created_at > ?', params: [since] },
203
- { sql: 'SELECT status, COUNT(*) AS n FROM orders GROUP BY status' },
204
- ]);
205
- // One result per statement, in order; rows are on .data
206
- // recent.data -> [{ id, email }, ...] totals.data -> [{ status, n }, ...]
207
- ```
208
-
209
- Dependent raw reads stay sequential, for the same reason dependent composed
210
- reads do.
211
-
212
- ## Writes, permissions, and freshness
213
-
214
- Three different guarantees get confused with each other. Keeping them apart is
215
- most of what you need:
216
-
217
- **Access checks remain enforced.** Session revocation checks read current
218
- authority. Structured queries apply declared row permissions; policy shapes
219
- that depend on mutable membership or parent authority retain their
220
- primary-read requirements. Identity-bearing requests bypass the shared
221
- public-result cache. Ordinary row reads still follow the consistency rules
222
- below.
223
-
224
- **Declared constraints and the conditions in an atomic write are checked when
225
- it commits.** Express balances, inventory and limits with those operations:
226
- reading a value and later writing a replacement does not prevent concurrent
227
- lost updates. The response to a write describes what committed.
228
-
229
- **Reading your own write is a carried position, not magic.** Your database may
230
- answer a read from a copy kept nearer the reader, which can be slightly behind.
231
- To make that safe, a response from your function publishes the position it
232
- reached — as an `x-sw-d1-bookmark` response header, and for browsers as a
233
- short-lived host-only cookie — and the next request presenting that position is
234
- answered at or after it. So a browser that just wrote through your app sees its
235
- own write on its next call. The conditions are worth knowing, because they are
236
- where the guarantee ends: the carried position is short-lived (about a minute),
237
- it belongs to that one client, and a DIFFERENT client, a later visit, or a
238
- request that never carried it can be answered from a copy that is slightly
239
- behind. This is another reason a read-then-write pair is the wrong shape for a
240
- balance or a seat count: put the condition in the write.
241
-
242
- **Public data is the one deliberate trade.** Anonymous reads of data you
243
- explicitly declared public may be answered from a shared copy kept near
244
- readers; a committed declared write drops that copy, and a copy that was missed
245
- expires on its own. `docs({ topic: 'declared-data' })` carries that contract in
246
- full — read it before building on public data that can be withdrawn.
247
-
248
- ## Files
249
-
250
- A public file is served from a nearby copy once it has been fetched there. A
251
- file reached through a signed link is cacheable only by the browser holding
252
- that link, for as long as the link is valid, and is fetched from storage
253
- otherwise.
254
-
255
- ## Measure your own app
256
-
257
- A function's clock advances across awaited work, so `Date.now()` around an
258
- awaited database call measures that call's round trip honestly. The same
259
- measurement around work that never awaits anything reads 0 — that is a property
260
- of the runtime clock, not a sign the work was free.
261
-
262
- ```ts
263
- const started = Date.now();
264
- const posts = await sw.db.from('posts', { limit: 20 });
265
- sw.logs.info('posts read', { ms: Date.now() - started, rows: posts.data.length });
266
- ```
267
-
268
- Read the result back with `project_logs`, which also reports each request's
269
- own duration. Compare warm requests with warm requests: the first request into
270
- a freshly deployed release does one-time work the next one does not, so it
271
- belongs to its own cohort and is not the number to plan against.
272
-
273
- Related: `sw.db`, `declared-data`, `database-engine`, `deploy`,
274
- `sw.logs`.
275
-
276
- ## Image and font caching
277
-
278
- Import images and fonts from source, or reference them with CSS `url()`, to
279
- ship them at content-hashed `/_compiled/` addresses. PNG, JPEG, GIF, WebP, AVIF,
280
- SVG, ICO, WOFF, WOFF2, TTF and OTF assets use the same
281
- `public, max-age=31536000, immutable` policy as compiled scripts and styles.
282
- Changing an asset changes its address; HTML references to emitted assets are
283
- rewritten too.
284
-
285
- Fixed-name media from `public/` or `static/` has a bounded policy:
286
- `public, max-age=60, stale-while-revalidate=60`, with an ETag. A changed file
287
- can remain cached for at most two minutes. This policy requires source-folder
288
- provenance from a new deployment; older deployments retain revalidation. It
289
- does not apply to HTML, API responses or authenticated views. Deploy and
290
- deploy-check name static-folder images or fonts of at least 32 KiB and suggest
291
- importing them from source for a permanent address.
292
-
293
- Project public configuration is inlined before module execution on ordinary
294
- HTML document requests. The external no-store script remains a fallback; it
295
- is not a shared cache across projects.
296
-
297
- Use `deploy-check` to check imported media and static-folder cache notices
298
- before publishing. It leaves the current app version unchanged.