@somewhere-cloud/cli 0.38.178 → 0.38.180

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.
@@ -44271,28 +44271,11 @@ Use \`client.intake\` for public submissions to a private parent row. See
44271
44271
 
44272
44272
  ### Run and verify
44273
44273
 
44274
- Prove the brief with a check list in \`checks/<name>.json\` and run \`somewhere test\`. The platform makes the named users itself (no sign-up form, browser or contract digest), runs each step on the live app as that user, prints PASS or FAIL per step with the expected and actual answer and the request ID, then deletes the users and the rows it can prove it created, naming anything it leaves. The list reruns after every deploy if it only reads, or if it sets \`"rerun_after_deploy": true\`.
44275
-
44276
- \`\`\`json
44277
- {
44278
- "users": ["owner", "member", { "name": "carol", "roles": ["staff"] }],
44279
- "steps": [
44280
- { "as": "owner", "post": "/api/teams", "body": { "name": "T" }, "expect": 201, "save": { "team": "id" } },
44281
- { "as": "owner", "post": "/api/teams/{team}/members", "body": { "email": "{member.email}" } },
44282
- { "as": "member", "data": { "table": "tasks", "operation": "create", "values": { "team_id": "{team}", "title": "x" } }, "save": { "task": "id" } },
44283
- { "as": "carol", "delete": "/api/tasks/{task}", "expect": [403, 404] },
44284
- { "as": "signed_out", "get": "/api/teams/{team}/tasks", "expect": 401, "lacks": "{member.email}" },
44285
- { "run": "daily-summary" }
44286
- ],
44287
- "cleanup": [{ "as": "owner", "delete": "/api/teams/{team}" }]
44288
- }
44289
- \`\`\`
44274
+ Prove the brief in \`tests/starter.mjs\` (\`npm test\`, from the app folder, after deploy). \`app.users('owner', 'member', 'outsider')\` makes signed-in test users with no sign-up form, and \`app.users({ agent: { roles: ['staff'] } })\` gives a role. Each user, and \`app.signedOut\`, has \`get\`, \`post\`, \`put\`, \`patch\`, \`delete\` and \`data(table, request)\`, each answering \`{ status, body, text, requestId }\`. \`app.expect(reply, 403, label)\` and \`app.check(label, ok)\` print PASS or FAIL without stopping the run. \`await app.refuse([outsider, app.signedOut], [['GET', path], ['DELETE', path]], { lacks: secretText })\` checks that each of them is refused each request, all at once. \`app.page(user, path)\` opens a signed-in Playwright page for the few checks that need the screen. \`app.done()\` deletes the users and sets the exit code. Keep the file to your assertions.
44290
44275
 
44291
- - A step is \`as\` (a name from \`users\`, or \`signed_out\`) and one of: \`get\`, \`post\`, \`put\`, \`patch\` or \`delete\` with a path (and \`body\`); \`data\` with the data endpoint's request (\`table\`, \`operation\`, \`values\`, \`id\`, \`where\`); or \`run\` with a schedule name, which runs it now and waits for its job.
44292
- - \`expect\` is a status or a list of them (default: any 2xx). \`has\` and \`lacks\` take text; \`has_fields\` and \`lacks_fields\` take JSON field names. \`save\` keeps a field of the answer (of the row, for \`data\`) as \`{name}\` for later steps. \`wait: 10\` retries the step for up to 10 seconds.
44293
- - \`{alice.email}\` and \`{alice.id}\` are each user's address and ID. \`roles\` gives roles your schema declares \`assignedBy: 'server'\`. Up to 6 users and 60 steps per list. \`cleanup\` steps run last, even after a failure. \`wait\` retries only reads. A failing step's output from a run you start can show data from the app; stored results keep only the step, status, request ID and failed expectation.
44276
+ Tests that write change rows in the live app. For an app with real customers, test on a preview instead: \`somewhere preview\`, then \`openTestApp({ preview: true })\`. After every deploy the platform also runs its own smoke check, plus any check lists saved in \`checks/\`; \`somewhere test\` shows the result.
44294
44277
 
44295
- Run \`somewhere typecheck\` before deploying. \`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\`. Inspect failures with \`somewhere errors\` and \`somewhere logs\`. For a check that needs a rendered page, save a browser flow with \`actions\` in \`checks/<name>.json\`, using \`checks/add-a-note.json\` from the notes starter as a model. Keep test IDs when restyling. See \`somewhere docs test\`.
44278
+ Run \`somewhere typecheck\` before deploying. \`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\`. Inspect failures with \`somewhere errors\` and \`somewhere logs\`. Keep test IDs when restyling. See \`somewhere docs test\`.
44296
44279
 
44297
44280
  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.
44298
44281
  `;
@@ -44318,7 +44301,7 @@ Download Markdown to \`.somewhere/docs/\` with \`somewhere docs pull\`.
44318
44301
  Without a global CLI, use \`npx @somewhere-cloud/cli deploy\` and \`npx @somewhere-cloud/cli test\`.
44319
44302
 
44320
44303
  For Node or Playwright tests, see [Testing your app](https://somewhere.cloud/docs/test).
44321
- In a generated starter, run \`npm test\` after its first deploy to verify the signed-in session.
44304
+ In a generated starter, \`npm test\` runs \`tests/starter.mjs\` against the deployed app.
44322
44305
 
44323
44306
  ${PORTABILITY_POINTER}
44324
44307
  ${MCP_POINTER}
@@ -44329,48 +44312,33 @@ ${PREVIEW_POINTER}
44329
44312
  });
44330
44313
 
44331
44314
  // dist/lib/init-test-template.js
44332
- function starterChecks(options2 = {}) {
44333
- return options2.privateData ? [{ path: "checks/add-a-note.json", content: JSON.stringify(ADD_A_NOTE, null, 2) + "\n" }] : [];
44334
- }
44335
- var ADD_A_NOTE, STARTER_CHECK_LIST, STARTER_AUTH_TEST;
44315
+ var STARTER_AUTH_TEST;
44336
44316
  var init_init_test_template = __esm({
44337
44317
  "dist/lib/init-test-template.js"() {
44338
44318
  "use strict";
44339
- ADD_A_NOTE = {
44340
- actions: [
44341
- { fill: "[data-testid=note-title]", value: "Lunch with Ana 42" },
44342
- { click: "[data-testid=note-save]" },
44343
- { expect: { selector: "[data-testid=note-item]", text: "Lunch with Ana 42" } }
44344
- ],
44345
- viewports: ["desktop", "mobile"],
44346
- signed_in: true
44347
- };
44348
- __name(starterChecks, "starterChecks");
44349
- STARTER_CHECK_LIST = {
44350
- path: "checks/signed-in.json",
44351
- content: `{
44352
- "users": ["ana"],
44353
- "steps": [
44354
- { "as": "ana", "get": "/api/auth/me", "has": "{ana.email}" },
44355
- { "as": "signed_out", "get": "/api/auth/me", "lacks": "{ana.email}" }
44356
- ]
44357
- }
44358
- `
44359
- };
44360
44319
  STARTER_AUTH_TEST = {
44361
44320
  path: "tests/starter.mjs",
44362
- content: `import assert from 'node:assert/strict';
44321
+ content: `// Your app, tested live as each kind of user. Run \`npm test\` after \`somewhere deploy\`.
44322
+ // Add your routes below; each user calls them as themselves. More: somewhere docs test
44363
44323
  import { openTestApp } from '@somewhere-cloud/cli/testing';
44364
44324
 
44365
44325
  const app = await openTestApp();
44366
44326
  try {
44367
- const [person] = await app.users(1);
44368
- const response = await person.session.request('/api/auth/me');
44369
- assert.equal(response.status, 200);
44370
- assert.equal((await response.json()).user.id, person.id);
44371
- console.log('The deployed app recognizes the test user.');
44327
+ // Signed-in test users made by the platform, no sign-up form. With a role: app.users({ agent: { roles: ['staff'] } })
44328
+ const { owner, outsider } = await app.users('owner', 'outsider');
44329
+ const me = app.expect(await owner.get('/api/auth/me'), 200, 'the app recognizes a test user');
44330
+ app.check('the session belongs to that user', me?.user?.id === owner.id);
44331
+ app.check('another user is someone else', (await outsider.get('/api/auth/me')).body?.user?.id === outsider.id);
44332
+ app.check('a signed-out visitor is nobody', !(await app.signedOut.get('/api/auth/me')).text.includes(owner.email));
44333
+
44334
+ // Your routes, for example:
44335
+ // const note = app.expect(await owner.post('/api/notes', { title: 'Draft' }), 200, 'owner adds a note');
44336
+ // await app.refuse([outsider, app.signedOut], [['GET', \`/api/notes/\${note.id}\`], ['DELETE', \`/api/notes/\${note.id}\`]], { label: 'only the owner' });
44337
+ // Screen checks (npm install -D playwright): const page = await app.page(owner, '/');
44338
+ } catch (error) {
44339
+ app.check('test ran to the end', false, error);
44372
44340
  } finally {
44373
- await app.cleanup();
44341
+ await app.done(); // deletes the test users, prints "N passed, M failed", exit code 1 on a failure
44374
44342
  }
44375
44343
  `
44376
44344
  };
@@ -44390,7 +44358,72 @@ var init_typecheck_version = __esm({
44390
44358
  }
44391
44359
  });
44392
44360
 
44361
+ // dist/lib/base-files.js
44362
+ import { createHash as createHash3 } from "node:crypto";
44363
+ import { existsSync as existsSync7, mkdirSync as mkdirSync7, readFileSync as readFileSync9, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "node:fs";
44364
+ import { join as join7 } from "node:path";
44365
+ function sha2562(content) {
44366
+ return createHash3("sha256").update(content).digest("hex");
44367
+ }
44368
+ function hashFiles(dir, paths) {
44369
+ const out = {};
44370
+ for (const path3 of paths)
44371
+ out[path3] = sha2562(readFileSync9(join7(dir, path3)));
44372
+ return out;
44373
+ }
44374
+ function saveBaseFiles(dir, base) {
44375
+ mkdirSync7(join7(dir, ".somewhere"), { recursive: true });
44376
+ writeFileSync7(join7(dir, BASE_FILES), JSON.stringify(base) + "\n");
44377
+ }
44378
+ function clearBaseFiles(dir) {
44379
+ rmSync2(join7(dir, BASE_FILES), { force: true });
44380
+ }
44381
+ function loadBaseFiles(dir, projectId, releaseId) {
44382
+ const path3 = join7(dir, BASE_FILES);
44383
+ if (!existsSync7(path3) || releaseId === void 0)
44384
+ return null;
44385
+ try {
44386
+ const parsed = JSON.parse(readFileSync9(path3, "utf8"));
44387
+ if (parsed.project_id !== projectId || parsed.release_id !== releaseId || !parsed.files || typeof parsed.files !== "object")
44388
+ return null;
44389
+ return parsed;
44390
+ } catch {
44391
+ return null;
44392
+ }
44393
+ }
44394
+ function saveLastActivation(dir, activation) {
44395
+ mkdirSync7(join7(dir, ".somewhere"), { recursive: true });
44396
+ writeFileSync7(join7(dir, LAST_ACTIVATION), JSON.stringify(activation) + "\n");
44397
+ }
44398
+ function loadLastActivation(dir) {
44399
+ const path3 = join7(dir, LAST_ACTIVATION);
44400
+ if (!existsSync7(path3))
44401
+ return null;
44402
+ try {
44403
+ return JSON.parse(readFileSync9(path3, "utf8"));
44404
+ } catch {
44405
+ return null;
44406
+ }
44407
+ }
44408
+ var BASE_FILES, LAST_ACTIVATION;
44409
+ var init_base_files = __esm({
44410
+ "dist/lib/base-files.js"() {
44411
+ "use strict";
44412
+ BASE_FILES = join7(".somewhere", "base-files.json");
44413
+ __name(sha2562, "sha256");
44414
+ __name(hashFiles, "hashFiles");
44415
+ __name(saveBaseFiles, "saveBaseFiles");
44416
+ __name(clearBaseFiles, "clearBaseFiles");
44417
+ __name(loadBaseFiles, "loadBaseFiles");
44418
+ LAST_ACTIVATION = join7(".somewhere", "last-activation.json");
44419
+ __name(saveLastActivation, "saveLastActivation");
44420
+ __name(loadLastActivation, "loadLastActivation");
44421
+ }
44422
+ });
44423
+
44393
44424
  // dist/lib/scaffold.js
44425
+ import { lstatSync as lstatSync3, readFileSync as readFileSync10 } from "node:fs";
44426
+ import { basename, join as join8 } from "node:path";
44394
44427
  function buildScaffoldGitignore() {
44395
44428
  return "node_modules\ndist\nbuild\n.env\n# Generated from db/schema.ts by somewhere typecheck, dev and deploy.\n__somewhere_data.d.ts\n__somewhere_files.d.ts\n.somewhere/\n";
44396
44429
  }
@@ -44460,10 +44493,31 @@ function extractDeps(packageJsonText) {
44460
44493
  }
44461
44494
  return {};
44462
44495
  }
44496
+ function unchangedPullScaffolds(dir, base) {
44497
+ const hashes = {};
44498
+ if (!base)
44499
+ return hashes;
44500
+ const defaults = {
44501
+ [SCAFFOLD_PACKAGE_FILENAME]: buildScaffoldPackageJson(basename(dir), {}),
44502
+ [SCAFFOLD_TSCONFIG_FILENAME]: buildScaffoldTsconfig()
44503
+ };
44504
+ for (const [path3, generated] of Object.entries(defaults)) {
44505
+ if (Object.hasOwn(base.files, path3))
44506
+ continue;
44507
+ const local = join8(dir, path3);
44508
+ if (!lstatSync3(local, { throwIfNoEntry: false })?.isFile())
44509
+ continue;
44510
+ const hash = sha2562(readFileSync10(local));
44511
+ if (hash === (base.scaffolds ? base.scaffolds[path3] : sha2562(generated)))
44512
+ hashes[path3] = hash;
44513
+ }
44514
+ return hashes;
44515
+ }
44463
44516
  var SCAFFOLD_TSCONFIG_FILENAME, SCAFFOLD_PACKAGE_FILENAME, SCAFFOLD_GITIGNORE_FILENAME;
44464
44517
  var init_scaffold = __esm({
44465
44518
  "dist/lib/scaffold.js"() {
44466
44519
  "use strict";
44520
+ init_base_files();
44467
44521
  init_typecheck_version();
44468
44522
  SCAFFOLD_TSCONFIG_FILENAME = "tsconfig.json";
44469
44523
  SCAFFOLD_PACKAGE_FILENAME = "package.json";
@@ -44473,6 +44527,7 @@ var init_scaffold = __esm({
44473
44527
  __name(buildScaffoldPackageJson, "buildScaffoldPackageJson");
44474
44528
  __name(sanitizePackageName, "sanitizePackageName");
44475
44529
  __name(extractDeps, "extractDeps");
44530
+ __name(unchangedPullScaffolds, "unchangedPullScaffolds");
44476
44531
  }
44477
44532
  });
44478
44533
 
@@ -44509,7 +44564,6 @@ declare module '*.${ext}' {
44509
44564
  function createGreenTemplate(appName = "somewhere-starter") {
44510
44565
  return [
44511
44566
  { path: ".gitignore", content: buildScaffoldGitignore() },
44512
- STARTER_CHECK_LIST,
44513
44567
  STARTER_AUTH_TEST,
44514
44568
  { path: "AGENTS.md", content: INIT_AGENTS_MD },
44515
44569
  { path: "CLAUDE.md", content: INIT_CLAUDE_MD },
@@ -46780,13 +46834,13 @@ var require_semver2 = __commonJS({
46780
46834
  });
46781
46835
 
46782
46836
  // dist/lib/project-pin.js
46783
- import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync7 } from "node:fs";
46784
- import { dirname as dirname2, join as join7 } from "node:path";
46837
+ import { existsSync as existsSync8, readFileSync as readFileSync11, writeFileSync as writeFileSync8 } from "node:fs";
46838
+ import { dirname as dirname2, join as join9 } from "node:path";
46785
46839
  function readJson(path3) {
46786
- if (!existsSync7(path3))
46840
+ if (!existsSync8(path3))
46787
46841
  return null;
46788
46842
  try {
46789
- const value = JSON.parse(readFileSync9(path3, "utf8"));
46843
+ const value = JSON.parse(readFileSync11(path3, "utf8"));
46790
46844
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
46791
46845
  } catch {
46792
46846
  return null;
@@ -46805,7 +46859,7 @@ function packageJsonSpec(pkg) {
46805
46859
  }
46806
46860
  function readProjectPins(dir) {
46807
46861
  const pins = [];
46808
- const pkg = readJson(join7(dir, "package.json"));
46862
+ const pkg = readJson(join9(dir, "package.json"));
46809
46863
  const settings = pkg?.somewhere;
46810
46864
  const fromSettings = settings && typeof settings === "object" && !Array.isArray(settings) ? settings[PIN_FILE_KEY] : void 0;
46811
46865
  if (typeof fromSettings === "string" && fromSettings.trim()) {
@@ -46814,7 +46868,7 @@ function readProjectPins(dir) {
46814
46868
  const fromPackage = packageJsonSpec(pkg);
46815
46869
  if (fromPackage)
46816
46870
  pins.push({ spec: fromPackage, source: "package.json" });
46817
- const recorded = readJson(join7(dir, ".somewhere.json"))?.[PIN_FILE_KEY];
46871
+ const recorded = readJson(join9(dir, ".somewhere.json"))?.[PIN_FILE_KEY];
46818
46872
  if (typeof recorded === "string" && recorded.trim())
46819
46873
  pins.push({ spec: recorded.trim(), source: ".somewhere.json" });
46820
46874
  return pins;
@@ -46827,8 +46881,8 @@ function pinSatisfied(pin, version2) {
46827
46881
  return import_semver.default.valid(version2) !== null && import_semver.default.satisfies(version2, pin.spec, { includePrerelease: true });
46828
46882
  }
46829
46883
  function installedPinnedCli(dir, pin, running) {
46830
- const root = join7(dir, "node_modules", ...CLI_PACKAGE_NAME.split("/"));
46831
- const pkg = readJson(join7(root, "package.json"));
46884
+ const root = join9(dir, "node_modules", ...CLI_PACKAGE_NAME.split("/"));
46885
+ const pkg = readJson(join9(root, "package.json"));
46832
46886
  const version2 = typeof pkg?.version === "string" ? pkg.version : null;
46833
46887
  if (!version2 || version2 === running || !pinSatisfied(pin, version2))
46834
46888
  return null;
@@ -46836,8 +46890,8 @@ function installedPinnedCli(dir, pin, running) {
46836
46890
  const rel = typeof binField === "string" ? binField : binField && typeof binField === "object" ? binField.somewhere : null;
46837
46891
  if (typeof rel !== "string")
46838
46892
  return null;
46839
- const bin = join7(root, rel);
46840
- return existsSync7(bin) ? { version: version2, bin } : null;
46893
+ const bin = join9(root, rel);
46894
+ return existsSync8(bin) ? { version: version2, bin } : null;
46841
46895
  }
46842
46896
  function pinNotice(pin, running, delegatedTo) {
46843
46897
  const head = `This project is pinned to somewhere CLI ${pin.spec} (${pin.source})`;
@@ -46885,9 +46939,9 @@ function pinnedNpx(version2) {
46885
46939
  const args = ["--yes", "--prefer-offline", "--ignore-scripts", `${CLI_PACKAGE_NAME}@${version2}`];
46886
46940
  if (process.platform !== "win32")
46887
46941
  return { command: "npx", args };
46888
- const besideNode = join7(dirname2(process.execPath), "node_modules", "npm", "bin", "npx-cli.js");
46889
- const besideNpm = process.env.npm_execpath?.endsWith("npm-cli.js") ? join7(dirname2(process.env.npm_execpath), "npx-cli.js") : besideNode;
46890
- const entry = [besideNpm, besideNode].find((path3) => existsSync7(path3));
46942
+ const besideNode = join9(dirname2(process.execPath), "node_modules", "npm", "bin", "npx-cli.js");
46943
+ const besideNpm = process.env.npm_execpath?.endsWith("npm-cli.js") ? join9(dirname2(process.env.npm_execpath), "npx-cli.js") : besideNode;
46944
+ const entry = [besideNpm, besideNode].find((path3) => existsSync8(path3));
46891
46945
  return entry ? { command: process.execPath, args: [entry, ...args] } : null;
46892
46946
  }
46893
46947
  function repairStarterReact(json, from) {
@@ -46909,8 +46963,8 @@ function writeProjectPins(dir, pins, version2) {
46909
46963
  const updated = [];
46910
46964
  let repairedStarter = false;
46911
46965
  for (const pin of pins) {
46912
- const path3 = join7(dir, pin.source);
46913
- const raw = readFileSync9(path3, "utf8");
46966
+ const path3 = join9(dir, pin.source);
46967
+ const raw = readFileSync11(path3, "utf8");
46914
46968
  const json = JSON.parse(raw);
46915
46969
  if (pin.versionOnly) {
46916
46970
  repairedStarter = repairStarterReact(json, pin.spec);
@@ -46925,7 +46979,7 @@ function writeProjectPins(dir, pins, version2) {
46925
46979
  json[PIN_FILE_KEY] = version2;
46926
46980
  }
46927
46981
  const indent = /^\{\s*\n(\s+)/.exec(raw)?.[1] ?? " ";
46928
- writeFileSync7(path3, JSON.stringify(json, null, indent) + "\n");
46982
+ writeFileSync8(path3, JSON.stringify(json, null, indent) + "\n");
46929
46983
  if (!updated.includes(pin.source))
46930
46984
  updated.push(pin.source);
46931
46985
  }
@@ -46934,16 +46988,16 @@ function writeProjectPins(dir, pins, version2) {
46934
46988
  function recordPinIfMissing(dir, version2) {
46935
46989
  if (!import_semver.default.valid(version2) || readProjectPins(dir).length)
46936
46990
  return false;
46937
- const path3 = join7(dir, ".somewhere.json");
46991
+ const path3 = join9(dir, ".somewhere.json");
46938
46992
  const config2 = readJson(path3);
46939
46993
  if (!config2)
46940
46994
  return false;
46941
46995
  config2[PIN_FILE_KEY] = version2;
46942
- writeFileSync7(path3, JSON.stringify(config2, null, 2) + "\n");
46996
+ writeFileSync8(path3, JSON.stringify(config2, null, 2) + "\n");
46943
46997
  return true;
46944
46998
  }
46945
46999
  function readBundledChangelog() {
46946
- return readFileSync9(join7(CLI_PACKAGE_ROOT, "CHANGELOG.md"), "utf8");
47000
+ return readFileSync11(join9(CLI_PACKAGE_ROOT, "CHANGELOG.md"), "utf8");
46947
47001
  }
46948
47002
  function changelogBetween(markdown, from, to2) {
46949
47003
  const entries = [];
@@ -48757,9 +48811,7 @@ function createFeatureTemplate(selection, options2) {
48757
48811
  const agent = selection.modules.includes("agent");
48758
48812
  const magicLink = selection.modules.includes("magic-link");
48759
48813
  const files = [
48760
- ...starterChecks({ privateData }),
48761
48814
  { path: ".gitignore", content: buildScaffoldGitignore() },
48762
- STARTER_CHECK_LIST,
48763
48815
  STARTER_AUTH_TEST,
48764
48816
  { path: "AGENTS.md", content: INIT_AGENTS_MD },
48765
48817
  { path: "CLAUDE.md", content: INIT_CLAUDE_MD },
@@ -51905,8 +51957,8 @@ __export(init_exports, {
51905
51957
  runInit: () => runInit,
51906
51958
  writeInitSkills: () => writeInitSkills
51907
51959
  });
51908
- import { basename, join as join8 } from "node:path";
51909
- import { existsSync as existsSync8 } from "node:fs";
51960
+ import { basename as basename2, join as join10 } from "node:path";
51961
+ import { existsSync as existsSync9 } from "node:fs";
51910
51962
  function registerInit(program2) {
51911
51963
  program2.command("init").description("Write a starter app with a generated AGENTS.md guide").option("--name <name>", "Project name (skip prompt); sign-in and invitation emails show it").option("--subdomain <slug>", "Subdomain for the new project; default: derived from --name").option("--link", "Link local source or scaffold an unpublished project").option("--project <ref>", "Existing project ID, name, slug, or subdomain (requires --link)").option("--bare", "Create and link only: no starter source or dependencies (AGENTS.md/CLAUDE.md are still added when absent)").option("--template <name>", "Starter to write: auth (default), minimal (auth route, no sign-in UI), or bare (link only)", "auth").option("--features <ids>", "Generate selected modules into an empty directory, comma-separated: auth, magic-link, private-data, agent (see --catalog)").option("--ui <mode>", "With --features: styled (default; src/ui + design tokens) or headless (hooks and plain markup)").option("--catalog", "Print the module catalog for --features and exit; no login, project or files").option("--dry-run", "With --features: validate the selection and print the file plan; nothing is created").option("--json", "Print the created or linked project as JSON").addHelpText("after", `
51912
51964
  ${FIRST_CLI_PERMISSION}
@@ -52014,13 +52066,13 @@ async function runInit(opts, command) {
52014
52066
  const storedConfig = loadConfig();
52015
52067
  if (!hasUsableCredential(storedConfig) && !opts.link && !opts.bare) {
52016
52068
  const expiredTemporaryAt = temporaryConfigExpired(storedConfig) ? storedConfig.temp_expires_at : void 0;
52017
- if (existing || existsSync8(join8(dir, ".somewhere.json")) || !shouldScaffold) {
52069
+ if (existing || existsSync9(join10(dir, ".somewhere.json")) || !shouldScaffold) {
52018
52070
  error(`Local starter generation requires an empty, unlinked directory. Existing files were kept. Run ${cliInvocation()} docs start for the anonymous deploy workflow.`);
52019
52071
  process.exit(1);
52020
52072
  }
52021
52073
  let localName = opts.name;
52022
52074
  if (!localName) {
52023
- const answer = await (0, import_prompts2.default)({ type: "text", name: "name", message: "App name", initial: basename(dir) || "my-app" });
52075
+ const answer = await (0, import_prompts2.default)({ type: "text", name: "name", message: "App name", initial: basename2(dir) || "my-app" });
52024
52076
  localName = answer.name;
52025
52077
  if (!localName)
52026
52078
  return;
@@ -52207,7 +52259,7 @@ function planFeatures(opts, command, dir) {
52207
52259
  throw new InitSelectionError(`--features cannot be combined with ${conflicts.join(", ")}: it writes a new app into an empty directory and never adds files to an existing project.`);
52208
52260
  }
52209
52261
  const selection = resolveInitSelection(opts.features, opts.ui ?? "styled");
52210
- const files = createFeatureTemplate(selection, { appName: opts.name ?? basename(dir) });
52262
+ const files = createFeatureTemplate(selection, { appName: opts.name ?? basename2(dir) });
52211
52263
  if (!canWriteInitScaffold(dir)) {
52212
52264
  throw new InitSelectionError("This directory already has files. --features writes only into an empty directory; nothing was created. Run it in a new directory.");
52213
52265
  }
@@ -52324,7 +52376,7 @@ async function linkExisting(client, dir, projectRef3, json = false, configureMcp
52324
52376
  function writeInitSkills(dir) {
52325
52377
  if (readLock(dir))
52326
52378
  return { kept: `${SKILLS_LOCK} already present` };
52327
- const taken = skillNames(BUNDLED_SKILLS_PACK).filter((name) => existsSync8(join8(dir, SKILLS_DIR, name)) || existsSync8(join8(dir, CLAUDE_SKILLS_DIR, name)));
52379
+ const taken = skillNames(BUNDLED_SKILLS_PACK).filter((name) => existsSync9(join10(dir, SKILLS_DIR, name)) || existsSync9(join10(dir, CLAUDE_SKILLS_DIR, name)));
52328
52380
  if (taken.length)
52329
52381
  return { kept: `Project skills ${taken.join(", ")} already exist` };
52330
52382
  return installSkills(dir, BUNDLED_SKILLS_PACK, { cli: CLI_VERSION2, source: "bundled" });
@@ -52407,12 +52459,12 @@ var init_link = __esm({
52407
52459
  });
52408
52460
 
52409
52461
  // dist/lib/claim-handoff.js
52410
- import { createDecipheriv, createHash as createHash3, randomBytes as randomBytes2 } from "node:crypto";
52462
+ import { createDecipheriv, createHash as createHash4, randomBytes as randomBytes2 } from "node:crypto";
52411
52463
  function readClaimConnection(client) {
52412
52464
  return client.call("GET", "/auth/temp-claim/status", void 0, void 0, { refresh: false });
52413
52465
  }
52414
52466
  function verifierHash(verifier) {
52415
- return createHash3("sha256").update(verifier, "utf8").digest("hex");
52467
+ return createHash4("sha256").update(verifier, "utf8").digest("hex");
52416
52468
  }
52417
52469
  function newVerifier() {
52418
52470
  return randomBytes2(32).toString("base64url");
@@ -52421,7 +52473,7 @@ function decodeCredentials(state, response) {
52421
52473
  if (!state.handoff_id || response.project_id !== state.project_id) {
52422
52474
  throw new Error("Claim continuation returned a different project. No credential was installed.");
52423
52475
  }
52424
- const key = createHash3("sha256").update(`claim-cli-handoff:v1:${state.verifier}`, "utf8").digest();
52476
+ const key = createHash4("sha256").update(`claim-cli-handoff:v1:${state.verifier}`, "utf8").digest();
52425
52477
  const combined = Buffer.from(response.ciphertext, "base64");
52426
52478
  if (combined.length <= 16)
52427
52479
  throw new Error("Claim continuation returned an invalid credential payload.");
@@ -74241,12 +74293,12 @@ var init_deploy_protected_files = __esm({
74241
74293
  });
74242
74294
 
74243
74295
  // dist/lib/role-method-hints.js
74244
- import { existsSync as existsSync9, readdirSync as readdirSync2, readFileSync as readFileSync10 } from "node:fs";
74296
+ import { existsSync as existsSync10, readdirSync as readdirSync2, readFileSync as readFileSync12 } from "node:fs";
74245
74297
  import { createRequire as createRequire3 } from "node:module";
74246
- import { join as join9, relative as relative2, resolve as resolve4 } from "node:path";
74298
+ import { join as join11, relative as relative2, resolve as resolve4 } from "node:path";
74247
74299
  function roleMethodHints(projectDir, { removedOnly = false } = {}) {
74248
- const api = join9(projectDir, "api");
74249
- if (!existsSync9(api))
74300
+ const api = join11(projectDir, "api");
74301
+ if (!existsSync10(api))
74250
74302
  return [];
74251
74303
  const skipped = ["Role-method hints skipped: TypeScript is unavailable in this project."];
74252
74304
  let ts2;
@@ -74273,14 +74325,14 @@ function roleMethodHints(projectDir, { removedOnly = false } = {}) {
74273
74325
  };
74274
74326
  var walk2 = walk3;
74275
74327
  __name(walk3, "walk");
74276
- const path3 = join9(dir, entry.name);
74328
+ const path3 = join11(dir, entry.name);
74277
74329
  if (entry.isDirectory()) {
74278
74330
  visitDir(path3);
74279
74331
  continue;
74280
74332
  }
74281
74333
  if (!entry.isFile() || !/\.[cm]?[jt]sx?$/.test(entry.name) || /\.d\.ts$/.test(entry.name))
74282
74334
  continue;
74283
- const file = ts2.createSourceFile(path3, readFileSync10(path3, "utf8"), ts2.ScriptTarget.Latest, true);
74335
+ const file = ts2.createSourceFile(path3, readFileSync12(path3, "utf8"), ts2.ScriptTarget.Latest, true);
74284
74336
  const exports = /* @__PURE__ */ new Set();
74285
74337
  let unknown2 = false;
74286
74338
  for (const statement of file.statements) {
@@ -74338,8 +74390,8 @@ var init_role_method_hints = __esm({
74338
74390
  });
74339
74391
 
74340
74392
  // dist/lib/notify/providers/update.js
74341
- import { existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync11, writeFileSync as writeFileSync8 } from "node:fs";
74342
- import { dirname as dirname3, join as join10 } from "node:path";
74393
+ import { existsSync as existsSync11, mkdirSync as mkdirSync8, readFileSync as readFileSync13, writeFileSync as writeFileSync9 } from "node:fs";
74394
+ import { dirname as dirname3, join as join12 } from "node:path";
74343
74395
  function isNewer(a, b2) {
74344
74396
  const parse3 = /* @__PURE__ */ __name((v2) => v2.split("-")[0].split(".").map((n) => Number(n)), "parse");
74345
74397
  const pa = parse3(a);
@@ -74354,7 +74406,7 @@ function isNewer(a, b2) {
74354
74406
  }
74355
74407
  function readCache(cachePath = CACHE_PATH) {
74356
74408
  try {
74357
- const c = JSON.parse(readFileSync11(cachePath, "utf8"));
74409
+ const c = JSON.parse(readFileSync13(cachePath, "utf8"));
74358
74410
  if (typeof c?.checkedAt !== "number")
74359
74411
  return null;
74360
74412
  return c;
@@ -74365,9 +74417,9 @@ function readCache(cachePath = CACHE_PATH) {
74365
74417
  function writeCache(latest, checkedAt, cachePath = CACHE_PATH) {
74366
74418
  try {
74367
74419
  const dir = dirname3(cachePath);
74368
- if (!existsSync10(dir))
74369
- mkdirSync7(dir, { recursive: true });
74370
- writeFileSync8(cachePath, JSON.stringify({ checkedAt, latest }) + "\n", { mode: 384 });
74420
+ if (!existsSync11(dir))
74421
+ mkdirSync8(dir, { recursive: true });
74422
+ writeFileSync9(cachePath, JSON.stringify({ checkedAt, latest }) + "\n", { mode: 384 });
74371
74423
  } catch {
74372
74424
  }
74373
74425
  }
@@ -74417,7 +74469,7 @@ async function getOutdatedWarning(currentVersion3, options2 = {}) {
74417
74469
  const warnedPath = options2.warnedPath ?? WARNED_PATH;
74418
74470
  const now2 = (options2.now ?? Date.now)();
74419
74471
  try {
74420
- const warned2 = JSON.parse(readFileSync11(warnedPath, "utf8"));
74472
+ const warned2 = JSON.parse(readFileSync13(warnedPath, "utf8"));
74421
74473
  if (typeof warned2.warnedAt === "number" && now2 - warned2.warnedAt < ONE_DAY && now2 >= warned2.warnedAt)
74422
74474
  return null;
74423
74475
  } catch {
@@ -74427,9 +74479,9 @@ async function getOutdatedWarning(currentVersion3, options2 = {}) {
74427
74479
  return null;
74428
74480
  try {
74429
74481
  const dir = dirname3(warnedPath);
74430
- if (!existsSync10(dir))
74431
- mkdirSync7(dir, { recursive: true });
74432
- writeFileSync8(warnedPath, JSON.stringify({ warnedAt: now2 }) + "\n", { mode: 384 });
74482
+ if (!existsSync11(dir))
74483
+ mkdirSync8(dir, { recursive: true });
74484
+ writeFileSync9(warnedPath, JSON.stringify({ warnedAt: now2 }) + "\n", { mode: 384 });
74433
74485
  } catch {
74434
74486
  }
74435
74487
  return outdatedMessage(currentVersion3, latest);
@@ -74458,7 +74510,7 @@ var init_update = __esm({
74458
74510
  init_output();
74459
74511
  init_config();
74460
74512
  PACKAGE = "@somewhere-cloud/cli";
74461
- CACHE_PATH = join10(cliConfigDir(), "update-check.json");
74513
+ CACHE_PATH = join12(cliConfigDir(), "update-check.json");
74462
74514
  REGISTRY = `https://registry.npmjs.org/${PACKAGE.replace("/", "%2F")}/latest`;
74463
74515
  ONE_DAY = 24 * 60 * 60 * 1e3;
74464
74516
  FETCH_TIMEOUT_MS = 1e3;
@@ -74472,7 +74524,7 @@ var init_update = __esm({
74472
74524
  __name(outdatedMessage, "outdatedMessage");
74473
74525
  __name(cachedLatestVersion, "cachedLatestVersion");
74474
74526
  __name(latestKnownVersion, "latestKnownVersion");
74475
- WARNED_PATH = join10(cliConfigDir(), "outdated-warning.json");
74527
+ WARNED_PATH = join12(cliConfigDir(), "outdated-warning.json");
74476
74528
  __name(getOutdatedWarning, "getOutdatedWarning");
74477
74529
  __name(fetchLatest, "fetchLatest");
74478
74530
  updateProvider = {
@@ -74489,8 +74541,8 @@ var init_update = __esm({
74489
74541
  });
74490
74542
 
74491
74543
  // dist/lib/notify/index.js
74492
- import { readFileSync as readFileSync12 } from "node:fs";
74493
- import { join as join11 } from "node:path";
74544
+ import { readFileSync as readFileSync14 } from "node:fs";
74545
+ import { join as join13 } from "node:path";
74494
74546
  function suppressExitNotices() {
74495
74547
  exitNoticesSuppressed = true;
74496
74548
  }
@@ -74504,7 +74556,7 @@ function subcommandSuppressesNotifications(argv) {
74504
74556
  }
74505
74557
  function currentVersion() {
74506
74558
  try {
74507
- const pkg = JSON.parse(readFileSync12(join11(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
74559
+ const pkg = JSON.parse(readFileSync14(join13(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
74508
74560
  return pkg.version;
74509
74561
  } catch {
74510
74562
  return "0.0.0";
@@ -74567,40 +74619,40 @@ __export(declared_data_exports, {
74567
74619
  localFilesContract: () => localFilesContract,
74568
74620
  prepareDeclaredData: () => prepareDeclaredData
74569
74621
  });
74570
- import { existsSync as existsSync11, readFileSync as readFileSync13, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "node:fs";
74622
+ import { existsSync as existsSync12, readFileSync as readFileSync15, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "node:fs";
74571
74623
  import { createRequire as createRequire4 } from "node:module";
74572
- import { join as join12, resolve as resolve5 } from "node:path";
74624
+ import { join as join14, resolve as resolve5 } from "node:path";
74573
74625
  function localFilesContract(projectDir) {
74574
- const path3 = join12(projectDir, "db", "schema.ts");
74626
+ const path3 = join14(projectDir, "db", "schema.ts");
74575
74627
  const generator = require4("./runtime/declared-data.cjs");
74576
- const digest = existsSync11(path3) && generator.filesContractFromFiles({ "db/schema.ts": readFileSync13(path3, "utf8") });
74628
+ const digest = existsSync12(path3) && generator.filesContractFromFiles({ "db/schema.ts": readFileSync15(path3, "utf8") });
74577
74629
  if (!digest)
74578
74630
  throw new Error("Declare file collections in db/schema.ts and deploy the app before testing files.");
74579
74631
  return { digest, singleRequestMaxBytes: generator.SINGLE_REQUEST_MAX_BYTES };
74580
74632
  }
74581
74633
  function generatedContents(path3) {
74582
- const previous = existsSync11(path3) ? readFileSync13(path3, "utf8") : void 0;
74634
+ const previous = existsSync12(path3) ? readFileSync15(path3, "utf8") : void 0;
74583
74635
  if (previous !== void 0 && !previous.startsWith(GENERATED_DATA_HEADER)) {
74584
74636
  throw new Error(`Cannot overwrite ${path3}; this path is reserved for a generated declaration.`);
74585
74637
  }
74586
74638
  return previous;
74587
74639
  }
74588
74640
  function prepareDeclaredData(projectDir) {
74589
- const schemaPath = join12(projectDir, "db", "schema.ts");
74590
- const declarationDir = existsSync11(join12(projectDir, "src")) ? join12(projectDir, "src") : projectDir;
74591
- const declarationPath = join12(declarationDir, DATA_DECLARATION_FILE);
74592
- const filesPath = join12(declarationDir, FILES_DECLARATION_FILE);
74593
- const previous = existsSync11(declarationPath) ? readFileSync13(declarationPath, "utf8") : void 0;
74594
- const previousFiles = existsSync11(filesPath) ? readFileSync13(filesPath, "utf8") : void 0;
74595
- if (!existsSync11(schemaPath)) {
74641
+ const schemaPath = join14(projectDir, "db", "schema.ts");
74642
+ const declarationDir = existsSync12(join14(projectDir, "src")) ? join14(projectDir, "src") : projectDir;
74643
+ const declarationPath = join14(declarationDir, DATA_DECLARATION_FILE);
74644
+ const filesPath = join14(declarationDir, FILES_DECLARATION_FILE);
74645
+ const previous = existsSync12(declarationPath) ? readFileSync15(declarationPath, "utf8") : void 0;
74646
+ const previousFiles = existsSync12(filesPath) ? readFileSync15(filesPath, "utf8") : void 0;
74647
+ if (!existsSync12(schemaPath)) {
74596
74648
  if (previousFiles?.startsWith(GENERATED_DATA_HEADER))
74597
- rmSync2(filesPath);
74649
+ rmSync3(filesPath);
74598
74650
  if (previous !== void 0 && !previous.startsWith(GENERATED_DATA_HEADER))
74599
74651
  return void 0;
74600
74652
  const generator2 = require4("./runtime/declared-data.cjs");
74601
74653
  const declaration2 = GENERATED_DATA_HEADER + NO_SCHEMA_NOTE + generator2.RUNTIME_CONTEXT_DECLARATION + generator2.ENDPOINT_DECLARATION + SW_ENDPOINT_GLOBAL;
74602
74654
  if (declaration2 !== previous)
74603
- writeFileSync9(declarationPath, declaration2);
74655
+ writeFileSync10(declarationPath, declaration2);
74604
74656
  return { client: void 0, declarationPath, filesDeclarationPath: void 0, schemaPath: void 0 };
74605
74657
  }
74606
74658
  generatedContents(declarationPath);
@@ -74612,7 +74664,7 @@ function prepareDeclaredData(projectDir) {
74612
74664
  let filesDeclaration;
74613
74665
  const generator = require4("./runtime/declared-data.cjs");
74614
74666
  try {
74615
- const files = { "db/schema.ts": readFileSync13(schemaPath, "utf8") };
74667
+ const files = { "db/schema.ts": readFileSync15(schemaPath, "utf8") };
74616
74668
  client = generator.generateFromFiles(files);
74617
74669
  localDeclaration = generator.localDeclarationFromFiles(files);
74618
74670
  tables = generator.declaredTablesFromFiles(files);
@@ -74620,19 +74672,19 @@ function prepareDeclaredData(projectDir) {
74620
74672
  filesDeclaration = generator.filesDeclarationFromFiles(files);
74621
74673
  } catch (error3) {
74622
74674
  if (previous !== void 0)
74623
- rmSync2(declarationPath);
74675
+ rmSync3(declarationPath);
74624
74676
  if (previousFiles !== void 0)
74625
- rmSync2(filesPath);
74677
+ rmSync3(filesPath);
74626
74678
  throw error3;
74627
74679
  }
74628
74680
  const declaration = GENERATED_DATA_HEADER + runtimeDeclaration + tables + generator.ENDPOINT_DECLARATION + SW_ENDPOINT_GLOBAL + generator.SCHEMA_DECLARATION + (localDeclaration ?? "");
74629
74681
  if (declaration !== previous)
74630
- writeFileSync9(declarationPath, declaration);
74682
+ writeFileSync10(declarationPath, declaration);
74631
74683
  if (filesDeclaration === void 0) {
74632
74684
  if (previousFiles !== void 0)
74633
- rmSync2(filesPath);
74685
+ rmSync3(filesPath);
74634
74686
  } else if (GENERATED_DATA_HEADER + filesDeclaration !== previousFiles) {
74635
- writeFileSync9(filesPath, GENERATED_DATA_HEADER + filesDeclaration);
74687
+ writeFileSync10(filesPath, GENERATED_DATA_HEADER + filesDeclaration);
74636
74688
  }
74637
74689
  return { client, declarationPath, filesDeclarationPath: filesDeclaration === void 0 ? void 0 : filesPath, schemaPath };
74638
74690
  }
@@ -74658,7 +74710,7 @@ function declaredDataPlugin(projectDir) {
74658
74710
  return prepared.client.runtime;
74659
74711
  },
74660
74712
  configureServer(server) {
74661
- server.watcher.add(join12(projectDir, "db"));
74713
+ server.watcher.add(join14(projectDir, "db"));
74662
74714
  const changed = /* @__PURE__ */ __name((path3) => {
74663
74715
  if (resolve5(path3) !== schemaPath)
74664
74716
  return;
@@ -74734,9 +74786,9 @@ __export(typecheck_exports, {
74734
74786
  typecheckTimeoutMs: () => typecheckTimeoutMs
74735
74787
  });
74736
74788
  import { spawn as spawn3, spawnSync } from "node:child_process";
74737
- import { existsSync as existsSync12, readFileSync as readFileSync14, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "node:fs";
74789
+ import { existsSync as existsSync13, readFileSync as readFileSync16, rmSync as rmSync4, writeFileSync as writeFileSync11 } from "node:fs";
74738
74790
  import { randomUUID as randomUUID4 } from "node:crypto";
74739
- import { dirname as dirname4, join as join13, relative as relative3 } from "node:path";
74791
+ import { dirname as dirname4, join as join15, relative as relative3 } from "node:path";
74740
74792
  function isGeneratedApiImport(e) {
74741
74793
  return e.code === "TS2307" && /^Cannot find module ['"]somewhere:api['"]/.test(e.message);
74742
74794
  }
@@ -74770,8 +74822,8 @@ function typecheckArgs(prefixArgs = []) {
74770
74822
  ];
74771
74823
  }
74772
74824
  function resolveTsc(projectDir) {
74773
- const projectBin = join13(projectDir, "node_modules", ".bin", process.platform === "win32" ? "tsc.cmd" : "tsc");
74774
- if (existsSync12(projectBin)) {
74825
+ const projectBin = join15(projectDir, "node_modules", ".bin", process.platform === "win32" ? "tsc.cmd" : "tsc");
74826
+ if (existsSync13(projectBin)) {
74775
74827
  return { command: projectBin, args: [], via: "project" };
74776
74828
  }
74777
74829
  return npxTscInvocation();
@@ -74779,7 +74831,7 @@ function resolveTsc(projectDir) {
74779
74831
  function declaredDependencies(projectDir) {
74780
74832
  let manifest;
74781
74833
  try {
74782
- manifest = JSON.parse(readFileSync14(join13(projectDir, "package.json"), "utf8"));
74834
+ manifest = JSON.parse(readFileSync16(join15(projectDir, "package.json"), "utf8"));
74783
74835
  } catch {
74784
74836
  return {};
74785
74837
  }
@@ -74805,7 +74857,7 @@ function declaredDependencies(projectDir) {
74805
74857
  }
74806
74858
  function dependencyInstalled(projectDir, name) {
74807
74859
  for (let dir = projectDir; ; dir = dirname4(dir)) {
74808
- if (existsSync12(join13(dir, "node_modules", name, "package.json")))
74860
+ if (existsSync13(join15(dir, "node_modules", name, "package.json")))
74809
74861
  return true;
74810
74862
  if (dirname4(dir) === dir)
74811
74863
  return false;
@@ -75042,9 +75094,9 @@ function typecheckCompilerSource(projectDir) {
75042
75094
  async function runTypecheckWith(projectDir, command, args, via, declaredData, deploy) {
75043
75095
  const fullArgs = typecheckArgs(args);
75044
75096
  let overlay;
75045
- const foreignDirectories = deploy ? ["supabase/functions/", "netlify/functions/", ".netlify/functions/", ".vercel/"].filter((path3) => existsSync12(join13(projectDir, path3))) : [];
75097
+ const foreignDirectories = deploy ? ["supabase/functions/", "netlify/functions/", ".netlify/functions/", ".vercel/"].filter((path3) => existsSync13(join15(projectDir, path3))) : [];
75046
75098
  const viteClient = "node_modules/vite/client.d.ts";
75047
- const viteTypes = deploy && existsSync12(join13(projectDir, viteClient)) ? [viteClient] : [];
75099
+ const viteTypes = deploy && existsSync13(join15(projectDir, viteClient)) ? [viteClient] : [];
75048
75100
  if (declaredData || foreignDirectories.length || viteTypes.length) {
75049
75101
  const config2 = await runBounded(command, [...args, "--project", SCAFFOLD_TSCONFIG_FILENAME, "--showConfig"], projectDir);
75050
75102
  if (config2.timedOut)
@@ -75063,8 +75115,8 @@ async function runTypecheckWith(projectDir, command, args, via, declaredData, de
75063
75115
  if (!Array.isArray(parsed.files) || !parsed.files.every((file) => typeof file === "string")) {
75064
75116
  throw new Error("TypeScript did not return the project file list.");
75065
75117
  }
75066
- overlay = join13(projectDir, `.__somewhere_typecheck_${randomUUID4()}.json`);
75067
- writeFileSync10(overlay, JSON.stringify({
75118
+ overlay = join15(projectDir, `.__somewhere_typecheck_${randomUUID4()}.json`);
75119
+ writeFileSync11(overlay, JSON.stringify({
75068
75120
  extends: "./" + SCAFFOLD_TSCONFIG_FILENAME,
75069
75121
  files: [.../* @__PURE__ */ new Set([
75070
75122
  ...parsed.files.filter((file) => !foreignDirectories.some((dir) => file.replaceAll("\\", "/").replace(/^\.\//, "").startsWith(dir))),
@@ -75079,13 +75131,13 @@ async function runTypecheckWith(projectDir, command, args, via, declaredData, de
75079
75131
  fullArgs[args.length + 1] = relative3(projectDir, overlay);
75080
75132
  } catch (error3) {
75081
75133
  if (overlay)
75082
- rmSync3(overlay, { force: true });
75134
+ rmSync4(overlay, { force: true });
75083
75135
  return { ok: false, errors: [], via, raw: error3 instanceof Error ? error3.message : String(error3) };
75084
75136
  }
75085
75137
  }
75086
75138
  const cleanup = /* @__PURE__ */ __name(() => {
75087
75139
  if (overlay)
75088
- rmSync3(overlay, { force: true });
75140
+ rmSync4(overlay, { force: true });
75089
75141
  }, "cleanup");
75090
75142
  const run = await runBounded(command, fullArgs, projectDir, { onAbort: cleanup });
75091
75143
  cleanup();
@@ -75321,10 +75373,10 @@ var init_esm3 = __esm({
75321
75373
  }
75322
75374
  async _formatEntry(dirent, path3) {
75323
75375
  let entry;
75324
- const basename12 = this._isDirent ? dirent.name : dirent;
75376
+ const basename13 = this._isDirent ? dirent.name : dirent;
75325
75377
  try {
75326
- const fullPath = presolve(pjoin(path3, basename12));
75327
- entry = { path: prelative(this._root, fullPath), fullPath, basename: basename12 };
75378
+ const fullPath = presolve(pjoin(path3, basename13));
75379
+ entry = { path: prelative(this._root, fullPath), fullPath, basename: basename13 };
75328
75380
  entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
75329
75381
  } catch (err) {
75330
75382
  this._onError(err);
@@ -75857,9 +75909,9 @@ var init_handler = __esm({
75857
75909
  _watchWithNodeFs(path3, listener) {
75858
75910
  const opts = this.fsw.options;
75859
75911
  const directory2 = sysPath.dirname(path3);
75860
- const basename12 = sysPath.basename(path3);
75912
+ const basename13 = sysPath.basename(path3);
75861
75913
  const parent = this.fsw._getWatchedDir(directory2);
75862
- parent.add(basename12);
75914
+ parent.add(basename13);
75863
75915
  const absolutePath = sysPath.resolve(path3);
75864
75916
  const options2 = {
75865
75917
  persistent: opts.persistent
@@ -75869,7 +75921,7 @@ var init_handler = __esm({
75869
75921
  let closer;
75870
75922
  if (opts.usePolling) {
75871
75923
  const enableBin = opts.interval !== opts.binaryInterval;
75872
- options2.interval = enableBin && isBinaryPath(basename12) ? opts.binaryInterval : opts.interval;
75924
+ options2.interval = enableBin && isBinaryPath(basename13) ? opts.binaryInterval : opts.interval;
75873
75925
  closer = setFsWatchFileListener(path3, absolutePath, options2, {
75874
75926
  listener,
75875
75927
  rawEmitter: this.fsw._emitRaw
@@ -75892,10 +75944,10 @@ var init_handler = __esm({
75892
75944
  return;
75893
75945
  }
75894
75946
  const dirname17 = sysPath.dirname(file);
75895
- const basename12 = sysPath.basename(file);
75947
+ const basename13 = sysPath.basename(file);
75896
75948
  const parent = this.fsw._getWatchedDir(dirname17);
75897
75949
  let prevStats = stats;
75898
- if (parent.has(basename12))
75950
+ if (parent.has(basename13))
75899
75951
  return;
75900
75952
  const listener = /* @__PURE__ */ __name(async (path3, newStats) => {
75901
75953
  if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
@@ -75920,9 +75972,9 @@ var init_handler = __esm({
75920
75972
  prevStats = newStats2;
75921
75973
  }
75922
75974
  } catch (error3) {
75923
- this.fsw._remove(dirname17, basename12);
75975
+ this.fsw._remove(dirname17, basename13);
75924
75976
  }
75925
- } else if (parent.has(basename12)) {
75977
+ } else if (parent.has(basename13)) {
75926
75978
  const at2 = newStats.atimeMs;
75927
75979
  const mt2 = newStats.mtimeMs;
75928
75980
  if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
@@ -76997,8 +77049,8 @@ __export(files_exports, {
76997
77049
  testFolderOf: () => testFolderOf
76998
77050
  });
76999
77051
  import { isUtf8 } from "node:buffer";
77000
- import { existsSync as existsSync13, readdirSync as readdirSync3, readFileSync as readFileSync15, statSync as statSync2 } from "node:fs";
77001
- import { extname as extname3, isAbsolute as isAbsolute2, join as join16, posix as posix2, relative as relative6 } from "node:path";
77052
+ import { existsSync as existsSync14, readdirSync as readdirSync3, readFileSync as readFileSync17, statSync as statSync2 } from "node:fs";
77053
+ import { extname as extname3, isAbsolute as isAbsolute2, join as join18, posix as posix2, relative as relative6 } from "node:path";
77002
77054
  function isTestSourcePath(relPath) {
77003
77055
  return TEST_SOURCE_NAME.test(relPath.slice(relPath.lastIndexOf("/") + 1));
77004
77056
  }
@@ -77073,6 +77125,8 @@ function collectFiles(baseDir, options2 = {}) {
77073
77125
  const deferred = [];
77074
77126
  const operational = /* @__PURE__ */ new Map();
77075
77127
  for (const relPath of candidates) {
77128
+ if (options2.localScaffolds?.has(relPath) && !optIn.has(relPath) && !ignore.reincludes(relPath))
77129
+ continue;
77076
77130
  const testReason = testExclusionReason(relPath, (path3, isDirectory) => optIn.has(path3) || ignore.reincludes(path3, isDirectory));
77077
77131
  if (testReason) {
77078
77132
  out.excluded.push({ path: relPath, reason: testReason });
@@ -77092,7 +77146,7 @@ function collectFiles(baseDir, options2 = {}) {
77092
77146
  }
77093
77147
  const corpusFiles = /* @__PURE__ */ __name((paths) => paths.filter((relPath) => isReferenceCorpusPath(relPath) && (sizes.get(relPath) ?? 0) <= MAX_FILE_SIZE).map((relPath) => {
77094
77148
  try {
77095
- return [relPath, readFileSync15(join16(baseDir, relPath), "utf-8")];
77149
+ return [relPath, readFileSync17(join18(baseDir, relPath), "utf-8")];
77096
77150
  } catch {
77097
77151
  return [relPath, ""];
77098
77152
  }
@@ -77168,7 +77222,7 @@ function collectFiles(baseDir, options2 = {}) {
77168
77222
  }
77169
77223
  function walk(baseDir, currentDir, out, ignore, candidates, sizes) {
77170
77224
  for (const entry of readdirSync3(currentDir, { withFileTypes: true })) {
77171
- const fullPath = join16(currentDir, entry.name);
77225
+ const fullPath = join18(currentDir, entry.name);
77172
77226
  const relPath = toDeployPath(relative6(baseDir, fullPath));
77173
77227
  if (!IGNORE.has(entry.name) && entry.name.startsWith(".") && entry.name !== ".well-known")
77174
77228
  out.dotfilesLeftOut = true;
@@ -77189,7 +77243,7 @@ function walk(baseDir, currentDir, out, ignore, candidates, sizes) {
77189
77243
  out.sensitive.push({ path: relPath, reason: SENSITIVE_FILE_REASON, referencedBy: [] });
77190
77244
  continue;
77191
77245
  }
77192
- if ((entry.name === DATA_DECLARATION_FILE || entry.name === FILES_DECLARATION_FILE) && readFileSync15(fullPath, "utf8").startsWith(GENERATED_DATA_HEADER))
77246
+ if ((entry.name === DATA_DECLARATION_FILE || entry.name === FILES_DECLARATION_FILE) && readFileSync17(fullPath, "utf8").startsWith(GENERATED_DATA_HEADER))
77193
77247
  continue;
77194
77248
  sizes.set(relPath, statSync2(fullPath).size);
77195
77249
  candidates.push(relPath);
@@ -77211,7 +77265,7 @@ function classifyKey(relPath) {
77211
77265
  }
77212
77266
  function classifyInto(out, baseDir, relPath, readBinary = true) {
77213
77267
  const { kind, key } = classifyKey(relPath);
77214
- const bytes = kind === "binary" && !readBinary ? Buffer.alloc(0) : readFileSync15(join16(baseDir, relPath));
77268
+ const bytes = kind === "binary" && !readBinary ? Buffer.alloc(0) : readFileSync17(join18(baseDir, relPath));
77215
77269
  const binary = kind === "binary" || !isUtf8(bytes);
77216
77270
  if (binary) {
77217
77271
  if (kind === "function")
@@ -77237,10 +77291,10 @@ function loadDeployIgnore(baseDir) {
77237
77291
  const rules = [];
77238
77292
  const unreachable = [];
77239
77293
  for (const fileName2 of [".gitignore", ".somewhereignore"]) {
77240
- const path3 = join16(baseDir, fileName2);
77241
- if (!existsSync13(path3))
77294
+ const path3 = join18(baseDir, fileName2);
77295
+ if (!existsSync14(path3))
77242
77296
  continue;
77243
- const lines = readFileSync15(path3, "utf8").split(/\r?\n/);
77297
+ const lines = readFileSync17(path3, "utf8").split(/\r?\n/);
77244
77298
  for (const raw of lines) {
77245
77299
  const rule = parseIgnoreRule(raw);
77246
77300
  if (!rule)
@@ -77346,7 +77400,7 @@ function includeHadNoEffect(baseDir, raw, published) {
77346
77400
  const path3 = toDeployPath(raw).replace(/^\.\//, "").replace(/\/+$/, "");
77347
77401
  if (!path3 || isAbsolute2(raw) || path3 === ".." || path3.startsWith("../"))
77348
77402
  return "it is outside this project folder; --include takes a path inside it";
77349
- if (!existsSync13(join16(baseDir, path3)))
77403
+ if (!existsSync14(join18(baseDir, path3)))
77350
77404
  return "there is no such file or folder in this project";
77351
77405
  if (published.some((p2) => p2 === path3 || p2.startsWith(`${path3}/`)))
77352
77406
  return null;
@@ -77369,7 +77423,7 @@ function previewBatchCheck(baseDir, paths) {
77369
77423
  }
77370
77424
  let bytes = 0;
77371
77425
  try {
77372
- bytes = statSync2(join16(baseDir, raw)).size;
77426
+ bytes = statSync2(join18(baseDir, raw)).size;
77373
77427
  } catch {
77374
77428
  }
77375
77429
  if (bytes > MAX_FILE_SIZE)
@@ -77511,12 +77565,12 @@ var init_files = __esm({
77511
77565
 
77512
77566
  // dist/lib/deploy-check.js
77513
77567
  import { randomUUID as randomUUID5 } from "node:crypto";
77514
- import { existsSync as existsSync14, mkdirSync as mkdirSync8, readFileSync as readFileSync16, realpathSync as realpathSync2, rmSync as rmSync4, writeFileSync as writeFileSync11 } from "node:fs";
77568
+ import { existsSync as existsSync15, mkdirSync as mkdirSync9, readFileSync as readFileSync18, realpathSync as realpathSync2, rmSync as rmSync5, writeFileSync as writeFileSync12 } from "node:fs";
77515
77569
  import { createRequire as createRequire5 } from "node:module";
77516
- import { isAbsolute as isAbsolute3, join as join17, relative as relative7, resolve as resolve8 } from "node:path";
77570
+ import { isAbsolute as isAbsolute3, join as join19, relative as relative7, resolve as resolve8 } from "node:path";
77517
77571
  function projectTypeScriptVersion(projectDir) {
77518
77572
  try {
77519
- const version2 = JSON.parse(readFileSync16(join17(projectDir, "node_modules", "typescript", "package.json"), "utf8")).version;
77573
+ const version2 = JSON.parse(readFileSync18(join19(projectDir, "node_modules", "typescript", "package.json"), "utf8")).version;
77520
77574
  return typeof version2 === "string" && version2 ? version2 : null;
77521
77575
  } catch {
77522
77576
  return null;
@@ -77528,7 +77582,7 @@ function announceDeployCheckFetch(projectDir) {
77528
77582
  `);
77529
77583
  }
77530
77584
  function deployCheckTsc(projectDir, platform2 = process.platform) {
77531
- const runner2 = join17(CLI_PACKAGE_ROOT, "bin", "deploy-check.cjs");
77585
+ const runner2 = join19(CLI_PACKAGE_ROOT, "bin", "deploy-check.cjs");
77532
77586
  if (projectTypeScriptVersion(projectDir) === DEPLOY_CHECK_TYPESCRIPT_VERSION) {
77533
77587
  return { command: process.execPath, args: [runner2] };
77534
77588
  }
@@ -77589,7 +77643,7 @@ function parseDeployOutput(output, projectDir, functions) {
77589
77643
  continue;
77590
77644
  const [, rawFile, lineText, columnText, code, message3] = match;
77591
77645
  const absolute = isAbsolute3(rawFile) ? rawFile : resolve8(root, rawFile);
77592
- const file = relative7(root, existsSync14(absolute) ? realpathSync2(absolute) : absolute).split("\\").join("/");
77646
+ const file = relative7(root, existsSync15(absolute) ? realpathSync2(absolute) : absolute).split("\\").join("/");
77593
77647
  if (!contract.isReferenceSource(file.split("/").pop() ?? file)) {
77594
77648
  problems.push(line);
77595
77649
  continue;
@@ -77632,24 +77686,24 @@ async function startDeployCheck(projectDir, onFetch) {
77632
77686
  if (checked.length === 0)
77633
77687
  return { ok: true, findings: [], typescript, checkedFiles: 0 };
77634
77688
  const { command, args } = deployCheckTsc(projectDir);
77635
- const tsconfigPath = join17(projectDir, "tsconfig.json");
77636
- const own2 = projectCompilerOptions(existsSync14(tsconfigPath) ? readFileSync16(tsconfigPath, "utf8") : void 0);
77689
+ const tsconfigPath = join19(projectDir, "tsconfig.json");
77690
+ const own2 = projectCompilerOptions(existsSync15(tsconfigPath) ? readFileSync18(tsconfigPath, "utf8") : void 0);
77637
77691
  const id = randomUUID5();
77638
- const config2 = join17(projectDir, `.__somewhere_deploy_check_${id}.json`);
77639
- const declarationsDir = join17(projectDir, `.__somewhere_deploy_check_${id}`);
77692
+ const config2 = join19(projectDir, `.__somewhere_deploy_check_${id}.json`);
77693
+ const declarationsDir = join19(projectDir, `.__somewhere_deploy_check_${id}`);
77640
77694
  const cleanup = /* @__PURE__ */ __name(() => {
77641
- rmSync4(config2, { force: true });
77642
- rmSync4(declarationsDir, { recursive: true, force: true });
77695
+ rmSync5(config2, { force: true });
77696
+ rmSync5(declarationsDir, { recursive: true, force: true });
77643
77697
  pendingCleanups.delete(cleanup);
77644
77698
  }, "cleanup");
77645
77699
  pendingCleanups.add(cleanup);
77646
77700
  try {
77647
- mkdirSync8(declarationsDir);
77701
+ mkdirSync9(declarationsDir);
77648
77702
  const declarations = Object.entries(vendor2.referenceCheckDeclarations(graph)).map(([name, text]) => {
77649
- writeFileSync11(join17(declarationsDir, name), text);
77650
- return relative7(projectDir, join17(declarationsDir, name));
77703
+ writeFileSync12(join19(declarationsDir, name), text);
77704
+ return relative7(projectDir, join19(declarationsDir, name));
77651
77705
  });
77652
- writeFileSync11(config2, JSON.stringify({
77706
+ writeFileSync12(config2, JSON.stringify({
77653
77707
  compilerOptions: contract.localCheckCompilerOptions(own2),
77654
77708
  files: [...checked, ...declarations],
77655
77709
  somewhereFunctionFiles: Object.keys(collected.functions)
@@ -77706,9 +77760,9 @@ var init_deploy_check = __esm({
77706
77760
  });
77707
77761
 
77708
77762
  // dist/lib/agent-hooks.js
77709
- import { existsSync as existsSync15, lstatSync as lstatSync3, mkdirSync as mkdirSync9, readFileSync as readFileSync17, realpathSync as realpathSync3, statSync as statSync3, writeFileSync as writeFileSync12 } from "node:fs";
77763
+ import { existsSync as existsSync16, lstatSync as lstatSync4, mkdirSync as mkdirSync10, readFileSync as readFileSync19, realpathSync as realpathSync3, statSync as statSync3, writeFileSync as writeFileSync13 } from "node:fs";
77710
77764
  import { homedir as homedir2 } from "node:os";
77711
- import { delimiter, dirname as dirname7, isAbsolute as isAbsolute4, join as join18, relative as relative8, resolve as resolve9, sep } from "node:path";
77765
+ import { delimiter, dirname as dirname7, isAbsolute as isAbsolute4, join as join20, relative as relative8, resolve as resolve9, sep } from "node:path";
77712
77766
  function isAgentHost(value) {
77713
77767
  return AGENT_HOSTS.includes(value);
77714
77768
  }
@@ -77717,7 +77771,7 @@ function pathCli(pathEnv = process.env.PATH ?? "", platform2 = process.platform)
77717
77771
  for (const dir of pathEnv.split(delimiter)) {
77718
77772
  for (const file of names) {
77719
77773
  try {
77720
- const candidate = join18(dir, file);
77774
+ const candidate = join20(dir, file);
77721
77775
  if (dir && statSync3(candidate).isFile())
77722
77776
  return realpathSync3(candidate);
77723
77777
  } catch {
@@ -77741,10 +77795,10 @@ function agentHookCommand(host, options2 = {}) {
77741
77795
  return `${cli} typecheck --deploy --hook ${host}`;
77742
77796
  }
77743
77797
  function readConfig(path3) {
77744
- if (!existsSync15(path3))
77798
+ if (!existsSync16(path3))
77745
77799
  return {};
77746
77800
  try {
77747
- const parsed = JSON.parse(readFileSync17(path3, "utf8"));
77801
+ const parsed = JSON.parse(readFileSync19(path3, "utf8"));
77748
77802
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : new Error("is not a JSON object");
77749
77803
  } catch (error3) {
77750
77804
  return error3 instanceof Error ? error3 : new Error(String(error3));
@@ -77753,9 +77807,9 @@ function readConfig(path3) {
77753
77807
  function escapesProject(projectDir, path3) {
77754
77808
  let current = projectDir;
77755
77809
  for (const part of relative8(projectDir, path3).split(sep)) {
77756
- current = join18(current, part);
77810
+ current = join20(current, part);
77757
77811
  try {
77758
- lstatSync3(current);
77812
+ lstatSync4(current);
77759
77813
  } catch {
77760
77814
  return null;
77761
77815
  }
@@ -77807,7 +77861,7 @@ function installAgentHooks(options2) {
77807
77861
  const command = options2.command ?? ((host) => agentHookCommand(host));
77808
77862
  return options2.hosts.map((host) => {
77809
77863
  const spec = HOSTS[host];
77810
- const path3 = join18(projectDir, spec.configPath);
77864
+ const path3 = join20(projectDir, spec.configPath);
77811
77865
  const refuse3 = /* @__PURE__ */ __name((why) => ({ host, path: path3, status: "refused", reason: `${spec.configPath} ${why}; left unchanged`, activation: spec.activation }), "refuse");
77812
77866
  const escape2 = escapesProject(projectDir, path3);
77813
77867
  if (escape2)
@@ -77837,8 +77891,8 @@ function installAgentHooks(options2) {
77837
77891
  status = "added";
77838
77892
  }
77839
77893
  if (status !== "unchanged") {
77840
- mkdirSync9(dirname7(path3), { recursive: true });
77841
- writeFileSync12(path3, JSON.stringify(config2, null, 2) + "\n");
77894
+ mkdirSync10(dirname7(path3), { recursive: true });
77895
+ writeFileSync13(path3, JSON.stringify(config2, null, 2) + "\n");
77842
77896
  }
77843
77897
  return { host, path: path3, status, activation: spec.activation };
77844
77898
  });
@@ -77879,12 +77933,12 @@ function hookProjectRoot(host, payload, env = process.env, cwd = process.cwd())
77879
77933
  host === "claude-code" ? env.CLAUDE_PROJECT_DIR : host === "cursor" ? env.CURSOR_PROJECT_DIR : void 0,
77880
77934
  typeof payload.cwd === "string" ? payload.cwd : void 0,
77881
77935
  cwd
77882
- ].find((dir) => typeof dir === "string" && isAbsolute4(dir) && existsSync15(dir));
77936
+ ].find((dir) => typeof dir === "string" && isAbsolute4(dir) && existsSync16(dir));
77883
77937
  if (!start)
77884
77938
  return null;
77885
77939
  for (let dir = resolve9(start); ; dir = dirname7(dir)) {
77886
- const config2 = join18(dir, HOSTS[host].configPath);
77887
- if (existsSync15(config2) && HOOK_MARKER.test(readFileSync17(config2, "utf8")))
77940
+ const config2 = join20(dir, HOSTS[host].configPath);
77941
+ if (existsSync16(config2) && HOOK_MARKER.test(readFileSync19(config2, "utf8")))
77888
77942
  return dir;
77889
77943
  if (dirname7(dir) === dir)
77890
77944
  return null;
@@ -77950,19 +78004,19 @@ var init_agent_hooks = __esm({
77950
78004
  AGENT_HOSTS = ["claude-code", "codex", "cursor"];
77951
78005
  HOSTS = {
77952
78006
  "claude-code": {
77953
- configPath: join18(".claude", "settings.json"),
78007
+ configPath: join20(".claude", "settings.json"),
77954
78008
  event: "PostToolUse",
77955
78009
  matcher: "Edit|MultiEdit|Write|NotebookEdit",
77956
78010
  activation: "Claude Code runs project hooks once the folder is trusted (the trust prompt when Claude Code opens it)."
77957
78011
  },
77958
78012
  codex: {
77959
- configPath: join18(".codex", "hooks.json"),
78013
+ configPath: join20(".codex", "hooks.json"),
77960
78014
  event: "PostToolUse",
77961
78015
  matcher: "Edit|Write",
77962
78016
  activation: "Codex runs it only after you review and trust it: run /hooks in Codex in this project."
77963
78017
  },
77964
78018
  cursor: {
77965
- configPath: join18(".cursor", "hooks.json"),
78019
+ configPath: join20(".cursor", "hooks.json"),
77966
78020
  event: "postToolUse",
77967
78021
  matcher: "Write",
77968
78022
  activation: "Cursor runs project hooks only in a trusted workspace."
@@ -77996,8 +78050,8 @@ var init_agent_hooks = __esm({
77996
78050
 
77997
78051
  // dist/lib/generic-lint.js
77998
78052
  import { spawnSync as spawnSync2 } from "node:child_process";
77999
- import { existsSync as existsSync16 } from "node:fs";
78000
- import { join as join19 } from "node:path";
78053
+ import { existsSync as existsSync17 } from "node:fs";
78054
+ import { join as join21 } from "node:path";
78001
78055
  function record2(value) {
78002
78056
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
78003
78057
  }
@@ -78009,8 +78063,8 @@ function checkerEnv() {
78009
78063
  return env;
78010
78064
  }
78011
78065
  function genericLint(directory2) {
78012
- const launcher = join19(directory2, "node_modules", "oxlint", "bin", "oxlint");
78013
- if (!existsSync16(launcher))
78066
+ const launcher = join21(directory2, "node_modules", "oxlint", "bin", "oxlint");
78067
+ if (!existsSync17(launcher))
78014
78068
  return {
78015
78069
  status: "unavailable",
78016
78070
  findings: [],
@@ -78080,10 +78134,14 @@ var init_generic_lint = __esm({
78080
78134
  // dist/lib/source-lint.js
78081
78135
  var source_lint_exports = {};
78082
78136
  __export(source_lint_exports, {
78083
- lintProject: () => lintProject
78137
+ dataFilterFindings: () => dataFilterFindings,
78138
+ lintProject: () => lintProject,
78139
+ readHeldBackTests: () => readHeldBackTests
78084
78140
  });
78085
78141
  import { createRequire as createRequire6 } from "node:module";
78086
78142
  import { performance as performance2 } from "node:perf_hooks";
78143
+ import { readdirSync as readdirSync4, readFileSync as readFileSync20, statSync as statSync4 } from "node:fs";
78144
+ import { join as join22 } from "node:path";
78087
78145
  async function lintProject(directory2, options2 = {}) {
78088
78146
  const started = performance2.now();
78089
78147
  const contract2 = platformContractVerdict(options2.apiBase ?? API_BASE_URL);
@@ -78094,6 +78152,7 @@ async function lintProject(directory2, options2 = {}) {
78094
78152
  const generic = options2.generic ? genericLint(directory2) : { status: "not-requested", findings: [] };
78095
78153
  return {
78096
78154
  ...report2,
78155
+ findings: [...report2.findings, ...dataFilterFindings({ ...collected.files, ...collected.functions, ...readHeldBackTests(directory2, collected.excluded.map((entry) => entry.path)) })],
78097
78156
  ok: collected.skipped.length === 0 && !["failed", "unavailable"].includes(generic.status),
78098
78157
  duration_ms: Math.round((performance2.now() - started) * 1e3) / 1e3,
78099
78158
  checked_files: Object.keys(collected.files).length + Object.keys(collected.functions).length,
@@ -78102,6 +78161,107 @@ async function lintProject(directory2, options2 = {}) {
78102
78161
  contract: contract2
78103
78162
  };
78104
78163
  }
78164
+ function balanced(text, start) {
78165
+ const open4 = text[start];
78166
+ const close = open4 === "(" ? ")" : open4 === "{" ? "}" : "]";
78167
+ let depth = 0;
78168
+ for (let i = start; i < text.length; i++) {
78169
+ const c = text[i];
78170
+ if (c === '"' || c === "'" || c === "`") {
78171
+ for (i++; i < text.length && text[i] !== c; i++)
78172
+ if (text[i] === "\\")
78173
+ i++;
78174
+ continue;
78175
+ }
78176
+ if (c === "/" && text[i + 1] === "/") {
78177
+ i = text.indexOf("\n", i);
78178
+ if (i < 0)
78179
+ return null;
78180
+ continue;
78181
+ }
78182
+ if (c === "/" && text[i + 1] === "*") {
78183
+ i = text.indexOf("*/", i + 2);
78184
+ if (i < 0)
78185
+ return null;
78186
+ i++;
78187
+ continue;
78188
+ }
78189
+ if (c === open4)
78190
+ depth++;
78191
+ else if (c === close && --depth === 0)
78192
+ return text.slice(start, i + 1);
78193
+ }
78194
+ return null;
78195
+ }
78196
+ function operatorIn(where) {
78197
+ const pattern = /([A-Za-z_$][\w$]*|"[^"]+"|'[^']+')\s*:\s*\{\s*([A-Za-z_$][\w$]*|"[^"]+"|'[^']+')\s*:/g;
78198
+ for (let m2; m2 = pattern.exec(where); ) {
78199
+ const operator = m2[2].replace(/^["']|["']$/g, "");
78200
+ if (OPERATORS.has(operator))
78201
+ return { column: m2[1].replace(/^["']|["']$/g, ""), operator };
78202
+ }
78203
+ return null;
78204
+ }
78205
+ function dataFilterFindings(files) {
78206
+ const findings = [];
78207
+ for (const [file, text] of Object.entries(files)) {
78208
+ if (!SOURCE2.test(file) || file.endsWith(".d.ts") || file.startsWith("node_modules/"))
78209
+ continue;
78210
+ if (!text.includes("somewhere:data") && !text.includes("@somewhere-cloud/cli/testing") && !text.includes("/__sw/data"))
78211
+ continue;
78212
+ for (const call of text.matchAll(CALL)) {
78213
+ const args = balanced(text, call.index + call[0].length - 1);
78214
+ if (!args)
78215
+ continue;
78216
+ const key = /\bwhere\s*(:\s*)?/.exec(args);
78217
+ if (!key)
78218
+ continue;
78219
+ let where = null;
78220
+ const after = args.slice(key.index + key[0].length);
78221
+ if (key[1] && after.startsWith("{"))
78222
+ where = balanced(after, 0);
78223
+ else {
78224
+ const name = key[1] ? /^[A-Za-z_$][\w$]*/.exec(after)?.[0] : "where";
78225
+ const declared = name ? new RegExp(`\\b(?:const|let|var)\\s+${name}\\b[^=]*=\\s*\\{`).exec(text) : null;
78226
+ if (declared)
78227
+ where = balanced(text, declared.index + declared[0].length - 1);
78228
+ }
78229
+ const hit = where && operatorIn(where);
78230
+ if (!hit)
78231
+ continue;
78232
+ findings.push({
78233
+ rule: "somewhere/data-filter",
78234
+ severity: "warning",
78235
+ file,
78236
+ line: text.slice(0, call.index).split("\n").length,
78237
+ message: `where.${hit.column} uses { ${hit.operator}: \u2026 }. The app data endpoint filters by equality only, so this call is refused live with 400 DATA_INPUT_INVALID.`,
78238
+ fix: `Filter with equal values (one list per value), or move the read into a server function: sw.db.from() accepts ${hit.operator}.`,
78239
+ docs: "https://somewhere.cloud/docs/declared-data.txt"
78240
+ });
78241
+ }
78242
+ }
78243
+ return findings;
78244
+ }
78245
+ function readHeldBackTests(root, paths) {
78246
+ const out = {};
78247
+ const visit = /* @__PURE__ */ __name((rel) => {
78248
+ if (Object.keys(out).length >= 500 || rel.split("/").includes("node_modules"))
78249
+ return;
78250
+ const full = join22(root, rel);
78251
+ const stat7 = statSync4(full, { throwIfNoEntry: false });
78252
+ if (stat7?.isDirectory()) {
78253
+ for (const name of readdirSync4(full))
78254
+ visit(rel.replace(/\/$/, "") + "/" + name);
78255
+ return;
78256
+ }
78257
+ if (stat7?.isFile() && SOURCE2.test(rel) && stat7.size <= 1024 * 1024)
78258
+ out[rel] = readFileSync20(full, "utf8");
78259
+ }, "visit");
78260
+ for (const path3 of paths)
78261
+ visit(path3);
78262
+ return out;
78263
+ }
78264
+ var OPERATORS, CALL, SOURCE2;
78105
78265
  var init_source_lint = __esm({
78106
78266
  "dist/lib/source-lint.js"() {
78107
78267
  "use strict";
@@ -78111,6 +78271,13 @@ var init_source_lint = __esm({
78111
78271
  init_client();
78112
78272
  init_platform_contract();
78113
78273
  __name(lintProject, "lintProject");
78274
+ OPERATORS = /* @__PURE__ */ new Set(["in", "ne", "gt", "gte", "lt", "lte", "like", "contains", "startsWith", "endsWith", "not"]);
78275
+ CALL = /\bdata\.[A-Za-z_$][\w$]*\.(?:list|aggregate)\s*\(|\.data\s*\(/g;
78276
+ SOURCE2 = /\.(?:[cm]?[jt]sx?)$/;
78277
+ __name(balanced, "balanced");
78278
+ __name(operatorIn, "operatorIn");
78279
+ __name(dataFilterFindings, "dataFilterFindings");
78280
+ __name(readHeldBackTests, "readHeldBackTests");
78114
78281
  }
78115
78282
  });
78116
78283
 
@@ -78152,8 +78319,8 @@ var init_lint = __esm({
78152
78319
  });
78153
78320
 
78154
78321
  // dist/commands/typecheck.js
78155
- import { existsSync as existsSync17 } from "node:fs";
78156
- import { join as join20, relative as relative9, resolve as resolve11 } from "node:path";
78322
+ import { existsSync as existsSync18 } from "node:fs";
78323
+ import { join as join23, relative as relative9, resolve as resolve11 } from "node:path";
78157
78324
  function registerTypecheck(program2) {
78158
78325
  program2.command("typecheck [dir]").description("Run the same project TypeScript check as deploy, then check the files that will be uploaded. Install the project dependencies first. Use --project or --deploy to run just one check.").option("--json", "Print typecheck and platform source findings as JSON").option("--deploy", "Only run the platform reference check on deployable files").addOption(new Option("--project", "Only check the project using its tsconfig.json and compiler").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) => {
78159
78326
  const dir = resolve11(process.cwd(), dirArg ?? ".");
@@ -78199,7 +78366,7 @@ function registerTypecheck(program2) {
78199
78366
  const result2 = await check2();
78200
78367
  process.exit(result2.ok ? 0 : 1);
78201
78368
  }
78202
- if (opts.project && !existsSync17(join20(dir, "tsconfig.json"))) {
78369
+ if (opts.project && !existsSync18(join23(dir, "tsconfig.json"))) {
78203
78370
  if (opts.json) {
78204
78371
  printJson({
78205
78372
  ok: false,
@@ -78220,7 +78387,7 @@ function registerTypecheck(program2) {
78220
78387
  }, "notInstalled");
78221
78388
  let announced = false;
78222
78389
  const check = /* @__PURE__ */ __name(async () => {
78223
- const checkProject = opts.project || existsSync17(join20(dir, "tsconfig.json"));
78390
+ const checkProject = opts.project || existsSync18(join23(dir, "tsconfig.json"));
78224
78391
  const projectVia = checkProject ? typecheckCompilerSource(dir) : void 0;
78225
78392
  const refused = notInstalled(projectVia ?? deployVia);
78226
78393
  if (!refused && !announced && projectVia === "npx") {
@@ -78243,6 +78410,9 @@ function registerTypecheck(program2) {
78243
78410
  ok: false,
78244
78411
  error: failure2 instanceof Error ? failure2.message : String(failure2)
78245
78412
  }));
78413
+ const refusedFilters = "error" in sourceLint ? 0 : sourceLint.findings.filter((finding) => finding.rule === "somewhere/data-filter").length;
78414
+ if (refusedFilters)
78415
+ result2.ok = false;
78246
78416
  if (opts.json) {
78247
78417
  const lintOutput = "error" in sourceLint ? sourceLint : { ...sourceLint, contract: publicContractVerdict(sourceLint.contract) };
78248
78418
  printJson({ ...result2, contract: publicContractVerdict(result2.contract), sourceLint: lintOutput });
@@ -78255,6 +78425,8 @@ function registerTypecheck(program2) {
78255
78425
  warn(`Source lint failed: ${sourceLint.error}`);
78256
78426
  else
78257
78427
  printLintFindings(sourceLint);
78428
+ if (refusedFilters)
78429
+ error(`${refusedFilters} data filter${refusedFilters === 1 ? "" : "s"} the platform refuses live (somewhere/data-filter above).`);
78258
78430
  }
78259
78431
  return result2;
78260
78432
  }, "check");
@@ -78622,69 +78794,6 @@ var init_deploy_checks = __esm({
78622
78794
  }
78623
78795
  });
78624
78796
 
78625
- // dist/lib/base-files.js
78626
- import { createHash as createHash4 } from "node:crypto";
78627
- import { existsSync as existsSync18, mkdirSync as mkdirSync10, readFileSync as readFileSync18, rmSync as rmSync5, writeFileSync as writeFileSync13 } from "node:fs";
78628
- import { join as join21 } from "node:path";
78629
- function sha2562(content) {
78630
- return createHash4("sha256").update(content).digest("hex");
78631
- }
78632
- function hashFiles(dir, paths) {
78633
- const out = {};
78634
- for (const path3 of paths)
78635
- out[path3] = sha2562(readFileSync18(join21(dir, path3)));
78636
- return out;
78637
- }
78638
- function saveBaseFiles(dir, base) {
78639
- mkdirSync10(join21(dir, ".somewhere"), { recursive: true });
78640
- writeFileSync13(join21(dir, BASE_FILES), JSON.stringify(base) + "\n");
78641
- }
78642
- function clearBaseFiles(dir) {
78643
- rmSync5(join21(dir, BASE_FILES), { force: true });
78644
- }
78645
- function loadBaseFiles(dir, projectId, releaseId) {
78646
- const path3 = join21(dir, BASE_FILES);
78647
- if (!existsSync18(path3) || releaseId === void 0)
78648
- return null;
78649
- try {
78650
- const parsed = JSON.parse(readFileSync18(path3, "utf8"));
78651
- if (parsed.project_id !== projectId || parsed.release_id !== releaseId || !parsed.files || typeof parsed.files !== "object")
78652
- return null;
78653
- return parsed;
78654
- } catch {
78655
- return null;
78656
- }
78657
- }
78658
- function saveLastActivation(dir, activation) {
78659
- mkdirSync10(join21(dir, ".somewhere"), { recursive: true });
78660
- writeFileSync13(join21(dir, LAST_ACTIVATION), JSON.stringify(activation) + "\n");
78661
- }
78662
- function loadLastActivation(dir) {
78663
- const path3 = join21(dir, LAST_ACTIVATION);
78664
- if (!existsSync18(path3))
78665
- return null;
78666
- try {
78667
- return JSON.parse(readFileSync18(path3, "utf8"));
78668
- } catch {
78669
- return null;
78670
- }
78671
- }
78672
- var BASE_FILES, LAST_ACTIVATION;
78673
- var init_base_files = __esm({
78674
- "dist/lib/base-files.js"() {
78675
- "use strict";
78676
- BASE_FILES = join21(".somewhere", "base-files.json");
78677
- __name(sha2562, "sha256");
78678
- __name(hashFiles, "hashFiles");
78679
- __name(saveBaseFiles, "saveBaseFiles");
78680
- __name(clearBaseFiles, "clearBaseFiles");
78681
- __name(loadBaseFiles, "loadBaseFiles");
78682
- LAST_ACTIVATION = join21(".somewhere", "last-activation.json");
78683
- __name(saveLastActivation, "saveLastActivation");
78684
- __name(loadLastActivation, "loadLastActivation");
78685
- }
78686
- });
78687
-
78688
78797
  // dist/lib/verify-progress.js
78689
78798
  async function withVerifyProgress(run, human) {
78690
78799
  const timer = human ? setTimeout(() => {
@@ -78779,8 +78888,8 @@ var init_live_refusal = __esm({
78779
78888
  });
78780
78889
 
78781
78890
  // dist/lib/build-errors.js
78782
- import { existsSync as existsSync19, readFileSync as readFileSync19 } from "node:fs";
78783
- import { isAbsolute as isAbsolute5, join as join22 } from "node:path";
78891
+ import { existsSync as existsSync19, readFileSync as readFileSync21 } from "node:fs";
78892
+ import { isAbsolute as isAbsolute5, join as join24 } from "node:path";
78784
78893
  function parseBundleErrorText(text) {
78785
78894
  const out = [];
78786
78895
  const re2 = /([^\s:]+(?:\/[^\s:]+)*):(\d+):(\d+): ERROR: ([^\n]+)/g;
@@ -78810,10 +78919,10 @@ function localCodeFrame(source, line, column) {
78810
78919
  }
78811
78920
  function frameFor(detail, baseDir, serverFrame) {
78812
78921
  if (detail.file && detail.line !== void 0) {
78813
- const abs = isAbsolute5(detail.file) ? detail.file : join22(baseDir, detail.file);
78922
+ const abs = isAbsolute5(detail.file) ? detail.file : join24(baseDir, detail.file);
78814
78923
  if (existsSync19(abs)) {
78815
78924
  try {
78816
- const frame = localCodeFrame(readFileSync19(abs, "utf-8"), detail.line, detail.column);
78925
+ const frame = localCodeFrame(readFileSync21(abs, "utf-8"), detail.line, detail.column);
78817
78926
  if (frame)
78818
78927
  return frame;
78819
78928
  } catch {
@@ -78904,7 +79013,7 @@ var init_build_errors = __esm({
78904
79013
 
78905
79014
  // dist/lib/deploy-blobs.js
78906
79015
  import { createReadStream } from "node:fs";
78907
- import { join as join23 } from "node:path";
79016
+ import { join as join25 } from "node:path";
78908
79017
  import { setTimeout as delay } from "node:timers/promises";
78909
79018
  async function uploadDeployBlobs(client, dir, projectId, paths, hashes) {
78910
79019
  const files = /* @__PURE__ */ new Map();
@@ -78943,7 +79052,7 @@ async function uploadDeployBlobs(client, dir, projectId, paths, hashes) {
78943
79052
  await new Promise((resolve27) => waiters.push(resolve27));
78944
79053
  active++;
78945
79054
  try {
78946
- const response = await client.callStream("PUT", `/deploy/blobs/${file.sha256}?${query}`, () => createReadStream(join23(dir, file.path)), {
79055
+ const response = await client.callStream("PUT", `/deploy/blobs/${file.sha256}?${query}`, () => createReadStream(join25(dir, file.path)), {
78947
79056
  headers: {
78948
79057
  "Content-Type": "application/octet-stream",
78949
79058
  "Content-Length": String(file.size),
@@ -79082,8 +79191,8 @@ var init_temp_auth = __esm({
79082
79191
  });
79083
79192
 
79084
79193
  // dist/lib/project-notices.js
79085
- import { existsSync as existsSync20, mkdirSync as mkdirSync11, readFileSync as readFileSync20, writeFileSync as writeFileSync14 } from "node:fs";
79086
- import { dirname as dirname8, join as join24 } from "node:path";
79194
+ import { existsSync as existsSync20, mkdirSync as mkdirSync11, readFileSync as readFileSync22, writeFileSync as writeFileSync14 } from "node:fs";
79195
+ import { dirname as dirname8, join as join26 } from "node:path";
79087
79196
  function localDay(now2) {
79088
79197
  const date4 = new Date(now2);
79089
79198
  return [date4.getFullYear(), date4.getMonth() + 1, date4.getDate()].map((part) => String(part).padStart(2, "0")).join("-");
@@ -79092,7 +79201,7 @@ function readState(path3) {
79092
79201
  if (!existsSync20(path3))
79093
79202
  return { shown: {} };
79094
79203
  try {
79095
- const parsed = JSON.parse(readFileSync20(path3, "utf8"));
79204
+ const parsed = JSON.parse(readFileSync22(path3, "utf8"));
79096
79205
  return parsed.shown && typeof parsed.shown === "object" ? { shown: parsed.shown } : { shown: {} };
79097
79206
  } catch {
79098
79207
  return { shown: {} };
@@ -79108,7 +79217,7 @@ function formatProjectNotice(notice) {
79108
79217
  async function showProjectNotices(client, projectRef3, options2 = {}) {
79109
79218
  const now2 = options2.now ?? Date.now();
79110
79219
  const day = localDay(now2);
79111
- const statePath = options2.statePath ?? join24(cliConfigDir(), "project-notices.json");
79220
+ const statePath = options2.statePath ?? join26(cliConfigDir(), "project-notices.json");
79112
79221
  const write = options2.write ?? ((line) => process.stderr.write(`${line}
79113
79222
  `));
79114
79223
  try {
@@ -79119,11 +79228,11 @@ async function showProjectNotices(client, projectRef3, options2 = {}) {
79119
79228
  return [];
79120
79229
  for (const notice of unseen)
79121
79230
  write(formatProjectNotice(notice));
79122
- const shown = Object.fromEntries(Object.entries(state.shown).filter(([, shownDay]) => shownDay === day));
79231
+ const shown2 = Object.fromEntries(Object.entries(state.shown).filter(([, shownDay]) => shownDay === day));
79123
79232
  for (const notice of unseen)
79124
- shown[`${response.project_id}:${notice.id}`] = day;
79233
+ shown2[`${response.project_id}:${notice.id}`] = day;
79125
79234
  mkdirSync11(dirname8(statePath), { recursive: true });
79126
- writeFileSync14(statePath, JSON.stringify({ shown }, null, 2) + "\n", { mode: 384 });
79235
+ writeFileSync14(statePath, JSON.stringify({ shown: shown2 }, null, 2) + "\n", { mode: 384 });
79127
79236
  return unseen;
79128
79237
  } catch {
79129
79238
  return [];
@@ -79144,8 +79253,8 @@ var init_project_notices = __esm({
79144
79253
  });
79145
79254
 
79146
79255
  // dist/lib/test-identities.js
79147
- import { chmodSync as chmodSync2, existsSync as existsSync21, mkdirSync as mkdirSync12, readFileSync as readFileSync21, renameSync as renameSync3, rmSync as rmSync6, writeFileSync as writeFileSync15 } from "node:fs";
79148
- import { join as join25 } from "node:path";
79256
+ import { chmodSync as chmodSync2, existsSync as existsSync21, mkdirSync as mkdirSync12, readFileSync as readFileSync23, renameSync as renameSync3, rmSync as rmSync6, writeFileSync as writeFileSync15 } from "node:fs";
79257
+ import { join as join27 } from "node:path";
79149
79258
  import { randomBytes as randomBytes3 } from "node:crypto";
79150
79259
  function parseActorSpecs(values) {
79151
79260
  if (!values.length)
@@ -79181,7 +79290,7 @@ function productionOrigin(prodFallback, requested) {
79181
79290
  return { origin, host };
79182
79291
  }
79183
79292
  function stateDir(root) {
79184
- return join25(root, TEST_STATE_DIR);
79293
+ return join27(root, TEST_STATE_DIR);
79185
79294
  }
79186
79295
  function ensurePrivateDir(dir) {
79187
79296
  mkdirSync12(dir, { recursive: true, mode: 448 });
@@ -79194,14 +79303,14 @@ function writePrivateFile(path3, content) {
79194
79303
  renameSync3(tmp, path3);
79195
79304
  }
79196
79305
  function ensureGitignored(root) {
79197
- const path3 = join25(root, ".gitignore");
79306
+ const path3 = join27(root, ".gitignore");
79198
79307
  if (!existsSync21(path3)) {
79199
79308
  writeFileSync15(path3, `# somewhere test-users: private signed-in test state
79200
79309
  ${TEST_STATE_GITIGNORE_LINE}
79201
79310
  `);
79202
79311
  return "created";
79203
79312
  }
79204
- const text = readFileSync21(path3, "utf8");
79313
+ const text = readFileSync23(path3, "utf8");
79205
79314
  const lines = text.split(/\r?\n/).map((line) => line.trim());
79206
79315
  if (lines.some((line) => [".somewhere/test/", ".somewhere/test", "/.somewhere/test/", "/.somewhere/test", ".somewhere/", ".somewhere", "/.somewhere/", "/.somewhere"].includes(line)))
79207
79316
  return "present";
@@ -79212,13 +79321,13 @@ ${TEST_STATE_GITIGNORE_LINE}
79212
79321
  return "added";
79213
79322
  }
79214
79323
  function readManifest(root) {
79215
- const path3 = join25(stateDir(root), MANIFEST_FILE);
79324
+ const path3 = join27(stateDir(root), MANIFEST_FILE);
79216
79325
  if (!existsSync21(path3))
79217
79326
  return null;
79218
79327
  const invalid = /* @__PURE__ */ __name((why) => Object.assign(new Error(`${path3} is not a valid test-users manifest (${why}); nothing was changed.`), { code: "MANIFEST_INVALID" }), "invalid");
79219
79328
  let value;
79220
79329
  try {
79221
- value = JSON.parse(readFileSync21(path3, "utf8"));
79330
+ value = JSON.parse(readFileSync23(path3, "utf8"));
79222
79331
  } catch {
79223
79332
  throw invalid("not JSON");
79224
79333
  }
@@ -79242,11 +79351,11 @@ function preparedActorState(root, target, name) {
79242
79351
  if (!actor || manifest?.project_id !== target.projectId || manifest.origin !== target.origin) {
79243
79352
  throw new Error("No prepared actor for this app. Run somewhere test-users prepare with the actor name.");
79244
79353
  }
79245
- const path3 = join25(stateDir(root), actor.state_file);
79354
+ const path3 = join27(stateDir(root), actor.state_file);
79246
79355
  const domain = new URL(target.origin).hostname;
79247
79356
  let state;
79248
79357
  try {
79249
- state = JSON.parse(readFileSync21(path3, "utf8"));
79358
+ state = JSON.parse(readFileSync23(path3, "utf8"));
79250
79359
  } catch {
79251
79360
  throw new Error("Could not read the saved test user session.");
79252
79361
  }
@@ -79256,7 +79365,7 @@ function preparedActorState(root, target, name) {
79256
79365
  return { path: path3, state: { cookies: state.cookies, origins: state.origins ?? [] }, access: token };
79257
79366
  }
79258
79367
  function writeManifest(root, manifest) {
79259
- writePrivateFile(join25(stateDir(root), MANIFEST_FILE), JSON.stringify(manifest, null, 2) + "\n");
79368
+ writePrivateFile(join27(stateDir(root), MANIFEST_FILE), JSON.stringify(manifest, null, 2) + "\n");
79260
79369
  }
79261
79370
  function tokenTimes(accessToken) {
79262
79371
  const part = accessToken.split(".")[1];
@@ -79317,8 +79426,8 @@ function expiryOf(issued, receivedAt) {
79317
79426
  return { accessExpiresAt: times.exp * 1e3, sessionExpiresAt: (times.iat + issued.session_ttl_seconds) * 1e3, source: "token" };
79318
79427
  return { accessExpiresAt: receivedAt + issued.expires_in * 1e3, sessionExpiresAt: receivedAt + issued.session_ttl_seconds * 1e3, source: "response" };
79319
79428
  }
79320
- async function createTestIdentities(client, projectId, role, count2, label) {
79321
- const body = await client.call("POST", "/auth/test-users", { project_id: projectId, count: count2, label, role, include_tokens: true });
79429
+ async function createTestIdentities(client, projectId, role, count2, label, options2 = {}) {
79430
+ const body = await client.call("POST", "/auth/test-users", { project_id: projectId, count: count2, label, role, include_tokens: true, ...options2 });
79322
79431
  const receivedAt = Date.now();
79323
79432
  const entries = Array.isArray(body?.identities) ? body.identities : [];
79324
79433
  const issued = [];
@@ -79371,7 +79480,7 @@ function removeStateFiles(root, actors) {
79371
79480
  for (const actor of actors) {
79372
79481
  if (!ACTOR.test(actor.name) || actor.state_file !== `${actor.name}.state.json`)
79373
79482
  continue;
79374
- const path3 = join25(stateDir(root), actor.state_file);
79483
+ const path3 = join27(stateDir(root), actor.state_file);
79375
79484
  if (existsSync21(path3)) {
79376
79485
  rmSync6(path3, { force: true });
79377
79486
  removed.push(actor.state_file);
@@ -79383,7 +79492,7 @@ var TEST_STATE_DIR, TEST_STATE_GITIGNORE_LINE, MANIFEST_FILE, CLEANUP_RECEIPT_FI
79383
79492
  var init_test_identities = __esm({
79384
79493
  "dist/lib/test-identities.js"() {
79385
79494
  "use strict";
79386
- TEST_STATE_DIR = join25(".somewhere", "test");
79495
+ TEST_STATE_DIR = join27(".somewhere", "test");
79387
79496
  TEST_STATE_GITIGNORE_LINE = ".somewhere/test/";
79388
79497
  MANIFEST_FILE = "manifest.json";
79389
79498
  CLEANUP_RECEIPT_FILE = "cleanup-receipt.json";
@@ -79415,8 +79524,8 @@ var init_test_identities = __esm({
79415
79524
  });
79416
79525
 
79417
79526
  // dist/lib/form-accounts.js
79418
- import { existsSync as existsSync22, readdirSync as readdirSync4, readFileSync as readFileSync22, rmSync as rmSync7 } from "node:fs";
79419
- import { join as join26 } from "node:path";
79527
+ import { existsSync as existsSync22, readdirSync as readdirSync5, readFileSync as readFileSync24, rmSync as rmSync7 } from "node:fs";
79528
+ import { join as join28 } from "node:path";
79420
79529
  import { randomBytes as randomBytes4 } from "node:crypto";
79421
79530
  function readDeletionAnswer(ids, answer) {
79422
79531
  const out = { done: [], kept: /* @__PURE__ */ new Map(), dropped: /* @__PURE__ */ new Map(), teamsDeleted: answer.groups_deleted ?? [] };
@@ -79492,12 +79601,12 @@ function generatedPassword() {
79492
79601
  function accountsDir(root, projectId) {
79493
79602
  if (!/^[A-Za-z0-9-]{1,64}$/.test(projectId))
79494
79603
  throw new Error("Unexpected project id in the test run record.");
79495
- return join26(root, ".somewhere", "tests", "accounts", projectId);
79604
+ return join28(root, ".somewhere", "tests", "accounts", projectId);
79496
79605
  }
79497
79606
  function recordAttempt(control, root, email2) {
79498
79607
  const dir = control.journalDir(root);
79499
79608
  ensurePrivateDir(dir);
79500
- const path3 = join26(dir, `${Date.now()}-${randomBytes4(4).toString("hex")}.json`);
79609
+ const path3 = join28(dir, `${Date.now()}-${randomBytes4(4).toString("hex")}.json`);
79501
79610
  const record3 = {
79502
79611
  project_id: control.projectId,
79503
79612
  email: email2,
@@ -79512,16 +79621,16 @@ function recordAttempt(control, root, email2) {
79512
79621
  return path3;
79513
79622
  }
79514
79623
  function recordId(path3, id) {
79515
- const record3 = JSON.parse(readFileSync22(path3, "utf8"));
79624
+ const record3 = JSON.parse(readFileSync24(path3, "utf8"));
79516
79625
  writePrivateFile(path3, JSON.stringify({ ...record3, id }) + "\n");
79517
79626
  }
79518
79627
  function forgetRecord(path3) {
79519
79628
  rmSync7(path3, { force: true });
79520
79629
  }
79521
- function deleteAccounts(client, projectId, ids) {
79630
+ function deleteAccounts(client, projectId, ids, { groups = true } = {}) {
79522
79631
  return inBatches(ids, async (batch) => {
79523
79632
  try {
79524
- return readDeletionAnswer(batch, await client.call("POST", "/auth/users/delete", { ids: batch, delete_groups_only_they_belong_to: true }, { project_id: projectId }));
79633
+ return readDeletionAnswer(batch, await client.call("POST", "/auth/users/delete", { ids: batch, delete_groups_only_they_belong_to: groups }, { project_id: projectId }));
79525
79634
  } catch (error3) {
79526
79635
  return failedDeletion(batch, describeCallError(error3));
79527
79636
  }
@@ -79544,11 +79653,11 @@ async function sweepAccounts(control, root) {
79544
79653
  if (!existsSync22(dir))
79545
79654
  return result;
79546
79655
  const pending = [];
79547
- for (const name of readdirSync4(dir).filter((entry) => /^\d+-[0-9a-f]{8}\.json$/.test(entry))) {
79548
- const path3 = join26(dir, name);
79656
+ for (const name of readdirSync5(dir).filter((entry) => /^\d+-[0-9a-f]{8}\.json$/.test(entry))) {
79657
+ const path3 = join28(dir, name);
79549
79658
  let record3;
79550
79659
  try {
79551
- record3 = JSON.parse(readFileSync22(path3, "utf8"));
79660
+ record3 = JSON.parse(readFileSync24(path3, "utf8"));
79552
79661
  } catch {
79553
79662
  result.failed.push(name);
79554
79663
  continue;
@@ -79735,21 +79844,21 @@ var init_test_target = __esm({
79735
79844
  });
79736
79845
 
79737
79846
  // dist/lib/preview-credential.js
79738
- import { existsSync as existsSync23, readFileSync as readFileSync23, unlinkSync as unlinkSync4 } from "node:fs";
79739
- import { join as join27 } from "node:path";
79847
+ import { existsSync as existsSync23, readFileSync as readFileSync25, unlinkSync as unlinkSync4 } from "node:fs";
79848
+ import { join as join29 } from "node:path";
79740
79849
  function loadPreviewCredential(projectId, previewSessionId) {
79741
- const path3 = join27(cliConfigDir(), SUBDIR, fileName(projectId, previewSessionId));
79850
+ const path3 = join29(cliConfigDir(), SUBDIR, fileName(projectId, previewSessionId));
79742
79851
  if (!existsSync23(path3))
79743
79852
  return null;
79744
79853
  try {
79745
- const stored = JSON.parse(readFileSync23(path3, "utf8"));
79854
+ const stored = JSON.parse(readFileSync25(path3, "utf8"));
79746
79855
  return stored.project_id === projectId && stored.preview_session_id === previewSessionId && typeof stored.credential === "string" ? stored.credential : null;
79747
79856
  } catch {
79748
79857
  return null;
79749
79858
  }
79750
79859
  }
79751
79860
  function forgetPreviewCredential(projectId, previewSessionId) {
79752
- const path3 = join27(cliConfigDir(), SUBDIR, fileName(projectId, previewSessionId));
79861
+ const path3 = join29(cliConfigDir(), SUBDIR, fileName(projectId, previewSessionId));
79753
79862
  if (existsSync23(path3))
79754
79863
  unlinkSync4(path3);
79755
79864
  }
@@ -79786,14 +79895,14 @@ var init_preview_credential = __esm({
79786
79895
  });
79787
79896
 
79788
79897
  // dist/lib/preview-record.js
79789
- import { existsSync as existsSync24, mkdirSync as mkdirSync13, readFileSync as readFileSync24, rmSync as rmSync8, writeFileSync as writeFileSync16 } from "node:fs";
79790
- import { join as join28 } from "node:path";
79898
+ import { existsSync as existsSync24, mkdirSync as mkdirSync13, readFileSync as readFileSync26, rmSync as rmSync8, writeFileSync as writeFileSync16 } from "node:fs";
79899
+ import { join as join30 } from "node:path";
79791
79900
  function loadPreviewRecord(dir, projectId) {
79792
- const path3 = join28(dir, PREVIEW_RECORD);
79901
+ const path3 = join30(dir, PREVIEW_RECORD);
79793
79902
  if (!existsSync24(path3))
79794
79903
  return null;
79795
79904
  try {
79796
- const parsed = JSON.parse(readFileSync24(path3, "utf8"));
79905
+ const parsed = JSON.parse(readFileSync26(path3, "utf8"));
79797
79906
  if (parsed.project_id !== projectId || typeof parsed.preview_session_id !== "string" || typeof parsed.preview_id !== "string" || !isRecord(parsed.files))
79798
79907
  return null;
79799
79908
  return parsed;
@@ -79802,11 +79911,11 @@ function loadPreviewRecord(dir, projectId) {
79802
79911
  }
79803
79912
  }
79804
79913
  function savePreviewRecord(dir, record3) {
79805
- mkdirSync13(join28(dir, ".somewhere"), { recursive: true });
79806
- writeFileSync16(join28(dir, PREVIEW_RECORD), JSON.stringify({ ...record3, saved_at: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
79914
+ mkdirSync13(join30(dir, ".somewhere"), { recursive: true });
79915
+ writeFileSync16(join30(dir, PREVIEW_RECORD), JSON.stringify({ ...record3, saved_at: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
79807
79916
  }
79808
79917
  function clearPreviewRecord(dir) {
79809
- rmSync8(join28(dir, PREVIEW_RECORD), { force: true });
79918
+ rmSync8(join30(dir, PREVIEW_RECORD), { force: true });
79810
79919
  }
79811
79920
  function openPreviewsFromStatus(status) {
79812
79921
  const data2 = unwrapPlatformData(status);
@@ -79860,7 +79969,7 @@ var init_preview_record = __esm({
79860
79969
  "dist/lib/preview-record.js"() {
79861
79970
  "use strict";
79862
79971
  init_platform_command();
79863
- PREVIEW_RECORD = join28(".somewhere", "preview.json");
79972
+ PREVIEW_RECORD = join30(".somewhere", "preview.json");
79864
79973
  __name(loadPreviewRecord, "loadPreviewRecord");
79865
79974
  __name(savePreviewRecord, "savePreviewRecord");
79866
79975
  __name(clearPreviewRecord, "clearPreviewRecord");
@@ -79974,7 +80083,7 @@ var init_test_diagnostics = __esm({
79974
80083
  });
79975
80084
 
79976
80085
  // dist/lib/test-control.js
79977
- import { join as join29 } from "node:path";
80086
+ import { join as join31 } from "node:path";
79978
80087
  function productionControl(client, target, options2 = {}) {
79979
80088
  const projectId = target.projectId;
79980
80089
  return {
@@ -79985,7 +80094,7 @@ function productionControl(client, target, options2 = {}) {
79985
80094
  const body = await client.call("GET", "/email/test-inbox", void 0, { project_id: projectId, address, limit: 20, ...options2.liveInboxOnly ? { environment: "production" } : {}, ...wait ? { wait_ms: wait.ms ?? 1e4, since: wait.since } : {} });
79986
80095
  return messagesAfter(body.messages, address, 0);
79987
80096
  },
79988
- deleteSignups: /* @__PURE__ */ __name((ids) => deleteAccounts(client, projectId, ids), "deleteSignups"),
80097
+ deleteSignups: /* @__PURE__ */ __name((ids, options3) => deleteAccounts(client, projectId, ids, options3), "deleteSignups"),
79989
80098
  journalDir: /* @__PURE__ */ __name((root) => accountsDir(root, projectId), "journalDir"),
79990
80099
  async prepareContext() {
79991
80100
  },
@@ -80070,10 +80179,10 @@ function previewControl(tool, target, _root) {
80070
80179
  }
80071
80180
  return messagesAfter(body.messages, address, 0);
80072
80181
  },
80073
- deleteSignups(ids) {
80182
+ deleteSignups(ids, { groups = true } = {}) {
80074
80183
  return inBatches(ids, async (batch) => {
80075
80184
  try {
80076
- return readDeletionAnswer(batch, await tool.call("POST", "/preview-tools/signups/delete", { ids: batch, delete_groups_only_they_belong_to: true }));
80185
+ return readDeletionAnswer(batch, await tool.call("POST", "/preview-tools/signups/delete", { ids: batch, delete_groups_only_they_belong_to: groups }));
80077
80186
  } catch (error3) {
80078
80187
  if (isDeadPreviewCredential(error3))
80079
80188
  return failedDeletion(batch, "the preview is closed, promoted or expired, and its accounts went with it", true);
@@ -80114,7 +80223,7 @@ function previewControl(tool, target, _root) {
80114
80223
  function previewAccountsDir(root, projectId, previewSessionId) {
80115
80224
  if (!/^[A-Za-z0-9-]{1,64}$/.test(projectId) || !/^draft_[A-Za-z0-9-]{1,80}$/.test(previewSessionId))
80116
80225
  throw new Error("Unexpected project or preview id in the test run record.");
80117
- return join29(root, ".somewhere", "tests", "preview-accounts", projectId, previewSessionId);
80226
+ return join31(root, ".somewhere", "tests", "preview-accounts", projectId, previewSessionId);
80118
80227
  }
80119
80228
  async function createPreviewManagedUser(tool) {
80120
80229
  let created;
@@ -80195,14 +80304,14 @@ var init_test_connectivity = __esm({
80195
80304
  // dist/lib/test-run.js
80196
80305
  import { createRequire as createRequire7 } from "node:module";
80197
80306
  import { pathToFileURL } from "node:url";
80198
- import { join as join30, dirname as dirname9 } from "node:path";
80307
+ import { join as join32, dirname as dirname9 } from "node:path";
80199
80308
  import { spawn as spawn4, spawnSync as spawnSync3 } from "node:child_process";
80200
- import { appendFileSync as appendFileSync2, existsSync as existsSync25, readFileSync as readFileSync25, readdirSync as readdirSync5, rmSync as rmSync9 } from "node:fs";
80309
+ import { appendFileSync as appendFileSync2, existsSync as existsSync25, readFileSync as readFileSync27, readdirSync as readdirSync6, rmSync as rmSync9 } from "node:fs";
80201
80310
  import { createHash as createHash6, randomUUID as randomUUID6 } from "node:crypto";
80202
80311
  function testImportEnv(root, env) {
80203
80312
  if (!readProjectPin(root)?.versionOnly)
80204
80313
  return env;
80205
- const hook2 = pathToFileURL(join30(CLI_PACKAGE_ROOT, "bin", "starter-test-imports.mjs"));
80314
+ const hook2 = pathToFileURL(join32(CLI_PACKAGE_ROOT, "bin", "starter-test-imports.mjs"));
80206
80315
  return { ...env, NODE_OPTIONS: [env.NODE_OPTIONS, "--import=" + hook2.href].filter(Boolean).join(" ") };
80207
80316
  }
80208
80317
  function testDependencyError(root) {
@@ -80212,7 +80321,7 @@ function testDependencyError(root) {
80212
80321
  return new Error(missingProjectDependencies(root).includes("@playwright/test") ? INSTALL_PROJECT_DEPENDENCIES : "Install project test dependencies: npm install -D @playwright/test @somewhere-cloud/cli");
80213
80322
  }
80214
80323
  async function prepareRunner(root) {
80215
- const require6 = createRequire7(join30(root, "package.json"));
80324
+ const require6 = createRequire7(join32(root, "package.json"));
80216
80325
  let cli;
80217
80326
  let pw;
80218
80327
  try {
@@ -80232,7 +80341,7 @@ async function prepareRunner(root) {
80232
80341
  throw error3;
80233
80342
  channel = void 0;
80234
80343
  process.stderr.write("Chrome is not installed; installing Playwright Chromium in the CLI cache.\n");
80235
- process.env.PLAYWRIGHT_BROWSERS_PATH ??= join30(cliConfigDir(), "cache", "playwright");
80344
+ process.env.PLAYWRIGHT_BROWSERS_PATH ??= join32(cliConfigDir(), "cache", "playwright");
80236
80345
  const install = spawnSync3(process.execPath, [cli, "install", "chromium"], { stdio: "inherit", env: process.env });
80237
80346
  if (install.status !== 0)
80238
80347
  throw new Error("Playwright Chromium installation failed");
@@ -80244,7 +80353,7 @@ async function prepareRunner(root) {
80244
80353
  mark("browser-probe:end");
80245
80354
  let playwright = "unknown";
80246
80355
  try {
80247
- playwright = JSON.parse(readFileSync25(join30(dirname9(cli), "package.json"), "utf8")).version ?? "unknown";
80356
+ playwright = JSON.parse(readFileSync27(join32(dirname9(cli), "package.json"), "utf8")).version ?? "unknown";
80248
80357
  } catch {
80249
80358
  }
80250
80359
  return { cli, channel, version: version2, browserLaunchMs, playwright };
@@ -80273,10 +80382,10 @@ async function runTests(input) {
80273
80382
  throw new Error(`The live release is ${target.releaseId}, not ${input.expectRelease} from this deploy (another deploy or rollback happened), so the tests were not run.`);
80274
80383
  }
80275
80384
  const { origin } = target;
80276
- const dir = join30(root, ".somewhere", "tests");
80385
+ const dir = join32(root, ".somewhere", "tests");
80277
80386
  ensurePrivateDir(dir);
80278
- const ignorePath = join30(root, ".gitignore");
80279
- const ignored = existsSync25(ignorePath) ? readFileSync25(ignorePath, "utf8") : "";
80387
+ const ignorePath = join32(root, ".gitignore");
80388
+ const ignored = existsSync25(ignorePath) ? readFileSync27(ignorePath, "utf8") : "";
80280
80389
  for (const line of [".somewhere/", "playwright-report/", "test-results/"])
80281
80390
  if (!ignored.split(/\r?\n/).includes(line))
80282
80391
  appendFileSync2(ignorePath, `
@@ -80287,10 +80396,10 @@ ${line}
80287
80396
  const files = options2.files ?? [];
80288
80397
  const failed = Boolean(options2.failed);
80289
80398
  const browser = `${prepared.channel ?? "chromium"} ${prepared.version}`;
80290
- const artifacts = join30(dir, createHash6("sha256").update(projectId + origin + (target.environment === "preview" ? `${target.previewSessionId}:${target.releaseId}` : "")).digest("hex").slice(0, 16));
80399
+ const artifacts = join32(dir, createHash6("sha256").update(projectId + origin + (target.environment === "preview" ? `${target.previewSessionId}:${target.releaseId}` : "")).digest("hex").slice(0, 16));
80291
80400
  if (failed) {
80292
- const lastRun = join30(artifacts, ".last-run.json");
80293
- if (!existsSync25(lastRun) || !JSON.parse(readFileSync25(lastRun, "utf8")).failedTests?.length) {
80401
+ const lastRun = join32(artifacts, ".last-run.json");
80402
+ if (!existsSync25(lastRun) || !JSON.parse(readFileSync27(lastRun, "utf8")).failedTests?.length) {
80294
80403
  throw new Error("No failed tests are recorded from the last run here; run somewhere test.");
80295
80404
  }
80296
80405
  }
@@ -80298,9 +80407,9 @@ ${line}
80298
80407
  process.env.SW_TEST_RUN = randomUUID6();
80299
80408
  for (const line of describeSweep(await span("sweep:before", {}, () => sweepAccounts(control, root)), "Before this run"))
80300
80409
  process.stderr.write(line + "\n");
80301
- const config2 = join30(dir, "runner.config.cjs");
80410
+ const config2 = join32(dir, "runner.config.cjs");
80302
80411
  const use = { baseURL: origin, channel: prepared.channel, trace: "off", video: "off", screenshot: "off", launchOptions: { args: ["--disable-features=AsyncDns"] } };
80303
- writePrivateFile(config2, `module.exports = ${JSON.stringify({ testDir: join30(root, "tests"), testMatch: "**/*.spec.ts", fullyParallel: true, forbidOnly: !subset, retries: 0, workers: Number(options2.workers), outputDir: artifacts, reporter: [[join30(CLI_PACKAGE_ROOT, "dist", "lib", "test-reporter.js")]], use, ...options2.phone ? { projects: [{ name: "desktop" }, { name: "phone", use: { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true } }] } : {} })};
80412
+ writePrivateFile(config2, `module.exports = ${JSON.stringify({ testDir: join32(root, "tests"), testMatch: "**/*.spec.ts", fullyParallel: true, forbidOnly: !subset, retries: 0, workers: Number(options2.workers), outputDir: artifacts, reporter: [[join32(CLI_PACKAGE_ROOT, "dist", "lib", "test-reporter.js")]], use, ...options2.phone ? { projects: [{ name: "desktop" }, { name: "phone", use: { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true } }] } : {} })};
80304
80413
  `);
80305
80414
  const args = [prepared.cli, "test", "--config", config2, ...files];
80306
80415
  if (options2.grep)
@@ -80308,7 +80417,7 @@ ${line}
80308
80417
  if (failed)
80309
80418
  args.push("--last-failed");
80310
80419
  const rerunFlags = `${options2.preview ? " --preview" : ""}${options2.phone ? " --phone" : ""}${options2.workers !== "5" ? ` --workers ${options2.workers}` : ""}`;
80311
- const resultsPath = join30(dir, "results.json");
80420
+ const resultsPath = join32(dir, "results.json");
80312
80421
  rmSync9(resultsPath, { force: true });
80313
80422
  mark("runner:spawn");
80314
80423
  const child = spawn4(process.execPath, args, { cwd: root, stdio: ["inherit", input.toStderr ? "pipe" : "inherit", "inherit"], env: { ...runnerEnv, SW_TEST_TARGET: JSON.stringify(target), SW_TEST_RELEASE: target.releaseId, PLAYWRIGHT_NO_COPY_PROMPT: "1", SW_TEST_ORIGIN: origin, SW_TEST_BROWSER_LAUNCH_MS: String(prepared.browserLaunchMs), SW_TEST_BROWSER: browser, SW_TEST_SUBSET: String(subset), SW_TEST_JSON: String(Boolean(options2.json)), SW_TEST_RESULTS: resultsPath, SW_TEST_RUN: process.env.SW_TEST_RUN, SW_TEST_RUN_PID: String(process.pid), SW_TEST_RERUN_FLAGS: rerunFlags } });
@@ -80327,8 +80436,8 @@ ${line}
80327
80436
  const cleanArtifacts = /* @__PURE__ */ __name((path3) => {
80328
80437
  if (!existsSync25(path3))
80329
80438
  return;
80330
- for (const entry of readdirSync5(path3, { withFileTypes: true })) {
80331
- const file = join30(path3, entry.name);
80439
+ for (const entry of readdirSync6(path3, { withFileTypes: true })) {
80440
+ const file = join32(path3, entry.name);
80332
80441
  if (entry.isDirectory())
80333
80442
  cleanArtifacts(file);
80334
80443
  else if (entry.name !== ".last-run.json" && !entry.name.endsWith(".png"))
@@ -80337,7 +80446,7 @@ ${line}
80337
80446
  }, "cleanArtifacts");
80338
80447
  cleanArtifacts(artifacts);
80339
80448
  const exitCode = status === null ? 1 : status || (after === null || after.failed.length || after.unknownId.length ? 1 : 0);
80340
- const results = existsSync25(resultsPath) ? JSON.parse(readFileSync25(resultsPath, "utf8")) : null;
80449
+ const results = existsSync25(resultsPath) ? JSON.parse(readFileSync27(resultsPath, "utf8")) : null;
80341
80450
  return { exitCode, results, target };
80342
80451
  }
80343
80452
  var init_test_run = __esm({
@@ -80650,8 +80759,8 @@ var init_browser_refusal = __esm({
80650
80759
  });
80651
80760
 
80652
80761
  // dist/lib/browser-actions.js
80653
- import { readFileSync as readFileSync26, statSync as statSync4 } from "node:fs";
80654
- import { basename as basename4, extname as extname4, resolve as resolve12 } from "node:path";
80762
+ import { readFileSync as readFileSync28, statSync as statSync5 } from "node:fs";
80763
+ import { basename as basename5, extname as extname4, resolve as resolve12 } from "node:path";
80655
80764
  function decodedBase64Bytes(base642) {
80656
80765
  if (!base642 || base642.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(base642))
80657
80766
  return null;
@@ -80692,7 +80801,7 @@ function resolveBrowserUpload(raw, baseDir = process.cwd()) {
80692
80801
  const absolute = resolve12(baseDir, raw);
80693
80802
  let stat7;
80694
80803
  try {
80695
- stat7 = statSync4(absolute);
80804
+ stat7 = statSync5(absolute);
80696
80805
  } catch {
80697
80806
  const inline = inlineBrowserUpload(raw);
80698
80807
  if (inline)
@@ -80704,9 +80813,9 @@ function resolveBrowserUpload(raw, baseDir = process.cwd()) {
80704
80813
  if (stat7.size > MAX_BROWSER_UPLOAD_BYTES) {
80705
80814
  throw new Error(`BROWSER_UPLOAD_TOO_LARGE: Upload file is ${stat7.size} bytes; the browser upload limit is ${MAX_BROWSER_UPLOAD_BYTES} bytes (10 MB).`);
80706
80815
  }
80707
- const name = basename4(absolute);
80816
+ const name = basename5(absolute);
80708
80817
  const contentType2 = MIME_TYPES[extname4(name).toLowerCase()] ?? "application/octet-stream";
80709
- const bytes = readFileSync26(absolute);
80818
+ const bytes = readFileSync28(absolute);
80710
80819
  if (bytes.length > MAX_BROWSER_UPLOAD_BYTES) {
80711
80820
  throw new Error(`BROWSER_UPLOAD_TOO_LARGE: Upload file is ${bytes.length} bytes; the browser upload limit is ${MAX_BROWSER_UPLOAD_BYTES} bytes (10 MB).`);
80712
80821
  }
@@ -81013,33 +81122,33 @@ var init_browser_actions = __esm({
81013
81122
  import { spawn as spawn5 } from "node:child_process";
81014
81123
  import { existsSync as existsSync26, mkdtempSync, rmSync as rmSync10 } from "node:fs";
81015
81124
  import { homedir as homedir3, tmpdir, userInfo } from "node:os";
81016
- import { join as join31 } from "node:path";
81017
- import { readdirSync as readdirSync6 } from "node:fs";
81125
+ import { join as join33 } from "node:path";
81126
+ import { readdirSync as readdirSync7 } from "node:fs";
81018
81127
  function candidatePaths() {
81019
81128
  const home = homedir3();
81020
81129
  const out = [];
81021
81130
  if (process.platform === "darwin") {
81022
- out.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser", join31(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"));
81131
+ out.push("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser", join33(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"));
81023
81132
  } else if (process.platform === "win32") {
81024
81133
  const programFiles = [
81025
81134
  process.env["PROGRAMFILES"] ?? "C:\\Program Files",
81026
81135
  process.env["PROGRAMFILES(X86)"] ?? "C:\\Program Files (x86)",
81027
- process.env["LOCALAPPDATA"] ?? join31(home, "AppData", "Local")
81136
+ process.env["LOCALAPPDATA"] ?? join33(home, "AppData", "Local")
81028
81137
  ];
81029
81138
  for (const base of programFiles) {
81030
- out.push(join31(base, "Google\\Chrome\\Application\\chrome.exe"), join31(base, "Microsoft\\Edge\\Application\\msedge.exe"), join31(base, "Chromium\\Application\\chrome.exe"));
81139
+ out.push(join33(base, "Google\\Chrome\\Application\\chrome.exe"), join33(base, "Microsoft\\Edge\\Application\\msedge.exe"), join33(base, "Chromium\\Application\\chrome.exe"));
81031
81140
  }
81032
81141
  } else {
81033
81142
  out.push("/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/microsoft-edge", "/snap/bin/chromium");
81034
81143
  }
81035
- out.push(...puppeteerCachePaths(join31(home, ".cache", "puppeteer")));
81144
+ out.push(...puppeteerCachePaths(join33(home, ".cache", "puppeteer")));
81036
81145
  return out;
81037
81146
  }
81038
81147
  function puppeteerCachePaths(cacheDir) {
81039
81148
  const out = [];
81040
81149
  let products;
81041
81150
  try {
81042
- products = readdirSync6(cacheDir);
81151
+ products = readdirSync7(cacheDir);
81043
81152
  } catch {
81044
81153
  return out;
81045
81154
  }
@@ -81048,13 +81157,13 @@ function puppeteerCachePaths(cacheDir) {
81048
81157
  continue;
81049
81158
  let builds;
81050
81159
  try {
81051
- builds = readdirSync6(join31(cacheDir, product)).sort().reverse();
81160
+ builds = readdirSync7(join33(cacheDir, product)).sort().reverse();
81052
81161
  } catch {
81053
81162
  continue;
81054
81163
  }
81055
81164
  for (const build of builds) {
81056
- const base = join31(cacheDir, product, build);
81057
- out.push(join31(base, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join31(base, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join31(base, "chrome-linux64", "chrome"), join31(base, "chrome-win64", "chrome.exe"), join31(base, "chrome-headless-shell-mac-arm64", "chrome-headless-shell"), join31(base, "chrome-headless-shell-mac-x64", "chrome-headless-shell"), join31(base, "chrome-headless-shell-linux64", "chrome-headless-shell"), join31(base, "chrome-headless-shell-win64", "chrome-headless-shell.exe"));
81165
+ const base = join33(cacheDir, product, build);
81166
+ out.push(join33(base, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join33(base, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"), join33(base, "chrome-linux64", "chrome"), join33(base, "chrome-win64", "chrome.exe"), join33(base, "chrome-headless-shell-mac-arm64", "chrome-headless-shell"), join33(base, "chrome-headless-shell-mac-x64", "chrome-headless-shell"), join33(base, "chrome-headless-shell-linux64", "chrome-headless-shell"), join33(base, "chrome-headless-shell-win64", "chrome-headless-shell.exe"));
81058
81167
  }
81059
81168
  }
81060
81169
  return out;
@@ -81101,7 +81210,7 @@ function readEndpoint(child, timeoutMs) {
81101
81210
  });
81102
81211
  }
81103
81212
  async function launchLocalBrowser(opts) {
81104
- const profileDir = mkdtempSync(join31(tmpdir(), "somewhere-browser-"));
81213
+ const profileDir = mkdtempSync(join33(tmpdir(), "somewhere-browser-"));
81105
81214
  const browserEnv = process.platform === "darwin" ? { ...process.env, HOME: userInfo().homedir } : process.env;
81106
81215
  const child = spawn5(opts.executablePath, [
81107
81216
  "--headless=new",
@@ -81291,7 +81400,7 @@ var init_chrome = __esm({
81291
81400
 
81292
81401
  // dist/lib/browser-run.js
81293
81402
  import { writeFileSync as writeFileSync17 } from "node:fs";
81294
- import { join as join32, resolve as resolve13 } from "node:path";
81403
+ import { join as join34, resolve as resolve13 } from "node:path";
81295
81404
  import { pathToFileURL as pathToFileURL2 } from "node:url";
81296
81405
  function isLoopbackUrl(raw) {
81297
81406
  let url3;
@@ -81308,7 +81417,7 @@ function isLoopbackUrl(raw) {
81308
81417
  return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
81309
81418
  }
81310
81419
  async function domOutlineScript() {
81311
- const path3 = join32(CLI_PACKAGE_ROOT, "runtime", "browser-probes.mjs");
81420
+ const path3 = join34(CLI_PACKAGE_ROOT, "runtime", "browser-probes.mjs");
81312
81421
  const probes = await import(pathToFileURL2(path3).href);
81313
81422
  return probes.DOM_OUTLINE_SCRIPT;
81314
81423
  }
@@ -81835,15 +81944,15 @@ var init_browser_run = __esm({
81835
81944
 
81836
81945
  // dist/lib/verify-report.js
81837
81946
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync2, renameSync as renameSync4, writeFileSync as writeFileSync18 } from "node:fs";
81838
- import { join as join33 } from "node:path";
81947
+ import { join as join35 } from "node:path";
81839
81948
  function saveVerifyReport(report2) {
81840
- const root = join33(cliConfigDir(), "verify-reports");
81949
+ const root = join35(cliConfigDir(), "verify-reports");
81841
81950
  mkdirSync14(root, { recursive: true, mode: 448 });
81842
81951
  chmodSync3(root, 448);
81843
- const directory2 = mkdtempSync2(join33(root, "run-"));
81952
+ const directory2 = mkdtempSync2(join35(root, "run-"));
81844
81953
  chmodSync3(directory2, 448);
81845
- const pending = join33(directory2, "report.pending");
81846
- const destination = join33(directory2, "report.json");
81954
+ const pending = join35(directory2, "report.pending");
81955
+ const destination = join35(directory2, "report.json");
81847
81956
  writeFileSync18(pending, JSON.stringify(report2, null, 2) + "\n", { mode: 384, flag: "wx" });
81848
81957
  renameSync4(pending, destination);
81849
81958
  return destination;
@@ -81862,7 +81971,7 @@ var init_verify_report = __esm({
81862
81971
 
81863
81972
  // dist/commands/browser.js
81864
81973
  import { dirname as dirname10, resolve as resolve14 } from "node:path";
81865
- import { readFileSync as readFileSync27 } from "node:fs";
81974
+ import { readFileSync as readFileSync29 } from "node:fs";
81866
81975
  function readBrowserIncomplete(r) {
81867
81976
  const raw = r.incomplete;
81868
81977
  if (!raw || typeof raw !== "object")
@@ -82231,7 +82340,7 @@ function registerBrowser(program2) {
82231
82340
  const collectActionsFile = /* @__PURE__ */ __name((file) => {
82232
82341
  try {
82233
82342
  const absolute = resolve14(file);
82234
- const raw = JSON.parse(readFileSync27(absolute, "utf8"));
82343
+ const raw = JSON.parse(readFileSync29(absolute, "utf8"));
82235
82344
  const normalized = normalizeBrowserActions(raw, dirname10(absolute));
82236
82345
  if (!normalized.ok)
82237
82346
  throw new InvalidArgumentError(normalized.error);
@@ -82385,16 +82494,16 @@ var init_browser = __esm({
82385
82494
 
82386
82495
  // dist/lib/verify-keep.js
82387
82496
  import { createHash as createHash7, randomBytes as randomBytes5 } from "node:crypto";
82388
- import { closeSync as closeSync4, existsSync as existsSync27, openSync as openSync4, readFileSync as readFileSync28, rmSync as rmSync11, statSync as statSync5, writeSync } from "node:fs";
82389
- import { join as join34 } from "node:path";
82497
+ import { closeSync as closeSync4, existsSync as existsSync27, openSync as openSync4, readFileSync as readFileSync30, rmSync as rmSync11, statSync as statSync6, writeSync } from "node:fs";
82498
+ import { join as join36 } from "node:path";
82390
82499
  function path(root) {
82391
- return join34(stateDir(root), KEEP_FILE);
82500
+ return join36(stateDir(root), KEEP_FILE);
82392
82501
  }
82393
82502
  function readFile(root) {
82394
82503
  if (!existsSync27(path(root)))
82395
82504
  return {};
82396
82505
  try {
82397
- const parsed = JSON.parse(readFileSync28(path(root), "utf-8"));
82506
+ const parsed = JSON.parse(readFileSync30(path(root), "utf-8"));
82398
82507
  return parsed && typeof parsed === "object" ? parsed : {};
82399
82508
  } catch {
82400
82509
  return {};
@@ -82449,7 +82558,7 @@ function reusableIdentities(entry, now2) {
82449
82558
  }
82450
82559
  function lockKeep(root, key, now2 = Date.now()) {
82451
82560
  ensurePrivateDir(stateDir(root));
82452
- const lock = join34(stateDir(root), `verify-actors-${key}.lock`);
82561
+ const lock = join36(stateDir(root), `verify-actors-${key}.lock`);
82453
82562
  for (let attempt = 0; attempt < 2; attempt++) {
82454
82563
  try {
82455
82564
  const fd = openSync4(lock, "wx", 384);
@@ -82466,7 +82575,7 @@ function lockKeep(root, key, now2 = Date.now()) {
82466
82575
  throw cause;
82467
82576
  let stale = true;
82468
82577
  try {
82469
- const held = JSON.parse(readFileSync28(lock, "utf-8"));
82578
+ const held = JSON.parse(readFileSync30(lock, "utf-8"));
82470
82579
  const alive2 = typeof held.pid === "number" && (() => {
82471
82580
  try {
82472
82581
  process.kill(held.pid, 0);
@@ -82475,7 +82584,7 @@ function lockKeep(root, key, now2 = Date.now()) {
82475
82584
  return false;
82476
82585
  }
82477
82586
  })();
82478
- stale = !alive2 || now2 - (held.at ?? statSync5(lock).mtimeMs) > KEEP_LOCK_STALE_MS;
82587
+ stale = !alive2 || now2 - (held.at ?? statSync6(lock).mtimeMs) > KEEP_LOCK_STALE_MS;
82479
82588
  } catch {
82480
82589
  stale = true;
82481
82590
  }
@@ -82588,7 +82697,7 @@ var init_verify_keep = __esm({
82588
82697
 
82589
82698
  // dist/commands/verify.js
82590
82699
  import { randomBytes as randomBytes6 } from "node:crypto";
82591
- import { existsSync as existsSync28, readFileSync as readFileSync29 } from "node:fs";
82700
+ import { existsSync as existsSync28, readFileSync as readFileSync31 } from "node:fs";
82592
82701
  import { dirname as dirname11, resolve as resolve15 } from "node:path";
82593
82702
  function navigationRetryNote(retries) {
82594
82703
  if (!retries.length)
@@ -82809,7 +82918,7 @@ function normalizeVerifyFlow(raw, baseDir = process.cwd()) {
82809
82918
  function readVerifyFlowFile(absolute, flag) {
82810
82919
  let source;
82811
82920
  try {
82812
- source = readFileSync29(absolute, "utf8");
82921
+ source = readFileSync31(absolute, "utf8");
82813
82922
  } catch (cause) {
82814
82923
  if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
82815
82924
  throw new Error(`Flow file not found. Pass ${flag} <path> with an existing JSON file. Run \`${cliInvocation()} verify --schema\` for the flow format.`);
@@ -84408,9 +84517,9 @@ var init_verify = __esm({
84408
84517
  });
84409
84518
 
84410
84519
  // dist/commands/deploy.js
84411
- import { existsSync as existsSync29, readFileSync as readFileSync30 } from "node:fs";
84412
- import { join as join35 } from "node:path";
84413
- import { basename as basename5, resolve as resolve16 } from "node:path";
84520
+ import { existsSync as existsSync29, readFileSync as readFileSync32 } from "node:fs";
84521
+ import { join as join37 } from "node:path";
84522
+ import { basename as basename6, resolve as resolve16 } from "node:path";
84414
84523
  function resolveTargetDir(dir, cwd = process.cwd()) {
84415
84524
  return dir ? resolve16(cwd, dir) : cwd;
84416
84525
  }
@@ -84471,7 +84580,7 @@ function randomSuffix() {
84471
84580
  return Math.random().toString(36).slice(2, 6).padEnd(4, "0");
84472
84581
  }
84473
84582
  function deriveNewProjectName(dirPath) {
84474
- const base = slugify2(basename5(dirPath)) || "project";
84583
+ const base = slugify2(basename6(dirPath)) || "project";
84475
84584
  return `${base}-${randomSuffix()}`;
84476
84585
  }
84477
84586
  function formatTempExpiry(expiresAt, ttlSeconds, nowMs = Date.now()) {
@@ -84575,6 +84684,10 @@ function readStaleReleaseDetails(data2) {
84575
84684
  active_version: num(d.active_version),
84576
84685
  base_version: num(d.base_version),
84577
84686
  active_release_source: str2(d.active_release_source),
84687
+ active_release_deployer: str2(d.active_release_deployer),
84688
+ active_release_note: str2(d.active_release_note),
84689
+ active_release_created_at: str2(d.active_release_created_at),
84690
+ changed_files_truncated: d.changed_files_truncated === true,
84578
84691
  active_release_activation: d.active_release_activation === "rollback" || d.active_release_activation === "publish" ? d.active_release_activation : void 0,
84579
84692
  active_release_activated_at: str2(d.active_release_activated_at)
84580
84693
  };
@@ -84585,15 +84698,19 @@ function formatStaleReleaseBaseExplanation(details = {}, historyUnavailable = fa
84585
84698
  const live = d.active_version !== void 0 ? `v${d.active_version}` : "a newer version";
84586
84699
  const folder = d.base_version !== void 0 ? `v${d.base_version}` : "an earlier version";
84587
84700
  const own2 = ownActivation && d.active_release_id && ownActivation.release_id === d.active_release_id ? ownActivation : null;
84588
- const when = d.active_release_activated_at ? ` at ${d.active_release_activated_at}` : "";
84589
- const how = own2 ? `Live is ${live}, put back by this folder's own \`somewhere ${own2.kind}\`${when}; this folder still holds ${folder}.` : d.active_release_activation === "rollback" ? `Live is ${live}, put back by a rollback or restore${when}; this folder came from ${folder}.` : d.active_release_source ? `Live is ${live}, deployed by ${SOURCE_WORDS[d.active_release_source] ?? `"${d.active_release_source}"`}${when}; this folder came from ${folder}.` : `Live is ${live}; this folder came from ${folder}.`;
84701
+ const at2 = d.active_release_activated_at ?? d.active_release_created_at;
84702
+ const elapsed = formatElapsed(at2);
84703
+ const when = elapsed ? `${elapsed} (${at2})` : "";
84704
+ const how = own2 ? `Live is ${live}, put back by this folder's own \`somewhere ${own2.kind}\`${when}; this folder still holds ${folder}.` : d.active_release_activation === "rollback" ? `Live is ${live}, put back by a rollback or restore${when}; this folder came from ${folder}.` : d.active_release_deployer ? `Live is ${live}, deployed by ${d.active_release_deployer}${when}; this folder came from ${folder}.` : d.active_release_source ? `Live is ${live}, deployed by ${SOURCE_WORDS[d.active_release_source] ?? `"${d.active_release_source}"`}${when}; this folder came from ${folder}.` : `Live is ${live}; this folder came from ${folder}.`;
84590
84705
  const list = changed.slice(0, 10).join(", ");
84591
84706
  const more = changed.length > 10 ? `, and ${changed.length - 10} more` : "";
84592
84707
  return [
84593
84708
  `${own2 || d.active_release_activation === "rollback" ? "Not deployed: live was moved to a different version than the one this folder came from." : "Not deployed: live is newer than this folder."} Nothing was changed. ${how}`,
84594
- changed.length > 0 ? `Files that differ between ${folder} and live: ${list}${more}.` : d.history_unavailable ? "The earlier version is no longer available to compare, so the differing files cannot be listed." : null,
84709
+ d.active_release_note ? formatUserSuppliedNote(d.active_release_note) : null,
84710
+ changed.length > 0 ? `Files that differ between ${folder} and live: ${list}${more}.${d.changed_files_truncated ? " The list is incomplete." : ""}` : d.history_unavailable ? "The earlier version is no longer available to compare, so the differing files cannot be listed." : null,
84595
84711
  "",
84596
- own2 ? `Next step: run \`${cliInvocation()} pull\` to bring this folder to live (local-only files are kept), or \`${cliInvocation()} restore ${d.base_version ?? "<version>"}\` to make ${folder} live again.` : `Next step: run \`${cliInvocation()} pull\`. It brings the published files up to live, keeps local-only files and your local edits, and stops on a file changed both here and live. Then deploy again.`
84712
+ own2 ? `Next step: run \`${cliInvocation()} pull\` to bring this folder to live (local-only files are kept), or \`${cliInvocation()} restore ${d.base_version ?? "<version>"}\` to make ${folder} live again.` : `Next step: run \`${cliInvocation()} pull\`. It brings the published files up to live, keeps your edits to other files, and stops if you both changed the same file so you can reconcile it. Then deploy again.`,
84713
+ `Use \`${cliInvocation()} deploy --force\` only to replace live source in the selected scope with this folder, which can overwrite or remove someone else\u2019s changes.`
84597
84714
  ].filter((line) => line !== null).join("\n");
84598
84715
  }
84599
84716
  function formatAmbiguousRetryStaleExplanation(transportFailure) {
@@ -84784,7 +84901,11 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84784
84901
  process.stderr.write("deploy --test: the documented form is `somewhere deploy && somewhere test`; --test still runs somewhere test once after a successful deploy.\n");
84785
84902
  const verifyFlow = opts.verify && !opts.dryRun ? loadVerifyFlow(typeof opts.verify === "string" ? opts.verify : void 0, targetDir) : void 0;
84786
84903
  const collectionStartedAt = performance.now();
84904
+ const localLink = loadProjectConfigEntry(targetDir);
84905
+ const localBase = localLink && resolve16(localLink.dir) === resolve16(targetDir) ? loadBaseFiles(targetDir, localLink.config.project_id, readSourceBase(localLink.config, localLink.config.project_id)?.releaseId) : null;
84906
+ const localScaffolds = unchangedPullScaffolds(targetDir, localBase);
84787
84907
  const collected = collectFiles(targetDir, {
84908
+ localScaffolds: new Set(Object.keys(localScaffolds)),
84788
84909
  include: opts.include ?? [],
84789
84910
  deployBlobs: process.env.SOMEWHERE_DEPLOY_BLOBS === "1" && !opts.dryRun && opts.scope !== "functions"
84790
84911
  });
@@ -84856,7 +84977,7 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84856
84977
  const sourceUnchanged = !opts.project && !opts.temporary && unchangedSinceLastPublish(foundProjectEntry, targetDir, publishedHashes);
84857
84978
  if (sourceUnchanged)
84858
84979
  process.stderr.write("No file changed since this folder's last deploy; types were not checked again.\n");
84859
- const hasTsconfig = !sourceUnchanged && existsSync29(join35(targetDir, "tsconfig.json"));
84980
+ const hasTsconfig = !sourceUnchanged && existsSync29(join37(targetDir, "tsconfig.json"));
84860
84981
  const missingDependencies = hasTsconfig && missingProjectDependencies(targetDir).length > 0;
84861
84982
  const checkingTypes = hasTsconfig && !missingDependencies;
84862
84983
  if (checkingTypes && typecheckCompilerSource(targetDir) === "npx") {
@@ -85195,7 +85316,7 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
85195
85316
  const baseDir = deployStateEntry?.dir ?? targetDir;
85196
85317
  saveSourceBase(baseDir, deployedProject, releaseId);
85197
85318
  if (resolve16(baseDir) === resolve16(targetDir))
85198
- saveBaseFiles(baseDir, { project_id: deployedProject, release_id: releaseId, files: publishedHashes });
85319
+ saveBaseFiles(baseDir, { project_id: deployedProject, release_id: releaseId, files: publishedHashes, scaffolds: localScaffolds });
85199
85320
  else
85200
85321
  clearBaseFiles(baseDir);
85201
85322
  }, "rememberDeployedBase");
@@ -85419,6 +85540,8 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
85419
85540
  if (formatted.projectRef)
85420
85541
  info(`Project: ${teal(formatted.projectRef)}`);
85421
85542
  }
85543
+ if (result.collaborators_behind_note)
85544
+ info(result.collaborators_behind_note);
85422
85545
  if (Array.isArray(result.build_log) && result.build_log.length > 0) {
85423
85546
  console.log(`
85424
85547
  ${dim("Build")}`);
@@ -85757,7 +85880,7 @@ function withLocalEnvHint(warning, dir) {
85757
85880
  if (!key)
85758
85881
  return warning;
85759
85882
  try {
85760
- const source = readFileSync30(join35(dir, ".env"), "utf8");
85883
+ const source = readFileSync32(join37(dir, ".env"), "utf8");
85761
85884
  if (new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`, "m").test(source)) {
85762
85885
  return `${warning} Copy ${key} from your local .env file.`;
85763
85886
  }
@@ -86063,6 +86186,7 @@ var init_deploy = __esm({
86063
86186
  init_typecheck_version();
86064
86187
  init_typecheck2();
86065
86188
  init_deploy_checks();
86189
+ init_scaffold();
86066
86190
  init_base_files();
86067
86191
  init_verify_progress();
86068
86192
  init_esm();
@@ -86224,8 +86348,8 @@ function registerDeploys(program2) {
86224
86348
  const note = entry.status === "success" && entry.message ? formatUserSuppliedNote(entry.message) : "";
86225
86349
  const restore = entry.restore?.body;
86226
86350
  const command = restore ? `${cliInvocation()} restore ${restore.version} --project ${shellQuote(restore.project_id)} --yes` : "";
86227
- const platform2 = entry.deployed_by?.kind === "platform" ? entry.deployed_by.name : void 0;
86228
- console.log([version2, entry.promoted_at ?? entry.at ?? "\u2014", state, platform2, note, command].filter(Boolean).join(" "));
86351
+ const deployer = entry.deployed_by?.email ?? (entry.deployed_by?.kind === "platform" ? entry.deployed_by.name : void 0);
86352
+ console.log([version2, entry.promoted_at ?? entry.at ?? "\u2014", state, deployer, note, command].filter(Boolean).join(" "));
86229
86353
  }
86230
86354
  } catch (err) {
86231
86355
  historyError(err, options2.json);
@@ -86271,8 +86395,8 @@ var init_deploys = __esm({
86271
86395
  });
86272
86396
 
86273
86397
  // dist/commands/pull.js
86274
- import { existsSync as existsSync30, lstatSync as lstatSync4, mkdirSync as mkdirSync15, readFileSync as readFileSync31, readdirSync as readdirSync7, rmSync as rmSync12, writeFileSync as writeFileSync19 } from "node:fs";
86275
- import { basename as basename6, dirname as dirname12, join as join36, relative as relative10, resolve as resolve17 } from "node:path";
86398
+ import { existsSync as existsSync30, lstatSync as lstatSync5, mkdirSync as mkdirSync15, readFileSync as readFileSync33, readdirSync as readdirSync8, rmSync as rmSync12, writeFileSync as writeFileSync19 } from "node:fs";
86399
+ import { basename as basename7, dirname as dirname12, join as join38, relative as relative10, resolve as resolve17 } from "node:path";
86276
86400
  function registerPull(program2) {
86277
86401
  program2.command("pull [project]").description(`Download a project's deployed source files to the current directory. Scaffolds a tsconfig.json + package.json (only if absent) so \`${cliInvocation()} typecheck\` can catch undefined symbols locally before you deploy. In a linked folder, plain pull is the safe update when live is newer: files you have not edited move to the live version, your local edits and local-only files (AGENTS.md, notes, tests) are kept, and it stops without writing anything if a file changed both here and live.`).option("--env <env>", "Environment to pull from (dev or prod)", "prod").option("--out <dir>", "Output directory", ".").option("--force", "Also replace files you edited here with live, and delete published files you edited that live no longer has. Never deletes a file a deploy would not upload (AGENTS.md, CLAUDE.md, README.md, tests, dotfiles, .somewhereignore matches)").option("--json", "Print the raw source response as JSON").action(async (projectArg, opts) => {
86278
86402
  const token = getToken();
@@ -86309,7 +86433,7 @@ function registerPull(program2) {
86309
86433
  }
86310
86434
  spinner?.stop();
86311
86435
  const deployStateEntry = loadProjectConfigEntry(outDir);
86312
- const configStat = lstatSync4(join36(outDir, ".somewhere.json"), { throwIfNoEntry: false });
86436
+ const configStat = lstatSync5(join38(outDir, ".somewhere.json"), { throwIfNoEntry: false });
86313
86437
  if (configStat && (configStat.isSymbolicLink() || !configStat.isFile() || !deployStateEntry)) {
86314
86438
  error("Cannot read the destination .somewhere.json. Pull into a fresh folder or repair the link first.");
86315
86439
  process.exit(1);
@@ -86319,9 +86443,11 @@ function registerPull(program2) {
86319
86443
  process.exit(1);
86320
86444
  }
86321
86445
  const base = deployStateEntry ? loadBaseFiles(outDir, body.project_id, deployStateEntry.config.source_base?.release_id ?? void 0) : null;
86446
+ const localScaffolds = unchangedPullScaffolds(outDir, base);
86322
86447
  const overwrite = /* @__PURE__ */ new Set();
86323
86448
  const keptEdits = [];
86324
86449
  const conflicts = [];
86450
+ let removals;
86325
86451
  const source = /* @__PURE__ */ new Map();
86326
86452
  const addSource = /* @__PURE__ */ __name((path3, content) => {
86327
86453
  const normalized = normalizeRelPath(path3);
@@ -86345,25 +86471,32 @@ function registerPull(program2) {
86345
86471
  if (i < parts.length && source.has(parts.slice(0, i).join("/"))) {
86346
86472
  throw new Error(`Conflicting exported source path: ${path3}`);
86347
86473
  }
86348
- const target2 = join36(outDir, ...parts.slice(0, i));
86349
- const stat7 = lstatSync4(target2, { throwIfNoEntry: false });
86474
+ const target2 = join38(outDir, ...parts.slice(0, i));
86475
+ const stat7 = lstatSync5(target2, { throwIfNoEntry: false });
86350
86476
  if (!stat7)
86351
86477
  continue;
86352
86478
  if (stat7.isSymbolicLink() || (i < parts.length ? !stat7.isDirectory() : !stat7.isFile())) {
86353
86479
  throw new Error(`Pull would conflict with local path ${path3}. Pull into a fresh folder.`);
86354
86480
  }
86355
86481
  }
86356
- const target = join36(outDir, path3);
86357
- if (!existsSync30(target))
86482
+ const target = join38(outDir, path3);
86483
+ const was = base?.files[path3];
86484
+ if (!existsSync30(target)) {
86485
+ if (!opts.force && was !== void 0) {
86486
+ if (was === sha2562(contents))
86487
+ keptEdits.push(path3);
86488
+ else
86489
+ conflicts.push(path3);
86490
+ }
86358
86491
  continue;
86359
- const local = readFileSync31(target);
86492
+ }
86493
+ const local = readFileSync33(target);
86360
86494
  if (local.equals(contents))
86361
86495
  continue;
86362
- if (opts.force) {
86496
+ if (opts.force || Object.hasOwn(localScaffolds, path3)) {
86363
86497
  overwrite.add(path3);
86364
86498
  continue;
86365
86499
  }
86366
- const was = base?.files[path3];
86367
86500
  if (was !== void 0 && was === sha2562(local))
86368
86501
  overwrite.add(path3);
86369
86502
  else if (was !== void 0 && was === sha2562(contents))
@@ -86371,18 +86504,30 @@ function registerPull(program2) {
86371
86504
  else
86372
86505
  conflicts.push(path3);
86373
86506
  }
86507
+ removals = planRemovedFiles(outDir, new Set(source.keys()), Boolean(opts.force), base);
86508
+ if (base)
86509
+ conflicts.push(...removals.skipped);
86374
86510
  if (conflicts.length > 0) {
86375
- const list = conflicts.slice(0, 10).join(", ") + (conflicts.length > 10 ? `, and ${conflicts.length - 10} more` : "");
86376
- throw new Error(base ? `Pull stopped: changed both in this folder and on live: ${list}. Nothing was written. Move your edits aside and pull again, or run \`${cliInvocation()} pull --force\` to replace them with live.` : `Pull stopped: these local files differ from live and this folder has no record of the version it came from, so local edits cannot be told apart: ${list}. Nothing was written. Pull into a fresh folder, or run \`${cliInvocation()} pull --force\` to replace them with live.`);
86511
+ const reason = base ? "changed both in this folder and on live" : "these local files differ from live and this folder has no saved base";
86512
+ const out = shellQuote(outDir);
86513
+ const live = `${cliInvocation()} pull ${shellQuote(body.project_id)} --env ${envSlot} --out <new-folder>`;
86514
+ const finish = `${cliInvocation()} pull ${shellQuote(body.project_id)} --env ${envSlot} --out ${out}`;
86515
+ throw new Error([
86516
+ `Pull stopped: ${reason}: ${conflicts.join(", ")}. Nothing was written.`,
86517
+ `Run \`${live}\` with an unused directory to fetch the deployed copies.`,
86518
+ `Save your local copies outside the app. Copy the deployed versions over the conflicting paths, or remove a path if it was deleted live. Then run \`${finish}\`. Reapply your edits to the pulled files and deploy.`,
86519
+ `Use \`${finish} --force\` only to discard conflicting local edits and take the deployed copies.`
86520
+ ].join("\n"));
86377
86521
  }
86378
86522
  } catch (err) {
86379
86523
  error(err instanceof Error ? err.message : String(err));
86380
86524
  process.exit(1);
86381
86525
  }
86382
86526
  const written = [];
86527
+ const editsToKeep = new Set(keptEdits);
86383
86528
  const writeOne = /* @__PURE__ */ __name((relPath, contents) => {
86384
- const target = join36(outDir, relPath);
86385
- if (existsSync30(target) && !overwrite.has(relPath)) {
86529
+ const target = join38(outDir, relPath);
86530
+ if (editsToKeep.has(relPath) || existsSync30(target) && !overwrite.has(relPath)) {
86386
86531
  return;
86387
86532
  }
86388
86533
  mkdirSync15(dirname12(target), { recursive: true });
@@ -86391,7 +86536,15 @@ function registerPull(program2) {
86391
86536
  }, "writeOne");
86392
86537
  for (const [path3, contents] of source)
86393
86538
  writeOne(path3, contents);
86394
- const removed = reconcileRemovedFiles(outDir, new Set(source.keys()), Boolean(opts.force), base);
86539
+ const removed = { removed: [], skipped: removals.skipped };
86540
+ for (const path3 of removals.remove) {
86541
+ try {
86542
+ rmSync12(join38(outDir, path3));
86543
+ removed.removed.push(path3);
86544
+ } catch {
86545
+ removed.skipped.push(path3);
86546
+ }
86547
+ }
86395
86548
  if (!deployStateEntry && removed.skipped.length === 0) {
86396
86549
  saveProjectConfig(outDir, { project_id: body.project_id, name: body.project_id, subdomain: "" });
86397
86550
  }
@@ -86403,11 +86556,19 @@ function registerPull(program2) {
86403
86556
  } else if (removed.skipped.length === 0 && linkedOutput?.config.project_id === body.project_id && !body.source_release_id && !body.active_release_id && body.counts.static_files + body.counts.binary_files + body.counts.functions === 0) {
86404
86557
  saveSourceBase(linkedOutput.dir, body.project_id, null);
86405
86558
  }
86559
+ const scaffolded = scaffoldTypecheckFiles(outDir, body.static_files);
86560
+ for (const path3 of scaffolded) {
86561
+ if (path3 !== SCAFFOLD_GITIGNORE_FILENAME)
86562
+ localScaffolds[path3] = sha2562(readFileSync33(join38(outDir, path3)));
86563
+ }
86564
+ for (const path3 of source.keys())
86565
+ delete localScaffolds[path3];
86406
86566
  const savedBase = loadProjectConfigEntry(outDir);
86407
86567
  if (savedBase?.config.project_id === body.project_id && savedBase.config.source_base && removed.skipped.length === 0) {
86408
86568
  saveBaseFiles(outDir, {
86409
86569
  project_id: body.project_id,
86410
86570
  release_id: savedBase.config.source_base.release_id,
86571
+ scaffolds: localScaffolds,
86411
86572
  files: Object.fromEntries([...source].map(([path3, contents]) => [path3, sha2562(contents)]))
86412
86573
  });
86413
86574
  }
@@ -86431,7 +86592,6 @@ function registerPull(program2) {
86431
86592
  if (removed.skipped.length > 10)
86432
86593
  info(dim(` ...and ${removed.skipped.length - 10} more`));
86433
86594
  }
86434
- const scaffolded = scaffoldTypecheckFiles(outDir, body.static_files);
86435
86595
  if (opts.json) {
86436
86596
  printJson(body);
86437
86597
  return;
@@ -86444,18 +86604,18 @@ function registerPull(program2) {
86444
86604
  }
86445
86605
  function scaffoldTypecheckFiles(outDir, staticFiles) {
86446
86606
  const added = [];
86447
- const tsconfigPath = join36(outDir, SCAFFOLD_TSCONFIG_FILENAME);
86607
+ const tsconfigPath = join38(outDir, SCAFFOLD_TSCONFIG_FILENAME);
86448
86608
  if (!existsSync30(tsconfigPath)) {
86449
86609
  writeFileSync19(tsconfigPath, buildScaffoldTsconfig());
86450
86610
  added.push(SCAFFOLD_TSCONFIG_FILENAME);
86451
86611
  }
86452
- const packagePath = join36(outDir, SCAFFOLD_PACKAGE_FILENAME);
86612
+ const packagePath = join38(outDir, SCAFFOLD_PACKAGE_FILENAME);
86453
86613
  if (!existsSync30(packagePath)) {
86454
86614
  const deps = extractDeps(staticFiles["package.json"]);
86455
- writeFileSync19(packagePath, buildScaffoldPackageJson(basename6(outDir), deps));
86615
+ writeFileSync19(packagePath, buildScaffoldPackageJson(basename7(outDir), deps));
86456
86616
  added.push(SCAFFOLD_PACKAGE_FILENAME);
86457
86617
  }
86458
- const gitignorePath = join36(outDir, SCAFFOLD_GITIGNORE_FILENAME);
86618
+ const gitignorePath = join38(outDir, SCAFFOLD_GITIGNORE_FILENAME);
86459
86619
  if (!existsSync30(gitignorePath)) {
86460
86620
  writeFileSync19(gitignorePath, buildScaffoldGitignore());
86461
86621
  added.push(SCAFFOLD_GITIGNORE_FILENAME);
@@ -86469,15 +86629,15 @@ function functionSourcePath(path3) {
86469
86629
  function normalizeRelPath(path3) {
86470
86630
  return path3.replace(/\\/g, "/");
86471
86631
  }
86472
- function reconcileRemovedFiles(outDir, expected, force, base = null) {
86473
- const removed = [];
86632
+ function planRemovedFiles(outDir, expected, force, base = null) {
86633
+ const remove = [];
86474
86634
  const skipped = [];
86475
86635
  const publishable = new Set(collectFiles(outDir, { readBinary: false }).published);
86476
86636
  const walk2 = /* @__PURE__ */ __name((dir) => {
86477
- for (const entry of readdirSync7(dir, { withFileTypes: true })) {
86637
+ for (const entry of readdirSync8(dir, { withFileTypes: true })) {
86478
86638
  if (IGNORE.has(entry.name) || entry.name.startsWith(".") && entry.name !== ".well-known")
86479
86639
  continue;
86480
- const fullPath = join36(dir, entry.name);
86640
+ const fullPath = join38(dir, entry.name);
86481
86641
  if (entry.isDirectory()) {
86482
86642
  walk2(fullPath);
86483
86643
  continue;
@@ -86490,21 +86650,16 @@ function reconcileRemovedFiles(outDir, expected, force, base = null) {
86490
86650
  const was = base?.files[relPath];
86491
86651
  if (base && was === void 0)
86492
86652
  continue;
86493
- const unedited = was !== void 0 && was === sha2562(readFileSync31(fullPath));
86653
+ const unedited = was !== void 0 && was === sha2562(readFileSync33(fullPath));
86494
86654
  if (!force && !unedited) {
86495
86655
  skipped.push(relPath);
86496
86656
  continue;
86497
86657
  }
86498
- try {
86499
- rmSync12(fullPath);
86500
- removed.push(relPath);
86501
- } catch {
86502
- skipped.push(relPath);
86503
- }
86658
+ remove.push(relPath);
86504
86659
  }
86505
86660
  }, "walk");
86506
86661
  walk2(outDir);
86507
- return { removed, skipped };
86662
+ return { remove, skipped };
86508
86663
  }
86509
86664
  var init_pull = __esm({
86510
86665
  "dist/commands/pull.js"() {
@@ -86517,12 +86672,13 @@ var init_pull = __esm({
86517
86672
  init_base_files();
86518
86673
  init_output();
86519
86674
  init_scaffold();
86675
+ init_next_actions();
86520
86676
  init_link_hint();
86521
86677
  __name(registerPull, "registerPull");
86522
86678
  __name(scaffoldTypecheckFiles, "scaffoldTypecheckFiles");
86523
86679
  __name(functionSourcePath, "functionSourcePath");
86524
86680
  __name(normalizeRelPath, "normalizeRelPath");
86525
- __name(reconcileRemovedFiles, "reconcileRemovedFiles");
86681
+ __name(planRemovedFiles, "planRemovedFiles");
86526
86682
  }
86527
86683
  });
86528
86684
 
@@ -87361,7 +87517,7 @@ var init_db_rows = __esm({
87361
87517
  import { createWriteStream as createWriteStream2, writeFileSync as writeFileSync20 } from "node:fs";
87362
87518
  import { rename, unlink } from "node:fs/promises";
87363
87519
  import { randomUUID as randomUUID7 } from "node:crypto";
87364
- import { basename as basename7, dirname as dirname13, join as join37 } from "node:path";
87520
+ import { basename as basename8, dirname as dirname13, join as join39 } from "node:path";
87365
87521
  import { Readable as Readable2 } from "node:stream";
87366
87522
  import { pipeline as pipeline2 } from "node:stream/promises";
87367
87523
  async function backgroundExport(client, projectId, plane, output, json, spinner) {
@@ -87393,7 +87549,7 @@ async function backgroundExport(client, projectId, plane, output, json, spinner)
87393
87549
  throw new Error(`Downloading the export failed (HTTP ${response.status}).`);
87394
87550
  const body = Readable2.fromWeb(response.body);
87395
87551
  if (output) {
87396
- const temp = join37(dirname13(output), `.${basename7(output)}.${randomUUID7()}.tmp`);
87552
+ const temp = join39(dirname13(output), `.${basename8(output)}.${randomUUID7()}.tmp`);
87397
87553
  try {
87398
87554
  await pipeline2(body, createWriteStream2(temp, { flags: "wx", mode: 384 }));
87399
87555
  await rename(temp, output);
@@ -87734,7 +87890,7 @@ var init_db = __esm({
87734
87890
  });
87735
87891
 
87736
87892
  // dist/commands/postgres.js
87737
- import { readFileSync as readFileSync32 } from "node:fs";
87893
+ import { readFileSync as readFileSync34 } from "node:fs";
87738
87894
  function str(value) {
87739
87895
  return typeof value === "string" && value.length > 0 ? value : null;
87740
87896
  }
@@ -87743,7 +87899,7 @@ async function readNeonApiKey() {
87743
87899
  if (fromEnv)
87744
87900
  return fromEnv;
87745
87901
  if (!process.stdin.isTTY) {
87746
- return readFileSync32(0, "utf8").trim();
87902
+ return readFileSync34(0, "utf8").trim();
87747
87903
  }
87748
87904
  const response = await (0, import_prompts8.default)({
87749
87905
  type: "password",
@@ -88072,44 +88228,44 @@ var init_postgres = __esm({
88072
88228
  });
88073
88229
 
88074
88230
  // dist/lib/local-docs.js
88075
- import { appendFileSync as appendFileSync3, existsSync as existsSync31, lstatSync as lstatSync5, mkdirSync as mkdirSync16, mkdtempSync as mkdtempSync3, readFileSync as readFileSync33, renameSync as renameSync5, rmSync as rmSync13, writeFileSync as writeFileSync21 } from "node:fs";
88076
- import { join as join38 } from "node:path";
88231
+ import { appendFileSync as appendFileSync3, existsSync as existsSync31, lstatSync as lstatSync6, mkdirSync as mkdirSync16, mkdtempSync as mkdtempSync3, readFileSync as readFileSync35, renameSync as renameSync5, rmSync as rmSync13, writeFileSync as writeFileSync21 } from "node:fs";
88232
+ import { join as join40 } from "node:path";
88077
88233
  function localDocsVersion(root = process.cwd()) {
88078
- const path3 = join38(root, FOLDER, DOCS, STAMP);
88234
+ const path3 = join40(root, FOLDER, DOCS, STAMP);
88079
88235
  if (!existsSync31(path3))
88080
88236
  return void 0;
88081
- const stamp2 = JSON.parse(readFileSync33(path3, "utf8"));
88237
+ const stamp2 = JSON.parse(readFileSync35(path3, "utf8"));
88082
88238
  return typeof stamp2.version === "string" && /^[a-f0-9]{16}$/.test(stamp2.version) ? stamp2.version : void 0;
88083
88239
  }
88084
88240
  function ensureGitIgnore(root) {
88085
- const path3 = join38(root, ".gitignore");
88086
- const text = existsSync31(path3) ? readFileSync33(path3, "utf8") : "";
88241
+ const path3 = join40(root, ".gitignore");
88242
+ const text = existsSync31(path3) ? readFileSync35(path3, "utf8") : "";
88087
88243
  if (text.split(/\r?\n/).some((line) => line === ".somewhere/" || line === "/.somewhere/"))
88088
88244
  return;
88089
88245
  appendFileSync3(path3, `${text && !text.endsWith("\n") ? "\n" : ""}/.somewhere/
88090
88246
  `);
88091
88247
  }
88092
88248
  function saveLocalDocs(version2, files, root = process.cwd()) {
88093
- const state = join38(root, FOLDER);
88094
- const target = join38(state, DOCS);
88095
- if (existsSync31(state) && !lstatSync5(state).isDirectory())
88249
+ const state = join40(root, FOLDER);
88250
+ const target = join40(state, DOCS);
88251
+ if (existsSync31(state) && !lstatSync6(state).isDirectory())
88096
88252
  throw new Error(`${state} must be a directory.`);
88097
- if (existsSync31(target) && (!lstatSync5(target).isDirectory() || !localDocsVersion(root))) {
88253
+ if (existsSync31(target) && (!lstatSync6(target).isDirectory() || !localDocsVersion(root))) {
88098
88254
  throw new Error(`Move the existing folder at ${target} before pulling docs.`);
88099
88255
  }
88100
88256
  ensureGitIgnore(root);
88101
88257
  mkdirSync16(state, { recursive: true });
88102
- const staging = mkdtempSync3(join38(state, "docs-pull-"));
88103
- const next = join38(staging, "next");
88104
- const previous = join38(staging, "previous");
88258
+ const staging = mkdtempSync3(join40(state, "docs-pull-"));
88259
+ const next = join40(staging, "next");
88260
+ const previous = join40(staging, "previous");
88105
88261
  let installed = false;
88106
88262
  try {
88107
88263
  mkdirSync16(next);
88108
88264
  for (const [name, content] of files)
88109
- writeFileSync21(join38(next, name), content, { flag: "wx" });
88265
+ writeFileSync21(join40(next, name), content, { flag: "wx" });
88110
88266
  const pulledAt = (/* @__PURE__ */ new Date()).toISOString();
88111
- writeFileSync21(join38(next, STAMP), JSON.stringify({ version: version2, pulledAt }) + "\n");
88112
- writeFileSync21(join38(next, "README.md"), `# Somewhere docs
88267
+ writeFileSync21(join40(next, STAMP), JSON.stringify({ version: version2, pulledAt }) + "\n");
88268
+ writeFileSync21(join40(next, "README.md"), `# Somewhere docs
88113
88269
 
88114
88270
  Pulled platform docs version ${version2} on ${pulledAt}. Run \`${cliInvocation()} docs\` to check whether this copy is older than the current docs and \`${cliInvocation()} docs pull\` to refresh it.
88115
88271
  `, { flag: "wx" });
@@ -88140,8 +88296,8 @@ var init_local_docs = __esm({
88140
88296
  });
88141
88297
 
88142
88298
  // dist/lib/advisor-context.js
88143
- import { readFileSync as readFileSync34, statSync as statSync6 } from "node:fs";
88144
- import { basename as basename8 } from "node:path";
88299
+ import { readFileSync as readFileSync36, statSync as statSync7 } from "node:fs";
88300
+ import { basename as basename9 } from "node:path";
88145
88301
  function tail(value, limit) {
88146
88302
  return value.length <= limit ? value : `\u2026${value.slice(-limit)}`;
88147
88303
  }
@@ -88153,16 +88309,16 @@ function redactAdvisorText(value, redactDotenvValues = false) {
88153
88309
  return redacted;
88154
88310
  }
88155
88311
  function isDotenvPath(path3) {
88156
- const name = basename8(path3);
88312
+ const name = basename9(path3);
88157
88313
  return name === ".env" || name.startsWith(".env.") || name.endsWith(".env");
88158
88314
  }
88159
88315
  function buildAdvisorContext(filePath) {
88160
88316
  const context = {};
88161
88317
  if (filePath) {
88162
- const stat7 = statSync6(filePath);
88318
+ const stat7 = statSync7(filePath);
88163
88319
  if (!stat7.isFile())
88164
88320
  throw new Error("--file must name a regular file.");
88165
- const content = readFileSync34(filePath, "utf8");
88321
+ const content = readFileSync36(filePath, "utf8");
88166
88322
  context.file = {
88167
88323
  path: filePath,
88168
88324
  content: tail(redactAdvisorText(content, isDotenvPath(filePath)), FILE_LIMIT)
@@ -88188,12 +88344,12 @@ var init_advisor_context = __esm({
88188
88344
 
88189
88345
  // dist/lib/advisor-runs.js
88190
88346
  import { randomBytes as randomBytes7, randomUUID as randomUUID8 } from "node:crypto";
88191
- import { chmodSync as chmodSync4, existsSync as existsSync32, mkdirSync as mkdirSync17, readFileSync as readFileSync35, renameSync as renameSync6, writeFileSync as writeFileSync22 } from "node:fs";
88192
- import { join as join39 } from "node:path";
88347
+ import { chmodSync as chmodSync4, existsSync as existsSync32, mkdirSync as mkdirSync17, readFileSync as readFileSync37, renameSync as renameSync6, writeFileSync as writeFileSync22 } from "node:fs";
88348
+ import { join as join41 } from "node:path";
88193
88349
  function path2(id) {
88194
88350
  if (!/^[a-f0-9-]{36}$/i.test(id))
88195
88351
  throw Error("Invalid Advisor request ID.");
88196
- return join39(directory(), id + ".json");
88352
+ return join41(directory(), id + ".json");
88197
88353
  }
88198
88354
  function save(record3) {
88199
88355
  mkdirSync17(directory(), { recursive: true, mode: 448 });
@@ -88225,7 +88381,7 @@ function expiredResult(record3) {
88225
88381
  function load(id) {
88226
88382
  if (!existsSync32(path2(id)))
88227
88383
  throw Error("Advisor request was not found in this CLI configuration.");
88228
- const record3 = JSON.parse(readFileSync35(path2(id), "utf8"));
88384
+ const record3 = JSON.parse(readFileSync37(path2(id), "utf8"));
88229
88385
  prune(record3);
88230
88386
  save(record3);
88231
88387
  return record3;
@@ -88331,7 +88487,7 @@ var init_advisor_runs = __esm({
88331
88487
  init_config();
88332
88488
  init_http();
88333
88489
  init_advisor_context();
88334
- directory = /* @__PURE__ */ __name(() => join39(cliConfigDir(), "advisor-runs"), "directory");
88490
+ directory = /* @__PURE__ */ __name(() => join41(cliConfigDir(), "advisor-runs"), "directory");
88335
88491
  __name(path2, "path");
88336
88492
  __name(save, "save");
88337
88493
  PAYLOAD_RETENTION_MS = 24 * 60 * 60 * 1e3;
@@ -88349,8 +88505,8 @@ var init_advisor_runs = __esm({
88349
88505
 
88350
88506
  // dist/lib/advisor-app.js
88351
88507
  import { createHash as createHash8 } from "node:crypto";
88352
- import { existsSync as existsSync33, mkdirSync as mkdirSync18, readFileSync as readFileSync36, rmSync as rmSync14, writeFileSync as writeFileSync23 } from "node:fs";
88353
- import { join as join40 } from "node:path";
88508
+ import { existsSync as existsSync33, mkdirSync as mkdirSync18, readFileSync as readFileSync38, rmSync as rmSync14, writeFileSync as writeFileSync23 } from "node:fs";
88509
+ import { join as join42 } from "node:path";
88354
88510
  async function gatherAdvisorApp(client, ref) {
88355
88511
  const project = await client.call("GET", `/projects/${encodeURIComponent(ref)}`);
88356
88512
  if (typeof project.id !== "string" || project.deleted === true)
@@ -88384,7 +88540,7 @@ async function gatherAdvisorApp(client, ref) {
88384
88540
  }
88385
88541
  function loadAdvisorTurns(dir, projectId, account, now2 = Date.now()) {
88386
88542
  try {
88387
- const saved = JSON.parse(readFileSync36(join40(dir, FILE), "utf8"));
88543
+ const saved = JSON.parse(readFileSync38(join42(dir, FILE), "utf8"));
88388
88544
  if (saved.project_id !== projectId || saved.owner !== ownerOf(account) || !Array.isArray(saved.turns))
88389
88545
  return [];
88390
88546
  const last = saved.turns.at(-1);
@@ -88394,22 +88550,22 @@ function loadAdvisorTurns(dir, projectId, account, now2 = Date.now()) {
88394
88550
  }
88395
88551
  }
88396
88552
  function saveAdvisorTurn(dir, projectId, account, earlier, turn) {
88397
- mkdirSync18(join40(dir, DIR), { recursive: true, mode: 448 });
88398
- writeFileSync23(join40(dir, FILE), JSON.stringify({ project_id: projectId, owner: ownerOf(account), turns: [...earlier, { question: turn.question.slice(0, 2e3), answer: turn.answer.slice(0, 3e3), at: turn.at }].slice(-3) }) + "\n", { mode: 384 });
88553
+ mkdirSync18(join42(dir, DIR), { recursive: true, mode: 448 });
88554
+ writeFileSync23(join42(dir, FILE), JSON.stringify({ project_id: projectId, owner: ownerOf(account), turns: [...earlier, { question: turn.question.slice(0, 2e3), answer: turn.answer.slice(0, 3e3), at: turn.at }].slice(-3) }) + "\n", { mode: 384 });
88399
88555
  ensureAdvisorStateIgnored(dir);
88400
88556
  }
88401
88557
  function clearAdvisorTurns(dir) {
88402
- if (existsSync33(join40(dir, FILE)))
88403
- rmSync14(join40(dir, FILE), { force: true });
88558
+ if (existsSync33(join42(dir, FILE)))
88559
+ rmSync14(join42(dir, FILE), { force: true });
88404
88560
  }
88405
88561
  function ensureAdvisorStateIgnored(dir) {
88406
- const path3 = join40(dir, ".gitignore");
88562
+ const path3 = join42(dir, ".gitignore");
88407
88563
  const covered = [".somewhere/", ".somewhere", "/.somewhere/", "/.somewhere", ".somewhere/advisor-conversation.json"];
88408
88564
  if (!existsSync33(path3)) {
88409
88565
  writeFileSync23(path3, "# somewhere: local CLI state (Advisor follow-ups, test users)\n.somewhere/\n");
88410
88566
  return;
88411
88567
  }
88412
- const text = readFileSync36(path3, "utf8");
88568
+ const text = readFileSync38(path3, "utf8");
88413
88569
  if (text.split(/\r?\n/).map((l) => l.trim()).some((l) => covered.includes(l)))
88414
88570
  return;
88415
88571
  writeFileSync23(path3, `${text}${text.endsWith("\n") || !text ? "" : "\n"}
@@ -88423,7 +88579,7 @@ var init_advisor_app = __esm({
88423
88579
  "use strict";
88424
88580
  __name(gatherAdvisorApp, "gatherAdvisorApp");
88425
88581
  DIR = ".somewhere";
88426
- FILE = join40(DIR, "advisor-conversation.json");
88582
+ FILE = join42(DIR, "advisor-conversation.json");
88427
88583
  IDLE_MS = 30 * 6e4;
88428
88584
  ownerOf = /* @__PURE__ */ __name((account) => createHash8("sha256").update(`advisor:${account}`).digest("hex"), "ownerOf");
88429
88585
  __name(loadAdvisorTurns, "loadAdvisorTurns");
@@ -89452,12 +89608,12 @@ function terminalContinuation(value, maxLines = 30) {
89452
89608
  if (!text)
89453
89609
  return [];
89454
89610
  const lines = text.split(/\r?\n/);
89455
- const shown = lines.slice(0, maxLines).map((line) => CONTINUATION_MARKER + terminalSafe(line));
89611
+ const shown2 = lines.slice(0, maxLines).map((line) => CONTINUATION_MARKER + terminalSafe(line));
89456
89612
  if (lines.length > maxLines) {
89457
89613
  const more = lines.length - maxLines;
89458
- shown.push(`${CONTINUATION_MARKER}... ${more} more line${more === 1 ? "" : "s"} (--json shows the whole stack)`);
89614
+ shown2.push(`${CONTINUATION_MARKER}... ${more} more line${more === 1 ? "" : "s"} (--json shows the whole stack)`);
89459
89615
  }
89460
- return shown;
89616
+ return shown2;
89461
89617
  }
89462
89618
  var UNSAFE, CONTINUATION_MARKER;
89463
89619
  var init_terminal_text = __esm({
@@ -89837,7 +89993,7 @@ var init_envfile_write = __esm({
89837
89993
  });
89838
89994
 
89839
89995
  // dist/commands/env.js
89840
- import { existsSync as existsSync34, readFileSync as readFileSync37, writeFileSync as writeFileSync24 } from "node:fs";
89996
+ import { existsSync as existsSync34, readFileSync as readFileSync39, writeFileSync as writeFileSync24 } from "node:fs";
89841
89997
  import { resolve as resolve19 } from "node:path";
89842
89998
  function resolveProjectId(explicit) {
89843
89999
  if (explicit)
@@ -89919,7 +90075,7 @@ function registerEnv(program2) {
89919
90075
  process.exit(1);
89920
90076
  }
89921
90077
  if (existsSync34(outPath) && !opts.force) {
89922
- const existing = readFileSync37(outPath, "utf-8");
90078
+ const existing = readFileSync39(outPath, "utf-8");
89923
90079
  const hasValues = existing.split("\n").some((l) => /^[^#=]+=.+/.test(l.trim()));
89924
90080
  const { ok } = await (0, import_prompts9.default)({
89925
90081
  type: "confirm",
@@ -89972,7 +90128,7 @@ function registerEnv(program2) {
89972
90128
  if (inputNote && !opts.json)
89973
90129
  process.stderr.write(`Note: ${inputNote}
89974
90130
  `);
89975
- const value = opts.stdin ? readFileSync37(0, "utf8").replace(/\r?\n$/, "") : positionalValue;
90131
+ const value = opts.stdin ? readFileSync39(0, "utf8").replace(/\r?\n$/, "") : positionalValue;
89976
90132
  const client = new ApiClient(getToken());
89977
90133
  const pid = resolveProjectId(opts.project);
89978
90134
  try {
@@ -90042,7 +90198,7 @@ var init_env = __esm({
90042
90198
  });
90043
90199
 
90044
90200
  // dist/commands/run.js
90045
- import { existsSync as existsSync35, readFileSync as readFileSync38 } from "node:fs";
90201
+ import { existsSync as existsSync35, readFileSync as readFileSync40 } from "node:fs";
90046
90202
  import { isAbsolute as isAbsolute6, resolve as resolve20 } from "node:path";
90047
90203
  import { createRequire as createRequire8 } from "node:module";
90048
90204
  function parseArgs(values) {
@@ -90113,7 +90269,7 @@ function registerRun(program2) {
90113
90269
  error(`File not found: ${script}`);
90114
90270
  process.exit(1);
90115
90271
  }
90116
- const code = readFileSync38(absPath, "utf-8");
90272
+ const code = readFileSync40(absPath, "utf-8");
90117
90273
  if (!code.trim()) {
90118
90274
  error(`${script} is empty \u2014 nothing to run.`);
90119
90275
  process.exit(1);
@@ -90551,7 +90707,7 @@ var init_claim = __esm({
90551
90707
  import { createRequire as createRequire9 } from "node:module";
90552
90708
  import { realpathSync as realpathSync4 } from "node:fs";
90553
90709
  import { createConnection, createServer as createNetServer } from "node:net";
90554
- import { join as join41 } from "node:path";
90710
+ import { join as join43 } from "node:path";
90555
90711
  import { pathToFileURL as pathToFileURL3 } from "node:url";
90556
90712
  function deployedOrigin(value) {
90557
90713
  const url3 = new URL(value);
@@ -90649,7 +90805,7 @@ async function startFrontendDev(cwd, target, port = 8787, open4 = false) {
90649
90805
  throw new Error(INSTALL_PROJECT_DEPENDENCIES);
90650
90806
  let vitePath;
90651
90807
  try {
90652
- vitePath = createRequire9(join41(cwd, "package.json")).resolve("vite");
90808
+ vitePath = createRequire9(join43(cwd, "package.json")).resolve("vite");
90653
90809
  } catch {
90654
90810
  if (readProjectPin(cwd)?.versionOnly) {
90655
90811
  throw new Error("Install the local frontend tools: npm install -D --save-exact vite@7.2.2");
@@ -90793,7 +90949,7 @@ var init_preview_jobs = __esm({
90793
90949
  // dist/commands/dev.js
90794
90950
  import { randomUUID as randomUUID9 } from "node:crypto";
90795
90951
  import { existsSync as existsSync36 } from "node:fs";
90796
- import { join as join42, relative as relative11 } from "node:path";
90952
+ import { join as join44, relative as relative11 } from "node:path";
90797
90953
  function previewFinishedReason(err) {
90798
90954
  if (!(err instanceof CliApiError) || err.code !== "DRAFT_SESSION_TERMINAL")
90799
90955
  return null;
@@ -91781,7 +91937,7 @@ async function deployBatch(client, projectId, cwd, changed, deleted, draftId, ex
91781
91937
  const updateBinary = {};
91782
91938
  const deleteKeys = [];
91783
91939
  for (const rel of changed) {
91784
- const abs = join42(cwd, rel);
91940
+ const abs = join44(cwd, rel);
91785
91941
  if (!existsSync36(abs))
91786
91942
  continue;
91787
91943
  classifyInto({ files: updateFiles, functions: updateFunctions, binaryFiles: updateBinary }, cwd, rel);
@@ -91847,7 +92003,7 @@ async function deployBatch(client, projectId, cwd, changed, deleted, draftId, ex
91847
92003
  for (const rel of deleted)
91848
92004
  delete nextFiles[rel];
91849
92005
  for (const rel of changed)
91850
- if (existsSync36(join42(cwd, rel)))
92006
+ if (existsSync36(join44(cwd, rel)))
91851
92007
  Object.assign(nextFiles, hashFiles(cwd, [rel]));
91852
92008
  savePreviewRecord(cwd, { ...record3, preview_id: nextCandidate, files: nextFiles });
91853
92009
  }
@@ -92043,7 +92199,7 @@ var init_dev = __esm({
92043
92199
 
92044
92200
  // dist/commands/check.js
92045
92201
  import { existsSync as existsSync37 } from "node:fs";
92046
- import { join as join43, resolve as resolve21 } from "node:path";
92202
+ import { join as join45, resolve as resolve21 } from "node:path";
92047
92203
  function buildCheckBody(collected, projectId) {
92048
92204
  const body = { project_id: projectId, files: collected.files };
92049
92205
  if (Object.keys(collected.functions).length > 0)
@@ -92148,7 +92304,7 @@ async function runLocalPreflight(targetDir, collected, typecheck = async (dir) =
92148
92304
  if (collected.excluded.length)
92149
92305
  source.not_published = collected.excluded;
92150
92306
  let typecheckStep;
92151
- if (!existsSync37(join43(targetDir, "tsconfig.json"))) {
92307
+ if (!existsSync37(join45(targetDir, "tsconfig.json"))) {
92152
92308
  typecheckStep = { name: "typecheck", status: "skipped", reason: MISSING_TSCONFIG_GUIDANCE };
92153
92309
  } else if (missingProjectDependencies(targetDir).length) {
92154
92310
  typecheckStep = { name: "typecheck", status: "skipped", reason: missingTypecheckDependenciesMessage() };
@@ -92565,7 +92721,7 @@ var init_api2 = __esm({
92565
92721
  import { createReadStream as createReadStream3, createWriteStream as createWriteStream3 } from "node:fs";
92566
92722
  import { stat as stat6, rename as rename2, unlink as unlink2 } from "node:fs/promises";
92567
92723
  import { randomUUID as randomUUID10 } from "node:crypto";
92568
- import { basename as basename9, dirname as dirname14, extname as extname6, join as join44, resolve as resolve23 } from "node:path";
92724
+ import { basename as basename10, dirname as dirname14, extname as extname6, join as join46, resolve as resolve23 } from "node:path";
92569
92725
  import { pipeline as pipeline3 } from "node:stream/promises";
92570
92726
  function registerFs(program2) {
92571
92727
  const fs2 = program2.command("fs").description("Manage project file storage");
@@ -92609,7 +92765,7 @@ function registerFs(program2) {
92609
92765
  if (!response.body)
92610
92766
  throw new Error("The server returned an empty file response.");
92611
92767
  const destination = resolve23(local);
92612
- tempPath = join44(dirname14(destination), `.${basename9(destination)}.${randomUUID10()}.tmp`);
92768
+ tempPath = join46(dirname14(destination), `.${basename10(destination)}.${randomUUID10()}.tmp`);
92613
92769
  await pipeline3(response.body, createWriteStream3(tempPath, { flags: "wx" }));
92614
92770
  await rename2(tempPath, destination);
92615
92771
  tempPath = void 0;
@@ -110419,7 +110575,7 @@ var require_polyfill = __commonJS({
110419
110575
  var {
110420
110576
  dirname: dirname17,
110421
110577
  isAbsolute: isAbsolute7,
110422
- join: join54,
110578
+ join: join57,
110423
110579
  parse: parse3,
110424
110580
  resolve: resolve27,
110425
110581
  sep: sep2,
@@ -110700,8 +110856,8 @@ var require_polyfill = __commonJS({
110700
110856
  const dir = await readdir3(src);
110701
110857
  for (let i = 0; i < dir.length; i++) {
110702
110858
  const item = dir[i];
110703
- const srcItem = join54(src, item);
110704
- const destItem = join54(dest, item);
110859
+ const srcItem = join57(src, item);
110860
+ const destItem = join57(dest, item);
110705
110861
  const { destStat } = await checkPaths(srcItem, destItem, opts);
110706
110862
  await startCopy(destStat, srcItem, destItem, opts);
110707
110863
  }
@@ -110777,7 +110933,7 @@ var require_cp = __commonJS({
110777
110933
  // node_modules/@npmcli/fs/lib/with-temp-dir.js
110778
110934
  var require_with_temp_dir = __commonJS({
110779
110935
  "node_modules/@npmcli/fs/lib/with-temp-dir.js"(exports, module) {
110780
- var { join: join54, sep: sep2 } = __require("path");
110936
+ var { join: join57, sep: sep2 } = __require("path");
110781
110937
  var getOptions = require_get_options();
110782
110938
  var { mkdir, mkdtemp, rm } = __require("fs/promises");
110783
110939
  var withTempDir = /* @__PURE__ */ __name(async (root, fn, opts) => {
@@ -110785,7 +110941,7 @@ var require_with_temp_dir = __commonJS({
110785
110941
  copy: ["tmpPrefix"]
110786
110942
  });
110787
110943
  await mkdir(root, { recursive: true });
110788
- const target = await mkdtemp(join54(`${root}${sep2}`, options2.tmpPrefix || ""));
110944
+ const target = await mkdtemp(join57(`${root}${sep2}`, options2.tmpPrefix || ""));
110789
110945
  let err;
110790
110946
  let result;
110791
110947
  try {
@@ -110810,13 +110966,13 @@ var require_with_temp_dir = __commonJS({
110810
110966
  var require_readdir_scoped = __commonJS({
110811
110967
  "node_modules/@npmcli/fs/lib/readdir-scoped.js"(exports, module) {
110812
110968
  var { readdir: readdir3 } = __require("fs/promises");
110813
- var { join: join54 } = __require("path");
110969
+ var { join: join57 } = __require("path");
110814
110970
  var readdirScoped = /* @__PURE__ */ __name(async (dir) => {
110815
110971
  const results = [];
110816
110972
  for (const item of await readdir3(dir)) {
110817
110973
  if (item.startsWith("@")) {
110818
- for (const scopedItem of await readdir3(join54(dir, item))) {
110819
- results.push(join54(item, scopedItem));
110974
+ for (const scopedItem of await readdir3(join57(dir, item))) {
110975
+ results.push(join57(item, scopedItem));
110820
110976
  }
110821
110977
  } else {
110822
110978
  results.push(item);
@@ -110831,7 +110987,7 @@ var require_readdir_scoped = __commonJS({
110831
110987
  // node_modules/@npmcli/fs/lib/move-file.js
110832
110988
  var require_move_file = __commonJS({
110833
110989
  "node_modules/@npmcli/fs/lib/move-file.js"(exports, module) {
110834
- var { dirname: dirname17, join: join54, resolve: resolve27, relative: relative15, isAbsolute: isAbsolute7 } = __require("path");
110990
+ var { dirname: dirname17, join: join57, resolve: resolve27, relative: relative15, isAbsolute: isAbsolute7 } = __require("path");
110835
110991
  var fs2 = __require("fs/promises");
110836
110992
  var pathExists = /* @__PURE__ */ __name(async (path3) => {
110837
110993
  try {
@@ -110861,7 +111017,7 @@ var require_move_file = __commonJS({
110861
111017
  if (sourceStat.isDirectory()) {
110862
111018
  const files = await fs2.readdir(source);
110863
111019
  await Promise.all(files.map(
110864
- (file) => moveFile(join54(source, file), join54(destination, file), options2, false, symlinks)
111020
+ (file) => moveFile(join57(source, file), join57(destination, file), options2, false, symlinks)
110865
111021
  ));
110866
111022
  } else if (sourceStat.isSymbolicLink()) {
110867
111023
  symlinks.push({ source, destination });
@@ -126687,7 +126843,7 @@ var require_commonjs4 = __commonJS({
126687
126843
  "use strict";
126688
126844
  Object.defineProperty(exports, "__esModule", { value: true });
126689
126845
  exports.range = exports.balanced = void 0;
126690
- var balanced = /* @__PURE__ */ __name((a, b2, str2) => {
126846
+ var balanced2 = /* @__PURE__ */ __name((a, b2, str2) => {
126691
126847
  const ma = a instanceof RegExp ? maybeMatch(a, str2) : a;
126692
126848
  const mb = b2 instanceof RegExp ? maybeMatch(b2, str2) : b2;
126693
126849
  const r = ma !== null && mb != null && (0, exports.range)(ma, mb, str2);
@@ -126699,7 +126855,7 @@ var require_commonjs4 = __commonJS({
126699
126855
  post: str2.slice(r[1] + mb.length)
126700
126856
  };
126701
126857
  }, "balanced");
126702
- exports.balanced = balanced;
126858
+ exports.balanced = balanced2;
126703
126859
  var maybeMatch = /* @__PURE__ */ __name((reg, str2) => {
126704
126860
  const m2 = str2.match(reg);
126705
126861
  return m2 ? m2[0] : null;
@@ -130229,12 +130385,12 @@ var require_url = __commonJS({
130229
130385
  "node_modules/tuf-js/dist/utils/url.js"(exports) {
130230
130386
  "use strict";
130231
130387
  Object.defineProperty(exports, "__esModule", { value: true });
130232
- exports.join = join54;
130388
+ exports.join = join57;
130233
130389
  var url_1 = __require("url");
130234
- function join54(base, path3) {
130390
+ function join57(base, path3) {
130235
130391
  return new url_1.URL(ensureTrailingSlash(base) + removeLeadingSlash(path3)).toString();
130236
130392
  }
130237
- __name(join54, "join");
130393
+ __name(join57, "join");
130238
130394
  function ensureTrailingSlash(path3) {
130239
130395
  return path3.endsWith("/") ? path3 : path3 + "/";
130240
130396
  }
@@ -132570,8 +132726,8 @@ var require_dist15 = __commonJS({
132570
132726
 
132571
132727
  // dist/lib/update-security.js
132572
132728
  import { createHash as createHash9, timingSafeEqual } from "node:crypto";
132573
- import { mkdirSync as mkdirSync19, readFileSync as readFileSync39, statSync as statSync7 } from "node:fs";
132574
- import { join as join45 } from "node:path";
132729
+ import { mkdirSync as mkdirSync19, readFileSync as readFileSync41, statSync as statSync8 } from "node:fs";
132730
+ import { join as join47 } from "node:path";
132575
132731
  import { Readable as Readable3 } from "node:stream";
132576
132732
  import { pipeline as pipeline4 } from "node:stream/promises";
132577
132733
  function expectedTarballUrl(version2) {
@@ -132936,15 +133092,15 @@ async function verifyLockedArtifact(artifact, extractionDir, release2) {
132936
133092
  seen2.add(path3);
132937
133093
  return true;
132938
133094
  });
132939
- const manifestPath = join45(extractionDir, "package.json");
132940
- const lockPath = join45(extractionDir, "npm-shrinkwrap.json");
133095
+ const manifestPath = join47(extractionDir, "package.json");
133096
+ const lockPath = join47(extractionDir, "npm-shrinkwrap.json");
132941
133097
  let manifest;
132942
133098
  let lock;
132943
133099
  try {
132944
- if (statSync7(lockPath).size > MAX_LOCKFILE_BYTES)
133100
+ if (statSync8(lockPath).size > MAX_LOCKFILE_BYTES)
132945
133101
  throw new Error("lockfile too large");
132946
- manifest = JSON.parse(readFileSync39(manifestPath, "utf8"));
132947
- lock = JSON.parse(readFileSync39(lockPath, "utf8"));
133102
+ manifest = JSON.parse(readFileSync41(manifestPath, "utf8"));
133103
+ lock = JSON.parse(readFileSync41(lockPath, "utf8"));
132948
133104
  } catch (cause) {
132949
133105
  throw new Error(`the verified artifact has no readable npm-shrinkwrap dependency lock: ${message(cause)}`);
132950
133106
  }
@@ -132981,8 +133137,8 @@ async function verifyLockedArtifact(artifact, extractionDir, release2) {
132981
133137
  }
132982
133138
  let bundledManifest;
132983
133139
  try {
132984
- const bundledPath = join45(extractionDir, ...lockPath2.split("/"), "package.json");
132985
- bundledManifest = JSON.parse(readFileSync39(bundledPath, "utf8"));
133140
+ const bundledPath = join47(extractionDir, ...lockPath2.split("/"), "package.json");
133141
+ bundledManifest = JSON.parse(readFileSync41(bundledPath, "utf8"));
132986
133142
  } catch (cause) {
132987
133143
  throw new Error(`the verified artifact has an unreadable bundled dependency ${lockPath2}: ${message(cause)}`);
132988
133144
  }
@@ -133052,10 +133208,10 @@ ${GITHUB_REPOSITORY_ID}`,
133052
133208
  // dist/commands/update.js
133053
133209
  import { spawn as spawn6 } from "node:child_process";
133054
133210
  import { randomBytes as randomBytes8 } from "node:crypto";
133055
- import { closeSync as closeSync5, constants as constants2, fstatSync, mkdtempSync as mkdtempSync4, openSync as openSync5, readFileSync as readFileSync40, readSync, rmSync as rmSync15, unlinkSync as unlinkSync5, writeFileSync as writeFileSync25 } from "node:fs";
133211
+ import { closeSync as closeSync5, constants as constants2, fstatSync, mkdtempSync as mkdtempSync4, openSync as openSync5, readFileSync as readFileSync42, readSync, rmSync as rmSync15, unlinkSync as unlinkSync5, writeFileSync as writeFileSync25 } from "node:fs";
133056
133212
  import { createServer } from "node:http";
133057
133213
  import { tmpdir as tmpdir2 } from "node:os";
133058
- import { join as join46 } from "node:path";
133214
+ import { join as join48 } from "node:path";
133059
133215
  function refuse2(cause) {
133060
133216
  error(`Update refused: ${message2(cause)}.`);
133061
133217
  info(`To install the latest release with npm instead, run: ${teal(NPM_UPDATE_COMMAND)}`);
@@ -133063,7 +133219,7 @@ function refuse2(cause) {
133063
133219
  }
133064
133220
  function currentVersion2() {
133065
133221
  try {
133066
- const pkg = JSON.parse(readFileSync40(join46(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
133222
+ const pkg = JSON.parse(readFileSync42(join48(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
133067
133223
  return pkg.version;
133068
133224
  } catch {
133069
133225
  return "0.0.0";
@@ -133202,10 +133358,10 @@ async function serveArtifactSnapshot(artifact) {
133202
133358
  }
133203
133359
  async function installVerifiedTarball(tarballPath, tempDir, release2) {
133204
133360
  const ambientEnvironment = { ...process.env };
133205
- const packageDir = join46(tempDir, "authenticated-package");
133206
- const cacheDir = join46(tempDir, "empty-cache");
133207
- const userConfigPath = join46(tempDir, "user-npmrc");
133208
- const globalConfigPath = join46(tempDir, "global-npmrc");
133361
+ const packageDir = join48(tempDir, "authenticated-package");
133362
+ const cacheDir = join48(tempDir, "empty-cache");
133363
+ const userConfigPath = join48(tempDir, "user-npmrc");
133364
+ const globalConfigPath = join48(tempDir, "global-npmrc");
133209
133365
  writeFileSync25(userConfigPath, "", { mode: 384 });
133210
133366
  writeFileSync25(globalConfigPath, "", { mode: 384 });
133211
133367
  const artifact = snapshotAuthenticatedArtifact(tarballPath);
@@ -133277,8 +133433,8 @@ async function runUpdate(opts, dependencies = {}) {
133277
133433
  const provenance = await fetchJson(fetchImpl, release2.attestationUrl, "the official npm provenance endpoint");
133278
133434
  await (dependencies.verifyProvenance ?? verifyPublishedProvenance)(provenance, release2);
133279
133435
  const tarball = await downloadTarball(fetchImpl, release2);
133280
- tempDir = mkdtempSync4(join46(tmpdir2(), "somewhere-update-"));
133281
- const tarballPath = join46(tempDir, `cli-${release2.version}.tgz`);
133436
+ tempDir = mkdtempSync4(join48(tmpdir2(), "somewhere-update-"));
133437
+ const tarballPath = join48(tempDir, `cli-${release2.version}.tgz`);
133282
133438
  writeFileSync25(tarballPath, tarball, { mode: 384 });
133283
133439
  info(`Cryptographically verified provenance and integrity for ${CLI_PACKAGE}@${release2.version}.`);
133284
133440
  info(`Updating ${CLI_PACKAGE} from its authenticated dependency lock \u2026`);
@@ -133410,7 +133566,7 @@ var init_upgrade = __esm({
133410
133566
  });
133411
133567
 
133412
133568
  // dist/commands/call.js
133413
- import { readFileSync as readFileSync41 } from "node:fs";
133569
+ import { readFileSync as readFileSync43 } from "node:fs";
133414
133570
  function parseArguments(value, file) {
133415
133571
  if (value === void 0)
133416
133572
  return {};
@@ -133434,7 +133590,7 @@ function readCallArguments(jsonArgs, file) {
133434
133590
  }
133435
133591
  let text;
133436
133592
  try {
133437
- text = readFileSync41(file, "utf8");
133593
+ text = readFileSync43(file, "utf8");
133438
133594
  } catch (err) {
133439
133595
  const code = err?.code;
133440
133596
  throw new Error(`Could not read --file ${file}${code ? ` (${code})` : ""}. The requested tool was not called.`);
@@ -134705,8 +134861,8 @@ function nextRunLabel(row, now2 = Date.now()) {
134705
134861
  return "paused";
134706
134862
  if (typeof row.next_run_at !== "string" || !row.next_run_at)
134707
134863
  return "\u2014";
134708
- const shown = isoSeconds(row.next_run_at);
134709
- return isOverdue(row, now2) ? `${shown} (overdue)` : shown;
134864
+ const shown2 = isoSeconds(row.next_run_at);
134865
+ return isOverdue(row, now2) ? `${shown2} (overdue)` : shown2;
134710
134866
  }
134711
134867
  function isOverdue(row, now2) {
134712
134868
  if (row.enabled === false || typeof row.next_run_at !== "string")
@@ -135762,8 +135918,8 @@ var init_test_response_capture = __esm({
135762
135918
  import { randomUUID as randomUUID12 } from "node:crypto";
135763
135919
  import { setDefaultResultOrder } from "node:dns";
135764
135920
  import { lookup } from "node:dns/promises";
135765
- import { existsSync as existsSync38, mkdirSync as mkdirSync20, readFileSync as readFileSync42, writeFileSync as writeFileSync26 } from "node:fs";
135766
- import { basename as basename10, dirname as dirname15, join as join47, relative as relative12, resolve as resolve24 } from "node:path";
135921
+ import { existsSync as existsSync38, mkdirSync as mkdirSync20, readFileSync as readFileSync44, writeFileSync as writeFileSync26 } from "node:fs";
135922
+ import { basename as basename11, dirname as dirname15, join as join49, relative as relative12, resolve as resolve24 } from "node:path";
135767
135923
  function launchOptions(extra = {}) {
135768
135924
  return { ...extra, args: ["--disable-features=AsyncDns", ...extra.args ?? []] };
135769
135925
  }
@@ -135784,13 +135940,13 @@ async function pageState(page) {
135784
135940
  if (page.isClosed())
135785
135941
  return "closed";
135786
135942
  try {
135787
- const shown = await page.evaluate(`(() => {
135943
+ const shown2 = await page.evaluate(`(() => {
135788
135944
  const said = [...document.querySelectorAll('[role="alert"], [data-sw-auth="error"], [data-sw-data="error"], [aria-invalid="true"], .error')]
135789
135945
  .filter((el) => el.getClientRects().length > 0).map((el) => el.innerText.trim()).filter(Boolean);
135790
135946
  return said.length ? 'shows: ' + said.slice(0, 3).join(' | ')
135791
135947
  : 'no error text; page starts: ' + (document.body ? document.body.innerText : '').trim().replace(/\\s+/g, ' ').slice(0, 160);
135792
135948
  })()`);
135793
- return scrub(`${page.url()} ${shown}`).slice(0, 400);
135949
+ return scrub(`${page.url()} ${shown2}`).slice(0, 400);
135794
135950
  } catch {
135795
135951
  return scrub(page.url());
135796
135952
  }
@@ -135813,10 +135969,10 @@ function undeployedChanges(root, projectId, preview = false) {
135813
135969
  return null;
135814
135970
  base = { project_id: record3.project_id, release_id: record3.preview_id, files: record3.files };
135815
135971
  } else {
135816
- const path3 = join47(root, ".somewhere", "base-files.json");
135972
+ const path3 = join49(root, ".somewhere", "base-files.json");
135817
135973
  if (!existsSync38(path3))
135818
135974
  return null;
135819
- base = JSON.parse(readFileSync42(path3, "utf8"));
135975
+ base = JSON.parse(readFileSync44(path3, "utf8"));
135820
135976
  }
135821
135977
  if (base.project_id !== projectId || !base.files)
135822
135978
  return null;
@@ -135985,8 +136141,8 @@ var init_app_test = __esm({
135985
136141
  process.env.SW_TEST_ORIGIN = target.origin;
135986
136142
  for (const line of describeSweep(await sweepAccounts(control, root), "Before this script"))
135987
136143
  process.stderr.write(line + "\n");
135988
- const scriptName = process.argv[1] ? basename10(process.argv[1]).replace(/\.[cm]?[jt]s$/, "") : "app-check";
135989
- const app = new _AppTest(root, control, resolve24(root, options2.results ?? join47(".somewhere", `${scriptName}${preview ? "-preview" : ""}.json`)));
136144
+ const scriptName = process.argv[1] ? basename11(process.argv[1]).replace(/\.[cm]?[jt]s$/, "") : "app-check";
136145
+ const app = new _AppTest(root, control, resolve24(root, options2.results ?? join49(".somewhere", `${scriptName}${preview ? "-preview" : ""}.json`)));
135990
136146
  return app;
135991
136147
  }
135992
136148
  /** What this run tests: the project, environment, preview, origin and script. */
@@ -136759,34 +136915,34 @@ var init_reference_check_note = __esm({
136759
136915
 
136760
136916
  // dist/lib/test-scripts.js
136761
136917
  import { createRequire as createRequire10 } from "node:module";
136762
- import { existsSync as existsSync39, mkdirSync as mkdirSync21, readFileSync as readFileSync43, readdirSync as readdirSync8, rmSync as rmSync17, statSync as statSync8, writeFileSync as writeFileSync27 } from "node:fs";
136763
- import { dirname as dirname16, join as join48, relative as relative13, resolve as resolve25 } from "node:path";
136918
+ import { existsSync as existsSync39, mkdirSync as mkdirSync21, readFileSync as readFileSync45, readdirSync as readdirSync9, rmSync as rmSync17, statSync as statSync9, writeFileSync as writeFileSync27 } from "node:fs";
136919
+ import { dirname as dirname16, join as join50, relative as relative13, resolve as resolve25 } from "node:path";
136764
136920
  import { spawn as spawn7, spawnSync as spawnSync5 } from "node:child_process";
136765
136921
  function hasSpecFiles(root) {
136766
136922
  const walk2 = /* @__PURE__ */ __name((dir) => {
136767
136923
  if (!existsSync39(dir))
136768
136924
  return false;
136769
- for (const entry of readdirSync8(dir, { withFileTypes: true })) {
136925
+ for (const entry of readdirSync9(dir, { withFileTypes: true })) {
136770
136926
  if (entry.name === "node_modules" || entry.name.startsWith("."))
136771
136927
  continue;
136772
- const path3 = join48(dir, entry.name);
136928
+ const path3 = join50(dir, entry.name);
136773
136929
  if (entry.isDirectory() ? walk2(path3) : /\.spec\.ts$/.test(entry.name))
136774
136930
  return true;
136775
136931
  }
136776
136932
  return false;
136777
136933
  }, "walk");
136778
- return walk2(join48(root, "tests"));
136934
+ return walk2(join50(root, "tests"));
136779
136935
  }
136780
136936
  function listScripts(root, files) {
136781
136937
  if (files.length)
136782
136938
  return files.map((file) => relative13(root, resolve25(root, file)));
136783
- const dir = join48(root, "tests");
136939
+ const dir = join50(root, "tests");
136784
136940
  if (!existsSync39(dir))
136785
136941
  return [];
136786
- return readdirSync8(dir).filter((name) => isScript(name) && statSync8(join48(dir, name)).isFile()).sort().map((name) => join48("tests", name));
136942
+ return readdirSync9(dir).filter((name) => isScript(name) && statSync9(join50(dir, name)).isFile()).sort().map((name) => join50("tests", name));
136787
136943
  }
136788
136944
  function scriptBrowserEnv(root) {
136789
- const require6 = createRequire10(join48(root, "package.json"));
136945
+ const require6 = createRequire10(join50(root, "package.json"));
136790
136946
  let cli;
136791
136947
  try {
136792
136948
  cli = require6.resolve("@playwright/test/cli");
@@ -136797,7 +136953,7 @@ function scriptBrowserEnv(root) {
136797
136953
  const probe = spawnSync5(process.execPath, ["-e", "require(process.argv[1]).chromium.launch().then(b => b.close()).then(() => process.exit(0), () => process.exit(3))", require6.resolve("@playwright/test")], { env, stdio: "ignore" });
136798
136954
  if (probe.status === 0)
136799
136955
  return env;
136800
- env.PLAYWRIGHT_BROWSERS_PATH ??= join48(cliConfigDir(), "cache", "playwright");
136956
+ env.PLAYWRIGHT_BROWSERS_PATH ??= join50(cliConfigDir(), "cache", "playwright");
136801
136957
  process.stderr.write("Installing Playwright Chromium in the CLI cache (once).\n");
136802
136958
  const install = spawnSync5(process.execPath, [cli, "install", "chromium"], { stdio: "inherit", env });
136803
136959
  if (install.status !== 0)
@@ -136820,7 +136976,7 @@ async function runScripts(root, scripts, extraArgs, env = scriptBrowserEnv(root)
136820
136976
  env = testImportEnv(root, env);
136821
136977
  const results = [];
136822
136978
  for (const script of scripts) {
136823
- if (!existsSync39(join48(root, script))) {
136979
+ if (!existsSync39(join50(root, script))) {
136824
136980
  results.push({ script, ok: false, exitCode: 1, ms: 0, reason: "no such file" });
136825
136981
  continue;
136826
136982
  }
@@ -136829,7 +136985,7 @@ async function runScripts(root, scripts, extraArgs, env = scriptBrowserEnv(root)
136829
136985
  `);
136830
136986
  const started = performance.now();
136831
136987
  let output = "";
136832
- const handOver = join48(root, ".somewhere", "tests", `report-${results.length}.json`);
136988
+ const handOver = join50(root, ".somewhere", "tests", `report-${results.length}.json`);
136833
136989
  mkdirSync21(dirname16(handOver), { recursive: true });
136834
136990
  rmSync17(handOver, { force: true });
136835
136991
  const askedForBrowserLog = /(^|,)\s*(pw:browser|pw:\*|\*)\s*(,|$)/.test(env.DEBUG ?? "");
@@ -136859,7 +137015,7 @@ async function runScripts(root, scripts, extraArgs, env = scriptBrowserEnv(root)
136859
137015
  stderrLines("", true);
136860
137016
  let report2 = null;
136861
137017
  try {
136862
- report2 = existsSync39(handOver) ? JSON.parse(readFileSync43(handOver, "utf8")) : null;
137018
+ report2 = existsSync39(handOver) ? JSON.parse(readFileSync45(handOver, "utf8")) : null;
136863
137019
  } catch {
136864
137020
  report2 = null;
136865
137021
  }
@@ -136892,20 +137048,20 @@ function describeScriptResults(results, options2 = {}) {
136892
137048
  return results.some((result) => result.browserCrashed) ? lines.map((line) => line.startsWith("Next: ") ? `Next: give the browser access as the FAIL line says, then run ${TEST_COMMAND} again.` : line) : lines;
136893
137049
  }
136894
137050
  function lastFailedScripts(root) {
136895
- const path3 = join48(root, LAST);
137051
+ const path3 = join50(root, LAST);
136896
137052
  if (!existsSync39(path3))
136897
137053
  return [];
136898
137054
  try {
136899
- return (JSON.parse(readFileSync43(path3, "utf8")).results ?? []).filter((r) => !r.ok).map((r) => r.script);
137055
+ return (JSON.parse(readFileSync45(path3, "utf8")).results ?? []).filter((r) => !r.ok).map((r) => r.script);
136900
137056
  } catch {
136901
137057
  return [];
136902
137058
  }
136903
137059
  }
136904
137060
  function recordScriptResults(root, results, rerunOnly) {
136905
- const previous = rerunOnly && existsSync39(join48(root, LAST)) ? JSON.parse(readFileSync43(join48(root, LAST), "utf8")).results ?? [] : [];
137061
+ const previous = rerunOnly && existsSync39(join50(root, LAST)) ? JSON.parse(readFileSync45(join50(root, LAST), "utf8")).results ?? [] : [];
136906
137062
  const merged = [...previous.filter((p2) => !results.some((r) => r.script === p2.script)), ...results];
136907
- mkdirSync21(join48(root, ".somewhere", "tests"), { recursive: true });
136908
- writeFileSync27(join48(root, LAST), JSON.stringify({ finished: (/* @__PURE__ */ new Date()).toISOString(), results: merged }, null, 2) + "\n");
137063
+ mkdirSync21(join50(root, ".somewhere", "tests"), { recursive: true });
137064
+ writeFileSync27(join50(root, LAST), JSON.stringify({ finished: (/* @__PURE__ */ new Date()).toISOString(), results: merged }, null, 2) + "\n");
136909
137065
  }
136910
137066
  var BROWSER_CRASH, BROWSER_CRASH_REASON, isScript, LAST;
136911
137067
  var init_test_scripts = __esm({
@@ -136923,7 +137079,7 @@ var init_test_scripts = __esm({
136923
137079
  __name(failureReason, "failureReason");
136924
137080
  __name(runScripts, "runScripts");
136925
137081
  __name(describeScriptResults, "describeScriptResults");
136926
- LAST = join48(".somewhere", "tests", "scripts-last.json");
137082
+ LAST = join50(".somewhere", "tests", "scripts-last.json");
136927
137083
  __name(lastFailedScripts, "lastFailedScripts");
136928
137084
  __name(recordScriptResults, "recordScriptResults");
136929
137085
  }
@@ -137018,8 +137174,8 @@ var init_test = __esm({
137018
137174
  });
137019
137175
 
137020
137176
  // dist/commands/test-users.js
137021
- import { existsSync as existsSync40, readFileSync as readFileSync44, rmSync as rmSync18 } from "node:fs";
137022
- import { basename as basename11, join as join49 } from "node:path";
137177
+ import { existsSync as existsSync40, readFileSync as readFileSync46, rmSync as rmSync18 } from "node:fs";
137178
+ import { basename as basename12, join as join51 } from "node:path";
137023
137179
  import { randomBytes as randomBytes9 } from "node:crypto";
137024
137180
  async function resolveTarget(projectOpt, originOpt) {
137025
137181
  const root = process.cwd();
@@ -137120,7 +137276,7 @@ function registerTestUsers(program2) {
137120
137276
  const record3 = /* @__PURE__ */ __name((spec, issued, receivedAt) => {
137121
137277
  const times = expiryOf(issued, receivedAt);
137122
137278
  const file = `${spec.name}.state.json`;
137123
- writePrivateFile(join49(dir, file), JSON.stringify(buildStorageState(target.origin, target.host, issued, times), null, 2) + "\n");
137279
+ writePrivateFile(join51(dir, file), JSON.stringify(buildStorageState(target.origin, target.host, issued, times), null, 2) + "\n");
137124
137280
  const actor = {
137125
137281
  name: spec.name,
137126
137282
  user_id: issued.user.id,
@@ -137218,11 +137374,11 @@ function registerTestUsers(program2) {
137218
137374
  if (opts.linkOut) {
137219
137375
  if (!newest.magic_link)
137220
137376
  throw Object.assign(new Error("The newest message has no magic link."), { code: "NO_MAGIC_LINK" });
137221
- const name = basename11(opts.linkOut);
137377
+ const name = basename12(opts.linkOut);
137222
137378
  if (name !== opts.linkOut || !/^[A-Za-z0-9._-]{1,64}$/.test(name))
137223
137379
  throw new Error(`--link-out takes a file name; it is written under ${TEST_STATE_DIR}/.`);
137224
137380
  ensurePrivateDir(stateDir(target.root));
137225
- writePrivateFile(join49(stateDir(target.root), name), newest.magic_link + "\n");
137381
+ writePrivateFile(join51(stateDir(target.root), name), newest.magic_link + "\n");
137226
137382
  linkFile = `${TEST_STATE_DIR}/${name}`;
137227
137383
  }
137228
137384
  const message3 = {
@@ -137293,12 +137449,12 @@ function registerTestUsers(program2) {
137293
137449
  local_state: { removed: localRemoved, kept: manifest.actors.map((actor) => actor.state_file).filter((file) => !localRemoved.includes(file)) },
137294
137450
  actors: manifest.actors.map(({ name, user_id, email: email2, role, created_at }) => ({ name, user_id, email: email2, role, created_at }))
137295
137451
  };
137296
- writePrivateFile(join49(stateDir(target.root), CLEANUP_RECEIPT_FILE), JSON.stringify(receipt, null, 2) + "\n");
137452
+ writePrivateFile(join51(stateDir(target.root), CLEANUP_RECEIPT_FILE), JSON.stringify(receipt, null, 2) + "\n");
137297
137453
  const left = manifest.actors.filter((actor) => !removed.includes(actor.user_id));
137298
137454
  if (left.length)
137299
137455
  writeManifest(target.root, { ...manifest, actors: left, status: "partial" });
137300
137456
  else
137301
- rmSync18(join49(stateDir(target.root), MANIFEST_FILE), { force: true });
137457
+ rmSync18(join51(stateDir(target.root), MANIFEST_FILE), { force: true });
137302
137458
  if (opts.json) {
137303
137459
  printJson(receipt);
137304
137460
  if (left.length)
@@ -137338,7 +137494,7 @@ var init_test_users = __esm({
137338
137494
  });
137339
137495
 
137340
137496
  // dist/commands/support.js
137341
- import { join as join50 } from "node:path";
137497
+ import { join as join52 } from "node:path";
137342
137498
  function commandPaths(program2) {
137343
137499
  const paths = /* @__PURE__ */ new Set();
137344
137500
  const walk2 = /* @__PURE__ */ __name((command, prefix) => {
@@ -137423,7 +137579,7 @@ function emitPacket(packet, opts) {
137423
137579
  if (opts.out) {
137424
137580
  if (!/^[A-Za-z0-9._-]{1,64}$/.test(opts.out))
137425
137581
  throw new Error("--out takes a plain file name in the current folder.");
137426
- writePrivateFile(join50(process.cwd(), opts.out), JSON.stringify(packet, null, 2) + "\n");
137582
+ writePrivateFile(join52(process.cwd(), opts.out), JSON.stringify(packet, null, 2) + "\n");
137427
137583
  }
137428
137584
  if (opts.json) {
137429
137585
  printJson(packet);
@@ -137545,7 +137701,7 @@ var init_skills = __esm({
137545
137701
  });
137546
137702
 
137547
137703
  // dist/commands/ai.js
137548
- import { readFileSync as readFileSync45 } from "node:fs";
137704
+ import { readFileSync as readFileSync47 } from "node:fs";
137549
137705
  function fail4(message3) {
137550
137706
  error(message3);
137551
137707
  process.exit(1);
@@ -137566,7 +137722,7 @@ async function readKey(stdin) {
137566
137722
  if (stdin) {
137567
137723
  if (process.stdin.isTTY)
137568
137724
  fail4("Pipe the key into --stdin, or leave out --stdin to type it into a hidden prompt.");
137569
- raw = readFileSync45(0, "utf8");
137725
+ raw = readFileSync47(0, "utf8");
137570
137726
  } else {
137571
137727
  if (!process.stdin.isTTY)
137572
137728
  fail4("Pass --stdin to read the key from a pipe. Nothing was sent.");
@@ -137713,13 +137869,13 @@ var init_startup_notice = __esm({
137713
137869
  });
137714
137870
 
137715
137871
  // dist/lib/last-run.js
137716
- import { lstatSync as lstatSync6, mkdirSync as mkdirSync22, renameSync as renameSync7, unlinkSync as unlinkSync6, writeFileSync as writeFileSync28 } from "node:fs";
137717
- import { join as join51 } from "node:path";
137872
+ import { lstatSync as lstatSync7, mkdirSync as mkdirSync22, renameSync as renameSync7, unlinkSync as unlinkSync6, writeFileSync as writeFileSync28 } from "node:fs";
137873
+ import { join as join53 } from "node:path";
137718
137874
  function removeStaleRunRecord(dir = cliConfigDir()) {
137719
137875
  for (const name of RUN_RECORD_FILES) {
137720
- const path3 = join51(dir, name);
137876
+ const path3 = join53(dir, name);
137721
137877
  try {
137722
- if (lstatSync6(path3).isDirectory()) {
137878
+ if (lstatSync7(path3).isDirectory()) {
137723
137879
  process.stderr.write(`Could not remove ${path3}: it is a directory, not this CLI's run record. Check it yourself.
137724
137880
  `);
137725
137881
  continue;
@@ -137757,8 +137913,8 @@ function recordLastRun(cliVersion) {
137757
137913
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
137758
137914
  cli_version: cliVersion
137759
137915
  };
137760
- const path3 = join51(dir, "last-run.json");
137761
- const temporary = join51(dir, "last-run.json.tmp");
137916
+ const path3 = join53(dir, "last-run.json");
137917
+ const temporary = join53(dir, "last-run.json.tmp");
137762
137918
  writeFileSync28(temporary, JSON.stringify(record3) + "\n", { mode: 384 });
137763
137919
  renameSync7(temporary, path3);
137764
137920
  } catch {
@@ -137796,8 +137952,8 @@ __export(dist_exports, {
137796
137952
  runCli: () => runCli
137797
137953
  });
137798
137954
  import { spawnSync as spawnSync6 } from "node:child_process";
137799
- import { readFileSync as readFileSync46 } from "node:fs";
137800
- import { join as join52 } from "node:path";
137955
+ import { readFileSync as readFileSync48 } from "node:fs";
137956
+ import { join as join54 } from "node:path";
137801
137957
  async function runCli() {
137802
137958
  const pinned = decidePin(process.cwd(), CLI_VERSION2, process.argv, process.env);
137803
137959
  if (pinned.notice)
@@ -137825,7 +137981,7 @@ async function runCli() {
137825
137981
  process.exit(child.status ?? 1);
137826
137982
  }
137827
137983
  removeStaleRunRecord();
137828
- const pkg = JSON.parse(readFileSync46(join52(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
137984
+ const pkg = JSON.parse(readFileSync48(join54(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
137829
137985
  const program2 = new Command().name(cliInvocation()).description(`CLI for somewhere.cloud. Run ${cliInvocation()} init first, then read generated AGENTS.md: call shapes and access patterns for a typical app; docs are for exceptions.`).version(pkg.version);
137830
137986
  recordLastRun(pkg.version);
137831
137987
  const jsonOutputRequested = process.argv.includes("--json");
@@ -138243,7 +138399,7 @@ var init_screenshot_guard = __esm({
138243
138399
 
138244
138400
  // dist/lib/playwright-fixtures.js
138245
138401
  import { createRequire as createRequire11 } from "node:module";
138246
- import { join as join53 } from "node:path";
138402
+ import { join as join55 } from "node:path";
138247
138403
  function waitOnNavigation(page) {
138248
138404
  async function wait(options2) {
138249
138405
  if (options2?.waitUntil === "commit")
@@ -138295,7 +138451,7 @@ async function previewControlForWorker() {
138295
138451
  function runner() {
138296
138452
  if (loaded)
138297
138453
  return loaded;
138298
- const require6 = createRequire11(join53(process.cwd(), "package.json"));
138454
+ const require6 = createRequire11(join55(process.cwd(), "package.json"));
138299
138455
  let pw;
138300
138456
  try {
138301
138457
  pw = require6("@playwright/test");
@@ -138966,6 +139122,8 @@ var init_testing_jobs = __esm({
138966
139122
 
138967
139123
  // dist/lib/testing-app.js
138968
139124
  import { resolve as resolve26 } from "node:path";
139125
+ import { createRequire as createRequire12 } from "node:module";
139126
+ import { join as join56 } from "node:path";
138969
139127
  async function openTestApp(options2 = {}) {
138970
139128
  const root = resolve26(options2.projectDir ?? process.cwd());
138971
139129
  const projectId = loadProjectConfig(root)?.project_id;
@@ -139003,12 +139161,18 @@ async function openTestApp(options2 = {}) {
139003
139161
  const signInLinks = /* @__PURE__ */ new Map();
139004
139162
  const cleanupSteps = [];
139005
139163
  let closed = false;
139164
+ let lostCreates = 0;
139165
+ let routeWrites = 0;
139006
139166
  const open4 = /* @__PURE__ */ __name(() => {
139007
139167
  if (closed)
139008
139168
  throw new Error("This test app has already been cleaned up.");
139009
139169
  }, "open");
139010
- const add = /* @__PURE__ */ __name((id, email2, session) => {
139011
- const actor = { id, email: email2, session };
139170
+ const results = new Results();
139171
+ const pages = new Pages(root, origin);
139172
+ const add = /* @__PURE__ */ __name((id, email2, session, roles = [], name = `user ${actors.size + 1}`) => {
139173
+ const actor = { name, id, email: email2, roles, session, ...callerOf(session, () => {
139174
+ routeWrites++;
139175
+ }) };
139012
139176
  actors.add(actor);
139013
139177
  managedFileSession(session, root, id);
139014
139178
  return actor;
@@ -139056,49 +139220,205 @@ async function openTestApp(options2 = {}) {
139056
139220
  });
139057
139221
  return id;
139058
139222
  }, "create");
139223
+ const makeUsers = /* @__PURE__ */ __name(async (count2, rolesOf, nameOf2 = () => void 0) => {
139224
+ if (!Number.isInteger(count2) || count2 < 1 || count2 > 25)
139225
+ throw new Error("Choose 1 to 25 test users.");
139226
+ const since = Date.now();
139227
+ if (control) {
139228
+ const out2 = [];
139229
+ for (let i = 0; i < count2; i++) {
139230
+ if (rolesOf(i).length)
139231
+ throw new Error("Roles are granted in production test runs only. In a preview, your app grants roles through its own server code.");
139232
+ const user = await control.createManagedUser();
139233
+ ids.add(user.id);
139234
+ rememberSecrets(user.password);
139235
+ const session = new UserSession(origin, { target, storageState: emptyState });
139236
+ const login = await session.post("/api/auth/login", { email: user.email, password: user.password });
139237
+ if (!login.ok)
139238
+ throw new Error(`Could not sign in preview test user ${user.id} (HTTP ${login.status}).`);
139239
+ managedRecipients.set(user.email.toLowerCase(), { id: user.id, since });
139240
+ out2.push(add(user.id, user.email, session, [], nameOf2(i)));
139241
+ }
139242
+ return out2;
139243
+ }
139244
+ const batches = [];
139245
+ for (let left = count2; left > 0; left -= MAX_PER_CREATE)
139246
+ batches.push(Math.min(MAX_PER_CREATE, left));
139247
+ const settled = await Promise.allSettled(batches.map((size) => createTestIdentities(client, projectId, "user", size, "script", { sweep: false })));
139248
+ const issued = [];
139249
+ let failure2;
139250
+ for (const [index, result] of settled.entries()) {
139251
+ if (result.status === "fulfilled") {
139252
+ for (const identity of result.value.issued)
139253
+ issued.push({ identity, receivedAt: result.value.receivedAt });
139254
+ continue;
139255
+ }
139256
+ failure2 ??= result.reason;
139257
+ const partial2 = result.reason;
139258
+ const named2 = (partial2?.createdIds ?? []).filter((id) => typeof id === "string");
139259
+ for (const id of named2)
139260
+ ids.add(id);
139261
+ const refused = result.reason instanceof CliApiError && result.reason.statusCode >= 400 && result.reason.statusCode < 500;
139262
+ if (!refused && named2.length < batches[index])
139263
+ lostCreates++;
139264
+ }
139265
+ for (const { identity } of issued) {
139266
+ ids.add(identity.user.id);
139267
+ rememberSecrets(identity.access_token, identity.refresh_token);
139268
+ }
139269
+ if (failure2 instanceof CliApiError && failure2.code === "TEST_USERS_CAP_REACHED") {
139270
+ throw new Error(`This app already has 25 live test users, from other or unfinished runs, so none were made. A test user stops counting 24 hours after it was made. To make room now, list them with somewhere api GET "/v1/auth/test-users?project_id=${projectId}" and delete the ones no run is using: somewhere api DELETE /v1/auth/test-users -d '{"project_id":"${projectId}","ids":["<id>"]}'.`);
139271
+ }
139272
+ if (failure2)
139273
+ throw new Error(scrub(failure2 instanceof Error ? failure2.message : String(failure2)));
139274
+ const out = issued.map(({ identity, receivedAt }, i) => {
139275
+ const state = buildStorageState(origin, new URL(origin).hostname, identity, expiryOf(identity, receivedAt));
139276
+ managedRecipients.set(identity.user.email.toLowerCase(), { id: identity.user.id, since });
139277
+ return add(identity.user.id, identity.user.email, new UserSession(origin, { target, storageState: state }), rolesOf(i), nameOf2(i));
139278
+ });
139279
+ await Promise.all(out.flatMap((actor) => actor.roles.map(async (role) => {
139280
+ try {
139281
+ await client.call("POST", "/auth/app-roles/grant", { project_id: projectId, user_id: actor.id, role });
139282
+ } catch (error3) {
139283
+ throw new Error(scrub(`Could not give test user ${actor.id} the role "${role}" (declare it in db/schema.ts appRoles with assignedBy: 'server'): ${describeCallError(error3)}`));
139284
+ }
139285
+ })));
139286
+ return out;
139287
+ }, "makeUsers");
139288
+ let attempt;
139289
+ const attemptCleanup = /* @__PURE__ */ __name(async () => {
139290
+ signInLinks.clear();
139291
+ const remains = [];
139292
+ try {
139293
+ await pages.close();
139294
+ } catch {
139295
+ remains.push("the test browser");
139296
+ }
139297
+ for (const step2 of [...cleanupSteps].reverse()) {
139298
+ try {
139299
+ await step2.action();
139300
+ cleanupSteps.splice(cleanupSteps.indexOf(step2), 1);
139301
+ } catch {
139302
+ remains.push(step2.label);
139303
+ }
139304
+ }
139305
+ if (invitees.size) {
139306
+ try {
139307
+ const result = await inbox2.deleteSignups([...invitees], { groups: false });
139308
+ for (const id of [...invitees])
139309
+ if (!result.kept.has(id))
139310
+ invitees.delete(id);
139311
+ for (const [id, why] of result.kept)
139312
+ remains.push(`invited test user ${id} (${why})`);
139313
+ } catch (error3) {
139314
+ remains.push(`invited test users ${[...invitees].join(", ")} (${describeCallError(error3)})`);
139315
+ }
139316
+ }
139317
+ if (control) {
139318
+ for (const id of [...ids]) {
139319
+ const reason = await control.deleteManagedUser(id);
139320
+ if (reason)
139321
+ remains.push(`test user ${id} (${reason})`);
139322
+ else
139323
+ ids.delete(id);
139324
+ }
139325
+ if (!ids.size && !remains.length)
139326
+ await control.close();
139327
+ } else if (ids.size) {
139328
+ try {
139329
+ await client.call("DELETE", "/auth/test-users", { project_id: projectId, ids: [...ids] });
139330
+ const { identities } = await client.call("GET", "/auth/test-users", void 0, { project_id: projectId });
139331
+ const left = new Set(identities.map((user) => user.id));
139332
+ for (const id of [...ids])
139333
+ if (left.has(id))
139334
+ remains.push(`test user ${id}`);
139335
+ else
139336
+ ids.delete(id);
139337
+ } catch (error3) {
139338
+ remains.push(`test users ${[...ids].join(", ")} (${describeCallError(error3)})`);
139339
+ }
139340
+ }
139341
+ if (lostCreates)
139342
+ remains.push(`test users from ${lostCreates} create request(s) whose answer was lost (GET /v1/auth/test-users lists them)`);
139343
+ return remains.map(scrub);
139344
+ }, "attemptCleanup");
139345
+ const cleanup = /* @__PURE__ */ __name(async () => {
139346
+ closed = true;
139347
+ const remains = await (attempt ??= attemptCleanup().finally(() => {
139348
+ attempt = void 0;
139349
+ }));
139350
+ if (remains.length)
139351
+ throw new Error(`Could not confirm cleanup of ${remains.join(", ")}.`);
139352
+ }, "cleanup");
139353
+ const anonymous = new UserSession(origin, { target, storageState: emptyState });
139354
+ const signedOut = callerOf(anonymous, () => {
139355
+ routeWrites++;
139356
+ });
139357
+ const nameOf = /* @__PURE__ */ __name((caller) => caller === signedOut ? "signed out" : [...actors].find((actor) => actor === caller)?.name ?? "caller", "nameOf");
139059
139358
  return {
139060
139359
  origin,
139061
- anonymous: new UserSession(origin, { target, storageState: emptyState }),
139062
- async users(count2) {
139360
+ anonymous,
139361
+ signedOut,
139362
+ check: /* @__PURE__ */ __name((label, ok, detail, options3) => results.check(label, ok, detail, options3), "check"),
139363
+ expect: /* @__PURE__ */ __name((reply, status, label, options3) => results.expect(reply, status, label, options3), "expect"),
139364
+ async refuse(who, requests, options3 = {}) {
139063
139365
  open4();
139064
- if (!Number.isInteger(count2) || count2 < 1 || count2 > 25)
139065
- throw new Error("Choose 1 to 25 test users.");
139066
- const since = Date.now();
139067
- if (control) {
139068
- const out2 = [];
139069
- for (let i = 0; i < count2; i++) {
139070
- const user = await control.createManagedUser();
139071
- ids.add(user.id);
139072
- const session = new UserSession(origin, { target, storageState: emptyState });
139073
- const login = await session.post("/api/auth/login", { email: user.email, password: user.password });
139074
- if (!login.ok)
139075
- throw new Error(`Could not sign in preview test user ${user.id} (HTTP ${login.status}).`);
139076
- managedRecipients.set(user.email.toLowerCase(), { id: user.id, since });
139077
- out2.push(add(user.id, user.email, session));
139078
- }
139079
- return out2;
139080
- }
139081
- const out = [];
139082
- try {
139083
- for (let offset = 0; offset < count2; offset += MAX_PER_CREATE) {
139084
- const { issued, receivedAt } = await createTestIdentities(client, projectId, "user", Math.min(MAX_PER_CREATE, count2 - offset), "script");
139085
- for (const identity of issued)
139086
- ids.add(identity.user.id);
139087
- for (const identity of issued) {
139088
- const state = buildStorageState(origin, new URL(origin).hostname, identity, expiryOf(identity, receivedAt));
139089
- managedRecipients.set(identity.user.email.toLowerCase(), { id: identity.user.id, since });
139090
- out.push(add(identity.user.id, identity.user.email, new UserSession(origin, { target, storageState: state })));
139091
- }
139366
+ const callers = Array.isArray(who) ? who : [who];
139367
+ const allowed = options3.status === void 0 ? [401, 403, 404] : typeof options3.status === "number" ? [options3.status] : options3.status;
139368
+ const lacks = options3.lacks === void 0 ? [] : typeof options3.lacks === "string" ? [options3.lacks] : options3.lacks;
139369
+ const label = options3.label ?? "refused";
139370
+ const pairs = callers.flatMap((caller) => requests.map(([method, path3, body]) => ({ caller, method, path: path3, body })));
139371
+ const replies = await Promise.allSettled(pairs.map(({ caller, method, path: path3, body }) => {
139372
+ const call = caller[method.toLowerCase()];
139373
+ return call(path3, body);
139374
+ }));
139375
+ let all = true;
139376
+ replies.forEach((settled, i) => {
139377
+ const { caller, method, path: path3 } = pairs[i];
139378
+ const line = `${label}: ${nameOf(caller)} ${method} ${path3}`;
139379
+ if (settled.status === "rejected") {
139380
+ all = results.check(line, false, settled.reason) && all;
139381
+ return;
139092
139382
  }
139093
- return out;
139094
- } catch (error3) {
139095
- if (error3 && typeof error3 === "object" && "createdIds" in error3 && Array.isArray(error3.createdIds)) {
139096
- for (const id of error3.createdIds)
139097
- if (typeof id === "string")
139098
- ids.add(id);
139383
+ const reply = settled.value;
139384
+ const leaked = lacks.findIndex((text) => text && reply.text.includes(text));
139385
+ if (!allowed.includes(reply.status)) {
139386
+ results.expect(reply, allowed, line);
139387
+ all = false;
139388
+ return;
139099
139389
  }
139100
- throw error3;
139390
+ if (!results.check(line, leaked < 0, `answered ${reply.status} but contains lacks[${leaked}]`))
139391
+ all = false;
139392
+ });
139393
+ return all;
139394
+ },
139395
+ async page(user, path3 = "/") {
139396
+ open4();
139397
+ if (user !== null && !actors.has(user))
139398
+ throw new Error("Choose a user created by this test app, or null for signed out.");
139399
+ return pages.open(user ? await user.session.storageState() : emptyState, path3);
139400
+ },
139401
+ async done() {
139402
+ let left;
139403
+ try {
139404
+ await cleanup();
139405
+ } catch (error3) {
139406
+ left = error3 instanceof Error ? error3.message : String(error3);
139101
139407
  }
139408
+ const rows = routeWrites ? " Rows your app's routes created during the run stay in its tables unless removed in app.onCleanup()." : "";
139409
+ console.log(`${results.passed} passed, ${results.failed} failed${left ? `. ${left}` : ". Test users deleted."}${rows}`);
139410
+ process.exitCode = left ? 2 : results.failed ? 1 : 0;
139411
+ },
139412
+ async users(...args) {
139413
+ open4();
139414
+ if (typeof args[0] === "number")
139415
+ return makeUsers(args[0], () => []);
139416
+ const spec = typeof args[0] === "object" && args[0] !== null ? args[0] : Object.fromEntries(args.map((name) => [String(name), {}]));
139417
+ const names = Object.keys(spec);
139418
+ if (!names.length || new Set(names).size !== names.length)
139419
+ throw new Error("Name each test user once, for example users('owner', 'member', 'outsider').");
139420
+ const made = await makeUsers(names.length, (i) => spec[names[i]].roles ?? [], (i) => names[i]);
139421
+ return Object.fromEntries(names.map((name, i) => [name, made[i]]));
139102
139422
  },
139103
139423
  inboxAddress(name = "invite") {
139104
139424
  open4();
@@ -139164,47 +139484,70 @@ async function openTestApp(options2 = {}) {
139164
139484
  open4();
139165
139485
  return runTestJob(target, job, opts, setup?.credential);
139166
139486
  },
139167
- async cleanup() {
139168
- if (closed)
139169
- return;
139170
- closed = true;
139171
- signInLinks.clear();
139172
- const remains = [];
139173
- for (const { label, action } of cleanupSteps.reverse()) {
139174
- try {
139175
- await action();
139176
- } catch {
139177
- remains.push(label);
139178
- }
139179
- }
139180
- if (invitees.size) {
139181
- const result = await inbox2.deleteSignups([...invitees]);
139182
- for (const [id, why] of result.kept)
139183
- remains.push(`invited test user ${id} (${why})`);
139184
- }
139185
- if (control) {
139186
- for (const id of ids) {
139187
- const reason = await control.deleteManagedUser(id);
139188
- if (reason)
139189
- remains.push(`test user ${id} (${reason})`);
139190
- }
139191
- await control.close();
139192
- } else if (ids.size) {
139193
- try {
139194
- await client.call("DELETE", "/auth/test-users", { project_id: projectId, ids: [...ids] });
139195
- const { identities } = await client.call("GET", "/auth/test-users", void 0, { project_id: projectId });
139196
- for (const user of identities)
139197
- if (ids.has(user.id))
139198
- remains.push(`test user ${user.id}`);
139199
- } catch (error3) {
139200
- remains.push(`test users ${[...ids].join(", ")} (${describeCallError(error3)})`);
139201
- }
139202
- }
139203
- if (remains.length)
139204
- throw new Error(`Could not confirm cleanup of ${remains.join(", ")}.`);
139205
- }
139487
+ cleanup
139488
+ };
139489
+ }
139490
+ async function readReply(response) {
139491
+ const text = await response.text();
139492
+ let body = null;
139493
+ try {
139494
+ body = text ? JSON.parse(text) : null;
139495
+ } catch {
139496
+ body = null;
139497
+ }
139498
+ return {
139499
+ status: response.status,
139500
+ ok: response.ok,
139501
+ body,
139502
+ text,
139503
+ requestId: response.headers.get("x-request-id") ?? response.headers.get("cf-ray")
139504
+ };
139505
+ }
139506
+ function callerOf(session, onWrite = () => {
139507
+ }) {
139508
+ const send = /* @__PURE__ */ __name(async (method, path3, body) => {
139509
+ const reply = await readReply(await session.request(path3, body === void 0 ? { method } : { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
139510
+ if (method !== "GET" && reply.ok)
139511
+ onWrite();
139512
+ return reply;
139513
+ }, "send");
139514
+ return {
139515
+ get: /* @__PURE__ */ __name((path3) => send("GET", path3), "get"),
139516
+ post: /* @__PURE__ */ __name((path3, body) => send("POST", path3, body ?? {}), "post"),
139517
+ put: /* @__PURE__ */ __name((path3, body) => send("PUT", path3, body ?? {}), "put"),
139518
+ patch: /* @__PURE__ */ __name((path3, body) => send("PATCH", path3, body ?? {}), "patch"),
139519
+ delete: /* @__PURE__ */ __name((path3, body) => send("DELETE", path3, body), "delete"),
139520
+ data: /* @__PURE__ */ __name(async (table2, request2) => {
139521
+ const reply = await readReply(await session.data(table2, request2));
139522
+ if (request2.operation !== "list" && request2.operation !== "get" && reply.ok)
139523
+ onWrite();
139524
+ return reply;
139525
+ }, "data")
139206
139526
  };
139207
139527
  }
139528
+ function shown(value, depth = 0) {
139529
+ if (Array.isArray(value))
139530
+ return depth > 6 ? "[\u2026]" : value.map((item) => shown(item, depth + 1));
139531
+ if (value && typeof value === "object") {
139532
+ if (depth > 6)
139533
+ return "{\u2026}";
139534
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, SECRET_KEY.test(key) ? "[hidden]" : shown(item, depth + 1)]));
139535
+ }
139536
+ return value;
139537
+ }
139538
+ function showBody(reply) {
139539
+ return cut(scrub(reply.body === null ? reply.text : JSON.stringify(shown(reply.body))), 2e3);
139540
+ }
139541
+ function isReply(value) {
139542
+ return typeof value.status === "number" && typeof value.text === "string";
139543
+ }
139544
+ function replySummary(reply) {
139545
+ const body = reply.body && typeof reply.body === "object" ? reply.body : {};
139546
+ const code = typeof body.error === "string" ? body.error : typeof body.code === "string" ? body.code : void 0;
139547
+ const message3 = typeof body.message === "string" ? body.message : void 0;
139548
+ return `${reply.status}${reply.requestId ? ` (request ${reply.requestId})` : ""}${code ? ` ${code}` : ""}${message3 ? `: ${cut(message3, 200)}` : ""}`;
139549
+ }
139550
+ var SECRET_KEY, cut, Results, Pages;
139208
139551
  var init_testing_app = __esm({
139209
139552
  "dist/lib/testing-app.js"() {
139210
139553
  "use strict";
@@ -139218,7 +139561,97 @@ var init_testing_app = __esm({
139218
139561
  init_test_response_capture();
139219
139562
  init_testing_jobs();
139220
139563
  init_test_session();
139564
+ init_test_diagnostics();
139565
+ init_client();
139221
139566
  __name(openTestApp, "openTestApp");
139567
+ __name(readReply, "readReply");
139568
+ __name(callerOf, "callerOf");
139569
+ SECRET_KEY = /token|secret|password|passcode|cookie|authorization|session|api[_-]?key|signature|otp|code_verifier|magic|credential/i;
139570
+ __name(shown, "shown");
139571
+ cut = /* @__PURE__ */ __name((text, max) => text.length > max ? text.slice(0, max) + "\u2026" : text, "cut");
139572
+ __name(showBody, "showBody");
139573
+ Results = class {
139574
+ static {
139575
+ __name(this, "Results");
139576
+ }
139577
+ passed = 0;
139578
+ failed = 0;
139579
+ line(label, ok, detail) {
139580
+ if (ok) {
139581
+ this.passed++;
139582
+ console.log(`PASS ${scrub(label)}`);
139583
+ return true;
139584
+ }
139585
+ this.failed++;
139586
+ console.log(`FAIL ${scrub(label)}${detail ? ` \u2014 ${cut(scrub(detail), 600)}` : ""}`);
139587
+ return false;
139588
+ }
139589
+ check(label, ok, detail, options2 = {}) {
139590
+ if (ok)
139591
+ return this.line(label, true);
139592
+ let text;
139593
+ if (detail === void 0 || detail === null)
139594
+ text = void 0;
139595
+ else if (detail instanceof Error)
139596
+ text = detail.message;
139597
+ else if (typeof detail !== "object")
139598
+ text = String(detail);
139599
+ else if (isReply(detail))
139600
+ text = replySummary(detail) + (options2.show ? `: ${showBody(detail)}` : "");
139601
+ else
139602
+ text = options2.show ? JSON.stringify(shown(detail)) : "details hidden; pass { show: true } to print them";
139603
+ return this.line(label, false, text);
139604
+ }
139605
+ expect(reply, status, label, options2 = {}) {
139606
+ const wanted = typeof status === "number" ? [status] : status;
139607
+ const ok = wanted.includes(reply.status);
139608
+ this.line(label, ok, ok ? void 0 : `expected ${wanted.join(" or ")}, got ${replySummary(reply)}${options2.show ? `: ${showBody(reply)}` : ""}`);
139609
+ return reply.body;
139610
+ }
139611
+ };
139612
+ __name(isReply, "isReply");
139613
+ __name(replySummary, "replySummary");
139614
+ Pages = class {
139615
+ static {
139616
+ __name(this, "Pages");
139617
+ }
139618
+ root;
139619
+ origin;
139620
+ browser;
139621
+ constructor(root, origin) {
139622
+ this.root = root;
139623
+ this.origin = origin;
139624
+ }
139625
+ async open(state, path3) {
139626
+ this.browser ??= (() => {
139627
+ const require6 = createRequire12(join56(this.root, "package.json"));
139628
+ let pw;
139629
+ try {
139630
+ pw = require6("playwright");
139631
+ } catch {
139632
+ try {
139633
+ pw = require6("@playwright/test");
139634
+ } catch {
139635
+ throw new Error("app.page() uses Playwright from this folder: npm install -D playwright && npx playwright install chromium");
139636
+ }
139637
+ }
139638
+ return pw.chromium.launch();
139639
+ })();
139640
+ const context = await (await this.browser).newContext({ baseURL: this.origin, storageState: state });
139641
+ const page = await context.newPage();
139642
+ await page.goto(path3);
139643
+ if (await page.locator("html[data-sw-auth]").count()) {
139644
+ await page.locator('html[data-sw-auth="checking"]').waitFor({ state: "detached", timeout: 1e4 });
139645
+ }
139646
+ return page;
139647
+ }
139648
+ async close() {
139649
+ const browser = this.browser;
139650
+ this.browser = void 0;
139651
+ if (browser)
139652
+ await (await browser).close();
139653
+ }
139654
+ };
139222
139655
  }
139223
139656
  });
139224
139657