@somewhere-cloud/cli 0.38.155 → 0.38.157
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -1
- package/dist/commands/docs.js +1 -1
- package/dist/lib/bundle.js +286 -188
- package/dist/lib/bundle.js.map +3 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -3
- package/dist/docs/adopt.md +0 -39
- package/dist/docs/analytics.md +0 -161
- package/dist/docs/api-reference.md +0 -339
- package/dist/docs/api-surface.md +0 -2067
- package/dist/docs/app-mcp.md +0 -162
- package/dist/docs/architecture-patterns.md +0 -334
- package/dist/docs/auth-client.md +0 -531
- package/dist/docs/billing.md +0 -76
- package/dist/docs/browser.md +0 -639
- package/dist/docs/calendar.md +0 -298
- package/dist/docs/changes.md +0 -323
- package/dist/docs/cli.md +0 -407
- package/dist/docs/common-mistakes.md +0 -199
- package/dist/docs/connect-agent.md +0 -72
- package/dist/docs/cors.md +0 -114
- package/dist/docs/cron.md +0 -167
- package/dist/docs/database-engine.md +0 -167
- package/dist/docs/declared-data.md +0 -1656
- package/dist/docs/declared-files.md +0 -475
- package/dist/docs/deploy-intelligence.md +0 -188
- package/dist/docs/deploy.md +0 -733
- package/dist/docs/design-system.md +0 -273
- package/dist/docs/dev-environments.md +0 -496
- package/dist/docs/domain-ownership.md +0 -31
- package/dist/docs/domains.md +0 -370
- package/dist/docs/feedback.md +0 -88
- package/dist/docs/file-tools.md +0 -116
- package/dist/docs/functions.md +0 -489
- package/dist/docs/getting-started.md +0 -238
- package/dist/docs/github.md +0 -95
- package/dist/docs/google-calendar.md +0 -212
- package/dist/docs/groups.md +0 -836
- package/dist/docs/guarantees.md +0 -58
- package/dist/docs/handled-for-you.md +0 -224
- package/dist/docs/inspect.md +0 -171
- package/dist/docs/limits.md +0 -68
- package/dist/docs/live-data.md +0 -197
- package/dist/docs/live.md +0 -92
- package/dist/docs/local-dev.md +0 -30
- package/dist/docs/migration-supabase.md +0 -58
- package/dist/docs/payments.md +0 -1102
- package/dist/docs/portability.md +0 -194
- package/dist/docs/postgres.md +0 -301
- package/dist/docs/pricing-comparison.md +0 -42
- package/dist/docs/pricing.md +0 -39
- package/dist/docs/project-groups.md +0 -107
- package/dist/docs/projects.md +0 -380
- package/dist/docs/recipe-ai-agent.md +0 -112
- package/dist/docs/recipe-ai-features.md +0 -227
- package/dist/docs/recipe-ai-receipts.md +0 -783
- package/dist/docs/recipe-background-jobs.md +0 -369
- package/dist/docs/recipe-booking.md +0 -348
- package/dist/docs/recipe-csv-import.md +0 -390
- package/dist/docs/recipe-ecommerce.md +0 -127
- package/dist/docs/recipe-email.md +0 -282
- package/dist/docs/recipe-escalation.md +0 -133
- package/dist/docs/recipe-file-uploads.md +0 -159
- package/dist/docs/recipe-import-app.md +0 -110
- package/dist/docs/recipe-login.md +0 -457
- package/dist/docs/recipe-multi-chat.md +0 -198
- package/dist/docs/recipe-paid-api.md +0 -161
- package/dist/docs/recipe-pdfs.md +0 -205
- package/dist/docs/recipe-push-notifications.md +0 -107
- package/dist/docs/recipe-seo.md +0 -200
- package/dist/docs/recipe-signed-in-app.md +0 -330
- package/dist/docs/render.md +0 -99
- package/dist/docs/rooms.md +0 -554
- package/dist/docs/sdk.md +0 -287
- package/dist/docs/sdks.md +0 -24
- package/dist/docs/search.md +0 -199
- package/dist/docs/security-model.md +0 -168
- package/dist/docs/setup.md +0 -212
- package/dist/docs/smoke.md +0 -102
- package/dist/docs/speed.md +0 -298
- package/dist/docs/sql-compatibility.md +0 -96
- package/dist/docs/sw.agent.md +0 -248
- package/dist/docs/sw.ai.md +0 -1291
- package/dist/docs/sw.auth.md +0 -1811
- package/dist/docs/sw.billing.md +0 -171
- package/dist/docs/sw.db.md +0 -2128
- package/dist/docs/sw.email.md +0 -661
- package/dist/docs/sw.endpoint.md +0 -187
- package/dist/docs/sw.env.md +0 -303
- package/dist/docs/sw.fetch.md +0 -115
- package/dist/docs/sw.fs.md +0 -424
- package/dist/docs/sw.groups.md +0 -836
- package/dist/docs/sw.image.md +0 -69
- package/dist/docs/sw.jobs.md +0 -520
- package/dist/docs/sw.logs.md +0 -61
- package/dist/docs/sw.mail.md +0 -106
- package/dist/docs/sw.notifications.md +0 -78
- package/dist/docs/sw.push.md +0 -161
- package/dist/docs/sw.rateLimit.md +0 -67
- package/dist/docs/sw.web.md +0 -128
- package/dist/docs/tasks.md +0 -269
- package/dist/docs/test.md +0 -220
- package/dist/docs/tool-reference-account.md +0 -7
- package/dist/docs/tool-reference-ai.md +0 -121
- package/dist/docs/tool-reference-analytics.md +0 -37
- package/dist/docs/tool-reference-api.md +0 -19
- package/dist/docs/tool-reference-artifacts.md +0 -35
- package/dist/docs/tool-reference-auth.md +0 -163
- package/dist/docs/tool-reference-browser.md +0 -114
- package/dist/docs/tool-reference-code.md +0 -26
- package/dist/docs/tool-reference-connect.md +0 -21
- package/dist/docs/tool-reference-cron.md +0 -48
- package/dist/docs/tool-reference-db.md +0 -282
- package/dist/docs/tool-reference-domains.md +0 -107
- package/dist/docs/tool-reference-email.md +0 -55
- package/dist/docs/tool-reference-env.md +0 -19
- package/dist/docs/tool-reference-feedback.md +0 -56
- package/dist/docs/tool-reference-fs.md +0 -265
- package/dist/docs/tool-reference-github.md +0 -57
- package/dist/docs/tool-reference-groups.md +0 -85
- package/dist/docs/tool-reference-help.md +0 -29
- package/dist/docs/tool-reference-jobs.md +0 -39
- package/dist/docs/tool-reference-live.md +0 -48
- package/dist/docs/tool-reference-logs.md +0 -16
- package/dist/docs/tool-reference-payments.md +0 -44
- package/dist/docs/tool-reference-project.md +0 -706
- package/dist/docs/tool-reference-push.md +0 -78
- package/dist/docs/tool-reference-rate-limit.md +0 -18
- package/dist/docs/tool-reference-search.md +0 -68
- package/dist/docs/tool-reference-security.md +0 -42
- package/dist/docs/tool-reference-smoke.md +0 -17
- package/dist/docs/tool-reference-stock-photos.md +0 -20
- package/dist/docs/tool-reference-tasks.md +0 -73
- package/dist/docs/tool-reference-telegram.md +0 -32
- package/dist/docs/tool-reference-usage.md +0 -9
- package/dist/docs/tool-reference-web.md +0 -71
- package/dist/docs/tool-reference-webhooks.md +0 -9
- package/dist/docs/troubleshooting.md +0 -411
- package/dist/docs/typed-functions.md +0 -94
- package/dist/docs/verify-before-deploy.md +0 -67
- package/dist/docs/vs-supabase.md +0 -75
- package/dist/docs/vs-vercel.md +0 -103
package/dist/docs/sw.fs.md
DELETED
|
@@ -1,424 +0,0 @@
|
|
|
1
|
-
# sw.fs — File Storage (inside deployed functions)
|
|
2
|
-
|
|
3
|
-
Read, write, delete, and manage files in the project's storage.
|
|
4
|
-
Call these methods directly in your function; there's no URL to build and
|
|
5
|
-
no key to pass. Files are PRIVATE by default — pass
|
|
6
|
-
`visibility: 'public'` on the write (or call the make-public action)
|
|
7
|
-
to serve a file at its public `/storage` URL.
|
|
8
|
-
|
|
9
|
-
App users reach a file only where a rule gives it to them. `sw.fs` acts as
|
|
10
|
-
the signed-in user of the request (with no valid signed-in user it throws
|
|
11
|
-
`AUTH_REQUIRED`, 401, before any file is touched), and that user may:
|
|
12
|
-
|
|
13
|
-
- use the files of a declared file collection, as its rules allow;
|
|
14
|
-
- read a public file;
|
|
15
|
-
- read and change a file they already own.
|
|
16
|
-
|
|
17
|
-
Nothing else. A signed-in `sw.fs` call cannot create a file outside a
|
|
18
|
-
collection, and cannot read or change the project's files (files you or your
|
|
19
|
-
functions wrote with `sw.fs.server` or your developer key): writes answer
|
|
20
|
-
403 `FILE_ACCESS_DENIED`, reads 404 `NOT_FOUND`. The answer is the same
|
|
21
|
-
whether or not something exists at the path.
|
|
22
|
-
|
|
23
|
-
Files a function keeps for a user, like the examples below, use
|
|
24
|
-
`sw.fs.server` after the function's own check, with the path confined to
|
|
25
|
-
that user (`/uploads/${user.id}/…`). Never pass a path the caller chose.
|
|
26
|
-
Work that runs without a user, such as a cron or a queue message, uses
|
|
27
|
-
`sw.fs.server` the same way. A public file's URL stays public to everyone.
|
|
28
|
-
|
|
29
|
-
Browser uploads with per-user or per-team rules need no function: declare a
|
|
30
|
-
file collection in `db/schema.ts` and use `somewhere:files`
|
|
31
|
-
(`docs({ topic: 'declared-files' })`). `sw.fs.server.setOwner(path, userId,
|
|
32
|
-
{ collection })` adopts an existing file into a collection.
|
|
33
|
-
|
|
34
|
-
There are two file surfaces: deployed source is read with
|
|
35
|
-
`project_files_list` / `project_file_read`; `sw.fs` is runtime
|
|
36
|
-
storage for uploads and generated files. If you want `src/App.tsx`
|
|
37
|
-
or `api/foo.ts`, use `project_file_read`, not `sw.fs.read`.
|
|
38
|
-
|
|
39
|
-
## What you get out of the box (the industry-standard checklist)
|
|
40
|
-
|
|
41
|
-
- **File-level ACL (visibility).** Every file row carries a
|
|
42
|
-
`visibility` flag (`public` | `private`); the platform checks
|
|
43
|
-
it before bytes go out the door. Bucket-level ACLs alone can't
|
|
44
|
-
give you private-by-row.
|
|
45
|
-
- **Object versioning + content-addressed writes.** Every write
|
|
46
|
-
generates a new immutable object with a content-hash suffix and
|
|
47
|
-
swaps the metadata pointer atomically. A half-written file never
|
|
48
|
-
becomes visible.
|
|
49
|
-
- **Safe delete.** A delete removes the file's record first and its
|
|
50
|
-
stored bytes afterwards, so a deleted file is never left listed without
|
|
51
|
-
its bytes. If a read finds a file's bytes missing, it answers
|
|
52
|
-
`NOT_FOUND` and removes the record; a developer can check a whole
|
|
53
|
-
project with `file-tools` → `integrity-check-orphan-file-records`.
|
|
54
|
-
- **Versions + retention** by tier (3 / 10 / 50 / unlimited prior
|
|
55
|
-
versions kept).
|
|
56
|
-
- **Signed URLs with TTL** via `sw.fs.signedUrl(path, { expiresIn })`.
|
|
57
|
-
- **SSRF protection on every platform-side fetch** (render, scrape,
|
|
58
|
-
webhooks, AI ingest) — private and metadata IPs blocked before
|
|
59
|
-
the request leaves.
|
|
60
|
-
- **Project-wide search, glob and diff** for developers and agents:
|
|
61
|
-
`file-tools`.
|
|
62
|
-
|
|
63
|
-
Full reviewer-facing depth: <https://somewhere.cloud/docs/llms.txt>.
|
|
64
|
-
|
|
65
|
-
## sw.fs.write(path, content, options?)
|
|
66
|
-
```ts
|
|
67
|
-
// api/avatar.ts — store the signed-in user's avatar from the request body
|
|
68
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
69
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
70
|
-
const user = await sw.auth.fromRequest(req)
|
|
71
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
72
|
-
const result = await sw.fs.server.write(`/uploads/${user.id}/avatar.png`, await req.arrayBuffer(), {
|
|
73
|
-
content_type: 'image/png'
|
|
74
|
-
})
|
|
75
|
-
// result = { ok: true, data: { path, size_bytes: 12400, content_type: 'image/png',
|
|
76
|
-
// version: 1, content_revision } }
|
|
77
|
-
// Read fields off result.data — e.g. result.data.path, result.data.size_bytes
|
|
78
|
-
// (size_bytes, NOT size). result.path is undefined.
|
|
79
|
-
return Response.json({ path: result.data.path, size_bytes: result.data.size_bytes })
|
|
80
|
-
}
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
## sw.fs.read(path, options?)
|
|
84
|
-
```ts
|
|
85
|
-
// api/avatar/get.ts — return the signed-in user's avatar
|
|
86
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
87
|
-
const user = await sw.auth.fromRequest(req)
|
|
88
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
89
|
-
try {
|
|
90
|
-
const file = await sw.fs.server.read(`/uploads/${user.id}/avatar.png`)
|
|
91
|
-
// Success: Response object — file.arrayBuffer() / file.text() / file.json()
|
|
92
|
-
return new Response(file.body, { headers: { 'Content-Type': file.headers.get('Content-Type') || 'application/octet-stream' } })
|
|
93
|
-
} catch (err) {
|
|
94
|
-
// Failure: throws an error with code, status, and message. Missing files throw
|
|
95
|
-
// NOT_FOUND (404); an error response body is never returned as file content.
|
|
96
|
-
if ((err as { status?: number }).status === 404) return new Response('Not found', { status: 404 })
|
|
97
|
-
throw err
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
The thrown error also applies to line-range reads. Apps deployed before this
|
|
103
|
-
behavior shipped need a new deploy to receive it. Reading a directory path,
|
|
104
|
-
such as `/uploads/<user id>/`, returns its listing as a JSON response;
|
|
105
|
-
`sw.fs.list` (below) returns a typed listing.
|
|
106
|
-
|
|
107
|
-
Read a line range from a stored text file (returns parsed JSON):
|
|
108
|
-
|
|
109
|
-
```ts
|
|
110
|
-
// api/imports/excerpt.ts — lines 50–75 of the signed-in user's import log
|
|
111
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
112
|
-
const user = await sw.auth.fromRequest(req)
|
|
113
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
114
|
-
const slice = await sw.fs.server.read(`/logs/${user.id}/import-run.txt`, { lines: [50, 75] })
|
|
115
|
-
// slice = { path, content: '...', lines: [50, 75], total_lines: 420,
|
|
116
|
-
// content_type, version, content_revision }
|
|
117
|
-
return Response.json({ content: slice.content, total_lines: slice.total_lines })
|
|
118
|
-
}
|
|
119
|
-
```
|
|
120
|
-
|
|
121
|
-
## sw.fs.list(path, options?)
|
|
122
|
-
```ts
|
|
123
|
-
// api/uploads/index.ts — every file under the signed-in user's folder
|
|
124
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
125
|
-
const user = await sw.auth.fromRequest(req)
|
|
126
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
127
|
-
// Directory listing. Pass { recursive: true } for the full subtree,
|
|
128
|
-
// or { recursive: true, depth: 2 } to cap the walk.
|
|
129
|
-
const all = await sw.fs.server.list(`/uploads/${user.id}/`, { recursive: true })
|
|
130
|
-
// all = { path, type: 'directory', recursive: true, depth: null, entries: [{ path, name,
|
|
131
|
-
// type, size_bytes, content_type, version, updated_at }, ...] }
|
|
132
|
-
// A listing without recursive also carries next_cursor.
|
|
133
|
-
return Response.json(all.entries.map((entry) => entry.path))
|
|
134
|
-
}
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
## sw.fs.server — explicit project-wide file access
|
|
138
|
-
|
|
139
|
-
In a deployed handler, use `sw.fs.server.read/write/list` and the other
|
|
140
|
-
ordinary file operations when the application intentionally needs project-wide
|
|
141
|
-
access. Authorize the caller in your application before choosing this view;
|
|
142
|
-
it does not apply the request user's ownership filter. It uses the same
|
|
143
|
-
signatures and result shapes as `sw.fs` and does not expose the cross-file
|
|
144
|
-
scanners in `file-tools`. It is also the file view for crons, queue
|
|
145
|
-
messages and other work without a signed-in user, where plain `sw.fs` throws
|
|
146
|
-
`AUTH_REQUIRED`.
|
|
147
|
-
|
|
148
|
-
## sw.fs.dev — project-wide file view (run_code only)
|
|
149
|
-
`sw.fs.dev` and its search, glob and diff are described in `file-tools` →
|
|
150
|
-
`who-can-use-them`. Ordinary `sw.fs` calls need a
|
|
151
|
-
signed-in user; without one (a cron, for example) they throw `AUTH_REQUIRED`,
|
|
152
|
-
so use `sw.fs.server` there. A job started by a signed-in user reads and
|
|
153
|
-
writes files as that user. A row-bound job's grant (`sw.jobs` →
|
|
154
|
-
`act-on-one-row-for-the-signed-in-user`) gives its user no file access: plain
|
|
155
|
-
`sw.fs` is refused there. `sw.fs.server` stays your server code's explicit
|
|
156
|
-
project authority, so use it only after your own check.
|
|
157
|
-
|
|
158
|
-
## sw.fs.delete(path)
|
|
159
|
-
```ts
|
|
160
|
-
// api/uploads/remove.ts — delete one of the signed-in user's files
|
|
161
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
162
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
163
|
-
const user = await sw.auth.fromRequest(req)
|
|
164
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
165
|
-
const result = await sw.fs.server.delete(`/uploads/${user.id}/old-file.txt`)
|
|
166
|
-
// Directory deletes are recursive. delete does not throw on a refused
|
|
167
|
-
// request: it resolves with the error body, so check ok.
|
|
168
|
-
if (!result.ok) return Response.json({ error: result.error, message: result.message }, { status: 400 })
|
|
169
|
-
return Response.json({ deleted: result.data.deleted })
|
|
170
|
-
}
|
|
171
|
-
```
|
|
172
|
-
|
|
173
|
-
## sw.fs.move(from, to, opts?)
|
|
174
|
-
```ts
|
|
175
|
-
// api/avatar/commit.ts — make a finished upload the signed-in user's avatar
|
|
176
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
177
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
178
|
-
const user = await sw.auth.fromRequest(req)
|
|
179
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
180
|
-
// Move a finished upload without sending the bytes through your function.
|
|
181
|
-
// overwrite replaces an existing destination in the same operation.
|
|
182
|
-
// Avoid a separate delete-then-move: another request can race between them.
|
|
183
|
-
const moved = await sw.fs.server.move(
|
|
184
|
-
`/uploads/${user.id}/avatar.upload`,
|
|
185
|
-
`/uploads/${user.id}/avatar.jpg`,
|
|
186
|
-
{ overwrite: true }
|
|
187
|
-
)
|
|
188
|
-
// moved = { from, to }. Without overwrite, a destination collision returns
|
|
189
|
-
// VALIDATION_ERROR ("Destination ... already exists").
|
|
190
|
-
return Response.json(moved)
|
|
191
|
-
}
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
## sw.fs.copy(from, to)
|
|
195
|
-
```ts
|
|
196
|
-
// api/drafts/duplicate.ts — copy one of the signed-in user's drafts
|
|
197
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
198
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
199
|
-
const user = await sw.auth.fromRequest(req)
|
|
200
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
201
|
-
// Server-side copy. Instant — no bytes flow through your function.
|
|
202
|
-
const copied = await sw.fs.server.copy(
|
|
203
|
-
`/drafts/${user.id}/welcome.html`,
|
|
204
|
-
`/drafts/${user.id}/welcome-copy.html`,
|
|
205
|
-
)
|
|
206
|
-
// copied = { from, to, content_revision }
|
|
207
|
-
return Response.json(copied)
|
|
208
|
-
}
|
|
209
|
-
```
|
|
210
|
-
|
|
211
|
-
## sw.fs.versions(path)
|
|
212
|
-
```ts
|
|
213
|
-
// api/notes/history.ts — earlier versions of the signed-in user's note
|
|
214
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
215
|
-
const user = await sw.auth.fromRequest(req)
|
|
216
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
217
|
-
const history = await sw.fs.server.versions(`/notes/${user.id}/draft.md`)
|
|
218
|
-
// Each write creates a new version. Earlier versions, most-recent first:
|
|
219
|
-
// history = { path, current_version: 7,
|
|
220
|
-
// versions: [{ version: 6, size_bytes, content_type, created_at }, ...] }
|
|
221
|
-
return Response.json(history.versions)
|
|
222
|
-
}
|
|
223
|
-
```
|
|
224
|
-
|
|
225
|
-
## sw.fs.restore(path, version)
|
|
226
|
-
```ts
|
|
227
|
-
// api/notes/restore.ts — body { version }, a number from sw.fs.versions
|
|
228
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
229
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
230
|
-
const user = await sw.auth.fromRequest(req)
|
|
231
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
232
|
-
const input: unknown = await req.json().catch(() => null)
|
|
233
|
-
const { version } = (input ?? {}) as { version?: unknown }
|
|
234
|
-
if (typeof version !== 'number' || !Number.isInteger(version)) return Response.json({ error: 'version' }, { status: 400 })
|
|
235
|
-
// Restores a previous version as the latest. Original versions stay in history.
|
|
236
|
-
const restored = await sw.fs.server.restore(`/notes/${user.id}/draft.md`, version)
|
|
237
|
-
// restored = { path, restored_version: 5, current_version: 8, content_revision }
|
|
238
|
-
return Response.json(restored)
|
|
239
|
-
}
|
|
240
|
-
```
|
|
241
|
-
|
|
242
|
-
## sw.fs.stat(path)
|
|
243
|
-
```ts
|
|
244
|
-
// api/avatar/info.ts — metadata for the signed-in user's avatar
|
|
245
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
246
|
-
const user = await sw.auth.fromRequest(req)
|
|
247
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
248
|
-
const info = await sw.fs.server.stat(`/uploads/${user.id}/avatar.png`)
|
|
249
|
-
// info = { path, name, type: 'file', size_bytes, content_type, content_revision,
|
|
250
|
-
// visibility, version, created_at, updated_at }
|
|
251
|
-
return Response.json({ size_bytes: info.size_bytes, updated_at: info.updated_at })
|
|
252
|
-
}
|
|
253
|
-
```
|
|
254
|
-
|
|
255
|
-
## sw.fs.replace({ path, find, replace })
|
|
256
|
-
```ts
|
|
257
|
-
// api/notes/rename-product.ts — find-and-replace in the signed-in user's note
|
|
258
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
259
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
260
|
-
const user = await sw.auth.fromRequest(req)
|
|
261
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
262
|
-
// This note was written with sw.fs.server.write. Replacement archives
|
|
263
|
-
// the previous version, which sw.fs.server.restore can recover.
|
|
264
|
-
const result = await sw.fs.server.replace({
|
|
265
|
-
path: `/notes/${user.id}/draft.md`,
|
|
266
|
-
find: 'Acme Beta',
|
|
267
|
-
replace: 'Acme',
|
|
268
|
-
})
|
|
269
|
-
// result = { ok: true, replacements: 1, path, version: 4, size_bytes, content_revision }
|
|
270
|
-
// Literal match (not regex). Text files only.
|
|
271
|
-
return Response.json({ replacements: result.replacements })
|
|
272
|
-
}
|
|
273
|
-
```
|
|
274
|
-
|
|
275
|
-
## sw.fs.uploadFromRequest(req, { path, maxBytes?, allowedTypes?, fieldName?, public? })
|
|
276
|
-
// One-call upload handler for browser <input type="file"> forms. Parses
|
|
277
|
-
// multipart/form-data from the request, validates size + type, writes to
|
|
278
|
-
// storage, returns a short-lived signed URL for the private file by default.
|
|
279
|
-
// Pass public: true only for a world-readable file; then url is its permanent
|
|
280
|
-
// /storage URL. The result includes visibility so the caller can tell which.
|
|
281
|
-
//
|
|
282
|
-
// The whole point: the developer chooses the path, the helper handles
|
|
283
|
-
// every failure mode. Three lines instead of fifteen, and you never
|
|
284
|
-
// JSON-stringify raw bytes (which is what corrupts images on project_patch
|
|
285
|
-
// — use binary_files for asset deploys, sw.fs.uploadFromRequest for
|
|
286
|
-
// runtime uploads).
|
|
287
|
-
|
|
288
|
-
```ts
|
|
289
|
-
// api/upload.ts
|
|
290
|
-
export default async function handler(req: Request, sw: SomewhereRuntimeContext) {
|
|
291
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
292
|
-
const user = await sw.auth.fromRequest(req)
|
|
293
|
-
if (!user) return new Response('unauthorized', { status: 401 })
|
|
294
|
-
const { url, path, size, contentType } = await sw.fs.server.uploadFromRequest(req, {
|
|
295
|
-
path: `/uploads/${user.id}/${crypto.randomUUID()}.bin`,
|
|
296
|
-
maxBytes: 5 * 1024 * 1024, // optional, 5 MB cap
|
|
297
|
-
allowedTypes: ['image/png', 'image/jpeg'], // optional whitelist
|
|
298
|
-
fieldName: 'file', // optional, default 'file'
|
|
299
|
-
})
|
|
300
|
-
return Response.json({ url, path, size, contentType })
|
|
301
|
-
}
|
|
302
|
-
```
|
|
303
|
-
|
|
304
|
-
// On the browser: const fd = new FormData(); fd.append('file', input.files[0])
|
|
305
|
-
// const r = await fetch('/api/upload', { method: 'POST', body: fd })
|
|
306
|
-
// const { url } = await r.json(); img.src = url
|
|
307
|
-
//
|
|
308
|
-
// Throws on every failure with a stable code in the message:
|
|
309
|
-
// UPLOAD_PATH_REQUIRED, UPLOAD_NOT_MULTIPART, UPLOAD_PARSE_FAILED,
|
|
310
|
-
// UPLOAD_FIELD_MISSING, UPLOAD_TYPE_NOT_ALLOWED, UPLOAD_FILE_EMPTY,
|
|
311
|
-
// UPLOAD_TOO_LARGE
|
|
312
|
-
// Wrap in try/catch and map to the HTTP status you want.
|
|
313
|
-
//
|
|
314
|
-
// For files larger than ~25 MB, mint a signed URL with sw.fs.uploadUrl
|
|
315
|
-
// instead and have the browser PUT direct — keeps the bytes off your
|
|
316
|
-
// function CPU.
|
|
317
|
-
|
|
318
|
-
## sw.fs.uploadUrl({ path, maxSize?, contentType?, expiresIn? })
|
|
319
|
-
// Mints a short-lived signed URL the browser can PUT bytes to directly
|
|
320
|
-
// — without ever seeing your platform key. Use this for big uploads
|
|
321
|
-
// (videos, large images, archives) so the bytes don't round-trip through
|
|
322
|
-
// your function.
|
|
323
|
-
```ts
|
|
324
|
-
// api/uploads/start.ts — a direct-upload URL for the signed-in user
|
|
325
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
326
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
327
|
-
const user = await sw.auth.fromRequest(req)
|
|
328
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
329
|
-
const { url, multipart_url, expires_at } = await sw.fs.server.uploadUrl({
|
|
330
|
-
path: `/uploads/${user.id}/photo.jpg`,
|
|
331
|
-
maxSize: 10 * 1024 * 1024, // optional, defaults to tier max
|
|
332
|
-
contentType: 'image/jpeg', // optional, '*' if omitted
|
|
333
|
-
expiresIn: 300, // optional, seconds (default 300, max 3600)
|
|
334
|
-
})
|
|
335
|
-
return Response.json({ url, multipart_url, expires_at })
|
|
336
|
-
}
|
|
337
|
-
```
|
|
338
|
-
// Browser side:
|
|
339
|
-
// await fetch(url, { method: 'PUT', headers: { 'Content-Type': 'image/jpeg' }, body: file })
|
|
340
|
-
// The PUT answers { path, size_bytes, content_type, version }.
|
|
341
|
-
//
|
|
342
|
-
// One request carries at most 100 MB. A bigger file (up to the plan's
|
|
343
|
-
// max_upload_mb) goes up in parts through the same URL — the response's
|
|
344
|
-
// multipart_url. Start, send each part, then complete:
|
|
345
|
-
// const s = (await (await fetch(multipart_url, { method: 'POST',
|
|
346
|
-
// headers: { 'Content-Type': 'application/json' },
|
|
347
|
-
// body: JSON.stringify({ size_bytes: file.size, content_type: file.type }) })).json()).data
|
|
348
|
-
// // s = { upload_id, part_size, part_count, parts_url, complete_url, abort_url, expires_at }
|
|
349
|
-
// for (let n = 1; n <= s.part_count; n++)
|
|
350
|
-
// await fetch(s.parts_url + '/' + n, { method: 'PUT',
|
|
351
|
-
// body: file.slice((n - 1) * s.part_size, n * s.part_size) })
|
|
352
|
-
// await fetch(s.complete_url, { method: 'POST' }) // → { path, size_bytes, content_type, version }
|
|
353
|
-
// Every part except the last is exactly part_size bytes (at most 90 MB).
|
|
354
|
-
// Starting uses up the URL. An upload not completed within 6 hours is
|
|
355
|
-
// discarded, parts included; DELETE abort_url discards it sooner. A file
|
|
356
|
-
// over the plan's limit is refused at start with PAYLOAD_TOO_LARGE.
|
|
357
|
-
|
|
358
|
-
## sw.fs.signedUrl(path, { expiresIn? })
|
|
359
|
-
// Mints a short-lived URL anyone can GET to download the file — no
|
|
360
|
-
// platform key, no app-user JWT. Use for email attachments, image
|
|
361
|
-
// previews, share links, "download once" handoffs. Default 1h, max 7d.
|
|
362
|
-
```ts
|
|
363
|
-
// api/invoices/link.ts — a one-hour download link for the signed-in user's invoice
|
|
364
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
365
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
366
|
-
const user = await sw.auth.fromRequest(req)
|
|
367
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
368
|
-
const { url, expires_at } = await sw.fs.server.signedUrl(`/invoices/${user.id}/invoice-42.pdf`, {
|
|
369
|
-
expiresIn: 3600, // optional, seconds (60..604800)
|
|
370
|
-
})
|
|
371
|
-
return Response.json({ url, expires_at })
|
|
372
|
-
}
|
|
373
|
-
```
|
|
374
|
-
// → url: 'https://api.somewhere.cloud/v1/fs-signed/<token>'
|
|
375
|
-
// → expires_at: ISO 8601 string
|
|
376
|
-
// Send the url in an email body, embed it in <img src=...>, etc.
|
|
377
|
-
// The URL stops working at expires_at; rotating JWT_SECRET invalidates
|
|
378
|
-
// every outstanding signed URL (bulk revocation lever).
|
|
379
|
-
|
|
380
|
-
For a smaller preview of a raster image, append `?w=384` to the signed URL.
|
|
381
|
-
The parameter is `w`, not `width`. Supported widths are 192, 384, 768 and 1536 pixels. Variants use WebP,
|
|
382
|
-
preserve aspect ratio and never upscale; the URL without `w` still returns
|
|
383
|
-
the original. Invalid `w` values and recognized unsupported image parameters
|
|
384
|
-
such as `width`, `height`, `format`, `quality` and `fit` return 400.
|
|
385
|
-
Other query parameters, including tracking tags and unrecognized names, are ignored.
|
|
386
|
-
Byte ranges work on originals; omit the `Range` header when requesting a variant.
|
|
387
|
-
An unsupported image type or failed transform returns the guarded original
|
|
388
|
-
with `X-Somewhere-Image-Variant: original`, rather than breaking the preview.
|
|
389
|
-
Signed downloads still verify the capability and current file revision before
|
|
390
|
-
using cached bytes. Cached bytes do not bypass expiry or permit another file.
|
|
391
|
-
|
|
392
|
-
## sw.fs.public_url(path, { makePublic? })
|
|
393
|
-
// Returns a file's permanent, unauthenticated public URL. Asking for the
|
|
394
|
-
// URL does NOT silently expose a private file:
|
|
395
|
-
// - already-public file → returns the URL, visibility unchanged.
|
|
396
|
-
// - private file + makePublic → publishes it, returns the URL.
|
|
397
|
-
// - private file, no opt-in → throws FILE_PRIVATE (file stays private).
|
|
398
|
-
// For a time-limited link to a private file WITHOUT making it world-readable,
|
|
399
|
-
// use sw.fs.server.signedUrl(path) instead.
|
|
400
|
-
```ts
|
|
401
|
-
// api/avatar/publish.ts — publish the signed-in user's avatar
|
|
402
|
-
export default async function(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
|
|
403
|
-
if (req.method !== 'POST') return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
|
|
404
|
-
const user = await sw.auth.fromRequest(req)
|
|
405
|
-
if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
406
|
-
// This avatar was written with sw.fs.server.write.
|
|
407
|
-
const { public_url } = await sw.fs.server.public_url(`/uploads/${user.id}/avatar.png`, {
|
|
408
|
-
makePublic: true, // required to publish a private file
|
|
409
|
-
})
|
|
410
|
-
return Response.json({ public_url })
|
|
411
|
-
}
|
|
412
|
-
```
|
|
413
|
-
// → public_url: 'https://myapp.somewhere.site/storage/uploads/<user id>/avatar.png'
|
|
414
|
-
|
|
415
|
-
## Public URL
|
|
416
|
-
Files written with `visibility: 'public'` are served (no auth) at:
|
|
417
|
-
https://{subdomain}.somewhere.site/storage/{path}
|
|
418
|
-
Private files (the default) return 404 here — they're reachable only from
|
|
419
|
-
your authenticated code (sw.fs.read) or a signed URL.
|
|
420
|
-
|
|
421
|
-
```html
|
|
422
|
-
<!-- Use the public URL directly in HTML -->
|
|
423
|
-
<img src="https://myapp.somewhere.site/storage/uploads/avatar.png" alt="Avatar" />
|
|
424
|
-
```
|