@somewhere-cloud/cli 0.38.154 → 0.38.155

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/docs/adopt.md +39 -0
  3. package/dist/docs/analytics.md +161 -0
  4. package/dist/docs/api-reference.md +339 -0
  5. package/dist/docs/api-surface.md +2067 -0
  6. package/dist/docs/app-mcp.md +162 -0
  7. package/dist/docs/architecture-patterns.md +334 -0
  8. package/dist/docs/auth-client.md +531 -0
  9. package/dist/docs/billing.md +76 -0
  10. package/dist/docs/browser.md +639 -0
  11. package/dist/docs/calendar.md +298 -0
  12. package/dist/docs/changes.md +323 -0
  13. package/dist/docs/cli.md +407 -0
  14. package/dist/docs/common-mistakes.md +199 -0
  15. package/dist/docs/connect-agent.md +72 -0
  16. package/dist/docs/cors.md +114 -0
  17. package/dist/docs/cron.md +167 -0
  18. package/dist/docs/database-engine.md +167 -0
  19. package/dist/docs/declared-data.md +1656 -0
  20. package/dist/docs/declared-files.md +475 -0
  21. package/dist/docs/deploy-intelligence.md +188 -0
  22. package/dist/docs/deploy.md +733 -0
  23. package/dist/docs/design-system.md +273 -0
  24. package/dist/docs/dev-environments.md +496 -0
  25. package/dist/docs/domain-ownership.md +31 -0
  26. package/dist/docs/domains.md +370 -0
  27. package/dist/docs/feedback.md +88 -0
  28. package/dist/docs/file-tools.md +116 -0
  29. package/dist/docs/functions.md +489 -0
  30. package/dist/docs/getting-started.md +238 -0
  31. package/dist/docs/github.md +95 -0
  32. package/dist/docs/google-calendar.md +212 -0
  33. package/dist/docs/groups.md +836 -0
  34. package/dist/docs/guarantees.md +58 -0
  35. package/dist/docs/handled-for-you.md +224 -0
  36. package/dist/docs/inspect.md +171 -0
  37. package/dist/docs/limits.md +68 -0
  38. package/dist/docs/live-data.md +197 -0
  39. package/dist/docs/live.md +92 -0
  40. package/dist/docs/local-dev.md +30 -0
  41. package/dist/docs/migration-supabase.md +58 -0
  42. package/dist/docs/payments.md +1102 -0
  43. package/dist/docs/portability.md +194 -0
  44. package/dist/docs/postgres.md +301 -0
  45. package/dist/docs/pricing-comparison.md +42 -0
  46. package/dist/docs/pricing.md +39 -0
  47. package/dist/docs/project-groups.md +107 -0
  48. package/dist/docs/projects.md +380 -0
  49. package/dist/docs/recipe-ai-agent.md +112 -0
  50. package/dist/docs/recipe-ai-features.md +227 -0
  51. package/dist/docs/recipe-ai-receipts.md +783 -0
  52. package/dist/docs/recipe-background-jobs.md +369 -0
  53. package/dist/docs/recipe-booking.md +348 -0
  54. package/dist/docs/recipe-csv-import.md +390 -0
  55. package/dist/docs/recipe-ecommerce.md +127 -0
  56. package/dist/docs/recipe-email.md +282 -0
  57. package/dist/docs/recipe-escalation.md +133 -0
  58. package/dist/docs/recipe-file-uploads.md +159 -0
  59. package/dist/docs/recipe-import-app.md +110 -0
  60. package/dist/docs/recipe-login.md +457 -0
  61. package/dist/docs/recipe-multi-chat.md +198 -0
  62. package/dist/docs/recipe-paid-api.md +161 -0
  63. package/dist/docs/recipe-pdfs.md +205 -0
  64. package/dist/docs/recipe-push-notifications.md +107 -0
  65. package/dist/docs/recipe-seo.md +200 -0
  66. package/dist/docs/recipe-signed-in-app.md +330 -0
  67. package/dist/docs/render.md +99 -0
  68. package/dist/docs/rooms.md +554 -0
  69. package/dist/docs/sdk.md +287 -0
  70. package/dist/docs/sdks.md +24 -0
  71. package/dist/docs/search.md +199 -0
  72. package/dist/docs/security-model.md +168 -0
  73. package/dist/docs/setup.md +212 -0
  74. package/dist/docs/smoke.md +102 -0
  75. package/dist/docs/speed.md +298 -0
  76. package/dist/docs/sql-compatibility.md +96 -0
  77. package/dist/docs/sw.agent.md +248 -0
  78. package/dist/docs/sw.ai.md +1291 -0
  79. package/dist/docs/sw.auth.md +1811 -0
  80. package/dist/docs/sw.billing.md +171 -0
  81. package/dist/docs/sw.db.md +2128 -0
  82. package/dist/docs/sw.email.md +661 -0
  83. package/dist/docs/sw.endpoint.md +187 -0
  84. package/dist/docs/sw.env.md +303 -0
  85. package/dist/docs/sw.fetch.md +115 -0
  86. package/dist/docs/sw.fs.md +424 -0
  87. package/dist/docs/sw.groups.md +836 -0
  88. package/dist/docs/sw.image.md +69 -0
  89. package/dist/docs/sw.jobs.md +520 -0
  90. package/dist/docs/sw.logs.md +61 -0
  91. package/dist/docs/sw.mail.md +106 -0
  92. package/dist/docs/sw.notifications.md +78 -0
  93. package/dist/docs/sw.push.md +161 -0
  94. package/dist/docs/sw.rateLimit.md +67 -0
  95. package/dist/docs/sw.web.md +128 -0
  96. package/dist/docs/tasks.md +269 -0
  97. package/dist/docs/test.md +220 -0
  98. package/dist/docs/tool-reference-account.md +7 -0
  99. package/dist/docs/tool-reference-ai.md +121 -0
  100. package/dist/docs/tool-reference-analytics.md +37 -0
  101. package/dist/docs/tool-reference-api.md +19 -0
  102. package/dist/docs/tool-reference-artifacts.md +35 -0
  103. package/dist/docs/tool-reference-auth.md +163 -0
  104. package/dist/docs/tool-reference-browser.md +114 -0
  105. package/dist/docs/tool-reference-code.md +26 -0
  106. package/dist/docs/tool-reference-connect.md +21 -0
  107. package/dist/docs/tool-reference-cron.md +48 -0
  108. package/dist/docs/tool-reference-db.md +282 -0
  109. package/dist/docs/tool-reference-domains.md +107 -0
  110. package/dist/docs/tool-reference-email.md +55 -0
  111. package/dist/docs/tool-reference-env.md +19 -0
  112. package/dist/docs/tool-reference-feedback.md +56 -0
  113. package/dist/docs/tool-reference-fs.md +265 -0
  114. package/dist/docs/tool-reference-github.md +57 -0
  115. package/dist/docs/tool-reference-groups.md +85 -0
  116. package/dist/docs/tool-reference-help.md +29 -0
  117. package/dist/docs/tool-reference-jobs.md +39 -0
  118. package/dist/docs/tool-reference-live.md +48 -0
  119. package/dist/docs/tool-reference-logs.md +16 -0
  120. package/dist/docs/tool-reference-payments.md +44 -0
  121. package/dist/docs/tool-reference-project.md +706 -0
  122. package/dist/docs/tool-reference-push.md +78 -0
  123. package/dist/docs/tool-reference-rate-limit.md +18 -0
  124. package/dist/docs/tool-reference-search.md +68 -0
  125. package/dist/docs/tool-reference-security.md +42 -0
  126. package/dist/docs/tool-reference-smoke.md +17 -0
  127. package/dist/docs/tool-reference-stock-photos.md +20 -0
  128. package/dist/docs/tool-reference-tasks.md +73 -0
  129. package/dist/docs/tool-reference-telegram.md +32 -0
  130. package/dist/docs/tool-reference-usage.md +9 -0
  131. package/dist/docs/tool-reference-web.md +71 -0
  132. package/dist/docs/tool-reference-webhooks.md +9 -0
  133. package/dist/docs/troubleshooting.md +411 -0
  134. package/dist/docs/typed-functions.md +94 -0
  135. package/dist/docs/verify-before-deploy.md +67 -0
  136. package/dist/docs/vs-supabase.md +75 -0
  137. package/dist/docs/vs-vercel.md +103 -0
  138. package/dist/lib/bundle.js +303 -221
  139. package/dist/lib/bundle.js.map +3 -3
  140. package/dist/types/lib/test-session.d.ts +8 -0
  141. package/npm-shrinkwrap.json +2 -2
  142. package/package.json +3 -2
@@ -0,0 +1,106 @@
1
+ # sw.mail — Mailboxes (inside deployed functions)
2
+
3
+ Read, search and send the mail your app receives. Every email in or out of a
4
+ mailbox is stored as one record with its conversation, status and attachments.
5
+
6
+ - `sw.mail.project` is the project's mailbox. Replies to your app's own
7
+ address (`<your-app-subdomain>@somewhere.site`) and mail to addresses
8
+ registered on the project land here.
9
+ - `sw.mail` is the signed-in app user's own mailbox. The platform picks it
10
+ from the verified session, so no method takes a user id and one user can
11
+ never read another's mail. Without a signed-in user it throws
12
+ `AUTH_REQUIRED`.
13
+
14
+ `sw.mail.project` carries project authority, like `sw.db.server`: check the
15
+ caller before you return project mail or send from it.
16
+
17
+ ```ts
18
+ // api/support/inbox.ts: the support team's view of the project mailbox
19
+ export default sw.endpoint({
20
+ auth: 'required',
21
+ handler: async ({ user }, sw) => {
22
+ if (user.role !== 'admin') return Response.json({ error: 'forbidden' }, { status: 403 });
23
+ const { emails } = await sw.mail.project.list({ limit: 20 });
24
+ return { emails };
25
+ },
26
+ });
27
+ ```
28
+
29
+ Every method below exists on both `sw.mail` and `sw.mail.project`. Failures
30
+ throw with the platform's error code; an email id from another mailbox reads
31
+ as not found.
32
+
33
+ ## Read mail
34
+
35
+ - `list({ limit?, before?, conversation? })` returns
36
+ `{ emails, mailbox }`, newest first, 50 by default (up to 200). Each email has `id`,
37
+ `direction` (`'in'` or `'out'`), `from`, `to`, `subject`, `status`,
38
+ `conversation`, `created_at` (epoch ms) and `attachments` (a count). Pass
39
+ the oldest `created_at` as `before` for the next page, or a `conversation`
40
+ to read one thread, oldest first. A mailbox that has never received mail answers
41
+ `{ emails: [], mailbox: null }`.
42
+ - `get(id)` returns `{ email }` with the full record: `text`, `html`,
43
+ `from_addr`, `to_addrs`, `cc_addrs`, `reply_to`, `message_id`, `status`,
44
+ `attachments` (`{ n, name, type, size }`), `headers` (raw header lines,
45
+ or `null` for older mail) and `checks` (`{ spf, dkim, dmarc }` as the
46
+ receiving server recorded them, or `null`).
47
+ - `attachment(id, n)` returns a `Response` with the file and a download
48
+ `Content-Disposition`. Return it to the browser as is. Check `res.ok`: a
49
+ missing attachment answers 404 rather than throwing.
50
+
51
+ ```ts
52
+ const { email } = await sw.mail.get(id);
53
+ if (email.attachments.length) return sw.mail.attachment(id, email.attachments[0].n);
54
+ ```
55
+
56
+ ## Search
57
+
58
+ `search(text, { limit? })` returns `{ results, searched }`: emails that
59
+ contain every word of `text`, newest first, 50 by default (up to 200). Each result has `id`, `subject`, `from_addr`,
60
+ `to_addrs`, `created_at`, `conversation`, `has_attachments`, `direction` and
61
+ `status`. `searched` names the mailbox that answered. Empty `text` is a
62
+ `VALIDATION_ERROR`.
63
+
64
+ ## Send and reply
65
+
66
+ `send({ from, to, subject, text?, html?, reply_to_email_id?, idempotency_key?, once?, unless_replied? })`
67
+ returns `{ email_id, status, duplicate }`.
68
+
69
+ - `from` is an address registered in this mailbox, on a domain the project
70
+ has verified for sending (`somewhere docs sw.email`).
71
+ - `to` is one address or a list of up to 10.
72
+ - `reply_to_email_id` replies to an email in this mailbox; the reply joins
73
+ its conversation.
74
+ - `idempotency_key` makes a retry return the first result with
75
+ `duplicate: true`.
76
+ - `once: '<step>'` sends this step to one recipient at most once;
77
+ `unless_replied: true` sends nothing to someone this mailbox has received
78
+ mail from and answers `status: 'skipped'`, `skipped: 'replied'`. A
79
+ complete follow-up example: `somewhere docs recipe-email`.
80
+
81
+ ```ts
82
+ const { email } = await sw.mail.project.get(id);
83
+ await sw.mail.project.send({
84
+ from: 'support@example.com',
85
+ to: email.from_addr,
86
+ subject: 'Re: ' + email.subject,
87
+ text: 'Thanks, we are on it.',
88
+ reply_to_email_id: email.id,
89
+ });
90
+ ```
91
+
92
+ For one-off notifications to your app's users, `sw.email.send` needs no
93
+ mailbox or address setup.
94
+
95
+ ## Addresses
96
+
97
+ To receive at your own domain, turn on inbound mail for it
98
+ (`somewhere docs domains`), then register addresses on its `receiving_host`:
99
+
100
+ - `addresses.create(address)` returns `{ address, mailbox, sends_as }`.
101
+ `sw.mail.project.addresses.create` adds it to the project mailbox;
102
+ `sw.mail.addresses.create` gives the signed-in user their own address.
103
+ An address is `name@host` without a `+` tag and must not already be
104
+ registered (`ALREADY_EXISTS`).
105
+ - `addresses.list()` returns `{ addresses: [{ address, signs_as_user_id }] }`.
106
+ - `addresses.remove(address)` returns `{ removed }`.
@@ -0,0 +1,78 @@
1
+ # sw.notifications — unified notify primitive
2
+
3
+ One call → fan-out across push, in-app bell, and (when an address is
4
+ provided) email, with one result per channel: `{ bell?, push?, email? }`.
5
+
6
+ `sw.notifications` is the in-app inbox: it stores each notification for its
7
+ recipient with read state, and the bell helpers read only the signed-in
8
+ user's own rows. `sw.push` is browser delivery only: it stores nothing for the
9
+ user to list later. Use `sw.notifications` when users need a list and unread
10
+ count; use `sw.push` directly to target devices or your own browser.
11
+
12
+ ## sw.notifications.send(userId, { title, body?, url?, email?, channels? })
13
+
14
+ ```ts
15
+ // api/_lib/line-alert.ts — call after your code has decided this user gets the alert
16
+ export function alertNorthernDelay(sw: SomewhereRuntimeContext, userId: string): Promise<SomewhereNotificationsSendResult> {
17
+ return sw.notifications.send(userId, {
18
+ title: 'Northern line: minor delays',
19
+ body: 'Reported 14:02 GMT. Estimated 10–15 min impact southbound.',
20
+ url: '/lines/northern',
21
+ channels: ['bell', 'push'], // optional; default ['bell', 'push']
22
+ })
23
+ }
24
+ ```
25
+
26
+ Returns { bell?, push?, email? } with per-channel result. Each entry
27
+ is { ok: true, ... } or { ok: false, error: '...', code? } so the
28
+ caller can branch without a try/catch per channel. A missing `userId` raises
29
+ `VALIDATION_ERROR`. The recipient can be any user of the app: authorize
30
+ the caller before letting them send notifications to another user.
31
+
32
+ Channels:
33
+ - bell — stores the notification in the recipient's in-app inbox. Render
34
+ it with sw.notifications.list() / unreadCount(). The recipient must be a
35
+ user of this app; otherwise the bell result is
36
+ `{ ok: false, code: 'APP_USER_NOT_FOUND' }` and nothing is stored. Each
37
+ user keeps their newest 1,000 notifications, and notifications older than
38
+ 90 days are removed. Projects created before managed data instead keep
39
+ these rows, without those two limits, in a _notifications table in the
40
+ project's own database, hidden from db_describe / db_browse like every
41
+ _-prefixed table.
42
+ - push — proxies to sw.push.send against every active subscription
43
+ for that userId. Silent no-op if the user hasn't subscribed.
44
+ - email — only fires when opts.email is set explicitly. We don't
45
+ auto-look up the address (your user-table shape is yours). Pair
46
+ with sw.auth.fromRequest(req, { enrichFrom: 'members' }) to pull
47
+ the email + send in two lines. It uses the platform-managed transactional
48
+ sender with the project name as its label, so a new project needs no sender
49
+ setup; opts.email must be the address of that userId (or the project's
50
+ owner). Pass opts.from only when using a verified sender domain of your own.
51
+ The project plan's email allowance and send rate limit still apply.
52
+
53
+ ## Bell helpers
54
+
55
+ The bell helpers act for the signed-in user of the request: they take no
56
+ user id, and with no signed-in user they throw `AUTH_REQUIRED` (401).
57
+ `markRead` changes only that user's own notification.
58
+
59
+ ```typescript
60
+ // api/notifications.ts
61
+ export default async function (req: Request, sw: SomewhereRuntimeContext) {
62
+ const { notifications } = await sw.notifications.list();
63
+ const unreadCount = await sw.notifications.unreadCount();
64
+ return Response.json({ notifications, unreadCount });
65
+ }
66
+ ```
67
+
68
+ Mark one notification with `await sw.notifications.markRead(notificationId)`,
69
+ or all of your notifications with `await sw.notifications.markAllRead()`.
70
+ Call these from a function handling the signed-in user's request.
71
+
72
+ ## What this is NOT (yet)
73
+
74
+ - No platform-level dedup, rate-limit, or per-user channel prefs.
75
+ Roll those in your handler if you need them — this is the
76
+ primitive.
77
+ - No retries — push / email failures surface immediately. Re-call
78
+ after fixing the cause.
@@ -0,0 +1,161 @@
1
+ # sw.push — Web Push notifications
2
+
3
+ Send a notification to a user's browser, even when your app's tab is closed.
4
+ Each signed-in user turns notifications on in their own browser, the device
5
+ is registered to that user, and your function sends with
6
+ `sw.push.send({ user_id })`. The platform holds the signing keys, encrypts each
7
+ message, removes devices the browser has revoked, and keeps 7 days of
8
+ per-device send history.
9
+
10
+ In the page, `enablePush()` from `somewhere:push` turns notifications on for
11
+ the signed-in user. In a function, `sw.push.send({ user_id, payload: { title,
12
+ url } })` notifies them, and `sw.push.deliveries({ user_id })` shows what each
13
+ of their devices got.
14
+
15
+ ## Turn on notifications in the page
16
+
17
+ The platform serves the browser helper and its service worker from your
18
+ app's own origin, so you write neither. `somewhere:push` is typed and builds
19
+ to the same-origin `/__sw/push/client.js`:
20
+
21
+ ```ts
22
+ // browser — call from a click; browsers only prompt after a user gesture
23
+ import { enablePush, disablePush, pushStatus, listenToPush } from 'somewhere:push'
24
+
25
+ await enablePush() // asks permission, subscribes, registers this browser for the signed-in user
26
+ await disablePush() // removes this browser's device and unsubscribes it
27
+ await pushStatus() // { supported, permission, subscribed, endpoint }
28
+ const stop = listenToPush(({ type, payload }) => {}) // 'push' or 'click' while a tab is open
29
+ ```
30
+
31
+ The browser belongs to the user signed in on that page: the helper sends the
32
+ page's cookies, which is how platform sign-in (`sw.auth`, the SDK's
33
+ `createSomewhereAuth`) keeps the session. It sends no user id, and the
34
+ platform refuses one. `enablePush()` without a signed-in user fails with
35
+ `AUTH_REQUIRED`. Your app's functions serve the helper, so the project needs
36
+ at least one file under `api/`. The service worker lives at
37
+ `/__sw/push/sw.js` with scope `/__sw/push/`, so it runs alongside any service
38
+ worker your app already has. Each user keeps up to 10 browsers; adding another removes the one registered longest ago.
39
+
40
+ On iPhone and iPad, web push works after the user adds the app to the Home
41
+ Screen; until then `enablePush()` fails with `PUSH_UNSUPPORTED`.
42
+
43
+ ## Send from a function
44
+
45
+ ```ts
46
+ // api/notify.ts — notify the signed-in user
47
+ export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
48
+ if (req.method !== 'POST') return new Response(null, { status: 405, headers: { Allow: 'POST' } })
49
+ const user = await sw.auth.fromRequest(req)
50
+ if (!user) return Response.json({ error: 'Sign in first.' }, { status: 401 })
51
+ const result = await sw.push.send({
52
+ user_id: user.id,
53
+ payload: { title: 'Notifications are ready', body: 'Your browser is connected.', url: '/inbox' },
54
+ })
55
+ return Response.json(result) // { sent, failed, gone, captured, recipients, history_recorded, devices }
56
+ }
57
+ ```
58
+
59
+ `payload` is a string or a JSON value. The service worker reads these fields:
60
+
61
+ | Field | Effect |
62
+ |---|---|
63
+ | `title`, `body`, `icon`, `badge`, `image`, `tag`, `renotify`, `requireInteraction`, `silent` | Passed to `showNotification` |
64
+ | `url` | Opened or focused on click. Same-origin paths only; anything else opens `/` |
65
+ | `badge_count` | Sets the app icon badge where the browser supports it (0 clears it) |
66
+ | `data` | Kept on the notification and delivered to `listenToPush` |
67
+
68
+ A string payload becomes the title.
69
+
70
+ ## Who receives a send
71
+
72
+ ONE object argument with exactly one target:
73
+
74
+ | Target | Reaches |
75
+ |---|---|
76
+ | `user_id` | Every device that signed-in user registered |
77
+ | `subscription_id` or `endpoint` | One device |
78
+ | `audience: 'developer'` | Devices you registered with developer credentials |
79
+ | `audience: 'all'` | Every device in the project |
80
+
81
+ A missing, `null` or empty target is refused with `VALIDATION_ERROR`, so an
82
+ unset id never becomes a broadcast. A send that would reach more than 500
83
+ devices is refused whole with `RECIPIENT_CAP_EXCEEDED`, and a project sends at
84
+ most 10 times a minute (`RATE_LIMITED`). `ttl` sets how
85
+ long the push service holds an undelivered message (seconds, default 86400).
86
+ A payload over 3000 bytes is refused with `PUSH_PAYLOAD_TOO_LARGE`; push an
87
+ id or URL and fetch the rest. A device the browser has revoked answers `gone` and is
88
+ removed.
89
+
90
+ Sending and reading history are server operations: a function or a developer
91
+ key. A browser session can register and remove only its own devices.
92
+
93
+ ## Register from a function instead
94
+
95
+ When your page already posts to your own function, register there:
96
+
97
+ ```ts
98
+ // api/push-device.ts — POST the PushSubscription's toJSON()
99
+ export default async function (req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
100
+ if (req.method !== 'POST') return new Response(null, { status: 405, headers: { Allow: 'POST' } })
101
+ const subscription = await req.json()
102
+ return Response.json(await sw.push.subscribe(subscription, { label: 'Phone' }))
103
+ }
104
+ ```
105
+
106
+ `sw.push.subscribe(subscription, { label? })` and
107
+ `sw.push.unsubscribe(endpoint)` act for the signed-in user of the request and
108
+ fail with `AUTH_REQUIRED` without one. `sw.push.vapidPublicKey()` returns the
109
+ `applicationServerKey` for `PushManager.subscribe()`.
110
+
111
+ One browser subscription is one device. Re-registering the same endpoint
112
+ with the same keys moves it to whoever is signed in, so a shared browser
113
+ follows its current user; the same endpoint with different keys is refused
114
+ with `PUSH_SUBSCRIPTION_CONFLICT` unless it comes from the device's own user.
115
+ Endpoints must come from a browser push service (Chrome, Edge, Firefox,
116
+ Safari); any other URL is refused with `VALIDATION_ERROR`.
117
+
118
+ ## Why didn't it arrive? Send history
119
+
120
+ ```ts
121
+ const { deliveries } = await sw.push.deliveries({ user_id: 'usr_123', limit: 20 })
122
+ // [{ device_label: 'Chrome on Android', outcome: 'sent', http_status: 201, title, url, created_at, ... }]
123
+ const { subscriptions } = await sw.push.subscriptions({ user_id: 'usr_123' })
124
+ ```
125
+
126
+ `outcome` is `sent` (the push service accepted it), `failed` (with
127
+ `http_status` and a reason), `gone` (the browser revoked the device; it was
128
+ removed) or `captured` (a test inbox device). Reads return the last 7
129
+ days and never contain keys or full endpoints. If a send could not record its
130
+ history, its result says `history_recorded: false`; the notifications were
131
+ still sent, so don't resend. The same reads are
132
+ `GET /v1/push/deliveries` and `GET /v1/push/subscriptions` with a developer
133
+ key, and the `push_deliveries` tool.
134
+
135
+ ## Push test inbox
136
+
137
+ A test device captures sends instead of delivering them, so a hosted or
138
+ headless browser can prove a notification reached a user:
139
+
140
+ ```ts
141
+ await enablePush({ test: true }) // no permission prompt, no service worker
142
+ ```
143
+
144
+ or `sw.push.subscribe({ test: true })` in a function. A test device is an
145
+ explicit opt-in: each signed-in user can turn on one for themselves. Sends to
146
+ that user then record a `captured` delivery that includes the full payload,
147
+ which the developer can read with `sw.push.deliveries({ user_id })` for 7
148
+ days. `disablePush({ test: true })` removes it.
149
+
150
+ ## Developer devices
151
+
152
+ `push_subscribe` and `POST /v1/push/subscribe` with a developer key register
153
+ your own browser for operator alerts. These devices carry no user id, so
154
+ `send({ user_id })` never reaches them; send to them with
155
+ `audience: 'developer'`.
156
+
157
+ A device listed with `owner: 'legacy'` has no verified owner.
158
+ No send reaches it, and a send that names it returns
159
+ `PUSH_DEVICE_REREGISTER_REQUIRED` (409). It becomes a normal device when its
160
+ browser registers again: the user turns notifications on with `enablePush()`,
161
+ or you call `push_subscribe` with the same subscription.
@@ -0,0 +1,67 @@
1
+ # sw.rateLimit — Rate limiting
2
+
3
+ Throttle abusive callers without standing up Redis or a token-bucket
4
+ library. One method, fixed-window counter, per-second granularity.
5
+
6
+ For one route, set `rateLimit: '30/minute'` on `sw.endpoint`.
7
+ With `auth: 'required'` or `'optional'`, signed-in callers are limited
8
+ by their verified user ID. Other callers are limited by IP. Each request path has its own counter
9
+ (each distinct URL on a dynamic route). The wrapper
10
+ answers 429 with `Retry-After` when the limit is reached; see `sw.endpoint`.
11
+
12
+ ## sw.rateLimit.check(key, max, windowSeconds)
13
+
14
+ Returns `{ allowed, remaining, reset, limit, window_seconds }`.
15
+ On `allowed: false`, return 429 to the caller. `reset` is the epoch
16
+ seconds when the current window rolls over.
17
+
18
+ A check stops waiting after five seconds. If it cannot confirm the answer,
19
+ it throws instead of allowing the action. The counter may already have
20
+ advanced; the failed check is not automatically retried.
21
+
22
+ ## Optional per-IP action throttle
23
+
24
+ Built-in password sign-in already has automatic attempt limits and progressive
25
+ lockout (`somewhere docs sw.auth --section automatic-password-sign-in-protection`).
26
+ This example adds a separate limit to an app-specific action; it is not a
27
+ required login setup step. Choose a limit that fits that action's normal use.
28
+
29
+ ```js
30
+ export default async function (req, sw) {
31
+ const ip = req.headers.get('cf-connecting-ip') || 'unknown'
32
+ const rl = await sw.rateLimit.check(`my-action:${ip}`, 5, 60)
33
+ if (!rl.allowed) {
34
+ return Response.json(
35
+ { error: 'too_many_attempts', retry_at: rl.reset },
36
+ { status: 429 }
37
+ )
38
+ }
39
+ // …validate and perform the app-specific action
40
+ }
41
+ ```
42
+
43
+ ## Per-user API throttle
44
+
45
+ ```js
46
+ const user = await sw.auth.fromRequest(req)
47
+ if (!user) return Response.json({ error: 'sign in' }, { status: 401 })
48
+ const rl = await sw.rateLimit.check(`api:${user.id}`, 100, 60)
49
+ if (!rl.allowed) return Response.json({ error: 'rate_limited' }, { status: 429 })
50
+ ```
51
+
52
+ ## Per-endpoint global cap
53
+
54
+ ```js
55
+ const rl = await sw.rateLimit.check('signup', 1000, 3600) // 1k signups/hour
56
+ if (!rl.allowed) return Response.json({ error: 'paused' }, { status: 429 })
57
+ ```
58
+
59
+ ## Notes
60
+
61
+ - Keys are scoped per project automatically — `login:1.2.3.4` in your
62
+ app does not collide with the same key in someone else's app.
63
+ - `max` is a positive integer up to 1,000,000.
64
+ - `windowSeconds` is between 1 and 86,400 (24h).
65
+ - Concurrent requests can exceed the requested count before all serving
66
+ instances record them. Use this counter for request throttling rather
67
+ than exact accounting.
@@ -0,0 +1,128 @@
1
+ # sw.web — Read pages from the public web
2
+
3
+ Available inside any deployed function via the sw argument
4
+ provided to the handler.
5
+
6
+ sw.web fetches public web pages and returns their content as clean
7
+ markdown. Use it when an agent or feature needs to ingest content from
8
+ a URL it doesn't host — docs, blog posts, marketing pages, articles.
9
+ The platform makes the request, so your function needs no provider key.
10
+
11
+ ## sw.web.scrape(url, opts?)
12
+
13
+ Fetch a URL and return its content as markdown by default. Strips
14
+ nav/footer/sidebar so you get the main article body.
15
+
16
+ ```ts
17
+ // api/read-guide.ts — POST /api/read-guide
18
+ export default async (req: Request, sw: SomewhereRuntimeContext): Promise<Response> => {
19
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405, headers: { Allow: 'POST' } })
20
+ await sw.auth.requireUser(req)
21
+ const page = await sw.web.scrape('https://somewhere.cloud/docs/deploy')
22
+ return Response.json({
23
+ url: page.url, title: page.title, status_code: page.status_code,
24
+ markdown: page.markdown ?? '',
25
+ })
26
+ }
27
+ ```
28
+
29
+ `status_code` is the page's own HTTP status. An error page's content comes
30
+ back like any other page's, so check `status_code` before using the content.
31
+
32
+ opts:
33
+ formats? — array of: markdown | html | rawHtml | links | screenshot
34
+ Default: ['markdown'].
35
+ only_main? — strip nav/footer/sidebar (default true). Set false to
36
+ keep the full DOM.
37
+ wait_for? — ms to wait for the page to settle (max 30000). Use for
38
+ SPAs that hydrate after initial load.
39
+
40
+ ## sw.web.search(query, opts?)
41
+
42
+ Search the public web by keyword. Returns ranked result URLs +
43
+ titles + snippets — no page bodies. Pair with `sw.web.scrape` when
44
+ you want the full content of a specific result.
45
+
46
+ ```ts
47
+ // api/web-search.ts — POST /api/web-search
48
+ export default async (req: Request, sw: SomewhereRuntimeContext): Promise<Response> => {
49
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405, headers: { Allow: 'POST' } })
50
+ const user = await sw.auth.requireUser(req)
51
+ // This app allows each user 10 web searches per hour.
52
+ const limit = await sw.rateLimit.check(`web-search:${user.id}`, 10, 3600)
53
+ if (!limit.allowed) return Response.json({ error: 'Too many searches. Try again later.' }, { status: 429 })
54
+ const hits = await sw.web.search('react server components streaming', { count: 5 })
55
+ // hits = {
56
+ // query: '...', count: 5,
57
+ // results: [
58
+ // { url: '...', title: '...', description: '...', age: '2 days ago', source: 'blog.example.dev' },
59
+ // ...
60
+ // ]
61
+ // }
62
+ return Response.json(hits.results.map((hit) => ({ url: hit.url, title: hit.title })))
63
+ }
64
+ ```
65
+
66
+ opts:
67
+ count? — 1 to 20, default 10.
68
+ country? — 2-letter code to bias results, e.g. 'us', 'gb', 'de'.
69
+ freshness? — 'pd' (past day) | 'pw' (past week) | 'pm' (past month)
70
+ | 'py' (past year).
71
+ safesearch? — 'off' | 'moderate' | 'strict'. Default 'moderate'.
72
+
73
+ ## When to use what
74
+
75
+ - Find URLs by keyword → `sw.web.search`. Returns titles + snippets.
76
+ - One page → `sw.web.scrape`. Returns markdown ready for an LLM prompt.
77
+ - Search, then scrape the top results. Each scrape succeeds or fails on its
78
+ own, so collect them with `Promise.allSettled`: one failed page keeps its
79
+ error code and the other pages keep their content.
80
+
81
+ ```ts
82
+ // api/research.ts — POST /api/research?q=...
83
+ export default async (req: Request, sw: SomewhereRuntimeContext): Promise<Response> => {
84
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405, headers: { Allow: 'POST' } })
85
+ await sw.auth.requireUser(req)
86
+ const question = new URL(req.url).searchParams.get('q')?.trim()
87
+ if (!question) return Response.json({ error: 'q is required' }, { status: 400 })
88
+
89
+ const hits = await sw.web.search(question, { count: 3 })
90
+ const urls = hits.results.map((hit) => hit.url)
91
+ const settled = await Promise.allSettled(urls.map((url) => sw.web.scrape(url)))
92
+
93
+ const pages = settled.map((result, i) => {
94
+ if (result.status === 'fulfilled') {
95
+ const page = result.value
96
+ return { url: urls[i], ok: true, status_code: page.status_code, title: page.title, markdown: page.markdown ?? '' }
97
+ }
98
+ const err = result.reason as { code?: string; status?: number } | undefined
99
+ return { url: urls[i], ok: false, code: err?.code ?? 'SCRAPE_FAILED', status: err?.status ?? null }
100
+ })
101
+ return Response.json({ query: hits.query, pages })
102
+ }
103
+ ```
104
+
105
+ The handler requires sign-in before making search or scrape calls. A failed
106
+ search still throws. Uncaught, the request answers 500 `FUNCTION_ERROR`,
107
+ and the project’s logs record the search error’s code.
108
+
109
+ - A whole site → not supported; scrape pages individually.
110
+
111
+ ## Errors
112
+
113
+ A refused or failed call throws an Error with `.code` and `.status`.
114
+ Rate-limit errors also carry `.retry_after_ms` when the platform sets one.
115
+
116
+ VALIDATION_ERROR (400) — a bad argument: the url or query is missing
117
+ or too long, the url is not a public http(s)
118
+ address, or an option has an invalid value.
119
+ RATE_LIMITED (429) — the project's per-minute limit for scrape or
120
+ search, or the provider is still busy after
121
+ the platform's one retry. Wait and call again.
122
+ UPSTREAM_QUOTA (402) — the platform's scrape or search allowance
123
+ with the provider is used up.
124
+ UPSTREAM_ERROR (502) — the provider failed, answered with an error,
125
+ returned an unreadable result, or could not
126
+ be reached.
127
+ UPSTREAM_NOT_CONFIGURED (503) — scrape or search has no provider set up in
128
+ this environment.