@somewhere-cloud/cli 0.38.125 → 0.38.127

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.
@@ -38281,7 +38281,7 @@ not enough. So tickets lists create: ['staff']; without it every staff reply is
38281
38281
  Publish pages in an owner-checked endpoint. Share with caller-scoped
38282
38282
  sw.db.insert('note_shares', { grantee_id, note_id }); it checks row ownership.
38283
38283
  Browser calls THROW, not { error }; catch below.
38284
- Browser list: max 100, paginate after; no order (sort locally or in an endpoint).
38284
+ Browser list: paginate with after. Sort locally or in an endpoint.
38285
38285
 
38286
38286
  \`\`\`ts
38287
38287
  import { data } from 'somewhere:data';
@@ -38368,8 +38368,8 @@ tests/app-check.mjs: change its checks to the journeys you changed and your acce
38368
38368
  Keep each run short:
38369
38369
  - Short waits: page.setDefaultTimeout(5_000) on every page; a deployed app answers in under
38370
38370
  a second. Never sleep for a fixed time: wait for the thing itself (the text, the response).
38371
- - Stop at the first failure and print what the page showed (page.url(), the visible error
38372
- text). Checks after a failure only wait out their timeouts. app.check() does both.
38371
+ - Keep independent checks running. For a dependent check, pass { requires: { name, passed } }
38372
+ to app.check() using the earlier check's boolean result, so a skip explains what it needed.
38373
38373
  - After a fix, rerun the scripts that failed, each one whole: npx @somewhere-cloud/cli test --failed.
38374
38374
  The CLI supplies its test helpers when it runs your tests. For the first browser test, install Playwright with npm install -D --save-exact @playwright/test@1.65.0.
38375
38375
  For a local Vite server, install the frontend tools with npm install -D --save-exact vite@7.2.2.
@@ -41047,84 +41047,84 @@ var init_init_test_template = __esm({
41047
41047
  "dist/lib/init-test-template.js"() {
41048
41048
  "use strict";
41049
41049
  init_first_cli_permission();
41050
- SCRIPT = /* @__PURE__ */ __name((privateData) => `// tests/app-check.mjs \u2014 an ordinary Playwright script for this app: change the checks to match
41051
- // what you built. Run it after a successful deploy, never after a refused one:
41050
+ SCRIPT = /* @__PURE__ */ __name((privateData) => `// Change these Playwright checks to match your app. Run after a successful deploy.
41052
41051
  // ${FIRST_CLI_PERMISSION}
41053
41052
  // npx @somewhere-cloud/cli deploy && npx @somewhere-cloud/cli test
41054
- // Tests that need the email inbox work after you claim the app.
41055
- // It writes its result once to .somewhere/app-check.json; the exit code is the verdict.
41056
- // It stops at the first failed check and prints the page's URL and visible error text.
41057
- // After a fix, rerun the scripts that failed, each one whole: npx @somewhere-cloud/cli test --failed.
41058
- // From a .cjs script: const { openAppTest } = require('@somewhere-cloud/cli/script');
41053
+ // Results: .somewhere/app-check.json. Rerun failed scripts with npx @somewhere-cloud/cli test --failed.
41059
41054
  import { chromium } from '@playwright/test';
41060
41055
  import { openAppTest${privateData ? ", captureResponses, dataReady" : ""} } from '@somewhere-cloud/cli/script';
41061
-
41062
41056
  const app = await openAppTest(); // stops if this folder has changes the live release lacks
41063
41057
  const browser = await chromium.launch(app.launchOptions());
41064
- // One person = one browser context, signed up through the app's own form (accounts are
41065
- // deleted by exact id in finish()).
41066
41058
  const person = async () => {
41067
41059
  const page = await browser.newPage({ baseURL: app.origin });
41068
41060
  page.setDefaultTimeout(5_000); // a deployed app answers in well under a second; never sleep, wait for the thing itself
41069
41061
  return { page, account: await app.signUp(page) };
41070
41062
  };
41071
41063
  try {
41072
- await app.check('the sign-in page loads', async () => {
41064
+ await app.check('the sign-in page loads', async (at) => {
41073
41065
  const page = await browser.newPage({ baseURL: app.origin });
41074
41066
  try {
41075
41067
  await page.goto('/');
41068
+ at('Wait for the signed-out page', '[data-app-state="signed-out"]');
41076
41069
  await page.locator('[data-app-state="signed-out"]').waitFor({ timeout: 5_000 });
41077
- } finally {
41078
- await page.close();
41079
- }
41070
+ } finally { await page.close(); }
41080
41071
  });
41081
41072
  let ana, ben;
41082
- const signedUp = await app.check('sign up through the app', async () => {
41073
+ const needsSignup = { name: 'sign up through the app', passed: false };
41074
+ needsSignup.passed = await app.check(needsSignup.name, async () => {
41083
41075
  // Finish both attempts before cleanup, even if one fails.
41084
41076
  const people = await Promise.allSettled([person(), person()]);
41085
41077
  for (const result of people) if (result.status === 'rejected') throw result.reason;
41086
41078
  [ana, ben] = people.map(result => result.value);
41087
41079
  });
41088
- if (signedUp) {
41089
- await app.check('the signed-in page shows the account', () => ana.page.getByText(ana.account.email).waitFor());
41090
- await app.check('sign out, then sign back in', async () => {
41091
- await app.signOut(ana.page);
41092
- await app.signIn(ana.page, ana.account);
41093
- });
41094
- ${privateData ? ` await app.check('a note stays private to its owner', async () => {
41095
- const secret = 'private ' + crypto.randomUUID(); // a unique value: search for it, not a common word
41096
- await ana.page.getByLabel('Title').fill(secret);
41097
- await ana.page.getByRole('button', { name: 'Add note' }).click();
41098
- await ana.page.getByRole('heading', { name: secret }).waitFor();
41099
- const seen = captureResponses(ben.page);
41080
+ await app.check('the signed-in page shows the account', () => ana.page.getByText(ana.account.email).waitFor(), { requires: needsSignup });
41081
+ const roundTrip = 'sign out, then sign back in';
41082
+ const signedBackIn = await app.check(roundTrip, async (at) => {
41083
+ await app.signOut(ana.page);
41084
+ at('Sign back in');
41085
+ await app.signIn(ana.page, ana.account);
41086
+ }, { requires: needsSignup });
41087
+ ${privateData ? ` await app.check('a note stays private to its owner', async (at) => {
41088
+ const secret = 'private ' + crypto.randomUUID();
41089
+ at('Create the first person\u2019s note');
41090
+ await ana.page.getByLabel('Title').fill(secret);
41091
+ await ana.page.getByRole('button', { name: 'Add note' }).click();
41092
+ await ana.page.getByRole('heading', { name: secret }).waitFor();
41093
+ const seen = captureResponses(ben.page);
41094
+ try {
41100
41095
  await ben.page.reload();
41101
- await dataReady(ben.page); // the list has loaded, not merely "signed in"
41102
- const leaks = await seen.find(secret);
41103
- if (leaks.length) throw new Error('the other person received the note: ' + JSON.stringify(leaks));
41104
- const { data: [note] } = await app.data(ana.page, { table: 'notes', operation: 'list', where: { title: secret } });
41105
- await app.expectRefused(ben.page, { table: 'notes', operation: 'get', id: note.id }, { allowed: ana.page });
41106
- await app.expectRefused(ben.page, { table: 'notes', operation: 'update', id: note.id, values: { title: 'changed' } }, { allowed: ana.page });
41107
- await app.expectRefused(ben.page, { table: 'notes', operation: 'delete', id: note.id }, { allowed: ana.page });
41108
- });
41109
- ` : ` // Your own tables (db/schema.ts), called as a signed-in person: app.data adds the release's
41110
- // data contract and the Origin, and says ok, empty or refused. No need to read either from the page.
41111
- // const { data: [task] } = await app.data(ana.page, { table: 'tasks', operation: 'list' });
41112
- // await app.expectRefused(ben.page, { table: 'tasks', operation: 'get', id: task.id }, { allowed: ana.page });
41113
- `} // A list item opens its page when a person clicks the item itself. Click the item element, not a link
41114
- // inside it: a test that clicks the inner link passes even when clicking the item does nothing.
41115
- // await ana.page.getByTestId('team-item').first().click();
41116
- // await ana.page.getByTestId('team-name').waitFor(); // the item's own page, reached in the app
41117
- await app.check('at phone width nothing scrolls sideways', async () => {
41118
- await ana.page.setViewportSize({ width: 390, height: 844 });
41119
- await ana.page.reload();
41120
- await ana.page.getByText(ana.account.email).waitFor();
41121
- const wide = await ana.page.evaluate(() => [document.documentElement, ...document.querySelectorAll('body *')]
41122
- .filter((el) => el.scrollWidth > el.clientWidth + 1
41123
- && (el === document.documentElement || ['auto', 'scroll'].includes(getComputedStyle(el).overflowX)))
41124
- .map((el) => el.tagName.toLowerCase() + (typeof el.className === 'string' && el.className ? '.' + el.className.split(' ')[0] : '')));
41125
- if (wide.length) throw new Error('scrolls sideways at 390 px: ' + wide.join(', '));
41126
- });
41127
- }
41096
+ // On the data view, set data-sw-data="loading" while fetching, "ready" once loaded, or "error" if fetching fails.
41097
+ at('Wait for the second person\u2019s notes to load', '[data-sw-data]');
41098
+ if (await dataReady(ben.page) === 'error') throw new Error('The second person\u2019s notes view reported a loading error.');
41099
+ const [leak] = await seen.find(secret);
41100
+ if (leak) {
41101
+ at('Check the second person\u2019s responses for the note', leak.url);
41102
+ throw new Error('The second person received the first person\u2019s note.');
41103
+ }
41104
+ } finally { seen.stop(); }
41105
+ at('Read the note as its owner');
41106
+ const owned = await app.data(ana.page, { table: 'notes', operation: 'list', where: { title: secret } });
41107
+ const note = owned.data?.[0];
41108
+ if (!note) throw new Error('The owner\u2019s request did not return the new note (HTTP ' + owned.status + ').');
41109
+ at('Check that the second person cannot read, edit, or delete the note');
41110
+ await app.expectRefused(ben.page, { table: 'notes', operation: 'get', id: note.id }, { allowed: ana.page });
41111
+ await app.expectRefused(ben.page, { table: 'notes', operation: 'update', id: note.id, values: { title: 'changed' } }, { allowed: ana.page });
41112
+ await app.expectRefused(ben.page, { table: 'notes', operation: 'delete', id: note.id }, { allowed: ana.page });
41113
+ }, { requires: needsSignup.passed ? { name: roundTrip, passed: signedBackIn } : needsSignup });
41114
+ ` : ` // After adding tables in db/schema.ts, test access with these helpers:
41115
+ // const { data: [task] } = await app.data(ana.page, { table: 'tasks', operation: 'list' });
41116
+ // await app.expectRefused(ben.page, { table: 'tasks', operation: 'get', id: task.id }, { allowed: ana.page });
41117
+ `} await app.check('at phone width nothing scrolls sideways', async (at) => {
41118
+ await ben.page.setViewportSize({ width: 390, height: 844 });
41119
+ await ben.page.reload();
41120
+ await ben.page.getByText(ben.account.email).waitFor();
41121
+ at('Measure horizontal overflow', app.origin);
41122
+ const wide = await ben.page.evaluate(() => [document.documentElement, ...document.querySelectorAll('body *')]
41123
+ .filter((el) => el.scrollWidth > el.clientWidth + 1
41124
+ && (el === document.documentElement || ['auto', 'scroll'].includes(getComputedStyle(el).overflowX)))
41125
+ .map((el) => el.tagName.toLowerCase() + (typeof el.className === 'string' && el.className ? '.' + el.className.split(' ')[0] : '')));
41126
+ if (wide.length) throw new Error('scrolls sideways at 390 px: ' + wide.join(', '));
41127
+ }, { requires: needsSignup });
41128
41128
  } finally {
41129
41129
  await app.finish(); // confirms the release, deletes the accounts, writes the result once
41130
41130
  await browser.close();
@@ -76386,7 +76386,6 @@ function decodeCredentials(state, response) {
76386
76386
  if (!state.handoff_id || response.project_id !== state.project_id) {
76387
76387
  throw new Error("Claim continuation returned a different project. No credential was installed.");
76388
76388
  }
76389
- const account = response.approved_scope === "account";
76390
76389
  const key = createHash5("sha256").update(`claim-cli-handoff:v1:${state.verifier}`, "utf8").digest();
76391
76390
  const combined = Buffer.from(response.ciphertext, "base64");
76392
76391
  if (combined.length <= 16)
@@ -76394,11 +76393,11 @@ function decodeCredentials(state, response) {
76394
76393
  const encrypted = combined.subarray(0, -16);
76395
76394
  const tag = combined.subarray(-16);
76396
76395
  const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(response.iv, "base64"));
76397
- decipher.setAAD(Buffer.from(`${state.handoff_id}:${state.project_id}${account ? ":account" : ""}`, "utf8"));
76396
+ decipher.setAAD(Buffer.from(`${state.handoff_id}:${state.project_id}`, "utf8"));
76398
76397
  decipher.setAuthTag(tag);
76399
76398
  const plaintext = Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");
76400
76399
  const parsed = JSON.parse(plaintext);
76401
- if (typeof parsed.token !== "string" || typeof parsed.refresh_token !== "string" || typeof parsed.expires_at !== "string" || typeof parsed.email !== "string" || parsed.project_id !== state.project_id || (account ? parsed.scope !== null || parsed.approved_scope !== "account" : parsed.scope?.projects?.length !== 1 || parsed.scope.projects[0] !== state.project_id)) {
76400
+ if (typeof parsed.token !== "string" || typeof parsed.refresh_token !== "string" || typeof parsed.expires_at !== "string" || typeof parsed.email !== "string" || parsed.project_id !== state.project_id || parsed.approved_scope !== void 0 && parsed.approved_scope !== "project" || parsed.scope?.projects?.length !== 1 || parsed.scope.projects[0] !== state.project_id) {
76402
76401
  throw new Error("Claim continuation credential did not match the approved project. Nothing was installed.");
76403
76402
  }
76404
76403
  return parsed;
@@ -76431,8 +76430,7 @@ async function ensureClaimHandoff(projectId) {
76431
76430
  project_id: projectId,
76432
76431
  verifier_hash: verifierHash(state.verifier),
76433
76432
  device_name: getDeviceKeyName(),
76434
- client: describeThisDevice(),
76435
- capabilities: CAPABILITIES
76433
+ client: describeThisDevice()
76436
76434
  }, config2.token);
76437
76435
  if (!response.ok || !envelope.ok || !envelope.data) {
76438
76436
  throw new Error(envelope.message || envelope.error || `CLI continuation registration failed (HTTP ${response.status}).`);
@@ -76497,6 +76495,12 @@ async function recoverClaimHandoff() {
76497
76495
  } catch {
76498
76496
  return { kind: "none" };
76499
76497
  }
76498
+ if (envelope.error === "CLAIM_CLI_ACCOUNT_SCOPE_FORBIDDEN" || envelope.data?.approved_scope !== void 0 && envelope.data.approved_scope !== "project") {
76499
+ return {
76500
+ kind: "manual",
76501
+ message: `A claim link connects this CLI only to the claimed project. Run \`${cliInvocation()} login\` for account access.`
76502
+ };
76503
+ }
76500
76504
  if (!response.ok || !envelope.ok || !envelope.data) {
76501
76505
  if (["CLAIM_CLI_HANDOFF_PENDING", "CLAIM_CLI_HANDOFF_IN_PROGRESS"].includes(envelope.error || "")) {
76502
76506
  return { kind: "none" };
@@ -76534,10 +76538,9 @@ async function recoverClaimHandoff() {
76534
76538
  }
76535
76539
  return {
76536
76540
  kind: "recovered",
76537
- message: delivered.scope === null ? `Connected to ${delivered.email} with access to all its projects. The existing project link was kept.` : `Connected to ${delivered.email} for this project only. The existing project link was kept.`
76541
+ message: `Connected to ${delivered.email} for this project only. The existing project link was kept. Run \`${cliInvocation()} login\` for account access.`
76538
76542
  };
76539
76543
  }
76540
- var CAPABILITIES;
76541
76544
  var init_claim_handoff = __esm({
76542
76545
  "dist/lib/claim-handoff.js"() {
76543
76546
  "use strict";
@@ -76547,7 +76550,6 @@ var init_claim_handoff = __esm({
76547
76550
  init_device_login();
76548
76551
  init_client();
76549
76552
  init_http();
76550
- CAPABILITIES = ["account_scope"];
76551
76553
  __name(verifierHash, "verifierHash");
76552
76554
  __name(newVerifier, "newVerifier");
76553
76555
  __name(decodeCredentials, "decodeCredentials");
@@ -77333,9 +77335,21 @@ function describeReport(groups, options2 = {}) {
77333
77335
  }, "note");
77334
77336
  const failed = checks.filter((check2) => !check2.ok && !check2.skipped);
77335
77337
  const notRun = checks.filter((check2) => check2.skipped === "after-failure");
77336
- const skipped = checks.filter((check2) => check2.skipped === "needs-claim");
77338
+ const skipped = checks.filter((check2) => check2.skipped && check2.skipped !== "after-failure");
77337
77339
  const lines = [
77338
- ...failed.map((check2) => `FAIL ${check2.name}${note(check2.script)}: ${firstLine(check2.error) || "failed"}`),
77340
+ ...failed.flatMap((check2) => {
77341
+ const name = `FAIL ${check2.name}${note(check2.script)}`;
77342
+ const failure = check2.failure;
77343
+ if (!failure)
77344
+ return [`${name}: ${firstLine(check2.error) || "failed"}`];
77345
+ return [
77346
+ name,
77347
+ ` Expected: ${failure.expected}`,
77348
+ ` Happened: ${failure.happened}`,
77349
+ ` Step: ${failure.step}`,
77350
+ ...failure.evidence ? [` Evidence: ${failure.evidence}`] : []
77351
+ ];
77352
+ }),
77339
77353
  ...checks.filter((check2) => check2.ok).map((check2) => `PASS ${check2.name}${note(check2.script)}`),
77340
77354
  ...skipped.map((check2) => `SKIPPED ${check2.name}${note(check2.script)}: ${firstLine(check2.error)}`),
77341
77355
  ...notRun.map((check2) => `NOT RUN ${check2.name}${note(check2.script, "after the first failure")}`)
@@ -77343,9 +77357,10 @@ function describeReport(groups, options2 = {}) {
77343
77357
  const scripts = plural(groups.length, "script");
77344
77358
  if (!checks.length)
77345
77359
  lines.push(`FAILED: no check ran in ${scripts}: it stopped before its first check (its error is in the script's output).`);
77346
- else if (failed.length)
77347
- lines.push(`FAILED: ${failed.length} of ${plural(checks.length, "check")} in ${scripts}${notRun.length ? ` (${notRun.length} not run)` : ""}`);
77348
- else if (skipped.length)
77360
+ else if (failed.length) {
77361
+ const omitted = [skipped.length && `${skipped.length} skipped`, notRun.length && `${notRun.length} not run`].filter(Boolean);
77362
+ lines.push(`FAILED: ${failed.length} of ${plural(checks.length, "check")} in ${scripts}${omitted.length ? ` (${omitted.join(", ")})` : ""}`);
77363
+ } else if (skipped.length)
77349
77364
  lines.push(`${checks.length - skipped.length} passed, ${skipped.length} skipped in ${scripts}`);
77350
77365
  else
77351
77366
  lines.push(`PASSED: ${plural(checks.length, "check")} in ${scripts}`);
@@ -77353,7 +77368,7 @@ function describeReport(groups, options2 = {}) {
77353
77368
  lines.push(`Next: fix the error in the script's output, then run ${TEST_COMMAND} again.`);
77354
77369
  else if (failed.length)
77355
77370
  lines.push(`Next: fix what each FAIL line names, run ${DEPLOY_COMMAND}, then ${TEST_COMMAND} --failed to rerun each script that failed.`);
77356
- if (skipped.length)
77371
+ if (skipped.some((check2) => check2.skipped === "needs-claim"))
77357
77372
  lines.push(TEST_INBOX_CLAIM_NEXT);
77358
77373
  const files = [...new Set(groups.map((group) => group.resultFile).filter((file2) => Boolean(file2)))];
77359
77374
  if (files.length && (failed.length || !checks.length || options2.verbose))
@@ -80015,7 +80030,7 @@ async function closeKept(client, entry) {
80015
80030
  const removed = await client.call("DELETE", "/auth/test-users", { project_id: entry.project_id, ids });
80016
80031
  return { browsers, identities: { status: "deleted", ...typeof removed?.deleted === "number" ? { deleted: removed.deleted } : {} } };
80017
80032
  } catch (cause) {
80018
- return { browsers, identities: { status: `unconfirmed (${cause instanceof CliApiError ? cause.code : "delete failed"}); they expire 24 hours after creation` } };
80033
+ return { browsers, identities: { status: `unconfirmed (${cause instanceof CliApiError ? cause.code : "delete failed"}); the platform removes them when they expire` } };
80019
80034
  }
80020
80035
  }
80021
80036
  function keepStartNote(entry, otherFlowsKept) {
@@ -80231,7 +80246,7 @@ function assertSessionSeedSize(flow) {
80231
80246
  headers: flow.headers ?? {}
80232
80247
  }));
80233
80248
  if (bytes > 8 * 1024)
80234
- throw new Error(`Verification session seed is ${bytes} bytes; the platform limit is 8192 bytes (8 KB).`);
80249
+ throw new Error("The verification session data is too large. Remove unused local storage entries, cookies, or headers and run again.");
80235
80250
  }
80236
80251
  function normalizeViewports(raw) {
80237
80252
  if (raw === void 0)
@@ -80895,7 +80910,7 @@ function createVerifyJourneyRun(target, journey, client, opts = {}) {
80895
80910
  }, "createTestUsers");
80896
80911
  const removeTestUsers = /* @__PURE__ */ __name(async () => {
80897
80912
  if (opts.keepTestUsers)
80898
- return { status: "kept", reason: "kept on request; they expire 24 hours after creation" };
80913
+ return { status: "kept", reason: "kept on request until they expire" };
80899
80914
  if (keep && keptForReuse.size > 0 && testActors.every((name) => keptForReuse.has(name)))
80900
80915
  return { status: "kept", reason: "kept with their browsers for the next --keep-actors run; remove them with --close-actors" };
80901
80916
  try {
@@ -80903,7 +80918,7 @@ function createVerifyJourneyRun(target, journey, client, opts = {}) {
80903
80918
  return { status: "deleted", deleted: typeof removed?.deleted === "number" ? removed.deleted : void 0 };
80904
80919
  } catch (cause) {
80905
80920
  const code = cause instanceof CliApiError ? cause.code : cause instanceof Error ? cause.message : String(cause);
80906
- return { status: "unconfirmed", reason: `delete failed (${code}); the platform removes test users 24 hours after creation` };
80921
+ return { status: "unconfirmed", reason: `delete failed (${code}); the platform removes test users when they expire` };
80907
80922
  }
80908
80923
  }, "removeTestUsers");
80909
80924
  const stop = /* @__PURE__ */ __name((code, message3) => {
@@ -81130,7 +81145,7 @@ function createVerifyJourneyRun(target, journey, client, opts = {}) {
81130
81145
  continue;
81131
81146
  }
81132
81147
  if (!first && report2.session_note) {
81133
- const message3 = `${segment.as}'s browser ended between segments (${report2.session_note}), so ${segment.as} is no longer the same signed-in user. Keep each actor's gap between segments under 5 minutes and run the journey again.`;
81148
+ const message3 = `${segment.as}'s browser ended between segments (${report2.session_note}), so ${segment.as} is no longer the same signed-in user. Shorten the gaps between that actor's segments and run the journey again.`;
81134
81149
  itemStop ??= stopAt("error", "VERIFY_ACTOR_SESSION_ENDED", message3);
81135
81150
  segments.push({ ...base, ...timing, ran: true, final_url: report2.final_url === void 0 ? void 0 : reportUrl(report2.final_url), error: { code: "VERIFY_ACTOR_SESSION_ENDED", message: message3 } });
81136
81151
  continue;
@@ -81490,7 +81505,7 @@ function registerVerify(program2) {
81490
81505
  cliCookies.push({ name: value.slice(0, at2), value: value.slice(at2 + 1) });
81491
81506
  return value;
81492
81507
  }, "collectCookie");
81493
- program2.command("verify [target]").description("Run one browser flow at desktop and phone size, report every step and health signal, and capture both screenshots.").option("--project <ref>", "Project to verify. With --url, use this when the directory is unlinked or points to another project.").option("--url <url>", "Live or local URL to verify.").option("--path <path>", "Path relative to the linked or selected project app, e.g. /settings. Cannot be combined with --url.").option("--flow <file.json>", "Flow JSON with actions, session seeds, expect_requests, visible_only, and viewports. Omit for the default health check.").option("--session <session-id>", "Existing app session value to seed as localStorage sw_auth in every viewport.").option("--cookie <name=value>", "Existing app cookie to seed in every viewport. Repeatable.", collectCookie).option("--json", "Print the structured verification report as JSON.").option("--out <file>", "Write the full report to a new private file; print a bounded summary (JSON with --json).").option("--keep-actors", "Multi-user flows: after a fully passed run, keep each actor's signed-in browser and test user, and reconnect to them on the next run of the same flow file in this project folder. Each run navigates every actor to its starting path and runs the same checks, but cookies, storage and app data the actors created carry over, so checks must not assume an empty account. One run per kept flow at a time. Close with --close-actors; otherwise the platform closes a kept browser after 5 minutes idle, and at most 10 minutes after it started.").option("--resume-page", "With --keep-actors: an explicit stateful warm continuation. An actor whose first segment starts at exactly the page path the last passed run left it on keeps that page as it was last observed (no reload, like reusing a Playwright page); if the app moved it afterwards, the run continues from there. A different actor, flow, project or start path, or a page told apart only by its query or fragment, reloads normally. The kept page may run code from before the latest deploy, so a resumed run is not fresh-release evidence; the report lists resumed actors.").option("--close-actors", "Close every browser and delete every test user that --keep-actors kept for this project in this folder, then exit.").option("--keep-test-users", 'Multi-user flows: keep the test users created for "test_user" actors instead of deleting them when the run ends (they expire 24 hours after creation).').option("--schema", "Print the JSON Schema for --flow files (one user, or several users) and exit.").addHelpText("after", `
81508
+ program2.command("verify [target]").description("Run one browser flow at desktop and phone size, report every step and health signal, and capture both screenshots.").option("--project <ref>", "Project to verify. With --url, use this when the directory is unlinked or points to another project.").option("--url <url>", "Live or local URL to verify.").option("--path <path>", "Path relative to the linked or selected project app, e.g. /settings. Cannot be combined with --url.").option("--flow <file.json>", "Flow JSON with actions, session seeds, expect_requests, visible_only, and viewports. Omit for the default health check.").option("--session <session-id>", "Existing app session value to seed as localStorage sw_auth in every viewport.").option("--cookie <name=value>", "Existing app cookie to seed in every viewport. Repeatable.", collectCookie).option("--json", "Print the structured verification report as JSON.").option("--out <file>", "Write the full report to a new private file; print a bounded summary (JSON with --json).").option("--keep-actors", "Multi-user flows: after a fully passed run, keep each actor's signed-in browser and test user, and reconnect to them on the next run of the same flow file in this project folder. Each run starts at the same paths and runs the same checks. Cookies, storage and app data carry over. One run per kept flow at a time. Use --close-actors to close the kept browsers, or let them expire.").option("--resume-page", "With --keep-actors: an explicit stateful warm continuation. An actor whose first segment starts at exactly the page path the last passed run left it on keeps that page as it was last observed (no reload, like reusing a Playwright page); if the app moved it afterwards, the run continues from there. A different actor, flow, project or start path, or a page told apart only by its query or fragment, reloads normally. The kept page may run code from before the latest deploy, so a resumed run is not fresh-release evidence; the report lists resumed actors.").option("--close-actors", "Close every browser and delete every test user that --keep-actors kept for this project in this folder, then exit.").option("--keep-test-users", 'Multi-user flows: keep the users created for "test_user" actors until they expire.').option("--schema", "Print the JSON Schema for --flow files (one user, or several users) and exit.").addHelpText("after", `
81494
81509
  Minimal --flow JSON:
81495
81510
  {
81496
81511
  "actions": [
@@ -81532,15 +81547,12 @@ Several users in one run (--project required; each actor is its own browser):
81532
81547
  }
81533
81548
  Segments run in order; a later segment for the same actor continues in that
81534
81549
  actor's browser (path becomes a goto). For realtime checks, an item
81535
- { "parallel": [segment, segment] } runs 2-${VERIFY_JOURNEY_LIMITS.parallel_segments} segments by different actors at the
81536
- same time (alice waits for a message while bob sends it). Limits: ${VERIFY_JOURNEY_LIMITS.actors} actors, ${VERIFY_JOURNEY_LIMITS.segments} segments,
81537
- ${VERIFY_JOURNEY_LIMITS.actions_per_segment} actions per segment, ${VERIFY_JOURNEY_LIMITS.total_actions} in total, ${VERIFY_JOURNEY_LIMITS.deadline_ms / 6e4} minutes. Each segment is one browser
81538
- run against your plan's browser limits. When the run ends or is interrupted,
81539
- every actor browser is closed within ${VERIFY_JOURNEY_LIMITS.cleanup_budget_ms / 1e3} seconds; any close that cannot be
81540
- confirmed is reported, and the platform closes idle browsers within 5 minutes.
81541
- Several users need a claimed account and a CLI login approved for all your
81542
- projects: a login approved for "Only these projects" cannot open named browsers
81543
- (SESSION_SCOPE_FORBIDDEN). Print the full flow schema with: ${cliInvocation()} verify --schema
81550
+ { "parallel": [segment, segment] } runs segments by different actors at the
81551
+ same time (alice waits for a message while bob sends it). When the run ends or is
81552
+ interrupted, verification closes each actor's browser and reports any close it
81553
+ could not confirm. The platform closes idle browsers when they expire.
81554
+ For named browsers in a multi-user run, claim the project and use ${cliInvocation()} login
81555
+ with account access. Print the full flow schema with ${cliInvocation()} verify --schema.
81544
81556
  `).action(async (target, opts) => {
81545
81557
  if (opts.schema) {
81546
81558
  console.log(JSON.stringify(verifyFlowSchema(), null, 2));
@@ -81853,7 +81865,7 @@ var init_verify = __esm({
81853
81865
  __name(isVerifyJourneyInput, "isVerifyJourneyInput");
81854
81866
  __name(normalizeVerifyJourney, "normalizeVerifyJourney");
81855
81867
  __name(loadVerifyInput, "loadVerifyInput");
81856
- UNCONFIRMED_BACKSTOP = "the platform closes an idle browser within 5 minutes";
81868
+ UNCONFIRMED_BACKSTOP = "the platform closes idle browsers when they expire";
81857
81869
  RECLOSE_AFTER_ABANDONED_MS = 5e3;
81858
81870
  __name(settleWithin, "settleWithin");
81859
81871
  __name(createVerifyJourneyRun, "createVerifyJourneyRun");
@@ -82201,7 +82213,7 @@ No project yet? Signed in, deploy never creates one on its own:
82201
82213
  ${cliInvocation()} init --bare --name <name> create a project in your account and link this folder
82202
82214
  ${cliInvocation()} deploy then deploy it
82203
82215
  Existing project: \`${cliInvocation()} init --link --project <ref>\` (see \`${cliInvocation()} projects\`), or \`--project <ref>\` here.
82204
- `).option("--project <ref>", `Existing project to deploy to \u2014 accepts the project UUID, slug, or subdomain (all three resolve server-side). To create one, run \`${cliInvocation()} init --bare --name <name>\``).option("--scope <scope>", "Partial deploy: 'functions' (backend only, leaves the site untouched) or 'static' (site only, leaves functions untouched). Default deploys both.").option("--dry-run", "Show what would change (added / modified / removed files) in an already deployed project, without deploying. The files a deploy would publish are sent to Somewhere to compute the change; nothing is published. Never creates a project or a temporary workspace.").option("--replace-functions", "Delete deployed functions that are not in this directory. A full deploy already does; use it with --scope functions, which otherwise keeps them.").option("--prebuilt", "Deploy pre-built / bundled output (e.g. a dist/ folder) instead of raw source. Raw source is the default and recommended path: the platform compiles your TSX/JSX/TS on deploy, which keeps the app editable end-to-end. Choosing --prebuilt trades that away \u2014 pull/export round-trips, find/replace patches, and visual (source-map) editing are disabled for the bundled files. Use it only when you need full control of your own build.").option("--allow-bundled", "Alias for --prebuilt.").option("--new", "Publish to a new project and replace this folder\u2019s .somewhere.json link").option("--temporary", "Deploy to a temporary workspace and show when it expires (automatic when logged out)").option("--force", "Overwrite remote changes even when this machine last deployed an older version").option("--include <paths>", 'Publish a file or folder the deploy would otherwise hold back, e.g. --include NOTES.md or --include tests (comma-separate several, or repeat the flag). A "!NOTES.md" or "!tests/" line in .somewhereignore does the same thing permanently.', (value, previous = []) => previous.concat(value.split(",").map((v2) => v2.trim()).filter(Boolean))).option("--yes", "Skip confirmation prompts (for --force)").option("--verify [flow.json]", "After the deploy is live, run one browser verification flow at desktop and phone size. Omit the file for the default health check.").addOption(new Option("--test", "After a successful deploy, run somewhere test once against the new release").hideHelp()).option("-m, --message <text>", "User-supplied note for this version (max 200 characters)").option("--json", "Print the deploy result and its uploaded file list as JSON on stdout. Stderr lists files left out locally by path and reason.").option("--list-unpublished", "List the local files deploy would keep on your machine, then exit").option("--allow-type-errors", "Upload even when the local TypeScript check fails").option("--timing", "Print deploy details and timings").action(async (dir, opts) => {
82216
+ `).option("--project <ref>", `Existing project to deploy to \u2014 accepts the project UUID, slug, or subdomain (all three resolve server-side). To create one, run \`${cliInvocation()} init --bare --name <name>\``).option("--scope <scope>", "Partial deploy: 'functions' (backend only, leaves the site untouched) or 'static' (site only, leaves functions untouched). Default deploys both.").option("--dry-run", "Show what would change (added / modified / removed files) in an already deployed project, without deploying. The files a deploy would publish are sent to Somewhere to compute the change; nothing is published. Never creates a project or a temporary workspace.").option("--replace-functions", "Delete deployed functions that are not in this directory. A full deploy already does; use it with --scope functions, which otherwise keeps them.").option("--prebuilt", "Deploy pre-built / bundled output (e.g. a dist/ folder) instead of raw source. Raw source is the default and recommended path: the platform compiles your TSX/JSX/TS on deploy, which keeps the app editable end-to-end. Choosing --prebuilt trades that away \u2014 pull/export round-trips, find/replace patches, and visual (source-map) editing are disabled for the bundled files. Use it only when you need full control of your own build.").option("--allow-bundled", "Alias for --prebuilt.").option("--new", "Publish to a new project and replace this folder\u2019s .somewhere.json link").option("--temporary", "Deploy to a temporary workspace and show when it expires (automatic when logged out)").option("--force", "Overwrite remote changes even when this machine last deployed an older version").option("--include <paths>", 'Publish a file or folder the deploy would otherwise hold back, e.g. --include NOTES.md or --include tests (comma-separate several, or repeat the flag). A "!NOTES.md" or "!tests/" line in .somewhereignore does the same thing permanently.', (value, previous = []) => previous.concat(value.split(",").map((v2) => v2.trim()).filter(Boolean))).option("--yes", "Skip confirmation prompts (for --force)").option("--verify [flow.json]", "After the deploy is live, run one browser verification flow at desktop and phone size. Omit the file for the default health check.").addOption(new Option("--test", "After a successful deploy, run somewhere test once against the new release").hideHelp()).option("-m, --message <text>", "Add a note for this version").option("--json", "Print the deploy result and its uploaded file list as JSON on stdout. Stderr lists files left out locally by path and reason.").option("--list-unpublished", "List the local files deploy would keep on your machine, then exit").option("--allow-type-errors", "Upload even when the local TypeScript check fails").option("--timing", "Print deploy details and timings").action(async (dir, opts) => {
82205
82217
  const startupMs = performance.now();
82206
82218
  const targetDir = resolveTargetDir(dir);
82207
82219
  if (opts.new && (opts.project || opts.dryRun || opts.temporary)) {
@@ -82275,7 +82287,7 @@ Existing project: \`${cliInvocation()} init --link --project <ref>\` (see \`${cl
82275
82287
  process.exit(1);
82276
82288
  }
82277
82289
  if (Object.keys(files).length === 0 && Object.keys(binaryFiles).length === 0 && Object.keys(functions).length === 0) {
82278
- const message3 = `No deployable source found. Create an index.html or add raw app source files, or add serverless handlers under functions/, then run \`${cliInvocation()} deploy\` again.`;
82290
+ const message3 = `No deployable source found. Create an index.html or add raw app source files, or add API handlers under api/, then run \`${cliInvocation()} deploy\` again.`;
82279
82291
  if (opts.json)
82280
82292
  printJsonError("NO_DEPLOYABLE_SOURCE", message3);
82281
82293
  else
@@ -82350,7 +82362,7 @@ Existing project: \`${cliInvocation()} init --link --project <ref>\` (see \`${cl
82350
82362
  try {
82351
82363
  const account = await mintTempAccount(void 0, () => {
82352
82364
  if (signupSpinner)
82353
- signupSpinner.text = "Solving the proof-of-work requested by the server\u2026";
82365
+ signupSpinner.text = "Completing the temporary session check\u2026";
82354
82366
  });
82355
82367
  signupSpinner?.stop();
82356
82368
  if (besideRealLogin) {
@@ -82384,7 +82396,18 @@ Existing project: \`${cliInvocation()} init --link --project <ref>\` (see \`${cl
82384
82396
  } catch (err) {
82385
82397
  signupSpinner?.fail("Could not create a temporary session");
82386
82398
  const status = err instanceof CliApiError ? ` ${dim(err.statusCode ? `[${err.code}, HTTP ${err.statusCode}]` : `[${err.code}]`)}` : "";
82387
- error(`${err instanceof Error ? err.message : String(err)}${status}`, err);
82399
+ const envelope = platformErrorEnvelope(err);
82400
+ if (envelope?.code === "INVALID_POW" || envelope?.code === "POW_REQUIRED") {
82401
+ const message3 = `The temporary session check failed. Run \`${cliInvocation()} deploy\` to try again.`;
82402
+ if (opts.json) {
82403
+ noteFailure(err);
82404
+ printJsonError(envelope.code, message3, envelope.extra);
82405
+ } else {
82406
+ error(`${message3}${status}`, err);
82407
+ }
82408
+ } else {
82409
+ error(`${err instanceof Error ? err.message : String(err)}${status}`, err);
82410
+ }
82388
82411
  process.exit(1);
82389
82412
  }
82390
82413
  }
@@ -82558,7 +82581,7 @@ Existing project: \`${cliInvocation()} init --link --project <ref>\` (see \`${cl
82558
82581
  warn(`This looks like a Node server app (${serverSignal}) \u2014 somewhere.cloud does not run server processes.`);
82559
82582
  warn("It will deploy as static files only: your routes will NOT run, and the");
82560
82583
  warn("server source will be publicly readable at its file path.");
82561
- warn("The platform shape: static files at the root + API handlers under functions/");
82584
+ warn("The platform accepts static files at the root and API handlers under api/.");
82562
82585
  warn("(each default-exports async (req, sw) and becomes a route).");
82563
82586
  warn(`Full quickstart: ${cliInvocation()} docs start`);
82564
82587
  }
@@ -82566,18 +82589,15 @@ Existing project: \`${cliInvocation()} init --link --project <ref>\` (see \`${cl
82566
82589
  spinner?.start();
82567
82590
  }
82568
82591
  const totalFiles = Object.keys(files).length + Object.keys(binaryFiles).length + Object.keys(functions).length;
82569
- const textBytes = Object.values(files).concat(Object.values(functions)).reduce((sum, c) => sum + c.length, 0);
82570
- const binaryBytes = Object.values(binaryFiles).reduce((sum, b64) => sum + Math.floor(b64.length * 3 / 4), 0);
82571
- const totalBytes = textBytes + binaryBytes;
82572
82592
  const inventory = uploadInventory(files, binaryFiles, functions, scope);
82573
82593
  if (opts.dryRun && !opts.json) {
82574
82594
  spinner?.stop();
82575
- info(dim(`Dry run: sending ${totalFiles} files (${formatBytes(totalBytes)}) to Somewhere to compute the change. Nothing is published.`));
82595
+ info(dim(`Dry run: sending ${totalFiles} files to Somewhere to check what would change. Nothing is published.`));
82576
82596
  if (process.stderr.isTTY)
82577
82597
  spinner?.start();
82578
82598
  }
82579
82599
  if (spinner) {
82580
- spinner.text = opts.dryRun ? `Checking ${totalFiles} files (${formatBytes(totalBytes)})...` : `Deploying ${totalFiles} files (${formatBytes(totalBytes)})...`;
82600
+ spinner.text = opts.dryRun ? `Checking ${totalFiles} files...` : `Deploying ${totalFiles} files...`;
82581
82601
  }
82582
82602
  let deployAnswered = false;
82583
82603
  let deployRequestStartedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -82724,7 +82744,6 @@ Existing project: \`${cliInvocation()} init --link --project <ref>\` (see \`${cl
82724
82744
  scope,
82725
82745
  functionCount: countFunctionRoutes(functions),
82726
82746
  staticFileCount: inventory.static_files.length,
82727
- totalBytes,
82728
82747
  linkedProject: await linkedProjectWithSubdomain(client, result, targetProjectConfig)
82729
82748
  });
82730
82749
  if (opts.timing && !opts.json) {
@@ -82918,7 +82937,7 @@ ${dim("Build")}`);
82918
82937
  info(formatTempExpiry(tempSession.expiresAt, tempSession.ttlSeconds));
82919
82938
  const link = teal(tempSession.claimUrl);
82920
82939
  if (tempSession.handoffReady) {
82921
- info(`Open ${link} and select "Save project and connect agent" to save the project to your account and connect this terminal automatically.`);
82940
+ info(`Open ${link} and select "Save and connect agent" to save the project and connect this terminal to it only. Run \`${cliInvocation()} login\` for account access.`);
82922
82941
  } else if (besideRealLogin) {
82923
82942
  info(`Open ${link} to save the project to your account, then run \`${cliInvocation()} init --link --project ${projectId}\` in an unlinked folder to work on it.`);
82924
82943
  } else {
@@ -83096,13 +83115,13 @@ function formatDeploySuccess(result, options2) {
83096
83115
  if (options2.scope === "functions") {
83097
83116
  headline = `${formatPublishSurface({ staticFiles: null, functions: options2.functionCount })} deployed \u2014 site left untouched`;
83098
83117
  } else if (options2.scope === "static") {
83099
- headline = `${staticLabel} uploaded (${formatBytes(options2.totalBytes)}) \u2014 functions left untouched`;
83118
+ headline = `${staticLabel} uploaded \u2014 functions left untouched`;
83100
83119
  } else {
83101
83120
  const both = formatPublishSurface({
83102
83121
  staticFiles: staticFileCount,
83103
83122
  functions: options2.functionCount
83104
83123
  });
83105
- headline = `${staticFileCount === null && options2.functionCount === 0 ? staticLabel : both} uploaded (${formatBytes(options2.totalBytes)})`;
83124
+ headline = `${staticFileCount === null && options2.functionCount === 0 ? staticLabel : both} uploaded`;
83106
83125
  }
83107
83126
  const responseUrl = typeof result.url === "string" && result.url.trim() ? result.url.trim() : null;
83108
83127
  const linkedSubdomain = typeof options2.linkedProject?.subdomain === "string" ? options2.linkedProject.subdomain.trim() : "";
@@ -86803,7 +86822,7 @@ function registerEnv(program2) {
86803
86822
  }
86804
86823
  success(`Wrote ${keys.length} key${keys.length === 1 ? "" : "s"} to ${teal(opts.out)} (values blank \u2014 fill them in for local runs)`);
86805
86824
  });
86806
- env.command("set <key> [value]").description("Set an environment value; use --stdin to keep it out of shell history").option("--project <id>", "Project ID").option("--stdin", "Read the value from stdin (removes one final line ending)").option("--public", "Explicitly allow browser exposure for a VITE_/REACT_APP_ name").option("--private", "Keep this value server-only").option("--scope <scope>", "Environment: all, dev, or prod (default: all)").option("--provider <name>", "Optional provider label (max 64 characters)").option("--purpose <text>", "Optional purpose description (max 240 characters)").option("--json", "Print the raw env response as JSON").action(async (key, positionalValue, opts) => {
86825
+ env.command("set <key> [value]").description("Set an environment value; use --stdin to keep it out of shell history").option("--project <id>", "Project ID").option("--stdin", "Read the value from stdin (removes one final line ending)").option("--public", "Explicitly allow browser exposure for a VITE_/REACT_APP_ name").option("--private", "Keep this value server-only").option("--scope <scope>", "Environment: all, dev, or prod (default: all)").option("--provider <name>", "Optional provider label").option("--purpose <text>", "Optional purpose description").option("--json", "Print the raw env response as JSON").action(async (key, positionalValue, opts) => {
86807
86826
  if (opts.public && opts.private) {
86808
86827
  error("--public and --private cannot be used together.");
86809
86828
  process.exit(1);
@@ -87342,7 +87361,7 @@ function registerClaim(program2) {
87342
87361
  program2.command("claim").description("Print the claim URL that keeps this computer's temporary (signed-out) projects").option("--json", "Print { claim_url, expires_at } as JSON").action((opts) => {
87343
87362
  const config2 = loadConfig();
87344
87363
  if (!config2?.temporary || !config2.claim_url) {
87345
- const message3 = config2?.token ? `This computer is signed in to an account, so there is nothing to claim: its projects are already yours (\`${cliInvocation()} projects\`).` : `This computer has no temporary workspace (nothing in ${cliConfigPathForDisplay()}). If you deployed signed out from another terminal, run \`${cliInvocation()} claim\` there; or run \`${cliInvocation()} deploy\` here to start one.`;
87364
+ const message3 = config2?.token ? `This terminal has no temporary workspace to claim. Run \`${cliInvocation()} projects\` to see the projects it can access.` : `This terminal has no temporary workspace. If you deployed signed out from another terminal, run \`${cliInvocation()} claim\` there. Run \`${cliInvocation()} deploy\` here to start one.`;
87346
87365
  if (opts.json)
87347
87366
  printJson({ ok: false, error: config2?.token ? "NOT_TEMPORARY" : "NO_TEMPORARY_WORKSPACE", message: message3 });
87348
87367
  else
@@ -87363,7 +87382,11 @@ function registerClaim(program2) {
87363
87382
  info(`Claim URL: ${teal(config2.claim_url)}`);
87364
87383
  if (config2.temp_expires_at)
87365
87384
  info(`Expires at: ${config2.temp_expires_at} (UTC)`);
87366
- info(`Open it in a browser and sign in (or create an account) to keep these projects. Choose "Save project and connect agent" to sign this CLI in as well; otherwise run \`${cliInvocation()} login\` here afterwards.`);
87385
+ info("Open it in a browser and sign in or create an account to keep these projects.");
87386
+ if (config2.claim_handoff?.handoff_id) {
87387
+ info('Choose "Save and connect agent" to connect this terminal to the claimed project only.');
87388
+ }
87389
+ info(`Run \`${cliInvocation()} login\` for account access.`);
87367
87390
  });
87368
87391
  }
87369
87392
  var init_claim = __esm({
@@ -87799,7 +87822,7 @@ function registerPreview(program2) {
87799
87822
  row.promotable ? "yes" : "no: production changed",
87800
87823
  row.this_folder ? "this folder" : ""
87801
87824
  ]));
87802
- console.log(dim("Each open preview holds a copy of production data until it is promoted, closed, or unused for 24 h (7 days at most)."));
87825
+ console.log(dim("Each open preview holds a copy of production data until it is promoted, closed, or expires."));
87803
87826
  console.log(dim(`Close one: ${cliInvocation()} preview close <preview_session_id>. Promote one: ${cliInvocation()} promote <preview_session_id> <preview_id>.`));
87804
87827
  } catch (err) {
87805
87828
  if (opts.json)
@@ -87877,9 +87900,9 @@ function registerPreview(program2) {
87877
87900
  previewToolFailed(err, opts.json, "PREVIEW_USER_REMOVE_FAILED", target);
87878
87901
  }
87879
87902
  });
87880
- preview.command("run-job <handler-path>").description("Run one handler path once in this folder's open preview, as one signed job delivery, and wait for its result (a scheduled task is a handler path plus a payload)").option("--payload <json>", "JSON payload the handler receives (default: none)").option("--no-wait", "Return as soon as the run is queued instead of waiting for its result").option("--timeout <seconds>", "How long to wait for the result (default 300; a preview run is capped at 270 s)").option("--project <id>", "Override project ID").option("--preview-session <id>", "Which preview (its preview_session_id); default: this folder's").option("--json", "Print the run (and its result) as JSON").addHelpText("after", `
87903
+ preview.command("run-job <handler-path>").description("Run one handler path once in this folder's open preview, as one signed job delivery, and wait for its result (a scheduled task is a handler path plus a payload)").option("--payload <json>", "JSON payload the handler receives (default: none)").option("--no-wait", "Return as soon as the run is queued instead of waiting for its result").option("--timeout <seconds>", "How long to wait for the result (default 300)").option("--project <id>", "Override project ID").option("--preview-session <id>", "Which preview (its preview_session_id); default: this folder's").option("--json", "Print the run (and its result) as JSON").addHelpText("after", `
87881
87904
  The run uses the preview's own code, data, files, users and mail; it has no signed-in user (like a scheduled
87882
- run in production), one attempt and at most 270 seconds. Nothing in your live app runs or changes.
87905
+ run in production). It runs once. Nothing in your live app runs or changes.
87883
87906
  To run a production schedule's handler and payload this way: ${cliInvocation()} cron run <name> --preview
87884
87907
  `).action(async (handlerPath, _opts, cmd) => {
87885
87908
  const opts = cmd.optsWithGlobals();
@@ -129846,7 +129869,7 @@ Shared organization board (requires access): ${cliInvocation()} tasks list -p de
129846
129869
  }
129847
129870
  await runTaskTool("tasks_update", args, opts.json, printTaskMutation);
129848
129871
  });
129849
- tasks.command("delete <task-ids...>").description("Delete a task that should never have existed; restorable for 30 days (board owner only)").option("-p, --project <project>", "Project slug or ID; defaults to the linked project").requiredOption("--reason <text>", "Why this task should never have existed").option("--json", "Print the complete response as JSON").action(async (taskIds, opts) => {
129872
+ tasks.command("delete <task-ids...>").description("Delete a task that should never have existed (board owner only)").option("-p, --project <project>", "Project slug or ID; defaults to the linked project").requiredOption("--reason <text>", "Why this task should never have existed").option("--json", "Print the complete response as JSON").action(async (taskIds, opts) => {
129850
129873
  if (taskIds.length > 200)
129851
129874
  throw new Error("At most 200 task IDs may be deleted per call.");
129852
129875
  await runTaskTool("tasks_delete", compactRecord([
@@ -129859,9 +129882,10 @@ Shared organization board (requires access): ${cliInvocation()} tasks list -p de
129859
129882
  printJson(value);
129860
129883
  return;
129861
129884
  }
129862
- const purgeAt = typeof data2.purge_at === "number" ? new Date(data2.purge_at).toISOString() : "in 30 days";
129863
129885
  console.log(`${teal(data2.id)} ${data2.already_deleted ? "was already deleted" : "deleted"}`);
129864
- console.log(dim(`Restorable until ${purgeAt}: ${cliInvocation()} tasks restore ${data2.id}`));
129886
+ const restore = `\`${cliInvocation()} tasks restore ${data2.id}\``;
129887
+ const deadline = typeof data2.purge_at === "number" ? ` until ${new Date(data2.purge_at).toISOString()}` : "";
129888
+ console.log(dim(`Restore${deadline} with ${restore}.`));
129865
129889
  });
129866
129890
  });
129867
129891
  tasks.command("restore <task-id>").description("Restore a deleted task with its comments and links (board owner only)").option("-p, --project <project>", "Project slug or ID; defaults to the linked project").option("--reason <text>", "Why it is being restored").option("--json", "Print the complete response as JSON").action(async (taskId, opts) => {
@@ -130144,7 +130168,7 @@ async function waitForChoices(client, repoName, quiet) {
130144
130168
  }
130145
130169
  await sleep2(2e3);
130146
130170
  }
130147
- throw new Error(`GitHub authorization was not completed within 5 minutes. Run \`${cliInvocation()} git connect\` again.`);
130171
+ throw new Error(`The wait for GitHub authorization ended. Run \`${cliInvocation()} git connect\` again.`);
130148
130172
  }
130149
130173
  async function chooseRepo(client, requestedRepo, quiet) {
130150
130174
  const app = await listInstallations(client);
@@ -130193,7 +130217,7 @@ async function waitForDeploy(client, projectId, commitSha) {
130193
130217
  }
130194
130218
  await sleep2(DEPLOY_POLL_MS);
130195
130219
  }
130196
- throw new Error(`Deploy of ${commitSha.slice(0, 7)} is still running after 10 minutes. Check the project logs.`);
130220
+ throw new Error(`The wait ended before deploy of ${commitSha.slice(0, 7)} finished. Check the project logs.`);
130197
130221
  }
130198
130222
  function urls(projectId, servingUrl) {
130199
130223
  return {
@@ -130815,7 +130839,7 @@ zone each trigger is stored in, and \`cron update --schedule\` keeps that zone u
130815
130839
  printTypedCronError(code, message3, opts.json, extra);
130816
130840
  }
130817
130841
  });
130818
- cron.command("runs <cron-id-or-name>").description("Show recent runs of a scheduled task, scheduled and manual, with its next run").option("-p, --project <project>", "Project slug or ID used to resolve a task name; defaults to the linked project").option("--limit <n>", "How many recent runs to show, 1-100 (default 20)").option("--wait-next", "Observe a natural scheduled occurrence after command start and wait for that job to finish").option("--timeout <seconds>", `With --wait-next, total observation time (default ${DEFAULT_WAIT_TIMEOUT_SECONDS}s)`).option("--json", "Print the trigger and its runs as JSON").addHelpText("after", '\nTRIGGER is "scheduled" for a run the schedule started (SCHEDULED FOR is the occurrence it\nserved) and "manual" for `cron run`. Times are UTC. A scheduled run is recorded shortly after\nits scheduled time, not exactly on it; until the schedule advances, the next run shows as\noverdue, and this command says whether a run for that occurrence appears in the recent\nhistory shown.\n\n--wait-next is read-only: it ignores manual runs and older scheduled slots, pins one job,\nand waits within --timeout. Changes to schedule settings or a disabled schedule stop the wait.\nThe observation uses at most --limit recent rows per read (default 100 while waiting).\nA timeout reports what was not observed; it does not mean the timer never fired.\nAn already-started login renewal finishes with its existing 10-second request budgets before\nthe command exits, so credential persistence can add grace beyond the observation deadline.\n').action(async (target, opts) => {
130842
+ cron.command("runs <cron-id-or-name>").description("Show recent runs of a scheduled task, scheduled and manual, with its next run").option("-p, --project <project>", "Project slug or ID used to resolve a task name; defaults to the linked project").option("--limit <n>", "How many recent runs to show, 1-100 (default 20)").option("--wait-next", "Observe a natural scheduled occurrence after command start and wait for that job to finish").option("--timeout <seconds>", `With --wait-next, total observation time (default ${DEFAULT_WAIT_TIMEOUT_SECONDS}s)`).option("--json", "Print the trigger and its runs as JSON").addHelpText("after", '\nTRIGGER is "scheduled" for a run the schedule started (SCHEDULED FOR is the occurrence it\nserved) and "manual" for `cron run`. Times are UTC. A scheduled run is recorded shortly after\nits scheduled time, not exactly on it; until the schedule advances, the next run shows as\noverdue, and this command says whether a run for that occurrence appears in the recent\nhistory shown.\n\n--wait-next is read-only: it ignores manual runs and older scheduled slots, pins one job,\nand waits within --timeout. Changes to schedule settings or a disabled schedule stop the wait.\nThe observation uses at most --limit recent rows per read (default 100 while waiting).\nA timeout reports what was not observed; it does not mean the timer never fired.\nIf a login renewal is already underway, it can finish after the observation deadline.\n').action(async (target, opts) => {
130819
130843
  try {
130820
130844
  const limit = parseRunsLimit(opts.limit);
130821
130845
  if (opts.timeout !== void 0 && !opts.waitNext)
@@ -131338,7 +131362,7 @@ var init_test_scripts = __esm({
131338
131362
 
131339
131363
  // dist/commands/test.js
131340
131364
  function registerTest(program2) {
131341
- program2.command("test [files...]").description("Run this project's tests: every tests/*.mjs and tests/*.cjs script (such as tests/app-check.mjs), or, when the project has tests/**/*.spec.ts, its Playwright specs against the live release (--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("--failed", "Rerun what failed last time: each failed tests/*.mjs or *.cjs script, all its checks (specs: only the failed tests)").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").action(async (files, opts) => {
131365
+ program2.command("test [files...]").description("Run this project's tests: every tests/*.mjs and tests/*.cjs script (such as tests/app-check.mjs), or, when the project has tests/**/*.spec.ts, its Playwright specs against the live release (--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("--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", '\nFor the starter privacy check, mark the data view with data-sw-data="loading" while fetching, "ready" once data loads, or "error" if fetching fails.\n').action(async (files, opts) => {
131342
131366
  markProcessStart("cli");
131343
131367
  mark("cli:action");
131344
131368
  if (opts.url)
@@ -131360,6 +131384,8 @@ function registerTest(program2) {
131360
131384
  const scripts = opts.failed ? lastFailedScripts(root) : listScripts(root, files);
131361
131385
  if (opts.failed && !scripts.length)
131362
131386
  throw new Error("No failed scripts are recorded from the last run here; run somewhere test.");
131387
+ if (opts.failFast)
131388
+ process.env.SW_TEST_FAIL_FAST = "1";
131363
131389
  const results = await runScripts(root, scripts, []);
131364
131390
  await note;
131365
131391
  if (results.length)
@@ -131373,6 +131399,8 @@ function registerTest(program2) {
131373
131399
  process.exitCode = failed || !results.length ? 1 : 0;
131374
131400
  return;
131375
131401
  }
131402
+ if (opts.failFast)
131403
+ throw new Error("--fail-fast applies to app-check scripts (tests/*.mjs or *.cjs).");
131376
131404
  const outcome2 = await runTests({ root, ...opts.preview ? {} : { client: new ApiClient(getToken()) }, projectId, prepared: prepareRunner(root), options: { ...opts, files } });
131377
131405
  await note;
131378
131406
  mark("cli:exit");
@@ -131534,7 +131562,7 @@ function registerTestUsers(program2) {
131534
131562
  info(RETAINED_NOTE);
131535
131563
  if (failure) {
131536
131564
  fail2(opts, failure);
131537
- warn(`Prepared ${manifest.actors.length} of ${specs.length} actors; the ones created are recorded in ${TEST_STATE_DIR}/${MANIFEST_FILE}. Run \`somewhere test-users cleanup\` to remove them. If the platform may have created more than were returned, they expire 24 hours after creation.`);
131565
+ warn(`Prepared ${manifest.actors.length} of ${specs.length} actors; the ones created are recorded in ${TEST_STATE_DIR}/${MANIFEST_FILE}. Run \`somewhere test-users cleanup\` to remove them. The platform removes any remaining test users when they expire.`);
131538
131566
  } else {
131539
131567
  success(`Prepared ${manifest.actors.length} signed-in test user${manifest.actors.length === 1 ? "" : "s"} for ${target.origin}.`);
131540
131568
  }
@@ -132716,7 +132744,7 @@ async function freshCodes(run, address, mark2, what) {
132716
132744
  if (codes.length)
132717
132745
  return codes;
132718
132746
  if (Date.now() > deadline)
132719
- throw new Error(`${what}: no code reached the project's test inbox for ${address} within 25 s. The test inbox holds at most a limited number of messages for 7 days; when it is full, new mail is not stored.`);
132747
+ throw new Error(`${what}: no code reached the project's test inbox for ${address}. Check whether the app sent the message, then try again.`);
132720
132748
  }
132721
132749
  }
132722
132750
  async function registerMailedCodes(run, address, submitted) {
@@ -132982,6 +133010,19 @@ import { basename as basename10, dirname as dirname15, join as join48, relative
132982
133010
  function launchOptions(extra = {}) {
132983
133011
  return { ...extra, args: ["--disable-features=AsyncDns", ...extra.args ?? []] };
132984
133012
  }
133013
+ function describeCheckFailure(message3, expected, step2, evidence, pageUrl) {
133014
+ const detail = /* @__PURE__ */ __name((pattern) => message3.match(pattern)?.[1]?.trim(), "detail");
133015
+ const observed = detail(/^Received(?: \w+)?: *(.*)$/m);
133016
+ const header = message3.split("\n").find((line) => line.trim())?.trim() || "The check did not finish.";
133017
+ const artifact = detail(/\b(HTTP [1-5][0-9]{2}(?: [A-Z][A-Z_0-9]+)?)/) ?? detail(/^(?:Locator|Selector): *(.*)$/mi) ?? evidence ?? pageUrl;
133018
+ const singleLine = /* @__PURE__ */ __name((value) => scrub(value).replace(/\s+/g, " ").trim().slice(0, 500), "singleLine");
133019
+ return {
133020
+ expected: singleLine(detail(/^Expected(?: \w+)?: *(.*)$/m) ?? expected),
133021
+ happened: singleLine(observed ? `Received ${observed}.` : header),
133022
+ step: singleLine(step2),
133023
+ ...artifact ? { evidence: singleLine(artifact) } : {}
133024
+ };
133025
+ }
132985
133026
  async function pageState(page) {
132986
133027
  if (page.isClosed())
132987
133028
  return "closed";
@@ -133061,7 +133102,15 @@ function captureResponses(page) {
133061
133102
  async function dataReady(scope, timeout = 5e3) {
133062
133103
  const root = typeof scope.goto === "function" ? scope.locator(":root") : scope;
133063
133104
  const views = root.locator("[data-sw-data]");
133064
- await views.first().waitFor({ state: "attached", timeout });
133105
+ try {
133106
+ await views.first().waitFor({ state: "attached", timeout });
133107
+ } catch (error3) {
133108
+ const page = root.page();
133109
+ if (error3 instanceof Error && error3.name === "TimeoutError" && page.url() !== "about:blank" && await page.evaluate('document.readyState !== "loading" && !!document.body').catch(() => false)) {
133110
+ throw new Error('The page loaded without the expected [data-sw-data] marker, which your app sets on the data view to "loading", "ready", or "error" as shown in `somewhere test --help`.');
133111
+ }
133112
+ throw error3;
133113
+ }
133065
133114
  await root.locator('[data-sw-data="loading"]').first().waitFor({ state: "detached", timeout }).catch(async () => {
133066
133115
  if (await root.locator('[data-sw-data="loading"]').count())
133067
133116
  throw new Error(`dataReady: a data view was still loading after ${timeout / 1e3} s`);
@@ -133084,6 +133133,7 @@ var init_app_test = __esm({
133084
133133
  init_test_diagnostics();
133085
133134
  init_test_timeline();
133086
133135
  __name(launchOptions, "launchOptions");
133136
+ __name(describeCheckFailure, "describeCheckFailure");
133087
133137
  __name(pageState, "pageState");
133088
133138
  __name(clientOf, "clientOf");
133089
133139
  __name(undeployedChanges, "undeployedChanges");
@@ -133257,19 +133307,26 @@ var init_app_test = __esm({
133257
133307
  }
133258
133308
  return result;
133259
133309
  }
133260
- /** Run one named check. The first failure stops the run: it prints the check, the error and
133261
- * what each signed-in page shows (URL, visible error text), and every later check is skipped
133262
- * instead of waiting out its own timeout. `somewhere test --failed` reruns a failed script whole,
133263
- * so setup done inside earlier checks runs again. */
133264
- async check(label, work) {
133310
+ /** Run one named check unless its prerequisite did not pass. Use at() inside a
133311
+ * check that has several steps. `somewhere test --failed` reruns the whole script. */
133312
+ async check(label, work, options2 = {}) {
133265
133313
  const name = scrub(label);
133266
133314
  if (this.stopped) {
133267
133315
  this.checks.push({ name, ok: false, ms: 0, skipped: "after-failure" });
133268
133316
  return false;
133269
133317
  }
133318
+ if (options2.requires && !options2.requires.passed) {
133319
+ this.checks.push({ name, ok: false, ms: 0, skipped: "prerequisite", error: `Requires \u201C${scrub(options2.requires.name)}\u201D, which did not pass.` });
133320
+ return false;
133321
+ }
133270
133322
  const start = performance.now();
133323
+ let step2 = label;
133324
+ let evidence;
133271
133325
  try {
133272
- await work();
133326
+ await work((current, artifact) => {
133327
+ step2 = current;
133328
+ evidence = artifact;
133329
+ });
133273
133330
  this.checks.push({ name, ok: true, ms: Math.round(performance.now() - start) });
133274
133331
  return true;
133275
133332
  } catch (error3) {
@@ -133280,14 +133337,12 @@ var init_app_test = __esm({
133280
133337
  await this.rememberPageSecrets();
133281
133338
  const pages = await Promise.all([...this.host.pages].map(pageState));
133282
133339
  const stopped = [...this.host.pages].map((page) => browserStoppedMessage(page, error3)).find(Boolean);
133283
- const message3 = stopped ?? scrub((error3 instanceof Error ? error3.message.split("\n").slice(0, 6).join("\n") : String(error3)) + pages.map((state, i) => `
133284
- page ${i + 1}: ${state}`).join(""));
133285
- this.checks.push({ name, ok: false, ms: Math.round(performance.now() - start), error: message3 });
133286
- this.stopped = true;
133287
- process.stdout.write(`FAIL ${name}
133288
- ${message3.replaceAll("\n", "\n ")}
133289
- Stopping here: later checks are skipped. After a fix, rerun the scripts that failed: ${TEST_COMMAND} --failed
133290
- `);
133340
+ const message3 = stopped ?? scrub(error3 instanceof Error ? error3.message : String(error3));
133341
+ const failure = describeCheckFailure(message3, options2.expected ?? name, step2, evidence, [...this.host.pages].find((page) => !page.isClosed())?.url() ?? this.origin);
133342
+ const detail = message3.split("\n").slice(0, 12).join("\n") + pages.map((state, i) => `
133343
+ page ${i + 1}: ${state}`).join("");
133344
+ this.checks.push({ name, ok: false, ms: Math.round(performance.now() - start), error: detail, failure });
133345
+ this.stopped = process.env.SW_TEST_FAIL_FAST === "1";
133291
133346
  return false;
133292
133347
  }
133293
133348
  }
@@ -133339,6 +133394,11 @@ Stopping here: later checks are skipped. After a fix, rerun the scripts that fai
133339
133394
  await this.control.close();
133340
133395
  if (cleanup.length)
133341
133396
  this.checks.push({ name: "cleanup of sign-up accounts", ok: false, ms: 0, error: cleanup.join("; ") });
133397
+ for (const check2 of this.checks) {
133398
+ if (!check2.ok && !check2.skipped && !check2.failure) {
133399
+ check2.failure = describeCheckFailure(check2.error ?? "", check2.name, check2.name, this.origin);
133400
+ }
133401
+ }
133342
133402
  const passed = this.checks.filter((check2) => check2.ok).length;
133343
133403
  const failed = this.checks.filter((check2) => !check2.ok && !check2.skipped).length;
133344
133404
  mkdirSync20(dirname15(this.resultsPath), { recursive: true });
@@ -133354,7 +133414,10 @@ Stopping here: later checks are skipped. After a fix, rerun the scripts that fai
133354
133414
  failed,
133355
133415
  checks: this.checks.map((check2) => ({ ...check2, ...check2.error ? { error: scrub(check2.error) } : {} }))
133356
133416
  }, null, 2) + "\n");
133357
- const reported = this.checks.map((check2) => ({ name: scrub(check2.name), ok: check2.ok, ...check2.skipped ? { skipped: check2.skipped } : {}, ...check2.error ? { error: scrub(check2.error) } : {} }));
133417
+ const reported = this.checks.map(({ ms: ms2, ...check2 }) => ({
133418
+ ...check2,
133419
+ ...check2.error ? { error: scrub(check2.error) } : {}
133420
+ }));
133358
133421
  const resultFile = relative14(this.root, this.resultsPath);
133359
133422
  const handOver = process.env.SW_TEST_REPORT;
133360
133423
  if (handOver)