@somewhere-cloud/cli 0.38.149 → 0.38.151

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.
@@ -43507,7 +43507,7 @@ var FIRST_CLI_PERMISSION;
43507
43507
  var init_first_cli_permission = __esm({
43508
43508
  "dist/lib/first-cli-permission.js"() {
43509
43509
  "use strict";
43510
- FIRST_CLI_PERMISSION = "Before your first Somewhere command for a user, ask their permission and say where it will run, either as an npm package in your own cloud workspace (nothing installs on their computer) or as an npm package on their machine. Approval in their first message covers this.";
43510
+ FIRST_CLI_PERMISSION = "Ask before destructive or paid actions unless the user already authorized them.";
43511
43511
  }
43512
43512
  });
43513
43513
 
@@ -44092,236 +44092,65 @@ var init_skills_pack = __esm({
44092
44092
  });
44093
44093
 
44094
44094
  // dist/lib/init-agent-guide.js
44095
- var AGENT_WORKFLOW, SKILLS_POINTER, PORTABILITY_POINTER, MCP_POINTER, PREVIEW_POINTER, TEST_ACCESS_RULES, INIT_AGENTS_MD, INIT_CLAUDE_MD;
44095
+ var AGENT_WORKFLOW, SKILLS_POINTER, PORTABILITY_POINTER, MCP_POINTER, PREVIEW_POINTER, INIT_AGENTS_MD, INIT_CLAUDE_MD;
44096
44096
  var init_init_agent_guide = __esm({
44097
44097
  "dist/lib/init-agent-guide.js"() {
44098
44098
  "use strict";
44099
- init_first_cli_permission();
44100
44099
  init_skills_pack();
44101
44100
  AGENT_WORKFLOW = `## Build, deploy, test
44102
44101
 
44103
- Enough to start a typical app: declare access and use the browser client; docs are for exceptions.
44104
-
44105
- | Requirement | Declaration below |
44102
+ | Does your app verify emails? | Choose the declared access rule |
44106
44103
  | --- | --- |
44107
- | Each user sees only their own rows | notes: owner() |
44108
- | Team: owner invites members; members read/write; creator or team owner deletes | tasks: anyOf(owner(), group()); sw.groups endpoints below |
44109
- | Owner/staff record with staff-only child notes | tickets: owner() or appRole(); parent() thread; staff-only notes; staff by verified emailDomain (or grantableBy) |
44110
- | Public pages from private drafts | pages: conditional publicRead |
44111
- | Share one record read-only | shared_notes/note_shares: read-only grant() |
44112
-
44113
- db/schema.ts is declaration only: imports, constants/spreads, default schema;
44114
- no helpers/expressions. id() is random text; owner() stamps user_id. client.read
44115
- includes the key. Inside anyOf(), owner() takes only column/read: it stamps the
44116
- creator, not create/delete options; group() gates placement (non-member create is
44117
- refused); inside anyOf an operation missing from roles allows no group role. Other fields: timestamp({ default: 'now' }), text({ nullable: true });
44118
- indexes: [['team_id']].
44119
-
44120
- \`\`\`ts
44121
- import { schema, table, id, text, owner, group, anyOf, parent, appRole, boolean, grant } from 'somewhere/db';
44122
- export default schema({
44123
- notes: table({ id: id(), title: text() }, { scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'], delete: true },
44124
- }),
44125
- tasks: table({ id: id(), team_id: text(), title: text() }, {
44126
- scope: anyOf(owner(), group({ column: 'team_id', roles: { read: ['owner', 'admin', 'member'],
44127
- create: ['owner', 'admin', 'member'], update: ['owner', 'admin', 'member'], delete: ['owner'] } })),
44128
- client: { read: ['id', 'team_id', 'title'], create: ['team_id', 'title'], update: ['title'], delete: true },
44129
- }),
44130
- tickets: table({ id: id(), subject: text() }, {
44131
- scope: anyOf(owner(), appRole({ roles: { read: ['staff'], create: ['staff'], update: ['staff'] } })),
44132
- client: { read: true, create: ['subject'], update: ['subject'] },
44133
- }),
44134
- messages: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {
44135
- scope: parent({ via: 'ticket_id' }),
44136
- client: { read: true, create: ['ticket_id', 'body'] },
44137
- }),
44138
- staff_notes: table({ id: id(), ticket_id: text({ references: 'tickets' }), body: text() }, {
44139
- scope: appRole({ roles: { read: ['staff'], create: ['staff'] } }),
44140
- client: { read: true, create: ['ticket_id', 'body'] },
44141
- }),
44142
- pages: table({ id: id(), title: text(), published: boolean({ default: false }) }, {
44143
- scope: owner(), client: { read: ['id', 'title'], create: ['title'], update: ['title'],
44144
- publicRead: { where: { published: true } } },
44145
- }),
44146
- note_shares: table({ id: id(), grantee_id: text(), note_id: text({ references: 'shared_notes', onDelete: 'cascade' }) }, {
44147
- scope: owner(), unique: [['note_id', 'grantee_id']],
44148
- }),
44149
- shared_notes: table({ id: id(), title: text() }, {
44150
- scope: anyOf(owner(), grant({ table: 'note_shares', grantee: 'grantee_id', row: 'note_id', operations: ['read'] })),
44151
- client: { read: ['id', 'title'], create: ['title'], update: ['title'] },
44152
- }),
44153
- }, { appRoles: { staff: { emailDomain: 'staff.example' } } });
44154
- \`\`\`
44104
+ | Yes, invited teams | Use \`group()\` and \`sw.groups\` for invitations, membership and owner/admin permissions. See \`somewhere docs sw.groups --section team-example\`. |
44105
+ | No, app-managed teams | Use \`member()\` over a server-only roster. Declare author-or-team-owner delete with \`anyOf()\` and a role-filtered branch. See \`somewhere docs declared-data --section teams-without-email-verification\`. |
44106
+ | Yes, staff by domain | Use \`appRole()\` and \`appRoles: { staff: { emailDomain: 'staff.example' } }\`. The address must be verified. |
44107
+ | No, staff by invitation | Use \`appRole()\` and \`assignedBy: 'server'\`. Redeem an app-issued invitation and call \`sw.auth.server.setRoles\` inside the sign-up route. See \`somewhere docs sw.auth --section server-assigned-app-roles-setroles\`. |
44108
+ | Either, personal rows | Use \`owner()\`. The platform stamps the owner from the signed-in user. |
44109
+ | Either, shared private row | Use a read-only \`grant()\` for a known app-user ID. Share by address only after verification. Adding the grant widens existing caller-scoped reads. See \`somewhere docs declared-data --section read-only-sharing-without-email-verification\`. |
44110
+ | Either, public pages from private drafts | Use conditional \`client.publicRead\`. Anonymous results can be cached for up to 120 seconds. For fresh pages, read with \`sw.db.server.from\` in a page handler, filter for published rows, select public fields, and set \`Cache-Control: no-store\`. |
44155
44111
 
44156
- Who is staff is your app's decision; the platform enforces what the role may do.
44157
- First choice, as above: emailDomain. The role holds once the person verifies an address
44158
- at that domain; no grant code. An email ending alone proves nothing: anyone can sign up
44159
- as anyone@your-domain without owning that mailbox. Without verification, grant only from
44160
- something the visitor cannot choose, such as an invitation your app issued, checked inside
44161
- the sign-up route: single use, bound to one account, its link delivered only to that person:
44162
- somewhere docs sw.auth --section server-assigned-app-roles-setroles.
44163
- messages use parent(): owner() would hide staff replies from the customer.
44164
- A staff reply is a messages row, and creating a parent() child needs create on the parent
44165
- for that person: its owner, or a role listed under the parent's create. Read or update is
44166
- not enough. So tickets lists create: ['staff']; without it every staff reply is refused
44167
- (403 POLICY_AUTHORITY_REQUIRED).
44168
- Publish pages in an owner-checked endpoint. Share with caller-scoped
44169
- sw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.
44170
- Browser calls THROW, not { error }; catch below.
44171
- Browser list: paginate with after. Sort locally or in an endpoint.
44172
-
44173
- \`\`\`ts
44174
- import { data } from 'somewhere:data';
44175
- export async function save(title: string) {
44176
- try { await data.notes.create({ title }); return null; }
44177
- catch (e) { return e instanceof Error ? e.message : 'Save failed'; }
44178
- }
44179
- export const list = (after?: string) => data.notes.list({ limit: 100, after });
44180
- \`\`\`
44112
+ ### Schema and data
44181
44113
 
44182
- A page that needs several reads: start them together and show it once every read it depends on has answered.
44183
- Keep an input disabled until the data it depends on has loaded, including who the user is.
44184
- Never let a late answer overwrite what the user typed: fill an input from loaded data only before it is enabled.
44185
-
44186
- Teams are built-in groups: the platform keeps the team, invitations, roster, removal,
44187
- leaving, last owner. Starting a team needs a signed-in user; joining needs a verified
44188
- email (a password sign-up joins once it enters its emailed code).
44189
- No email verification in your app: keep membership in your own table with member() (somewhere docs sw.groups --section relationships-that-are-not-teams) and assign staff with setRoles in the sign-up route (above).
44190
- The browser cannot call
44191
- sw.groups: pass each call through an endpoint. A parent() child's delete follows the task
44192
- (creator or team owner), so "comment author or team owner deletes" is an endpoint.
44193
- Staff making others staff: appRoles { staff: { grantableBy: ['staff'] } } and
44194
- sw.groups.appRoles.grant(request, userId, 'staff') in an endpoint (never to oneself).
44195
- Complete apps and specs: somewhere docs sw.groups --section team-example or staff-example.
44196
-
44197
- \`\`\`ts
44198
- // api/teams.ts \u2014 GET my teams (completes invitations to me); POST starts one I own
44199
- const refusal = (e: { code: string; message: string; status: number }) =>
44200
- Response.json({ error: e.code, message: e.message }, { status: e.status });
44201
- export const GET = sw.endpoint({ auth: 'required', handler: async ({ request }, sw) => {
44202
- const page = await sw.groups.list(request, { limit: 100 });
44203
- return page.error ? refusal(page.error) : { teams: page.data.items, next_cursor: page.data.next_cursor };
44204
- } });
44205
- export default sw.endpoint({ auth: 'required', body: { name: 'string' }, handler: async ({ request, body }, sw) => {
44206
- const made = await sw.groups.create(request, { name: body.name });
44207
- return made.error ? refusal(made.error) : { id: made.data.id };
44208
- } });
44209
- \`\`\`
44114
+ Declare tables in \`db/schema.ts\` with imports, literal values, constants and spreads.
44115
+ New \`id()\` keys are text. Reference them with \`text({ references: 'table_name' })\`.
44116
+ Existing integer IDs stay integers. Declare composite uniqueness with \`unique: [['a', 'b']]\`.
44210
44117
 
44211
- \`\`\`ts
44212
- // api/teams/[id]/invitations.ts \u2014 owners invite; others 403; a member's address 409 ALREADY_MEMBER
44213
- export default sw.endpoint({ auth: 'required', body: { email: 'string' }, handler: async ({ request, params, body }, sw) => {
44214
- const sent = await sw.groups.invite(request, params.id, { email: body.email, role: 'member', redirect_uri: '/' });
44215
- return sent.error ? Response.json({ error: sent.error.code }, { status: sent.error.status }) : { delivery: sent.data.delivery };
44216
- } });
44217
- \`\`\`
44118
+ - Browser reads and writes use generated \`somewhere:data\`. \`client\` sets allowed operations and fields. Include the key in explicit read lists. Browser calls throw errors, and list pages use the returned \`next\` as \`after\` (at most 100 rows per page).
44119
+ - \`anyOf()\` grants access through either branch. \`allOf()\` requires both the membership gate and the action rule. \`parent()\` inherits the parent row's access. To let a child author update or delete, declare \`parent({ author, update, delete })\`. It evaluates the child author and the parent operation separately. For staff replies through \`parent()\`, grant staff create permission on the ticket's rule. See \`somewhere docs declared-data --section comments-that-their-author-may-edit\`.
44120
+ - \`sw.db.from/insert/update/remove\` apply the caller's scope and return \`{ data, count, changes }\`. Use \`where\`, \`columns\`, \`order\`, \`limit\` and \`offset\` for server reads. \`sw.db.tx\` takes an array of write intents. Supply related IDs up front.
44121
+ - Authorize before \`sw.db.server\` calls, which bypass the caller's scope. Keep declared scopes on records users work with, even when an exceptional write needs server authority. Use \`serverOnly()\` for protected ledgers and job state. Raw SQL uses a separate raw database.
44122
+ - For booking and help desk schemas, see \`somewhere docs sw.db --section provider-or-booker-and-owner-or-staff-recipes\`. For browser paging, server paging and transactions, see \`somewhere docs sw.db\`.
44218
44123
 
44219
- Same shape: sw.groups.get/members(request, id), remove(request, id, userId), leave(request, id)
44220
- (last owner: 409 LAST_OWNER), delete(request, id) by owners.
44124
+ Use \`client.intake\` for public submissions to a private parent row. See
44125
+ \`somewhere docs declared-data\` for intake, scoped writes and related rows.
44221
44126
 
44222
- Do not hand-write access to app-read/write data: declare who may read/write it.
44223
- serverOnly() fits job/import/audit/counter state.
44224
- Grant ledgers use owner() without browser writes. Undeclarable: arbitrary predicates
44225
- (e.g. expiry) or per-role writable fields (split tables or check that write).
44127
+ ### Routes and auth
44226
44128
 
44227
- Build src/pages/HomePage.tsx; routes src/App.tsx + src/routes.ts; auth src/auth/hooks.ts.
44228
- Auth is wired: keep api/auth/[...path].ts; src/config.ts controls providers.
44229
- api/notes/[id]/sub.ts \u2192 params.id; underscore files are helpers. POST: default export;
44230
- GET/DELETE: named exports.
44129
+ - \`src/App.tsx\` and \`src/routes.ts\` route React pages. \`api/notes/[id].ts\` serves \`/api/notes/:id\`. A root \`[...path].ts\` handles document routes, including \`/\`. Underscore-prefixed files are import-only helpers.
44130
+ - JSON routes use \`sw.endpoint({ auth, body, rateLimit, handler })\`. Set \`auth\` to \`'required'\`, \`'optional'\` or \`'none'\`. Use a limit like \`'30/minute'\`. Read route parameters from the handler's \`params\`. Use a default handler or named HTTP method exports. For streaming, webhooks or custom responses, use a bare \`(req, sw)\` handler and \`sw.params\`. See \`somewhere docs functions\`.
44131
+ - Keep \`api/auth/[...path].ts\` and extend the starter's \`src/auth/hooks.ts\`. Configure providers in \`src/config.ts\`. Gate private UI on auth state. Password sign-up starts unverified, and signed-in unverified users pass \`auth: 'required'\`. See \`somewhere docs auth-client\`.
44132
+ - Render a view when the reads it depends on finish. Keep inputs disabled until their initial data and identity are ready, and preserve edits when a late response arrives.
44133
+ - Browser requests use same-origin cookies. For scripted writes with a cookie session, send the app's origin in the \`Origin\` header. Use the CLI test helper to send data endpoint calls with the deployed contract digest.
44231
44134
 
44232
- \`\`\`ts
44233
- export const GET = sw.endpoint({ auth: 'required', handler: async (_, sw) => sw.db.from('notes', { limit: 100 }) });
44234
- \`\`\`
44135
+ ### Run and verify
44235
44136
 
44236
- sw.db applies caller scopes; sw.db.server bypasses them: authorize first.
44237
- Caller-scoped sw.db.insert needs no client.create grant: client limits only the browser.
44238
- Reads: from(table, { where, columns, order: [['id', 'asc']], limit, offset }).
44239
- Filter: { id: { in: ids } }; unique: [['a', 'b']] in schema.
44240
- Writes: insert(table, values), update(table, { where, set }), remove(table, { where }).
44241
- tx takes an ARRAY of write intents, never a callback; pre-generate related IDs.
44242
-
44243
- Browser: fetch(path, { method: 'POST', credentials: 'same-origin',
44244
- headers: { 'content-type': 'application/json' }, body: JSON.stringify(values) }).
44245
- Access cookies refresh automatically. Cookie-auth POST/PATCH/DELETE from scripts
44246
- need Origin equal to the app URL.
44247
-
44248
- After every deploy the platform checks the live app in its own browser: pages load signed out and as a
44249
- test user, a stranger and a signed-out visitor cannot read a person's data, and your saved checks pass.
44250
- Save each journey you want re-checked after every deploy as checks/<plain-name>.json; the platform runs them
44251
- in its browser after each deploy and \`somewhere test\` runs them now.
44252
- ${FIRST_CLI_PERMISSION}
44253
- Run them now: npx @somewhere-cloud/cli test (one PASS or FAIL line per check, failures first; exit 1 when one fails).
44254
- A saved check is the somewhere verify --flow actions list; "signed_in": true runs it as a test user the platform
44255
- creates and removes, and "viewports": ["desktop", "mobile"] runs it at both sizes:
44256
- { "actions": [ { "fill": "[data-testid=note-title]", "value": "Lunch with Ana 42" },
44257
- { "click": "[data-testid=note-save]" },
44258
- { "expect": { "selector": "[data-testid=note-item]", "text": "Lunch with Ana 42" } } ],
44259
- "signed_in": true, "viewports": ["desktop", "mobile"] }
44260
- Find controls by data-testid so renaming a button does not break a check; keep the ids when you restyle.
44261
- The notes starter ships this one as checks/add-a-note.json (note-title, note-save, note-item): start from it.
44262
- Open a list item by clicking the item element itself (what a person clicks), not a link inside it.
44263
- Deploy raw source, no frontend build; type errors stop upload.
44264
- The complete team spec, with removal and leaving: somewhere docs sw.groups --section team-example.
44265
- Diagnose with somewhere errors and somewhere logs.
44266
-
44267
- On demand:
44268
- - Server paging: \`somewhere docs sw.db --section server-read-paging\`
44269
-
44270
- ## Testing shared access
44271
-
44272
- With the team endpoints above, the owner invites a fixture by email; test users are verified,
44273
- so its next GET /api/teams shows the team. A test user who still owns a team is not deleted:
44274
- delete the team last (api/teams/[id].ts DELETE: sw.groups.delete). Group calls take
44275
- about a second, so raise the timeout:
44276
-
44277
- \`\`\`ts
44278
- // tests/team.spec.ts
44279
- import { test, expect } from '@somewhere-cloud/cli/testing';
44280
- test.describe.configure({ timeout: 90_000 });
44281
- test('owner invites a second user by email', async ({ newUser }) => {
44282
- const [owner, bob] = await Promise.all([newUser(), newUser()]);
44283
- const { id } = await (await owner.request.post('/api/teams', { data: { name: 'Shared team' } })).json();
44284
- expect((await owner.request.post(\`/api/teams/\${id}/invitations\`, { data: { email: bob.email } })).ok()).toBeTruthy();
44285
- const { teams } = await (await bob.request.get('/api/teams')).json();
44286
- expect(teams).toContainEqual(expect.objectContaining({ id, role: 'member' }));
44287
- expect((await owner.request.delete(\`/api/teams/\${id}\`)).status()).toBe(204);
44288
- });
44289
- \`\`\`
44290
- `;
44291
- SKILLS_POINTER = `Task-specific skills: \`${SKILLS_DIR}/\`. Inspect/update with somewhere skills status/update.`;
44292
- PORTABILITY_POINTER = "Data/code export limits: `somewhere docs portability`.";
44293
- MCP_POINTER = "Use this app from Claude as its signed-in user (MCP tools): `somewhere docs sw.endpoint --section mcp-tools-for-claude`.";
44294
- PREVIEW_POINTER = "somewhere preview runs your change on a copy of production data with its own sign-in: a preview starts with no users (sign up in it or `somewhere preview user-add`), its sign-in mail is captured (`somewhere preview mail`), and rows private to a production user stay hidden from preview users. Server user lookup, roles and built-in teams work in a preview (its own users, its own copy; team invitations are captured); jobs/cron handlers do not yet: check those in production after promoting (`somewhere docs dev-environments`). Test your change in the preview before you promote it: `somewhere test --preview`.";
44295
- TEST_ACCESS_RULES = `## Testing access rules
44296
-
44297
- In a linked test app, run \`somewhere test-users prepare alice bob\`. For an
44298
- owner() table with client create and read, create a fixture as Alice and read it
44299
- as both users:
44137
+ Run \`somewhere typecheck\` and focused tests. \`somewhere deploy-check\` checks compilation and schema without publishing. \`somewhere deploy\` uploads raw source directly to production. When testing changes with real users or data, use \`somewhere preview\`, test with \`somewhere test --preview\`, then promote. See \`somewhere docs dev-environments\`.
44300
44138
 
44301
- \`\`\`sh
44302
- ID=$(somewhere data create notes --as alice --values '{"title":"Access test"}' | jq -er 'select(.status == 200 and .kind == "ok") | .data.id') &&
44303
- somewhere data get notes --as alice --id "$ID" | jq -e '.status == 200 and .kind == "ok"' &&
44304
- somewhere data get notes --as bob --id "$ID" | jq -e '.status == 200 and .kind == "empty" and .data == null and .access == {"filtered":true}'
44305
- \`\`\`
44139
+ Save journeys in \`checks/<name>.json\`, using \`checks/add-a-note.json\` from the notes starter as a model. Keep test IDs when restyling and click the item a person would use. Set \`"signed_in": true\` for a test user and \`"viewports": ["desktop", "mobile"]\` to check both sizes. Saved checks run after deploy. Use \`somewhere test\` to rerun them and \`somewhere verify --flow flow.json\` for a focused journey. For shared access, test the owner, a recipient and an unrelated user separately. The team fixture is in \`somewhere docs sw.groups --section team-example\`. For schedules, trigger \`somewhere cron run <id> --wait\` before asserting its effects. Inspect failures with \`somewhere errors\` and \`somewhere logs\`.
44306
44140
 
44307
- 200 with access.filtered means the rule constrained the read, even when rows
44308
- are returned. 404 DATA_NOT_FOUND on update or delete hides whether the row
44309
- exists. 401 AUTH_REQUIRED needs a signed-in session. 403 names the access rule
44310
- or operation that refused the call. DATA_CONTRACT_* means the operation never
44311
- ran. Assert the exact outcome in handed-over tests and confirm a refused write
44312
- left the owner's fixture unchanged.
44141
+ Use \`somewhere docs <topic> --section <id>\` for one section or \`--full\` for all examples. Ask before destructive or paid actions unless the user already authorized them.
44313
44142
  `;
44143
+ SKILLS_POINTER = `Task-specific skills: \`${SKILLS_DIR}/\`. Inspect/update with somewhere skills status/update.`;
44144
+ PORTABILITY_POINTER = "Data/code export limits: `somewhere docs portability`.";
44145
+ MCP_POINTER = "App MCP tools: `somewhere docs app-mcp`.";
44146
+ PREVIEW_POINTER = "Preview users are separate from live users. Sign up in the preview or use `somewhere preview user-add`. Check captured mail with `somewhere preview mail`.";
44314
44147
  INIT_AGENTS_MD = `# somewhere.cloud project contract
44315
- ${FIRST_CLI_PERMISSION}
44316
-
44148
+ ${AGENT_WORKFLOW}
44317
44149
  ${SKILLS_POINTER}
44150
+ Without a global CLI, use \`npx @somewhere-cloud/cli deploy\` and \`npx @somewhere-cloud/cli test\`.
44318
44151
 
44319
- Build your app. Deploy the raw source and run its tests: \`npx @somewhere-cloud/cli deploy && npx @somewhere-cloud/cli test\`.
44320
-
44321
- For an app with sign-in, keep the starter's auth gate. Render private UI only after the session is confirmed. Keep the pending and retry views. In a browser test wait for the expected screen; if the SDK publishes \`data-sw-auth\` on \`<html>\`, first wait for the expected sign-in state there.
44152
+ For a signed-in browser test, wait for the SDK's expected \`data-sw-auth\` state when available. See \`somewhere docs auth-client --section wait-for-auth-in-a-browser-test\`. For direct data checks, prepare fixture users with \`somewhere test-users prepare alice bob\`, then call \`somewhere data get notes --as alice --id <id>\` as each user. Assert the exact outcome. See \`somewhere docs test --section testing-access-rules\`.
44322
44153
 
44323
- ${AGENT_WORKFLOW}
44324
- ${TEST_ACCESS_RULES}
44325
44154
  ${PORTABILITY_POINTER}
44326
44155
  ${MCP_POINTER}
44327
44156
  ${PREVIEW_POINTER}
@@ -44669,8 +44498,8 @@ var init_skills_pack_generated = __esm({
44669
44498
  BUNDLED_SKILLS_PACK = {
44670
44499
  "schema": 1,
44671
44500
  "name": "somewhere-skills",
44672
- "version": "1+c727c92e8193",
44673
- "sha256": "c727c92e81938d2e7cbf125de17c4d8a6feef4cf5bc4530f173f6dc04fe0da3e",
44501
+ "version": "1+30e51d444ef2",
44502
+ "sha256": "30e51d444ef28d9ad6eda0999739679f9fe13e9a102b8d908044694378bbfc96",
44674
44503
  "files": [
44675
44504
  {
44676
44505
  "path": "adopt/SKILL.md",
@@ -44679,18 +44508,18 @@ var init_skills_pack_generated = __esm({
44679
44508
  },
44680
44509
  {
44681
44510
  "path": "deploy-verify-loop/SKILL.md",
44682
- "sha256": "b394c2944cd64a48517dff6c80917b0e9332758f429e96600587ca91e4e951f8",
44683
- "content": '---\nname: deploy-verify-loop\ndescription: After edits, typecheck and run focused tests; verify the final deployed journey and rerun after relevant fixes.\n---\n\n# Deploy, verify, read the failure\n\n## The loop\n\nBefore your first Somewhere command for a user, ask their permission and say where it will run, either as an npm package in your own cloud workspace (nothing installs on their computer) or as an npm package on their machine. Approval in their first message covers this.\n\n```bash\nsomewhere typecheck\nsomewhere deploy\n```\n\nDon\'t bundle the source yourself; the platform runs the frontend build.\n\nRun `somewhere claim` and open its link to keep a temporary app.\n\n```bash\nsomewhere deploy-check --run /api/hello -X POST -d \'{"name":"Ada"}\'\n```\n\n| Step | Command | What it tells you |\n|---|---|---|\n| Verify | `somewhere verify [--flow flow.json]` | Runs the live app at desktop and phone sizes: named steps, console/network health, both screenshots. |\n| Inspect | `somewhere browser [target]` | One page: screenshot, snapshot, DOM, network, or an evaluated expression. |\n| Diagnose | `somewhere logs --tail 10`, `somewhere errors` | Recent function output, then failures split into refused and exception. `errors` also works on a temporary project. |\n\n## A flow for verify --flow\n\n```json\n{ "actions": [{ "fill": "#title", "value": "Verify entry" }, { "fill": "#from_email", "value": "v@example.com" },\n { "click": "#send" }, { "expect": { "selector": "#status", "text": "Received" } }], "viewports": ["desktop"] }\n```\n\n`passed` requires successful steps and request expectations, no page errors, and no unexpected failed requests. It can be false even when every step succeeded.\n\n## Failure 1: the live site still shows the old version\n\nBrowser or CDN cache. Hard-reload (Cmd-Shift-R), or check with `curl -sI https://{subdomain}.somewhere.site`.\n\n## Failure 2: a route fails\n\nShow recent failures with a `kind` column: **refused** for a 4xx your own handler returned on purpose, **exception** for an uncaught throw or a 5xx.\n\nThe `stack` field is the single most useful field for debugging \u2014 it tells you the exact file + line in your code where the throw originated.\n\n| `somewhere rollback [project]` | `-y, --yes`, `--json` | Select the previous retained production release. By default this changes code without restoring data. |\n\nSources (`somewhere docs <topic>`): browser, cli, common-mistakes, deploy, getting-started, recipe-signed-in-app, troubleshooting.\n'
44511
+ "sha256": "a8d6850065722efe3098ed54008d22066d8274338b037758d0d8490df7e68986",
44512
+ "content": '---\nname: deploy-verify-loop\ndescription: After edits, typecheck and run focused tests; verify the final deployed journey and rerun after relevant fixes.\n---\n\n# Deploy, verify, read the failure\n\n## The loop\n\nAsk before destructive or paid actions unless the user already authorized them.\n\n```bash\nnpx somewhere typecheck\nnpx somewhere deploy\n```\n\nDon\'t bundle the source yourself; the platform runs the frontend build.\n\nRun `somewhere claim` and open its link to keep a temporary app.\n\n```bash\nsomewhere deploy-check --run /api/hello -X POST -d \'{"name":"Ada"}\'\n```\n\n| Step | Command | What it tells you |\n|---|---|---|\n| Verify | `somewhere verify [--flow flow.json]` | Runs the live app at desktop and phone sizes: named steps, console/network health, both screenshots. |\n| Inspect | `somewhere browser [target]` | One page: screenshot, snapshot, DOM, network, or an evaluated expression. |\n| Diagnose | `somewhere logs --tail 10`, `somewhere errors` | Recent function output, then failures split into refused and exception. `errors` also works on a temporary project. |\n\n## A flow for verify --flow\n\n```json\n{ "actions": [{ "fill": "#title", "value": "Verify entry" }, { "fill": "#from_email", "value": "v@example.com" },\n { "click": "#send" }, { "expect": { "selector": "#status", "text": "Received" } }], "viewports": ["desktop"] }\n```\n\n`passed` requires successful steps and request expectations, no page errors, and no unexpected failed requests. It can be false even when every step succeeded.\n\n## Failure 1: the live site still shows the old version\n\nBrowser or CDN cache. Hard-reload (Cmd-Shift-R), or check with `curl -sI https://{subdomain}.somewhere.site`.\n\n## Failure 2: a route fails\n\nShow recent failures with a `kind` column: **refused** for a 4xx your own handler returned on purpose, **exception** for an uncaught throw or a 5xx.\n\nThe `stack` field is the single most useful field for debugging \u2014 it tells you the exact file + line in your code where the throw originated.\n\n| `somewhere rollback [project]` | `-y, --yes`, `--json` | Select the previous retained production release. By default this changes code without restoring data. |\n\nSources (`somewhere docs <topic>`): browser, cli, common-mistakes, deploy, getting-started, recipe-signed-in-app, troubleshooting.\n'
44684
44513
  },
44685
44514
  {
44686
44515
  "path": "schema-changes/SKILL.md",
44687
- "sha256": "ab5a21715672de983d2bb1ed19822563a8d94fad936b2424f3653c0c087642b2",
44688
- "content": "---\nname: schema-changes\ndescription: Before adding, changing, or removing a table or column in db/schema.ts.\n---\n\n# Change the database schema safely\n\n## The file is the contract\n\nThe default `somewhere init` starter has no `db/schema.ts`: create it at the project root, or run `somewhere init --name my-app --features private-data` to start with a schema.\n\n```ts\n// db/schema.ts\nimport { id, owner, schema, table, text, timestamp } from 'somewhere/db';\n\nexport default schema({\n notes: table(\n {\n id: id(),\n title: text(),\n body: text({ default: '' }),\n created_at: timestamp({ default: 'now' }),\n },\n {\n scope: owner(),\n client: {\n read: ['id', 'title', 'body', 'created_at'],\n create: ['title', 'body'],\n update: ['title', 'body'],\n delete: true,\n },\n },\n ),\n});\n```\n\nA table without a `client` block can't be reached from the browser at all.\n\nBefore the first deploy, delete an unused starter table declaration outright: there is no deployed table to retire. After a table has been deployed, mark it `removedTable()` to retire it with 30-day data retention, including when the table is empty.\n\nRun `somewhere typecheck` before deploying schema changes.\n\n## What a deploy does with it\n\n- **Additive changes apply**: a new table, a new nullable-or-defaulted column, a new index, a new unique group. Unchanged schema is a no-op.\n- **Unmarked removals and shape changes refuse** with `409 SCHEMA_DEPLOY_REFUSED` and a message naming the change.\n- **Access-rule changes apply in place**: a later deploy can change an existing table's scope, and its rows stay.\n- a production deploy or a promotion that would remove or rename a column is refused before anything changes, so a running release never loses a column it uses. Keep the column declared and leave its data in place.\n\n## Failure: raw SQL refused after the schema file deploys\n\nOn an older shared database, ordinary `sw.db.query` / `sw.db.batch` fail before transport with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`, including in job, queue, and cron handlers; with a separate SQL database they run there and never see declared tables. Fix: write with `sw.db.insert` / `sw.db.update` / `sw.db.remove` (the table needs a declared intent)\n\nSources (`somewhere docs <topic>`): declared-data, getting-started, sw.db, troubleshooting.\n"
44516
+ "sha256": "3b74e0482260cc6673f12a2d5105950357dab8d0d9960fd5de8a3f54a153faef",
44517
+ "content": "---\nname: schema-changes\ndescription: Before adding, changing, or removing a table or column in db/schema.ts.\n---\n\n# Change the database schema safely\n\n## The file is the contract\n\nThe default `somewhere init` starter has no `db/schema.ts`: create it at the project root, or run `somewhere init --name my-app --features private-data` to start with a schema.\n\n```ts\n// db/schema.ts\nimport { id, owner, schema, table, text, timestamp } from 'somewhere/db';\n\nexport default schema({\n notes: table(\n {\n id: id(),\n title: text(),\n body: text({ default: '' }),\n created_at: timestamp({ default: 'now' }),\n },\n {\n scope: owner(),\n client: {\n read: ['id', 'title', 'body', 'created_at'],\n create: ['title', 'body'],\n update: ['title', 'body'],\n delete: true,\n },\n },\n ),\n});\n```\n\nA table without a `client` block can't be reached from the browser at all.\n\nDelete a never-deployed starter table's declaration and references. A `removedTable()` marker for it is a no-op. **Removing a table** is `old_table: removedTable()`. The deploy keeps the table while your previous version is still serving; once the new version is live it retires the table and keeps its data for 30 days.\n\nRun `somewhere typecheck` before deploying schema changes.\n\n## What a deploy does with it\n\n- **Additive changes apply**: a new table, a new nullable-or-defaulted column, a new index, a new unique group. Unchanged schema is a no-op.\n- **Unmarked removals and shape changes refuse** with `409 SCHEMA_DEPLOY_REFUSED` and a message naming the change.\n- **Access-rule changes apply in place**: a later deploy can change an existing table's scope, and its rows stay.\n- a production deploy or a promotion that would remove or rename a column is refused before anything changes, so a running release never loses a column it uses. Keep the column declared and leave its data in place.\n\n## Failure: raw SQL refused after the schema file deploys\n\nOn an older shared database, ordinary `sw.db.query` / `sw.db.batch` fail before transport with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`, including in job, queue, and cron handlers; with a separate SQL database they run there and never see declared tables. Fix: write with `sw.db.insert` / `sw.db.update` / `sw.db.remove` (the table needs a declared intent)\n\nSources (`somewhere docs <topic>`): declared-data, getting-started, sw.db, troubleshooting.\n"
44689
44518
  },
44690
44519
  {
44691
44520
  "path": "sign-in-setup/SKILL.md",
44692
- "sha256": "ffc4f29eb96c0a18c5ea0ce10308f696f227ec842c37e0bd70951b2284d885ba",
44693
- "content": "---\nname: sign-in-setup\ndescription: When the app needs users to sign up, sign in, or sign out.\n---\n\n# Set up sign-in\n\n## Server: one route file\n\n`login` / `signup` are developer-key-gated (the browser can't call them), so one server route mediates them and sets the session cookies.\n\n```ts\n// api/auth/[...path].ts\nexport { somewhereAuth as default } from '@somewhere-cloud/sdk/server';\n```\n\nIt serves `POST /signup`, `/login`, `/logout`, `/magic-link`, `/magic-link/verify`, `GET /me`, and the Google/GitHub/Discord `GET /<provider>-url` + `POST /<provider>` code exchange, and `POST /mfa/challenge`, the email sign-in code step: in the page, `auth.completeMfa({ code })` finishes a sign-in that rejected with code `MFA_REQUIRED` (`sw.auth` \u2192 `email-sign-in-codes`).\n\n## Client and React state reference\n\nRead `docs({ topic: 'auth-client', section: 'react-auth-state' })` for the SDK's React state contract. Extend the starter's existing provider and auth client.\n\n## Page: the SDK client\n\n```bash\nnpm i @somewhere-cloud/sdk\n```\n\n```ts\n// src/auth.ts \u2014 page code\nimport { createSomewhereAuth } from '@somewhere-cloud/sdk/auth'\n\nexport const auth = createSomewhereAuth()\n\n// Call from your sign-up form; throws AuthError with the message on failure.\nexport async function signUp(email: string, password: string) {\n await auth.signUp({ email, password }) // or auth.signIn({ email, password })\n return auth.getUser() // the signed-in user, or null\n}\nexport async function signOut() {\n await auth.signOut();\n if (auth.getState().signOutUnconfirmed) {\n throw new Error('Sign-out could not be confirmed. Please try again.');\n }\n // Only navigate or reload after confirmed logout.\n}\n```\n\nAwait `signOut()` in the click handler before navigating or reloading. While it is pending, keep the current screen or show a disabled signing-out state. Do not use the appearance of a signed-out form as proof that the server session has ended. After awaiting, check `auth.getState().signOutUnconfirmed`; show a retry message when true. `signOut()` can settle without confirming server logout.\n\nCalls to your own `api/*` functions just send `credentials: 'include'`.\n\nDon't write `getCookie()` / token-parsing helpers \u2192 `sw.auth.fromRequest(req)` reads cookie + Bearer header and returns the validated user (or null) in one call.\n\nMail to `<name>@<project>.test.somewhere.site` is read with `somewhere email test-inbox <address>`.\n\n## Failure 1: sign-in errors\n\nexpected failures (wrong password, duplicate email, weak password) come back as structured 4xx with the real message, never an opaque 500.\n\n## Failure 2: AUTH_REQUIRED from an owner() table\n\nThe table is user-owned, so the platform scopes it to a principal, and this request had none: there is no signed-in user, and this table does not declare `owner({ visitors: true })`, which is the declaration that accepts a stable anonymous visitor identity.\n\nSources (`somewhere docs <topic>`): auth-client, common-mistakes, recipe-signed-in-app, sdk, troubleshooting.\n"
44521
+ "sha256": "c0c2095f24ced94d6457389d4943b79cc101cc66adc60b23114944e3a64a0d71",
44522
+ "content": "---\nname: sign-in-setup\ndescription: When the app needs users to sign up, sign in, or sign out.\n---\n\n# Set up sign-in\n\n## Server: one route file\n\n`login` / `signup` are developer-key-gated (the browser can't call them), so one server route mediates them and sets the session cookies.\n\n```ts\n// api/auth/[...path].ts\nexport { somewhereAuth as default } from '@somewhere-cloud/sdk/server';\n```\n\nIt serves `POST /signup`, `/login`, `/logout`, `/magic-link`, `/magic-link/verify`, `GET /me`, and the Google/GitHub/Discord `GET /<provider>-url` + `POST /<provider>` code exchange, and `POST /mfa/challenge`, the email sign-in code step: in the page, `auth.completeMfa({ code })` finishes a sign-in that rejected with code `MFA_REQUIRED` (`sw.auth` \u2192 `email-sign-in-codes`).\n\n## Client and React state reference\n\nRead `docs({ topic: 'auth-client', section: 'react-auth-state' })` for the SDK's React state contract. Extend the starter's existing provider and auth client.\n\n## Page: the SDK client\n\n```bash\nnpm i @somewhere-cloud/sdk\n```\n\n```ts\n// src/auth.ts \u2014 page code\nimport { createSomewhereAuth } from '@somewhere-cloud/sdk/auth'\n\nexport const auth = createSomewhereAuth()\n\n// Call from your sign-up form; throws AuthError with the message on failure.\nexport async function signUp(email: string, password: string) {\n return auth.signUp({ email, password }) // or auth.signIn({ email, password })\n}\nexport async function signOut() {\n await auth.signOut();\n if (auth.getState().signOutUnconfirmed) {\n throw new Error('Sign-out could not be confirmed. Please try again.');\n }\n // Only navigate or reload after confirmed logout.\n}\n```\n\nAwait `signOut()` in the click handler before navigating or reloading. While it is pending, keep the current screen or show a disabled signing-out state. Do not use the appearance of a signed-out form as proof that the server session has ended. After awaiting, check `auth.getState().signOutUnconfirmed`; show a retry message when true. `signOut()` can settle without confirming server logout.\n\nCalls to your own `api/*` functions just send `credentials: 'include'`.\n\nDon't write `getCookie()` / token-parsing helpers \u2192 `sw.auth.fromRequest(req)` reads cookie + Bearer header and returns the validated user (or null) in one call.\n\nMail to `<name>@<project>.test.somewhere.site` is read with `somewhere email test-inbox <address>`.\n\n## Failure 1: sign-in errors\n\nexpected failures (wrong password, duplicate email, weak password) come back as structured 4xx with the real message, never an opaque 500.\n\n## Failure 2: AUTH_REQUIRED from an owner() table\n\nThe table is user-owned, so the platform scopes it to a principal, and this request had none: there is no signed-in user, and this table does not declare `owner({ visitors: true })`, which is the declaration that accepts a stable anonymous visitor identity.\n\nSources (`somewhere docs <topic>`): auth-client, common-mistakes, recipe-signed-in-app, sdk, troubleshooting.\n"
44694
44523
  },
44695
44524
  {
44696
44525
  "path": "troubleshooting/SKILL.md",
@@ -77374,7 +77203,7 @@ function parseDeployOutput(output, projectDir, functions) {
77374
77203
  if (contract.isIgnoredDiagnostic(code))
77375
77204
  continue;
77376
77205
  const kind = contract.classifyDiagnostic(code);
77377
- if (!kind)
77206
+ if (!kind || kind === "type" && vendor2.isPlainPageScript(file, functions))
77378
77207
  continue;
77379
77208
  const finding = { kind, code, file, line: Number(lineText), column: Number(columnText), message: message3 };
77380
77209
  if (vendor2.isRuntimeEndpointGlobal(finding, functions))
@@ -77384,9 +77213,9 @@ function parseDeployOutput(output, projectDir, functions) {
77384
77213
  }
77385
77214
  return { findings, problems };
77386
77215
  }
77387
- async function runDeployCheck(projectDir) {
77216
+ async function runDeployCheck(projectDir, onFetch) {
77388
77217
  try {
77389
- return await startDeployCheck(projectDir);
77218
+ return await startDeployCheck(projectDir, onFetch);
77390
77219
  } catch (error3) {
77391
77220
  return {
77392
77221
  ok: false,
@@ -77397,7 +77226,7 @@ async function runDeployCheck(projectDir) {
77397
77226
  };
77398
77227
  }
77399
77228
  }
77400
- async function startDeployCheck(projectDir) {
77229
+ async function startDeployCheck(projectDir, onFetch) {
77401
77230
  const typescript = DEPLOY_CHECK_TYPESCRIPT_VERSION;
77402
77231
  const collected = collectFiles(projectDir);
77403
77232
  const graph = {};
@@ -77408,6 +77237,7 @@ async function startDeployCheck(projectDir) {
77408
77237
  const checked = Object.keys(graph);
77409
77238
  if (checked.length === 0)
77410
77239
  return { ok: true, findings: [], typescript, checkedFiles: 0 };
77240
+ const { command, args } = deployCheckTsc(projectDir);
77411
77241
  const tsconfigPath = join17(projectDir, "tsconfig.json");
77412
77242
  const own2 = projectCompilerOptions(existsSync14(tsconfigPath) ? readFileSync16(tsconfigPath, "utf8") : void 0);
77413
77243
  const id = randomUUID5();
@@ -77429,11 +77259,12 @@ async function startDeployCheck(projectDir) {
77429
77259
  compilerOptions: contract.localCheckCompilerOptions(own2),
77430
77260
  files: [...checked, ...declarations]
77431
77261
  }));
77262
+ if (command !== process.execPath)
77263
+ onFetch?.();
77432
77264
  } catch (error3) {
77433
77265
  cleanup();
77434
77266
  throw error3;
77435
77267
  }
77436
- const { command, args } = deployCheckTsc(projectDir);
77437
77268
  const run = await runBounded(command, [...args, "--project", config2, "--pretty", "false"], projectDir, { onAbort: cleanup });
77438
77269
  cleanup();
77439
77270
  const out = run.out;
@@ -77927,7 +77758,7 @@ var init_lint = __esm({
77927
77758
  import { existsSync as existsSync17 } from "node:fs";
77928
77759
  import { join as join20, relative as relative9, resolve as resolve11 } from "node:path";
77929
77760
  function registerTypecheck(program2) {
77930
- program2.command("typecheck [dir]").description(`Check TypeScript and report advisory Somewhere source warnings. Reports TypeScript errors with file:line before deploy and exits 1 when there are any; \`${cliInvocation()} deploy\` stops on type errors. Requires a local tsconfig.json; add one for a new app, or run \`${cliInvocation()} pull\` for an existing deployed app. It never installs the project's dependencies: if the project has missing dependencies, it says so and stops; run npm install first. Without TypeScript in the project it fetches TypeScript with npx (network; npm caches it) and says so on stderr. Every run stops after SOMEWHERE_TYPECHECK_TIMEOUT_MS (default 300000). With --deploy, runs the deploy's advisory reference check instead (the files a deploy uploads, its generated types, options and TypeScript ${DEPLOY_CHECK_TYPESCRIPT_VERSION}) against the packages installed here; no tsconfig.json needed. It reports a narrower set than the default project check, which stays the stricter of the two.`).option("--json", "Print typecheck and platform source findings as JSON").option("--deploy", "Run the deploy's reference check: the undefined-name and type findings a deploy reports. Fetches TypeScript " + DEPLOY_CHECK_TYPESCRIPT_VERSION + " through npx unless the project has exactly that version").option("--hook <host>", `With --deploy: run as an agent after-edit hook (${AGENT_HOSTS.join(", ")}), reading the host's event on stdin. Installed by \`${cliInvocation()} hooks install\``).option("--watch", "Keep running and re-check after each save while this command is open. It is not installed into your editor or agent; start it yourself. Never deploys or touches live data").action(async (dirArg, opts) => {
77761
+ program2.command("typecheck [dir]").description(`Check the deployable source with the platform's TypeScript ${DEPLOY_CHECK_TYPESCRIPT_VERSION}, generated types and checker settings. Reports file and line for deploy-check type findings and exits 1 when there are findings. Install the project dependencies first. The CLI fetches the pinned TypeScript with npx if needed. Use --project to check the full project with its own tsconfig.json and compiler.`).option("--json", "Print typecheck and platform source findings as JSON").option("--deploy", "Run the deploy reference check and return its findings").addOption(new Option("--project", "Run the full project TypeScript check using tsconfig.json").conflicts("deploy")).option("--hook <host>", `With --deploy: run as an agent after-edit hook (${AGENT_HOSTS.join(", ")}), reading the host's event on stdin. Installed by \`${cliInvocation()} hooks install\``).option("--watch", "Keep running and re-check after each save while this command is open. It is not installed into your editor or agent; start it yourself. Never deploys or touches live data").action(async (dirArg, opts) => {
77931
77762
  const dir = resolve11(process.cwd(), dirArg ?? ".");
77932
77763
  for (const hint of roleMethodHints(dir))
77933
77764
  console.error(hint);
@@ -77950,11 +77781,16 @@ function registerTypecheck(program2) {
77950
77781
  process.stderr.write(outcome2.stderr);
77951
77782
  process.exit(outcome2.exitCode);
77952
77783
  }
77784
+ let deployFetchAnnounced = false;
77785
+ const announceDeployFetch = /* @__PURE__ */ __name(() => {
77786
+ if (deployFetchAnnounced)
77787
+ return;
77788
+ deployFetchAnnounced = true;
77789
+ announceDeployCheckFetch(dir);
77790
+ }, "announceDeployFetch");
77953
77791
  if (opts.deploy) {
77954
- if (/^npx(\.cmd)?$/.test(deployCheckTsc(dir).command))
77955
- announceDeployCheckFetch(dir);
77956
77792
  const check2 = /* @__PURE__ */ __name(async () => {
77957
- const result3 = await runDeployCheck(dir);
77793
+ const result3 = await runDeployCheck(dir, announceDeployFetch);
77958
77794
  if (opts.json)
77959
77795
  printJson(result3);
77960
77796
  else
@@ -77966,7 +77802,7 @@ function registerTypecheck(program2) {
77966
77802
  const result2 = await check2();
77967
77803
  process.exit(result2.ok ? 0 : 1);
77968
77804
  }
77969
- if (!existsSync17(join20(dir, "tsconfig.json"))) {
77805
+ if (opts.project && !existsSync17(join20(dir, "tsconfig.json"))) {
77970
77806
  if (opts.json) {
77971
77807
  printJson({
77972
77808
  ok: false,
@@ -77980,23 +77816,33 @@ function registerTypecheck(program2) {
77980
77816
  error(MISSING_TSCONFIG_GUIDANCE);
77981
77817
  process.exit(1);
77982
77818
  }
77819
+ const deployVia = deployCheckTsc(dir).command === process.execPath ? "project" : "npx";
77820
+ const via = opts.project ? typecheckCompilerSource(dir) : deployVia;
77983
77821
  const notInstalled = /* @__PURE__ */ __name(() => {
77984
77822
  const missing = missingProjectDependencies(dir);
77985
- return missing.length ? { ok: false, errors: [], via: typecheckCompilerSource(dir), raw: "", spawnError: missingTypecheckDependenciesMessage() } : null;
77823
+ return missing.length ? { ok: false, errors: [], via, raw: "", spawnError: missingTypecheckDependenciesMessage() } : null;
77986
77824
  }, "notInstalled");
77987
77825
  let announced = false;
77988
77826
  const announceFetch = /* @__PURE__ */ __name(() => {
77989
- if (announced || typecheckCompilerSource(dir) !== "npx")
77827
+ if (announced || via !== "npx")
77990
77828
  return;
77991
77829
  announced = true;
77992
77830
  announceNpxTypeScriptFetch(TYPECHECK_TYPESCRIPT_VERSION);
77993
77831
  }, "announceFetch");
77994
77832
  const check = /* @__PURE__ */ __name(async () => {
77995
77833
  const refused = notInstalled();
77996
- if (!refused)
77834
+ if (!refused && opts.project)
77997
77835
  announceFetch();
77998
77836
  const spinner = opts.json || refused || opts.watch ? null : ora("Typechecking (tsc --noEmit)...").start();
77999
- const result2 = refused ?? await runTypecheck(dir);
77837
+ const deployResult = refused || opts.project ? void 0 : await runDeployCheck(dir, announceDeployFetch);
77838
+ const result2 = deployResult ? {
77839
+ ok: deployResult.ok,
77840
+ errors: deployResult.findings,
77841
+ via,
77842
+ raw: deployResult.error ?? "",
77843
+ spawnError: deployResult.error,
77844
+ typescript: deployResult.typescript
77845
+ } : refused ?? await runTypecheck(dir);
78000
77846
  spinner?.stop();
78001
77847
  const sourceLint = await lintProject(dir).catch((failure2) => ({
78002
77848
  ok: false,
@@ -78005,7 +77851,10 @@ function registerTypecheck(program2) {
78005
77851
  if (opts.json)
78006
77852
  printJson({ ...result2, sourceLint });
78007
77853
  else {
78008
- reportTypecheck(result2);
77854
+ if (deployResult)
77855
+ reportDeployCheck(deployResult, "Typecheck");
77856
+ else
77857
+ reportTypecheck(result2);
78009
77858
  if ("error" in sourceLint)
78010
77859
  warn(`Source lint failed: ${sourceLint.error}`);
78011
77860
  else
@@ -78055,18 +77904,18 @@ function reportTypecheck(result) {
78055
77904
  }
78056
77905
  console.log("");
78057
77906
  }
78058
- function reportDeployCheck(result) {
77907
+ function reportDeployCheck(result, label = "Deploy check") {
78059
77908
  if (result.error) {
78060
77909
  error(`Could not run the deploy check (TypeScript ${result.typescript}): ${result.error}`);
78061
77910
  return;
78062
77911
  }
78063
77912
  if (result.ok) {
78064
- success(`Deploy check clean ${dim(`(${result.checkedFiles} file${result.checkedFiles === 1 ? "" : "s"}, TypeScript ${result.typescript})`)}.`);
77913
+ success(`${label} clean ${dim(`(${result.checkedFiles} file${result.checkedFiles === 1 ? "" : "s"}, TypeScript ${result.typescript})`)}.`);
78065
77914
  return;
78066
77915
  }
78067
77916
  const references = result.findings.filter((f2) => f2.kind === "reference").length;
78068
77917
  const n = result.findings.length;
78069
- error(`${bold(String(n))} deploy finding${n === 1 ? "" : "s"} ${dim(`(TypeScript ${result.typescript})`)} \u2014 a deploy reports these as warnings${references ? `; ${references} undefined name${references === 1 ? "" : "s"} will fail at runtime` : ""}.`);
77918
+ error(`${bold(String(n))} deploy finding${n === 1 ? "" : "s"} ${dim(`(TypeScript ${result.typescript})`)} \u2014 fix these before running \`${cliInvocation()} deploy-check\`${references ? `. Found ${references} undefined name${references === 1 ? "" : "s"}` : ""}.`);
78070
77919
  console.log("");
78071
77920
  for (const f2 of result.findings) {
78072
77921
  const tag = f2.kind === "reference" ? red(f2.code) : dim(f2.code);
@@ -78121,6 +77970,7 @@ var init_typecheck2 = __esm({
78121
77970
  "use strict";
78122
77971
  init_cli_invocation();
78123
77972
  init_role_method_hints();
77973
+ init_esm();
78124
77974
  init_esm4();
78125
77975
  init_spinner();
78126
77976
  init_deploy_check();
@@ -78140,6 +77990,21 @@ var init_typecheck2 = __esm({
78140
77990
  }
78141
77991
  });
78142
77992
 
77993
+ // dist/lib/check-summary.js
77994
+ function summarizeChecks(counts) {
77995
+ return { outcome: counts.failed ? "failed" : counts.could_not_check ? "could_not_check" : "passed", counts };
77996
+ }
77997
+ function checkSummaryExitCode(summary) {
77998
+ return summary.outcome === "failed" ? 1 : summary.outcome === "could_not_check" ? 2 : 0;
77999
+ }
78000
+ var init_check_summary = __esm({
78001
+ "dist/lib/check-summary.js"() {
78002
+ "use strict";
78003
+ __name(summarizeChecks, "summarizeChecks");
78004
+ __name(checkSummaryExitCode, "checkSummaryExitCode");
78005
+ }
78006
+ });
78007
+
78143
78008
  // dist/lib/deploy-checks.js
78144
78009
  function parseChecksRead(read) {
78145
78010
  const match = /^GET\s+(\/\S+)$/.exec(read.trim());
@@ -78183,33 +78048,133 @@ async function runChecksNow(client, projectId, opts = {}) {
78183
78048
  const started = await client.call("POST", "/deploy/checks", { project_id: projectId });
78184
78049
  return awaitDeployChecks(client, { read: started?.read }, { waitMs: TEST_CHECKS_WAIT_MS, ...opts });
78185
78050
  }
78186
- function formatChecksReport(check) {
78187
- if (!check || check.status === "pending") {
78188
- return [`The checks did not finish within ${TEST_CHECKS_WAIT_MS / 1e3} s; \`${cliInvocation()} call project_deploy_log '{}'\` shows the result when they do.`];
78189
- }
78190
- const lines = Array.isArray(check.checks) ? check.checks : [];
78051
+ function lineOutcome(line) {
78052
+ if (line.outcome)
78053
+ return line.outcome;
78054
+ if (line.pass)
78055
+ return "passed";
78056
+ return line.as === "stranger" || line.as === "signed_out" && line.method !== "flow" ? "could_not_check" : "failed";
78057
+ }
78058
+ function deployChecksSummary(check) {
78059
+ const lines = check?.checks ?? [];
78060
+ const counts = { passed: 0, failed: 0, could_not_check: cleanupFindings(check).length, warnings: functionWarnings(check).length };
78061
+ for (const line of lines)
78062
+ counts[lineOutcome(line)]++;
78063
+ if (check?.status !== "checked" || !lines.length || check.passed === false && !counts.failed && !counts.could_not_check && (!check.findings?.length || check.findings.some((finding) => finding.kind !== "crash")))
78064
+ counts.could_not_check++;
78065
+ return summarizeChecks(counts);
78066
+ }
78067
+ function checksJsonReport(check) {
78068
+ const summary = deployChecksSummary(check);
78069
+ const checked = check?.checks ?? [];
78070
+ const confirmedAccessFailure = checked.some((line) => line.outcome === "failed" && (line.as === "stranger" || line.as === "signed_out") && line.method !== "flow");
78071
+ const findings = (check?.findings ?? []).filter((item) => (item.kind !== "crash" || Boolean(item.request_id)) && (item.kind !== "read" && item.kind !== "write" || confirmedAccessFailure));
78072
+ return {
78073
+ ...check,
78074
+ checks: checked.map((line) => ({ ...line, pass: lineOutcome(line) === "passed", outcome: lineOutcome(line) })),
78075
+ findings,
78076
+ sentence: findings.length !== (check?.findings?.length ?? 0) ? null : check?.sentence ?? null,
78077
+ passed: summary.outcome === "passed",
78078
+ ...summary,
78079
+ not_checked: check?.not_checked ?? null
78080
+ };
78081
+ }
78082
+ function resultEvidence(line) {
78083
+ const request2 = line.request ?? { method: line.method, url: line.path };
78084
+ const responses = line.responses?.length ? line.responses : [{ status: line.status, observed: line.detail }];
78191
78085
  return [
78192
- ...lines.filter((line) => !line.pass).map((line) => `FAIL ${line.name}`),
78193
- ...lines.filter((line) => line.pass).map((line) => `PASS ${line.name}`),
78194
- ...check.sentence ? [check.sentence] : []
78086
+ ` Did: ${request2.method ?? "check"} ${request2.url ?? line.name} as ${line.as ?? "the test actor"}`,
78087
+ ...line.expected ? [` Expected: ${line.expected}`] : [],
78088
+ ...responses.map((r, i) => ` Response ${i + 1}: ${r.status ? `HTTP ${r.status}` : "no HTTP status"}${r.observed ? ` \u2014 ${r.observed}` : ""}${"request_id" in r && r.request_id ? ` (request ID ${r.request_id})` : ""}`),
78089
+ ` Reproduce: ${JSON.stringify(request2)}`,
78090
+ ...responses.flatMap((r) => "request" in r && r.request ? [` Confirmation request: ${JSON.stringify(r.request)}`] : [])
78195
78091
  ];
78196
78092
  }
78197
- function checksExitCode(check) {
78198
- return check?.passed === true ? 0 : 1;
78093
+ function formatChecksReport(check) {
78094
+ const summary = deployChecksSummary(check);
78095
+ const lines = [];
78096
+ if (!check || check.status === "pending") {
78097
+ lines.push(`Could not check: the run did not finish within ${TEST_CHECKS_WAIT_MS / 1e3} s.`);
78098
+ } else if (check.status !== "checked") {
78099
+ lines.push(`Could not check: ${check.sentence ?? "The check run is unavailable."}`);
78100
+ } else {
78101
+ const checks = check.checks ?? [];
78102
+ for (const line of checks.filter((item) => lineOutcome(item) !== "passed")) {
78103
+ const label = lineOutcome(line) === "failed" ? "FAIL" : "Could not check";
78104
+ lines.push(`${label} ${line.name}`, ...resultEvidence(line));
78105
+ if (line.detail && line.responses?.length)
78106
+ lines.push(` ${line.detail}`);
78107
+ if (!line.outcome && label === "Could not check")
78108
+ lines.push(` Run ${cliInvocation()} test --again to confirm this access check.`);
78109
+ }
78110
+ for (const line of checks.filter((item) => lineOutcome(item) === "passed")) {
78111
+ const observation = line.responses?.[0]?.observed || line.detail || "The stored result has no observation.";
78112
+ const label = check.not_checked ? line.name : `${line.method === "flow" ? "Browser flow" : line.method ?? "Check"} ${line.path ?? "(surface unavailable)"}`;
78113
+ const status = line.status ? ` (HTTP ${line.status})` : "";
78114
+ lines.push(`PASS ${label}${status} \u2014 ${observation}`);
78115
+ }
78116
+ for (const finding of functionWarnings(check)) {
78117
+ if (finding.kind === "crash") {
78118
+ lines.push(`Warning: A server function crashed: ${finding.via} (request ID ${finding.request_id}).`);
78119
+ } else {
78120
+ const receipt = [finding.status ? `HTTP ${finding.status}` : "", finding.request_id ? `request ID ${finding.request_id}` : ""].filter(Boolean).join(", ");
78121
+ lines.push(`Warning: ${finding.via} returned 5xx; no error record found yet${receipt ? ` (${receipt})` : ""}.`);
78122
+ }
78123
+ }
78124
+ for (const finding of cleanupFindings(check)) {
78125
+ const receipt = [finding.status ? `HTTP ${finding.status}` : "", finding.request_id ? `request ID ${finding.request_id}` : ""].filter(Boolean).join(", ");
78126
+ lines.push(`Could not check cleanup: ${finding.left_behind ?? (finding.table ? `A test row in ${finding.table} may remain.` : `Check whether any ${finding.via ?? "test data"} remain.`)}${receipt ? ` (${receipt})` : ""}`);
78127
+ }
78128
+ if (!checks.length)
78129
+ lines.push("Could not check: no named checks ran.");
78130
+ if (summary.counts.could_not_check && !lines.some((line) => line.startsWith("Could not check")))
78131
+ lines.push(`Could not check: run ${cliInvocation()} test --again to get named results.`);
78132
+ }
78133
+ const coverage = check?.not_checked ?? null;
78134
+ if (coverage) {
78135
+ if (typeof check?.routes_discovered === "number")
78136
+ lines.push(`${check.routes_checked ?? 0} of ${check.routes_discovered} app routes had a completed read check.`);
78137
+ const { routes_without_read_check: reads, routes_without_write_check: writes, schedules_not_run: schedules, other } = coverage;
78138
+ if (reads === null || writes === null)
78139
+ lines.push("App route coverage could not be listed.");
78140
+ if (reads?.length)
78141
+ lines.push(`${reads.length} ${reads.length === 1 ? "route" : "routes"} without a read check (${reads.join(", ")}).`);
78142
+ if (writes?.length)
78143
+ lines.push(`${writes.length} ${writes.length === 1 ? "route" : "routes"} without a write check (${writes.join(", ")}).`);
78144
+ if (schedules === null)
78145
+ lines.push("Registered schedules could not be listed.");
78146
+ if (schedules?.length)
78147
+ lines.push(`${schedules.length} registered ${schedules.length === 1 ? "schedule" : "schedules"} did not run (${schedules.join(", ")}).`);
78148
+ if (other.length)
78149
+ lines.push(`Other checks skipped or out of scope: ${other.join(", ")}.`);
78150
+ } else {
78151
+ lines.push("Coverage details are unavailable for this run.");
78152
+ }
78153
+ return [...lines, JSON.stringify({
78154
+ ...summary,
78155
+ not_checked: coverage,
78156
+ ...coverage ? { routes_checked: check?.routes_checked, routes_discovered: check?.routes_discovered } : {}
78157
+ })];
78199
78158
  }
78200
- var DEPLOY_CHECKS_POLL_MS, DEPLOY_CHECKS_RUNNING, TEST_CHECKS_WAIT_MS;
78159
+ var DEPLOY_CHECKS_POLL_MS, DEPLOY_CHECKS_RUNNING, TEST_CHECKS_WAIT_MS, cleanupFindings, functionWarnings;
78201
78160
  var init_deploy_checks = __esm({
78202
78161
  "dist/lib/deploy-checks.js"() {
78203
78162
  "use strict";
78204
78163
  init_cli_invocation();
78164
+ init_check_summary();
78205
78165
  DEPLOY_CHECKS_POLL_MS = 3e3;
78206
78166
  __name(parseChecksRead, "parseChecksRead");
78207
78167
  __name(awaitDeployChecks, "awaitDeployChecks");
78208
78168
  DEPLOY_CHECKS_RUNNING = `Checks: running in the background; \`${cliInvocation()} test\` shows the result.`;
78209
78169
  TEST_CHECKS_WAIT_MS = 15e4;
78210
78170
  __name(runChecksNow, "runChecksNow");
78171
+ __name(lineOutcome, "lineOutcome");
78172
+ cleanupFindings = /* @__PURE__ */ __name((check) => (check?.findings ?? []).filter((f2) => f2.kind === "cleanup"), "cleanupFindings");
78173
+ functionWarnings = /* @__PURE__ */ __name((check) => (check?.findings ?? []).filter((finding) => finding.kind === "function_http_error" || finding.kind === "crash" && Boolean(finding.request_id)), "functionWarnings");
78174
+ __name(deployChecksSummary, "deployChecksSummary");
78175
+ __name(checksJsonReport, "checksJsonReport");
78176
+ __name(resultEvidence, "resultEvidence");
78211
78177
  __name(formatChecksReport, "formatChecksReport");
78212
- __name(checksExitCode, "checksExitCode");
78213
78178
  }
78214
78179
  });
78215
78180
 
@@ -82880,7 +82845,8 @@ function createVerifyJourneyRun(target, journey, client, opts = {}) {
82880
82845
  return { status: "kept", reason: "kept with their browsers for the next --keep-actors run; remove them with --close-actors" };
82881
82846
  try {
82882
82847
  const removed = await client.call("DELETE", "/auth/test-users", { project_id: target.project_id, ids: [...testIdentities.values()].map((item) => item.user_id) });
82883
- return { status: "deleted", deleted: typeof removed?.deleted === "number" ? removed.deleted : void 0 };
82848
+ const deleted = removed?.deleted;
82849
+ return deleted === testIdentities.size ? { status: "deleted", deleted } : { status: "unconfirmed", deleted, reason: "The platform did not confirm removal of every test user." };
82884
82850
  } catch (cause) {
82885
82851
  const code = cause instanceof CliApiError ? cause.code : cause instanceof Error ? cause.message : String(cause);
82886
82852
  return { status: "unconfirmed", reason: `delete failed (${code}); the platform removes test users when they expire` };
@@ -83187,6 +83153,11 @@ function createVerifyJourneyRun(target, journey, client, opts = {}) {
83187
83153
  const deleteStartedAt = now2();
83188
83154
  const testUsers = testIdentities.size ? { identities: [...testIdentities].map(([actor, item]) => ({ actor, ...item })), cleanup: await removeTestUsers() } : void 0;
83189
83155
  const testUsersDeleteMs = testUsers ? now2() - deleteStartedAt : void 0;
83156
+ if (testUsers?.cleanup.status === "unconfirmed") {
83157
+ passed = false;
83158
+ const note = `Could not check cleanup. Test users for ${testUsers.identities.map((user) => user.actor).join(", ")} may remain.`;
83159
+ verdict = verdict.startsWith("PASS") ? `INCOMPLETE \u2014 ${note}` : `${verdict} ${note}`;
83160
+ }
83190
83161
  if (cleanup.some((item) => item.status === "unconfirmed")) {
83191
83162
  passed = false;
83192
83163
  const lifecycle = cleanup.filter((item) => item.status === "unconfirmed").map((item) => ({ viewport: item.actor, detail: { status: "cleanup_unknown", outcome_unknown: true } }));
@@ -83205,7 +83176,7 @@ function createVerifyJourneyRun(target, journey, client, opts = {}) {
83205
83176
  limits: VERIFY_JOURNEY_LIMITS,
83206
83177
  cleanup,
83207
83178
  cleanup_ms,
83208
- cleanup_confirmed: cleanup.every((item) => item.status !== "unconfirmed"),
83179
+ cleanup_confirmed: cleanup.every((item) => item.status !== "unconfirmed") && testUsers?.cleanup.status !== "unconfirmed",
83209
83180
  kept_sessions: [...kept.values()],
83210
83181
  ...testUsers ? { test_users: testUsers } : {},
83211
83182
  ...keep ? { keep_actors: {
@@ -83461,6 +83432,40 @@ function formatJourneyCleanup(cleanup, cleanupMs) {
83461
83432
  }
83462
83433
  return lines;
83463
83434
  }
83435
+ function verifyResultSummary(report2) {
83436
+ const failedSteps = report2.steps.filter((step2) => step2.ran !== false && !step2.passed).length;
83437
+ const failedRequests = report2.health.network.failed_requests.length + report2.health.network.expectations.filter((item) => !item.detail.ok).length;
83438
+ const refused = report2.refusals?.length ?? 0;
83439
+ const cleanup = "cleanup" in report2 ? Number(report2.test_users?.cleanup.status === "unconfirmed") : 0;
83440
+ const segmentsNotStarted = "segments" in report2 ? report2.segments.filter((segment) => !segment.ran && segment.error).length : 0;
83441
+ const incomplete = report2.incomplete.length + (report2.lifecycle?.length ?? 0) + refused + segmentsNotStarted + cleanup;
83442
+ const failed = failedSteps + failedRequests + report2.health.page.errors.length + report2.health.console.errors.length;
83443
+ return summarizeChecks({
83444
+ passed: report2.steps.filter((step2) => step2.ran !== false && step2.passed).length || report2.viewports.filter((item) => item.passed).length,
83445
+ failed: failed || Number(!report2.passed && incomplete === 0 && report2.verdict.startsWith("FAIL")),
83446
+ could_not_check: incomplete || Number(!report2.passed && failed === 0 && !report2.verdict.startsWith("FAIL")),
83447
+ warnings: report2.layout.filter((item) => OVERFLOW_FINDING.test(item.detail)).length
83448
+ });
83449
+ }
83450
+ function printVerificationResult(report2, opts) {
83451
+ const result = verifyResultSummary(report2);
83452
+ if (opts.out !== void 0) {
83453
+ writeVerifyReportTo(opts.out, report2);
83454
+ const summary = summarizeVerifyReport(report2);
83455
+ if (opts.json)
83456
+ console.log(JSON.stringify({ ...summary, ...result }));
83457
+ else
83458
+ console.log(formatVerifySummaryLine(summary) + "\n" + JSON.stringify(result));
83459
+ noteVerifyRefusal(summary);
83460
+ } else if (opts.json) {
83461
+ console.log(JSON.stringify({ ...report2, ...result }));
83462
+ } else {
83463
+ for (const line of formatVerifyOutput(report2))
83464
+ console.log(line);
83465
+ console.log(JSON.stringify(result));
83466
+ }
83467
+ process.exitCode = checkSummaryExitCode(result);
83468
+ }
83464
83469
  function registerVerify(program2) {
83465
83470
  const cliCookies = [];
83466
83471
  const collectCookie = /* @__PURE__ */ __name((value) => {
@@ -83491,6 +83496,8 @@ Signed-in check (from a linked folder):
83491
83496
  Run: ${cliInvocation()} verify --path /admin --flow owner-flow.json
83492
83497
  When done, run: ${cliInvocation()} test-users cleanup
83493
83498
 
83499
+ A run ends with one JSON line containing outcome and counts.
83500
+ Exit 0 means passed, 1 means a named check failed, and 2 means a check or cleanup could not finish.
83494
83501
  Reports default to verify-reports/ inside the CLI config directory.
83495
83502
  Set SOMEWHERE_CONFIG_DIR before signing in to relocate both the CLI config
83496
83503
  and default reports. Use --out to choose just the report file for one run.
@@ -83646,7 +83653,7 @@ with account access. Print the full flow schema with ${cliInvocation()} verify -
83646
83653
  console.log("Some cleanup is unconfirmed; its record is kept so --close-actors can run again.");
83647
83654
  }
83648
83655
  if (!allConfirmed)
83649
- process.exitCode = 1;
83656
+ process.exitCode = 2;
83650
83657
  return;
83651
83658
  }
83652
83659
  const releaseKeepLock = keepKeyValue ? lockKeep(root, keepKeyValue) : void 0;
@@ -83695,17 +83702,8 @@ with account access. Print the full flow schema with ${cliInvocation()} verify -
83695
83702
  releaseKeepLock?.();
83696
83703
  }
83697
83704
  }
83698
- if (opts.out !== void 0) {
83699
- writeVerifyReportTo(opts.out, report3);
83700
- const summary = summarizeVerifyReport(report3);
83701
- console.log(opts.json ? JSON.stringify(summary, null, 2) : formatVerifySummaryLine(summary));
83702
- noteVerifyRefusal(summary);
83703
- } else if (opts.json)
83704
- console.log(JSON.stringify(report3, null, 2));
83705
- else
83706
- for (const line of formatVerifyOutput(report3))
83707
- console.log(line);
83708
- process.exit(report3.passed ? 0 : 1);
83705
+ printVerificationResult(report3, opts);
83706
+ return;
83709
83707
  }
83710
83708
  const loadedFlow = input.flow;
83711
83709
  const flow = {
@@ -83715,17 +83713,7 @@ with account access. Print the full flow schema with ${cliInvocation()} verify -
83715
83713
  };
83716
83714
  assertSessionSeedSize(flow);
83717
83715
  const report2 = await withVerifyProgress(() => runVerification({ ...project ? { project_id: project } : {}, ...url3 ? { url: url3 } : {} }, flow, client), !opts.json);
83718
- if (opts.out !== void 0) {
83719
- writeVerifyReportTo(opts.out, report2);
83720
- const summary = summarizeVerifyReport(report2);
83721
- console.log(opts.json ? JSON.stringify(summary, null, 2) : formatVerifySummaryLine(summary));
83722
- noteVerifyRefusal(summary);
83723
- } else if (opts.json)
83724
- console.log(JSON.stringify(report2, null, 2));
83725
- else
83726
- for (const line of formatVerifyOutput(report2))
83727
- console.log(line);
83728
- process.exit(report2.passed ? 0 : 1);
83716
+ printVerificationResult(report2, opts);
83729
83717
  } catch (cause) {
83730
83718
  if (cause instanceof CliApiError && cause.code === "VALIDATION_ERROR" && /provide exactly one of|unknown action|unsupported action|upload is not supported|screenshot is not supported/i.test(cause.message)) {
83731
83719
  error("VERIFY_ACTION_NOT_AVAILABLE: Browser upload and named screenshot actions are not available on this platform version yet.");
@@ -83748,6 +83736,7 @@ var VERIFY_TIMEOUT_MS, VERIFY_BUDGET_MS, VERIFY_MIN_BUDGET_MS, VERIFY_TRANSPORT_
83748
83736
  var init_verify = __esm({
83749
83737
  "dist/commands/verify.js"() {
83750
83738
  "use strict";
83739
+ init_check_summary();
83751
83740
  init_cli_invocation();
83752
83741
  init_repro_packet();
83753
83742
  init_browser_flow_preflight();
@@ -83844,6 +83833,8 @@ var init_verify = __esm({
83844
83833
  __name(noteVerifyRefusal, "noteVerifyRefusal");
83845
83834
  __name(formatVerifySummaryLine, "formatVerifySummaryLine");
83846
83835
  __name(formatJourneyCleanup, "formatJourneyCleanup");
83836
+ __name(verifyResultSummary, "verifyResultSummary");
83837
+ __name(printVerificationResult, "printVerificationResult");
83847
83838
  __name(registerVerify, "registerVerify");
83848
83839
  }
83849
83840
  });
@@ -135059,7 +135050,7 @@ var init_test_scripts = __esm({
135059
135050
 
135060
135051
  // dist/commands/test.js
135061
135052
  function registerTest(program2) {
135062
- program2.command("test [files...]").description("Run the live release's checks now in Somewhere's browser: your saved checks/*.json journeys, the stranger and signed-out access probes and a page crawl (the same check that runs after every deploy). Exits 1 when one fails. With a file, runs that tests/*.mjs or *.cjs script; a project with tests/**/*.spec.ts runs its Playwright specs (--preview: this folder's open preview)").option("--preview", "Test this folder's open preview (its own users, data copy and captured mail), pinned to the version saved when the run starts. Production is never touched.").option("--workers <count>", "Parallel workers", "5").option("--again", "Start a fresh run of the checks on the live release instead of reading the result of the last deploy's run").option("--failed", "Rerun what failed last time: each failed tests/*.mjs or *.cjs script, all its checks (specs: only the failed tests)").option("--fail-fast", "Stop app-check scripts at their first failed check").option("--grep <name>", "Filter test names (subset)").option("--url <url>", "Unsupported in phase 1").option("--phone", "Run every test again in a 390x844 phone viewport ([phone] in results)").option("--json", "Print structured results").option("--verbose", "Also print where the full result file is when everything passed").addHelpText("after", "\nSave each journey you want re-checked after every deploy as checks/<plain-name>.json; the platform runs them in its browser after each deploy and `somewhere test` runs them now.\n").action(async (files, opts) => {
135053
+ program2.command("test [files...]").description("Read the live release's latest checks, run in Somewhere's browser: your saved checks/*.json journeys, the stranger and signed-out access probes and a page crawl (the same check that runs after every deploy). Exits 0 when they pass, 1 for a named failure, or 2 when a check or cleanup could not finish. With a file, runs that tests/*.mjs or *.cjs script; a project with tests/**/*.spec.ts runs its Playwright specs (--preview: this folder's open preview)").option("--preview", "Test this folder's open preview (its own users, data copy and captured mail), pinned to the version saved when the run starts. Production is never touched.").option("--workers <count>", "Parallel workers", "5").option("--again", "Start a fresh run of the checks on the live release instead of reading the result of the last deploy's run").option("--failed", "Rerun what failed last time: each failed tests/*.mjs or *.cjs script, all its checks (specs: only the failed tests)").option("--fail-fast", "Stop app-check scripts at their first failed check").option("--grep <name>", "Filter test names (subset)").option("--url <url>", "Unsupported in phase 1").option("--phone", "Run every test again in a 390x844 phone viewport ([phone] in results)").option("--json", "Print structured results").option("--verbose", "Also print where the full result file is when everything passed").addHelpText("after", "\nSave each journey you want re-checked after every deploy as checks/<plain-name>.json; the platform runs them in its browser after each deploy and `somewhere test` reads the latest result. Use --again for a fresh run. The last line of a platform run is JSON with outcome and counts.\n").action(async (files, opts) => {
135063
135054
  markProcessStart("cli");
135064
135055
  mark("cli:action");
135065
135056
  if (opts.url)
@@ -135074,13 +135065,19 @@ function registerTest(program2) {
135074
135065
  const unsupported = [opts.phone && "--phone", opts.grep && "--grep", opts.workers !== "5" && "--workers", opts.failFast && "--fail-fast"].filter(Boolean);
135075
135066
  if (unsupported.length)
135076
135067
  throw new Error(`${unsupported.join(", ")} apply to Playwright specs and scripts; the platform runs checks/*.json as saved.`);
135077
- const check = await runChecksNow(new ApiClient(getToken()), projectId, { again: opts.again === true });
135068
+ let check;
135069
+ try {
135070
+ check = await runChecksNow(new ApiClient(getToken()), projectId, { again: opts.again === true });
135071
+ } catch (cause) {
135072
+ check = { status: "unavailable", sentence: cause instanceof Error ? cause.message : "The platform could not start the checks." };
135073
+ }
135078
135074
  mark("cli:exit");
135075
+ const summary = deployChecksSummary(check);
135079
135076
  if (opts.json)
135080
- process.stdout.write(JSON.stringify(check, null, 2) + "\n");
135077
+ process.stdout.write(JSON.stringify(checksJsonReport(check)) + "\n");
135081
135078
  else
135082
135079
  process.stdout.write(formatChecksReport(check).join("\n") + "\n");
135083
- process.exitCode = checksExitCode(check);
135080
+ process.exitCode = checkSummaryExitCode(summary);
135084
135081
  return;
135085
135082
  }
135086
135083
  const note = (opts.preview ? Promise.resolve(null) : referenceCheckNote(() => new ApiClient(getToken()), projectId)).then((line) => {
@@ -135126,6 +135123,7 @@ var init_test = __esm({
135126
135123
  init_test_timeline();
135127
135124
  init_reference_check_note();
135128
135125
  init_deploy_checks();
135126
+ init_check_summary();
135129
135127
  init_test_scripts();
135130
135128
  __name(registerTest, "registerTest");
135131
135129
  }