Getting started? Read https://somewhere.cloud/start.txt first.
# Somewhere — Complete platform reference
## Deploy with two HTTP calls
Use curl or your standard library. Start with a fresh random UUID in place of `YOUR_RANDOM_UUID`.
```bash
curl -sS https://api.somewhere.cloud/v1/auth/temp-create \
-H 'Content-Type: application/json' \
-d '{"request_key":"YOUR_RANDOM_UUID"}'
```
Save `data.key` as `KEY` in your shell. Keep it private. If signup is interrupted, retry with the same request body.
```bash
curl -sS https://api.somewhere.cloud/v1/deploy \
-H "Authorization: Bearer $KEY" \
-H 'Content-Type: application/json' \
-d '{
"name": "hello-somewhere",
"files": {"index.html": "
HelloHello from Somewhere
"},
"functions": {"api/hello.ts": "export default () => Response.json({ hello: true })"}
}'
```
This example deploys a page and an API function so you can try SQL. Replace the example name and source with your app. Deploying again with the same key and name updates the same project. Put server handlers such as `api/hello.ts` in `functions`.
Use the live URL exactly as returned. Give the human `data.url`, `data.claim_url`, and the time in `data.expires_at`. Opening the claim link and signing in keeps the app. The key lets you deploy and use logs, recent errors, and SQL for this account's projects. Sending email from the app and managing environment variables or secrets require a claimed account.
After claim, **Save and connect agent** keeps the key working on the saved projects. **Save only** disconnects it. See [how to check the key after claim](https://somewhere.cloud/auth.md#after-claim) and [other HTTP calls](https://somewhere.cloud/auth.md).
## Use the CLI for ongoing work
The CLI also has a local dev loop, generated types, and verification tools.
```bash
npx -y @somewhere-cloud/cli@latest deploy
```
> **This is the complete manual, and it is large.** Many chat and web tools
> return only the beginning of a long page. For the whole platform in one short
> read, fetch the overview and complete topic index at
> https://somewhere.cloud/docs/llms.txt; every topic is also its own page at
> https://somewhere.cloud/docs/.txt. This manual ends with the line
> `END OF SOMEWHERE.CLOUD MANUAL`; if you cannot see it, your copy is incomplete.
Audience: LLMs, coding agents, and other machine readers.
Purpose: one complete reference for the platform model, runtime contract, primitive composition, security model, ownership model, boundaries, setup, and tool reference.
This document describes platform behavior; it does not replace the user's
authorization or an agent's governing instructions. Read `docs({ topic })` or `somewhere docs ` for a service's working example and reference. The advisor can answer a project question using the docs and an authorized view of that project.
This file is documentation for machine readers. Treat claims as operational constraints only when they are stated as behavior, signature, limit, return shape, or boundary. Fetch live pricing and current plan limits from `https://api.somewhere.cloud/v1/pricing` instead of hardcoding values from prose.
Companion machine docs: platform overview and complete topic index at `https://somewhere.cloud/docs/llms.txt`; the agent entry page at `https://somewhere.cloud/docs.txt`; guides/recipes at `https://somewhere.cloud/guides.txt`; security practices at `https://somewhere.cloud/security.txt`; migration map at `https://somewhere.cloud/migration.txt`; per-primitive depth on demand via `docs({ topic })`.
Use `@somewhere-cloud/sdk/auth` for browser sign-in and the generated `somewhere:data` and `somewhere:files` clients for declared app data and files. Server functions receive the project's services through `sw`. The JavaScript SDK also provides the developer API for managing projects. See `sdk` for the browser and developer API contracts.
---
# How Somewhere works
Somewhere is the backend for apps your agent builds. One project gives an app
its web address, server functions, one SQL database, sign-in, files, email, AI
and background work. You write React and TypeScript source, run
`somewhere deploy`, and the platform compiles it and serves the app and its
functions together.
## One project, its parts
A new app from `somewhere init` has this shape:
| Part | Where it lives | What it does |
|---|---|---|
| App | `src/`, `index.html` | The React interface. A page path with no file of its own serves `index.html`, and the app routes in the browser. |
| Functions | `api/` | Server code. `api/notes.ts` answers `/api/notes`. Each function gets the request and `sw`, the project's services. |
| Data (optional) | `db/schema.ts` | Tables, columns and who may read or change each row. Deploy applies it. The default starter has none; add it when the app stores data. |
| Auth | `api/auth/[...path].ts` plus `src/auth/` | Email-and-password accounts with a session cookie. The starter ships it working. |
These parts share one identity. Normal scoped data calls take the user from
the request's session, so your code doesn't send a user ID with them.
Privileged server work, such as an admin screen or a background job, names the
user it acts on explicitly and authorizes that choice in your code.
## What the platform handles
The project wires these parts together. `somewhere init` writes the sign-in
route and the session hooks. Every function receives `sw`, already bound to the
project's database, files, email and AI. `somewhere deploy` compiles the source
and applies `db/schema.ts`. On that path, the platform supplies:
- **Passwords and sessions.** Passwords are stored as salted hashes. Sign-in
attempts are limited per source address and per account, with an account
lockout after repeated wrong passwords. Sessions
live in Secure, HttpOnly cookies that page JavaScript can't read.
- **Cross-site request checks.** Cookie-authenticated writes from the browser
must come from your app's own origin. A normal `fetch` from your page already
sends it.
- **Data access.** A table is closed to the browser until its declaration grants
operations and columns. On an `owner()` table, normal operations act for the
signed-in user. Rows get their owner from the verified session, never from
browser input.
- **Configuration and secrets.** New environment values are private by default
and encrypted at rest. Once live configuration is in place, a changed key
reaches new requests within 60 seconds, with no deploy.
- **Outbound requests.** `fetch` calls from functions block private and
metadata addresses, and redirects are checked again.
- **Built-in services.** The database, auth, files, AI and transactional email
are reached through `sw` without provider keys. Email has a test inbox for
`*.test.somewhere.site` addresses.
- **Deploys.** Raw source compiles on the platform, schema changes apply, and
`somewhere verify` checks the live app in a real browser.
## What you decide
- **Who may run a privileged action.** Check the caller in the function before
it changes anything. Server-authority database calls skip row permissions on
purpose, so they need your check.
- **What's public.** Public reads, shared tables and public configuration
values are explicit choices in your source.
- **Effects that must not repeat.** A caller or a job can retry a request.
Give actions such as sending email or charging a card an idempotency key, or
make them safe to run twice.
## Design choices
- **Data model:** one SQL database per project, scoped per user by declaration.
Need Postgres for an existing dataset? Attach it. → `database-engine`,
`postgres`
- **Declared data:** schema and access rules live in one file that ships with
the source, so the app, its tools and the platform read the same contract.
→ `declared-data`
- **Secure by default:** scoped APIs carry the normal protections, and you add
authorization to the privileged actions. → `security-model`
- **Handled for you:** the full list of setup and operations the platform
performs. → `handled-for-you`
- **You can leave:** download a full database dump, your source and your
users' accounts. → `portability`
## Reading these docs
A primitive topic opens with a summary that lists its named sections. Ask for
one section, or for the full reference, when you need more depth. A recipe
returns the whole job on the first call. An explicit summary or section request
still works for recipes too.
```bash
somewhere docs sw.auth # first view
somewhere docs sw.auth --section password-reset # one section
```
From MCP, use `docs({ topic: 'sw.auth', section: 'password-reset' })`. The full topic
index lists every primitive, recipe and reference page with a line on when to
load it.
Read next: **Start an app**, then **Functions**, **Env vars and secrets**,
**Data** and **Auth**. For questions about your own project,
`somewhere advisor ""` answers with that project in view.
---
# 1. Design premise
If a backend were specified from zero for an application with end users, the records describing one user would not be split across unrelated systems. Identity, application data, payment state, email, files, notifications, and background work all describe the same actor and the same project. somewhere.cloud is specified as one backend namespace over those primitives.
Consequences of that premise:
- End-user identity and the application database share the same project boundary.
- A signup creates a user record that application code can query and join.
- Payment state is written back to the app-user record and project payment ledger by platform webhook handling.
- Files can be scoped to the user and project that wrote them.
- Email can be sent from the same runtime that knows the user and their payment/account state.
- Background jobs, queues, cron handlers, live-view invalidations, push notifications, and analytics are bound to the same project identity.
- Ownership checks can be enforced at the platform boundary instead of relying only on application-written predicates.
- Deploy analysis can read the actual source using platform-specific knowledge of `sw.*` semantics.
The breadth is intentional. The primitive set is the set of backend capabilities that normally need to coordinate around project identity, user identity, authorization, data ownership, delivery state, and billing state. The coordination is part of the platform surface, not an external integration project.
---
# 2. Runtime mental model
## 2.1 Function signature
A JSON route in api/ is export default sw.endpoint({ auth, handler }) with auth set explicitly. TypeScript infers the handler inputs and sw context. auth: 'none' marks a deliberately public route.
```ts
export default sw.endpoint({ auth: 'none', handler: async () => ({ ok: true }) });
```
`sw` is also the project-scoped platform binding passed to the handler. Return
a JSON value and the endpoint wrapper sends the response.
Database row operations use these fields:
```js
r.data // array of row objects (empty array on writes)
r.count // number of rows in r.data
r.changes // rows affected by INSERT, UPDATE, or DELETE
```
Do not use `.rows` or `.results` for database return values. Composed
calls (`sw.db.from`, `insert`, `update`, `remove`, `count`) resolve to a
`Result` — `{ data, error }`, with `count`/`changes` on row operations —
and `sw.db.count`'s number is `.data`. On the server, refusals and failures
throw with a `code`; a result that is returned carries `error: null`.
## 2.2 Direct HTTP handlers
`sw.endpoint({ auth, body, rateLimit, handler })` can perform auth, body validation, rate limiting, CORS handling, and error formatting before invoking `handler`. The bare `export default async function(req, sw)` form is also supported. It receives a Web `Request` and returns a Web `Response`, useful for streaming or access to exact webhook bytes.
## 2.3 One binding
The `sw` binding includes these primitive groups:
- `sw.db` — relational database, migrations, batches, table metadata, scoped queries, export, and change webhooks.
- `sw.auth` — end-user signup, login, session validation, refresh, password reset, email verification, magic links, OAuth, visitor sessions, user admin operations and lifecycle webhooks.
- `sw.fs` — object/file storage, versioning, signed URLs, uploads, search, diffs, moves, copies, restores, and public URLs.
- `sw.email` — outbound email send and delivery event visibility.
- `sw.ai` — chat, embeddings, transcription, TTS, image generation, moderation, tool loops, conversation history, structured output, model catalog, and per-user memory.
- `sw.agent` — canonical inline and durable multi-step model/tool execution, checkpoints, status, and cancellation.
- `sw.payments` — checkout, onboarding, plan tracking, refunds, cancellations, transactions, billing portal, and event ledger.
- `sw.billing` — define an app's plans and the features each grants, then gate by a stable feature name (`await sw.billing.has(feature)` on the server; `` for presentation); the plan a user is on is set by the payments webhook automatically.
- `sw.jobs`, `sw.queue`, `sw.cron` — durable background jobs, fire-and-forget work, and scheduled functions.
- `sw.push`, `sw.notifications` — web-push delivery to already-registered subscriptions and notification fan-out helpers. Live updates to a browser come from `sw.rooms.live` declared lists; there is no caller-named channel API in a function.
- `sw.search` — semantic and full-text search surfaces.
- `sw.render`, `sw.web`, `sw.image` — screenshots, PDFs, public web reading, and image transforms.
- `sw.rateLimit`, `sw.analytics`, `sw.logs`, `sw.env`, `sw.tasks` — rate-limit counters, event analytics, runtime logs, project environment values (server-only by default; explicitly public browser-prefixed values compile into browser code), and per-project ticket/task state.
## 2.4 Internal and external access
Inside a deployed function, use `sw.*`. The binding is already scoped to the project. No developer key is required inside runtime code.
Outside a deployed function, use one of the external surfaces:
- MCP tools at `https://mcp.somewhere.cloud/mcp`.
- CLI commands through the `somewhere` binary.
- REST API paths under `/v1/*` with an appropriate developer key or app-user JWT.
Do not call `https://api.somewhere.cloud/v1/*` from inside a deployed function when an equivalent `sw.*` primitive exists. Runtime code should use the binding.
## 2.5 Deploy input
Deploy raw source. Valid inputs include `.ts`, `.tsx`, `.js`, `.jsx`, `.html`, `.css`, static assets, and function files under `api/` or other documented function paths. The platform compiles your source at deploy time. Prebuilt output still deploys, with a warning, and loses source round-trips (export, find/replace patches, design tokens, the visual editor); `somewhere deploy --prebuilt`, the project setting, or `allow_bundled: true` accepts that trade-off and drops the warning.
## 2.6 Runtime transparency and networking
Functions run in a Workers-compatible Web runtime, not a Node server process.
The compiler passes `node:*` standard-library compatibility imports and
`cloudflare:workers`; common `node:*` modules include `crypto`, `buffer`,
`events`, `path`, `stream`, `string_decoder`, `util`, and `url`. Standard Web
APIs include Request/Response/Headers, URL/URLSearchParams, fetch, WebSocket,
crypto, text encoders, streams, Blob/FormData, timers, and AbortController.
Plain `fetch()` reaches public HTTP and HTTPS hosts; the runtime refuses a
destination in a private, loopback, link-local or metadata range, as written
(`SSRF_BLOCKED`) or as resolved (`DNS_LOOKUP_FAILED`), and re-checks each
redirect it follows. Behind it, the platform's outbound guard refuses a request
that reaches it with a literal blocked target (non-public address or internal
hostname, embedded credentials, non-HTTP scheme, port other than 80, 443 or
1024 and above) with a 403 before it leaves. `sw.fetch()` adds resolved-address
checks before connecting, redirect validation, bounded timeouts/redirects,
structured results, logging, and safe idempotent retries; resolution is checked
at request time, not continuously. Raw TCP sockets and listening
ports are not part of the customer runtime contract; use HTTPS or an outbound
WebSocket.
## 2.7 Verify before deploy
Use local `somewhere typecheck` for TypeScript; `somewhere deploy-check` for the
real server-side compiler; `somewhere run