@somewhere-cloud/cli 0.38.182 → 0.38.184

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.
@@ -20315,7 +20315,7 @@ var require_snapshot_recorder = __commonJS({
20315
20315
  "node_modules/undici/lib/mock/snapshot-recorder.js"(exports, module) {
20316
20316
  "use strict";
20317
20317
  var { writeFile: writeFile2, readFile: readFile3, mkdir } = __require("node:fs/promises");
20318
- var { dirname: dirname17, resolve: resolve27 } = __require("node:path");
20318
+ var { dirname: dirname18, resolve: resolve27 } = __require("node:path");
20319
20319
  var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = __require("node:timers");
20320
20320
  var { InvalidArgumentError: InvalidArgumentError2, UndiciError } = require_errors();
20321
20321
  var { setHeader } = require_util();
@@ -20571,7 +20571,7 @@ var require_snapshot_recorder = __commonJS({
20571
20571
  throw new InvalidArgumentError2("Snapshot path is required");
20572
20572
  }
20573
20573
  const resolvedPath = resolve27(path3);
20574
- await mkdir(dirname17(resolvedPath), { recursive: true });
20574
+ await mkdir(dirname18(resolvedPath), { recursive: true });
20575
20575
  const data2 = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
20576
20576
  hash,
20577
20577
  snapshot
@@ -33775,10 +33775,31 @@ var init_package_root = __esm({
33775
33775
  }
33776
33776
  });
33777
33777
 
33778
+ // dist/lib/version.js
33779
+ import { readFileSync as readFileSync3 } from "node:fs";
33780
+ import { join as join3 } from "node:path";
33781
+ function readVersion() {
33782
+ try {
33783
+ const pkg = JSON.parse(readFileSync3(join3(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
33784
+ return typeof pkg.version === "string" ? pkg.version : "unknown";
33785
+ } catch {
33786
+ return "unknown";
33787
+ }
33788
+ }
33789
+ var CLI_VERSION2;
33790
+ var init_version = __esm({
33791
+ "dist/lib/version.js"() {
33792
+ "use strict";
33793
+ init_package_root();
33794
+ __name(readVersion, "readVersion");
33795
+ CLI_VERSION2 = readVersion();
33796
+ }
33797
+ });
33798
+
33778
33799
  // dist/lib/platform-contract.js
33779
- import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
33800
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
33780
33801
  import { createRequire } from "node:module";
33781
- import { join as join3 } from "node:path";
33802
+ import { join as join4 } from "node:path";
33782
33803
  import { debuglog } from "node:util";
33783
33804
  function cliConsumerContract() {
33784
33805
  return vendor().CONSUMER_CONTRACT ?? null;
@@ -33787,8 +33808,10 @@ function readSeenFile() {
33787
33808
  if (!existsSync3(seenPath()))
33788
33809
  return { origins: {} };
33789
33810
  try {
33790
- const value = JSON.parse(readFileSync3(seenPath(), "utf8"));
33791
- return value && typeof value === "object" && value.origins && typeof value.origins === "object" ? { origins: value.origins } : { origins: {} };
33811
+ const value = JSON.parse(readFileSync4(seenPath(), "utf8"));
33812
+ if (!value || typeof value !== "object" || !value.origins || typeof value.origins !== "object")
33813
+ return { origins: {} };
33814
+ return { origins: value.origins, warned: value.warned && typeof value.warned === "object" ? value.warned : {} };
33792
33815
  } catch {
33793
33816
  return { origins: {} };
33794
33817
  }
@@ -33806,10 +33829,13 @@ function recordPlatformContract(headers, url3, now2 = Date.now()) {
33806
33829
  const file = readSeenFile();
33807
33830
  const seen2 = { ...announced, seen_at: now2, origin };
33808
33831
  file.origins[origin] = seen2;
33832
+ writeSeenFile(file);
33833
+ observeContract(contractVerdict(seen2, now2), now2);
33834
+ return seen2;
33835
+ }
33836
+ function writeSeenFile(file) {
33809
33837
  mkdirSync3(cliConfigDir(), { recursive: true, mode: 448 });
33810
33838
  writeFileSync3(seenPath(), JSON.stringify(file, null, 2) + "\n", { mode: 384 });
33811
- observeContract(contractVerdict(seen2, now2));
33812
- return seen2;
33813
33839
  }
33814
33840
  function seenPlatformContract(apiBase) {
33815
33841
  let origin;
@@ -33827,7 +33853,7 @@ function contractVerdict(platform2, now2) {
33827
33853
  }
33828
33854
  function platformContractVerdict(apiBase, now2 = Date.now()) {
33829
33855
  const verdict = contractVerdict(seenPlatformContract(apiBase), now2);
33830
- observeContract(verdict);
33856
+ observeContract(verdict, now2);
33831
33857
  return verdict;
33832
33858
  }
33833
33859
  function describePlatformContract(verdict) {
@@ -33846,26 +33872,34 @@ function configureContractWarning(command, apiBase) {
33846
33872
  } catch {
33847
33873
  }
33848
33874
  }
33849
- function observeContract(verdict) {
33875
+ function observeContract(verdict, now2) {
33850
33876
  debug("%s", describePlatformContract(verdict));
33851
33877
  if (warned || !warningOrigin || verdict.platform?.origin !== warningOrigin || verdict.status !== "outdated")
33852
33878
  return;
33853
33879
  warned = true;
33854
- console.error("Warning: Your Somewhere CLI is behind the platform. Run npx -y @somewhere-cloud/cli@latest upgrade in this project.");
33880
+ const file = readSeenFile();
33881
+ const last = file.warned?.[warningOrigin];
33882
+ if (typeof last === "number" && now2 - last < CONTRACT_WARNING_INTERVAL_MS)
33883
+ return;
33884
+ file.warned = { ...file.warned, [warningOrigin]: now2 };
33885
+ writeSeenFile(file);
33886
+ console.error(CONTRACT_WARNING);
33855
33887
  }
33856
- var require2, CONTRACT_HEADER, vendor, seenPath, debug, warningOrigin, warned;
33888
+ var require2, CONTRACT_HEADER, vendor, seenPath, debug, warningOrigin, warned, CONTRACT_WARNING_INTERVAL_MS, CONTRACT_WARNING;
33857
33889
  var init_platform_contract = __esm({
33858
33890
  "dist/lib/platform-contract.js"() {
33859
33891
  "use strict";
33860
33892
  init_package_root();
33861
33893
  init_config();
33894
+ init_version();
33862
33895
  require2 = createRequire(CLI_PACKAGE_ROOT);
33863
33896
  CONTRACT_HEADER = "x-sw-consumer-contract";
33864
33897
  vendor = /* @__PURE__ */ __name(() => require2("./runtime/declared-data.cjs"), "vendor");
33865
- seenPath = /* @__PURE__ */ __name(() => join3(cliConfigDir(), "platform-contract.json"), "seenPath");
33898
+ seenPath = /* @__PURE__ */ __name(() => join4(cliConfigDir(), "platform-contract.json"), "seenPath");
33866
33899
  __name(cliConsumerContract, "cliConsumerContract");
33867
33900
  __name(readSeenFile, "readSeenFile");
33868
33901
  __name(recordPlatformContract, "recordPlatformContract");
33902
+ __name(writeSeenFile, "writeSeenFile");
33869
33903
  __name(seenPlatformContract, "seenPlatformContract");
33870
33904
  __name(contractVerdict, "contractVerdict");
33871
33905
  __name(platformContractVerdict, "platformContractVerdict");
@@ -33874,6 +33908,8 @@ var init_platform_contract = __esm({
33874
33908
  debug = debuglog("somewhere-contract");
33875
33909
  warned = false;
33876
33910
  __name(configureContractWarning, "configureContractWarning");
33911
+ CONTRACT_WARNING_INTERVAL_MS = 12 * 60 * 60 * 1e3;
33912
+ CONTRACT_WARNING = `This Somewhere CLI (${CLI_VERSION2}) is older than the platform, so its local checks may miss newer rules. To update this project, run npx -y @somewhere-cloud/cli@latest upgrade here. Shown once every 12 hours.`;
33877
33913
  __name(observeContract, "observeContract");
33878
33914
  }
33879
33915
  });
@@ -39936,9 +39972,9 @@ var require_prompts = __commonJS({
39936
39972
  $2.date = (args) => toPrompt("DatePrompt", args);
39937
39973
  $2.confirm = (args) => toPrompt("ConfirmPrompt", args);
39938
39974
  $2.list = (args) => {
39939
- const sep2 = args.separator || ",";
39975
+ const sep3 = args.separator || ",";
39940
39976
  return toPrompt("TextPrompt", args, {
39941
- onSubmit: /* @__PURE__ */ __name((str2) => str2.split(sep2).map((s3) => s3.trim()), "onSubmit")
39977
+ onSubmit: /* @__PURE__ */ __name((str2) => str2.split(sep3).map((s3) => s3.trim()), "onSubmit")
39942
39978
  });
39943
39979
  };
39944
39980
  $2.toggle = (args) => toPrompt("TogglePrompt", args);
@@ -42299,9 +42335,9 @@ var require_prompts2 = __commonJS({
42299
42335
  $2.date = (args) => toPrompt("DatePrompt", args);
42300
42336
  $2.confirm = (args) => toPrompt("ConfirmPrompt", args);
42301
42337
  $2.list = (args) => {
42302
- const sep2 = args.separator || ",";
42338
+ const sep3 = args.separator || ",";
42303
42339
  return toPrompt("TextPrompt", args, {
42304
- onSubmit: /* @__PURE__ */ __name((str2) => str2.split(sep2).map((s3) => s3.trim()), "onSubmit")
42340
+ onSubmit: /* @__PURE__ */ __name((str2) => str2.split(sep3).map((s3) => s3.trim()), "onSubmit")
42305
42341
  });
42306
42342
  };
42307
42343
  $2.toggle = (args) => toPrompt("TogglePrompt", args);
@@ -42548,10 +42584,10 @@ var init_spinner = __esm({
42548
42584
  });
42549
42585
 
42550
42586
  // dist/lib/device.js
42551
- import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
42587
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "node:fs";
42552
42588
  import { hostname } from "node:os";
42553
42589
  import { randomUUID as randomUUID3 } from "node:crypto";
42554
- import { join as join4 } from "node:path";
42590
+ import { join as join5 } from "node:path";
42555
42591
  function ensureDir2() {
42556
42592
  if (!existsSync4(CONFIG_DIR2))
42557
42593
  mkdirSync4(CONFIG_DIR2, { recursive: true });
@@ -42560,7 +42596,7 @@ function loadDevice() {
42560
42596
  if (!existsSync4(DEVICE_PATH))
42561
42597
  return null;
42562
42598
  try {
42563
- const parsed = JSON.parse(readFileSync4(DEVICE_PATH, "utf-8"));
42599
+ const parsed = JSON.parse(readFileSync5(DEVICE_PATH, "utf-8"));
42564
42600
  if (typeof parsed.id !== "string" || parsed.id.length < 8)
42565
42601
  return null;
42566
42602
  return parsed;
@@ -42595,7 +42631,7 @@ var init_device = __esm({
42595
42631
  "use strict";
42596
42632
  init_config();
42597
42633
  CONFIG_DIR2 = cliConfigDir();
42598
- DEVICE_PATH = join4(CONFIG_DIR2, "device.json");
42634
+ DEVICE_PATH = join5(CONFIG_DIR2, "device.json");
42599
42635
  __name(ensureDir2, "ensureDir");
42600
42636
  __name(loadDevice, "loadDevice");
42601
42637
  __name(saveDevice, "saveDevice");
@@ -42761,27 +42797,6 @@ var init_auth = __esm({
42761
42797
  }
42762
42798
  });
42763
42799
 
42764
- // dist/lib/version.js
42765
- import { readFileSync as readFileSync5 } from "node:fs";
42766
- import { join as join5 } from "node:path";
42767
- function readVersion() {
42768
- try {
42769
- const pkg = JSON.parse(readFileSync5(join5(CLI_PACKAGE_ROOT, "package.json"), "utf8"));
42770
- return typeof pkg.version === "string" ? pkg.version : "unknown";
42771
- } catch {
42772
- return "unknown";
42773
- }
42774
- }
42775
- var CLI_VERSION2;
42776
- var init_version = __esm({
42777
- "dist/lib/version.js"() {
42778
- "use strict";
42779
- init_package_root();
42780
- __name(readVersion, "readVersion");
42781
- CLI_VERSION2 = readVersion();
42782
- }
42783
- });
42784
-
42785
42800
  // dist/lib/device-login.js
42786
42801
  import { createHash, randomBytes, randomInt } from "node:crypto";
42787
42802
  import { arch, hostname as hostname2, platform, release } from "node:os";
@@ -44290,6 +44305,8 @@ Use \`client.intake\` for public submissions to a private parent row. See
44290
44305
  - Add React pages where your app handles navigation. To serve a dynamic endpoint such as \`/api/notes/:id\`, create \`api/notes/[id].ts\`. A root \`[...path].ts\` handles document routes, including \`/\`. Underscore-prefixed files are import-only helpers.
44291
44306
  - JSON routes use \`sw.endpoint({ auth, body, rateLimit, handler })\`. Set \`auth\` to \`'required'\`, \`'optional'\` or \`'none'\`. Use a limit like \`'30/minute'\`. Read route parameters from the handler's \`params\`. Use a default handler or named HTTP method exports. For streaming, webhooks or custom responses, use a bare \`(req, sw)\` handler and \`sw.params\`. See \`somewhere docs functions\`.
44292
44307
  - Keep the SDK auth handler at \`api/auth/[...path].ts\` when your app uses sign-in. Gate private UI on auth state. Password sign-up starts unverified, and signed-in unverified users pass \`auth: 'required'\`. See \`somewhere docs auth-client\`.
44308
+ - Mail from the app's built-in address reaches only the owner and app users who verified their email and signed in. Password sign-up starts unverified: if the app emails its users (confirmations, reminders), keep the starter's "Verify your email" step, or verify your own sender domain. See \`somewhere docs sw.email\`.
44309
+ - When users must see each other's changes without reloading (a queue, chat or status board), do not poll. Return the list through \`sw.rooms.live\` and follow it in the page with \`watchLive\`. See \`somewhere docs live --section realtime-live-updates-two-users-see-the-same-change\`.
44293
44310
  - Render a view when the reads it depends on finish. Keep inputs disabled until their initial data and identity are ready, and preserve edits when a late response arrives.
44294
44311
  - Browser requests use same-origin cookies. For scripted writes with a cookie session, send the app's origin in the \`Origin\` header. Use the CLI test helper to send data endpoint calls with the deployed contract digest. For an update, use \`data(table, { operation: 'update', id, values: { title } })\`.
44295
44312
 
@@ -44306,7 +44323,7 @@ Prove the brief in \`tests/starter.mjs\` (\`npm test\`, from the app folder, aft
44306
44323
 
44307
44324
  If the folder already has Playwright tests, keep running them; put new checks in \`tests/starter.mjs\`. Tests that write change rows in the live app: for an app with real customers, test on a preview (\`somewhere preview\`, then \`openTestApp({ preview: true })\`). After every deploy the platform runs its own smoke check, plus any check lists saved in \`checks/\`; \`somewhere test\` shows the result.
44308
44325
 
44309
- 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\`.
44326
+ Deploy with \`somewhere deploy\`; there is no build step, and a routine edit needs no separate check first. A deploy type-checks locally when dependencies are installed and runs the platform's compile, schema and secret checks; a refusal from those checks changes nothing, so fix what it names and deploy again. If a later step fails, the answer says which version is live and whether the database changed; act on that. Run \`somewhere deploy --dry-run\` first when a change removes a table, column, file or handler, or widens who can read existing rows: it lists those effects before they happen. 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\`.
44310
44327
 
44311
44328
  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.
44312
44329
  `;
@@ -44719,7 +44736,6 @@ To share your own rows with specific people, read:
44719
44736
 
44720
44737
  \`\`\`sh
44721
44738
  somewhere typecheck
44722
- somewhere deploy-check .
44723
44739
  somewhere deploy
44724
44740
  somewhere browser
44725
44741
  \`\`\`
@@ -44743,8 +44759,8 @@ var init_skills_pack_generated = __esm({
44743
44759
  BUNDLED_SKILLS_PACK = {
44744
44760
  "schema": 1,
44745
44761
  "name": "somewhere-skills",
44746
- "version": "1+1e0c3eaa6dc4",
44747
- "sha256": "1e0c3eaa6dc4845dd123571f032574719560336e5e097641958e556a2c4dfe7d",
44762
+ "version": "1+7afa5a8a338d",
44763
+ "sha256": "7afa5a8a338d554b0f90630eb85dccad9ff8e0e170e550b73650bee538d1e927",
44748
44764
  "files": [
44749
44765
  {
44750
44766
  "path": "adopt/SKILL.md",
@@ -44758,8 +44774,8 @@ var init_skills_pack_generated = __esm({
44758
44774
  },
44759
44775
  {
44760
44776
  "path": "schema-changes/SKILL.md",
44761
- "sha256": "05a028ec47a901a07151b912e4ac967e3535a10163a3ffdb83c9ec2bd5a48a1a",
44762
- "content": "---\nname: schema-changes\ndescription: Before adding, changing, or removing a table or column in db/schema.ts.\n---\n\n# Change the database schema safely\n\n## The file is the contract\n\nThe default `somewhere init` starter has no `db/schema.ts`: create it at the project root, or run `somewhere init --name my-app --features private-data` to start with a schema.\n\n```ts\n// db/schema.ts\nimport { id, owner, schema, table, text, timestamp } from 'somewhere/db';\n\nexport default schema({\n notes: table(\n {\n id: id(),\n title: text(),\n body: text({ default: '' }),\n created_at: timestamp({ default: 'now' }),\n },\n {\n scope: owner(),\n client: {\n read: ['id', 'title', 'body', 'created_at'],\n create: ['title', 'body'],\n update: ['title', 'body'],\n delete: true,\n },\n },\n ),\n});\n```\n\nA table without a `client` block can't be reached from the browser at all.\n\nChoose the `parent({ author })` column and its author permissions in the table's first deploy. To change them on a deployed table, declare a new table with the desired rule and move the rows from server code.\n\nDelete a never-deployed starter table's declaration and references. A `removedTable()` marker for it is a no-op. **Removing a table** is `old_table: removedTable()`. The deploy keeps the table while your previous version is still serving; once the new version is live it retires the table and keeps its data for 30 days.\n\nRun `somewhere typecheck` before deploying schema changes.\n\n## What a deploy does with it\n\n- **Additive changes apply**: a new table, a new nullable-or-defaulted column, a new index, a new unique group. Unchanged schema is a no-op.\n- **Unmarked removals and shape changes refuse** with `409 SCHEMA_DEPLOY_REFUSED` and a message naming the change.\n- **Supported table scope changes apply in place.** See Two worlds for the supported transitions, including role-list edits on an existing `group()` or `appRole()` rule.\n- **Column rules and child author rules are set on a new table.** A deploy refuses additions, edits or removals of `columns` rules (`write` and `memberOf`) or `parent({ author })` rules on a deployed table. Keep its current declaration and handle the operation in an authorized server endpoint, closing any direct browser write path that could bypass the endpoint. To change the declared rule, create a new table with the desired rule and migrate the rows from server code.\n- a production deploy or a promotion that would remove or rename a column is refused before anything changes, so a running release never loses a column it uses. Keep the column declared and leave its data in place.\n\n## Failure: raw SQL refused after the schema file deploys\n\nOn an older shared database, ordinary `sw.db.query` / `sw.db.batch` fail before transport with `MANAGED_RAW_SQL_REQUIRES_SERVER_AUTHORITY`, including in job, queue, and cron handlers; with a separate SQL database they run there and never see declared tables. Fix: write with `sw.db.insert` / `sw.db.update` / `sw.db.remove` (the table needs a declared intent)\n\nSources (`somewhere docs <topic>`): declared-data, getting-started, sw.db, troubleshooting.\n"
44777
+ "sha256": "05fa17d25e504a44b3e8f6b88710dffc85a367a7bed289e81bca65c5cc6bb492",
44778
+ "content": "---\nname: schema-changes\ndescription: Before adding, changing, or removing a table or column in db/schema.ts.\n---\n\n# Change the database schema safely\n\n## The file is the contract\n\nThe default `somewhere init` starter has no `db/schema.ts`: create it at the project root, or run `somewhere init --name my-app --features private-data` to start with a schema.\n\n```ts\n// db/schema.ts\nimport { id, owner, schema, table, text, timestamp } from 'somewhere/db';\n\nexport default schema({\n notes: table(\n {\n id: id(),\n title: text(),\n body: text({ default: '' }),\n created_at: timestamp({ default: 'now' }),\n },\n {\n scope: owner(),\n client: {\n read: ['id', 'title', 'body', 'created_at'],\n create: ['title', 'body'],\n update: ['title', 'body'],\n delete: true,\n },\n },\n ),\n});\n```\n\nA table without a `client` block can't be reached from the browser at all.\n\nChoose the `parent({ author })` column and its author permissions in the table's first deploy. To change them on a deployed table, declare a new table with the desired rule and move the rows from server code.\n\nDelete a never-deployed starter table's declaration and references. A `removedTable()` marker for it is a no-op. **Removing a table** is `old_table: removedTable()`. The deploy keeps the table while your previous version is still serving; once the new version is live it retires the table and keeps its data for 30 days.\n\nRun `somewhere typecheck` before deploying schema changes.\n\n## What a deploy does with it\n\n- **Additive changes apply**: a new table, a new nullable-or-defaulted column, a new index, a new unique group. Unchanged schema is a no-op.\n- **Unmarked removals and shape changes refuse** with `409 SCHEMA_DEPLOY_REFUSED` and a message naming the change.\n- **Supported table scope changes apply in place.** See Two worlds for the supported transitions, including role-list edits on an existing `group()` or `appRole()` rule.\n- **Column rules and child author rules are set on a new table.** A deploy refuses additions, edits or removals of `columns` rules (`write` and `memberOf`) or `parent({ author })` rules on a deployed table. Keep its current declaration and handle the operation in an authorized server endpoint, closing any direct browser write path that could bypass the endpoint. To change the declared rule, create a new table with the desired rule and migrate the rows from server code.\n- a production deploy or a promotion that would remove or rename a column is refused before anything changes, so a running release never loses a column it uses. Keep the column declared and leave its data in place.\n\n## Failure: raw SQL refused after the schema file deploys\n\nRaw SQL (`sw.db.query`, `sw.db.server.query` and their batch forms) never reads or writes declared tables, including in job, queue, and cron handlers: Fix: read with `sw.db.from` / `sw.db.count` / `sw.db.aggregate` and write with `sw.db.insert` / `sw.db.update` / `sw.db.remove` (the table needs a declared intent)\n\nSources (`somewhere docs <topic>`): declared-data, getting-started, sw.db, troubleshooting.\n"
44763
44779
  },
44764
44780
  {
44765
44781
  "path": "sign-in-setup/SKILL.md",
@@ -44773,8 +44789,8 @@ var init_skills_pack_generated = __esm({
44773
44789
  },
44774
44790
  {
44775
44791
  "path": "realtime-and-background/SKILL.md",
44776
- "sha256": "052f73a08a0fe58cae7ddab2ef85a35f4e0dbf4150db09ce1c76d3cf30d07cd3",
44777
- "content": "---\nname: realtime-and-background\ndescription: When the page must update without a reload, or work must run outside one request.\n---\n\n# Live lists, jobs, cron\n\n## Live list: the page updates when rows change\n\nDeclare the list in a function with `sw.rooms.live(name, sw.db.from(...))` and follow it with `watchLive` from `/__sw/rooms/client.js`.\n\n```ts\n// api/open-notes.ts\nexport default async function (_req: Request, sw: SomewhereRuntimeContext) {\n return Response.json(await sw.rooms.live('notes.open', sw.db.from('notes', {\n where: { done: false },\n columns: ['id', 'title', 'done', 'created_at'],\n order: [['created_at', 'desc'], ['id', 'asc']],\n limit: 20,\n })))\n}\n```\n\n```js\n// browser\nimport { watchLive } from '/__sw/rooms/client.js'\n\nconst stop = watchLive(\n () => fetch('/api/open-notes', { credentials: 'include' }).then((r) => {\n if (!r.ok) throw new Error('Could not load notes (' + r.status + ').')\n return r.json()\n }),\n (rows) => render(rows),\n (err) => showProblem(err.message), // optional; console.error otherwise\n)\n```\n\n## Job: slow work with a status\n\nRun work that shouldn't block a user request in a job. Make handlers idempotent \u2014 they may run more than once.\n\n```ts\nconst job = await sw.jobs.create({\n handler: '/api/jobs/summarize-notes',\n idempotency_key: `summary:${user.id}:${operationId}`,\n // user_id comes from the verified session, so the handler can trust it.\n payload: { summary_id: `${user.id}:${operationId}`, user_id: user.id },\n});\n```\n\n```ts\nif (!(await sw.jobs.verifyInvocation(request))) {\n return Response.json({ error: 'forbidden' }, { status: 403 });\n}\n```\n\n## Cron: on a schedule\n\nThe finest granularity is one minute: a 5-field expression has no seconds field.\n\n```js\ncron_create({\n project_id: \"my-app\",\n schedule: \"0 9 * * *\", // 5-field cron expression\n timezone: \"America/Los_Angeles\", // optional; defaults to UTC\n handler: \"/api/jobs/daily-digest\",\n payload: { segment: \"daily\" } // optional\n})\n```\n\n## Failure 1: CRON_SCHEDULE_TOO_FREQUENT\n\nA schedule tighter than `min_interval_minutes` is refused when you create or edit it, with `CRON_SCHEDULE_TOO_FREQUENT` naming both intervals.\n\nSources (`somewhere docs <topic>`): cron, live, sw.jobs.\n"
44792
+ "sha256": "b67dd797fd09f655584ad779605ec2d5526e329aba9ea18069e12db0f41deaf3",
44793
+ "content": "---\nname: realtime-and-background\ndescription: When the page must update without a reload, or work must run outside one request.\n---\n\n# Live lists, jobs, cron\n\n## Live list: the page updates when rows change\n\nDeclare the list in a function with `sw.rooms.live(name, sw.db.from(...))` and follow it with `watchLive` from `/__sw/rooms/client.js`.\n\n```ts\n// api/open-notes.ts\nexport default async function (_req: Request, sw: SomewhereRuntimeContext) {\n return Response.json(await sw.rooms.live('notes.open', sw.db.from('notes', {\n where: { done: false },\n columns: ['id', 'title', 'done', 'created_at'],\n order: [['created_at', 'desc'], ['id', 'asc']],\n limit: 20,\n })))\n}\n```\n\n```js\n// browser\nimport { watchLive } from '/__sw/rooms/client.js'\nconst stop = watchLive(\n () => fetch('/api/tickets', { credentials: 'include' }).then((r) => r.json()),\n (rows) => render(rows),\n)\n```\n\n## Job: slow work with a status\n\nRun work that shouldn't block a user request in a job. Make handlers idempotent \u2014 they may run more than once.\n\n```ts\nconst job = await sw.jobs.create({\n handler: '/api/jobs/summarize-notes',\n idempotency_key: `summary:${user.id}:${operationId}`,\n // user_id comes from the verified session, so the handler can trust it.\n payload: { summary_id: `${user.id}:${operationId}`, user_id: user.id },\n});\n```\n\n```ts\nif (!(await sw.jobs.verifyInvocation(request))) {\n return Response.json({ error: 'forbidden' }, { status: 403 });\n}\n```\n\n## Cron: on a schedule\n\nThe finest granularity is one minute: a 5-field expression has no seconds field.\n\n```js\ncron_create({\n project_id: \"my-app\",\n schedule: \"0 9 * * *\", // 5-field cron expression\n timezone: \"America/Los_Angeles\", // optional; defaults to UTC\n handler: \"/api/jobs/daily-digest\",\n payload: { segment: \"daily\" } // optional\n})\n```\n\n## Failure 1: CRON_SCHEDULE_TOO_FREQUENT\n\nA schedule tighter than `min_interval_minutes` is refused when you create or edit it, with `CRON_SCHEDULE_TOO_FREQUENT` naming both intervals.\n\nSources (`somewhere docs <topic>`): cron, live, sw.jobs.\n"
44778
44794
  },
44779
44795
  {
44780
44796
  "path": "email-and-test-inbox/SKILL.md",
@@ -46862,7 +46878,7 @@ function pinNotice(pin, running, delegatedTo) {
46862
46878
  const newer = import_semver.default.valid(running) !== null && import_semver.default.gtr(running, pin.spec, { includePrerelease: true });
46863
46879
  const move = `Run \`${cliInvocation()} upgrade\` to move the project to ${running}.`;
46864
46880
  if (delegatedTo) {
46865
- return `${head}; running its installed ${delegatedTo} instead of ${running}.${newer ? ` ${move}` : ""}`;
46881
+ return newer ? `${head}; running its installed ${delegatedTo}, not ${running}. ${move}` : null;
46866
46882
  }
46867
46883
  if (newer)
46868
46884
  return `${head}; you are running ${running}. ${move}`;
@@ -52765,7 +52781,7 @@ function registerProject(program2) {
52765
52781
  process.exit(1);
52766
52782
  }
52767
52783
  });
52768
- proj.command("delete <name-or-id>").description("Permanently delete a project and all its data").option("--confirm-code <code>", "Confirm deletion using the confirm_code returned by the first call").option("--json", "Print the deletion result as JSON").addOption(new Option("--yes").hideHelp()).addOption(new Option("--force").hideHelp()).action(async (nameOrId, opts) => {
52784
+ proj.command("delete <name-or-id>").description("Delete a project: it goes offline now and its data is erased after 30 days. --undo restores it within those 30 days.").option("--confirm-code <code>", "Confirm deletion using the confirm_code returned by the first call").option("--undo", "Restore a project you deleted within the last 30 days. It comes back offline; deploy it again to put it online.").option("--json", "Print the deletion result as JSON").addOption(new Option("--yes").hideHelp()).addOption(new Option("--force").hideHelp()).action(async (nameOrId, opts) => {
52769
52785
  const unsupported = opts.yes ? "--yes" : opts.force ? "--force" : void 0;
52770
52786
  if (unsupported) {
52771
52787
  const message3 = `Unknown option '${unsupported}'. Run ${cliInvocation()} project delete <name-or-id> to get a code, then repeat with --confirm-code <code>.`;
@@ -52775,7 +52791,38 @@ function registerProject(program2) {
52775
52791
  error(message3);
52776
52792
  process.exit(1);
52777
52793
  }
52794
+ if (opts.undo && opts.confirmCode) {
52795
+ const message3 = "--undo restores a deleted project and takes no confirmation code. Run it without --confirm-code.";
52796
+ if (opts.json)
52797
+ printJsonError("UNKNOWN_OPTION", message3);
52798
+ else
52799
+ error(message3);
52800
+ process.exit(1);
52801
+ }
52778
52802
  const client = new ApiClient(getToken());
52803
+ if (opts.undo) {
52804
+ const spinner2 = opts.json ? null : ora("Restoring...").start();
52805
+ try {
52806
+ const restored = await client.call("POST", `/projects/${encodeURIComponent(nameOrId)}/restore`, {});
52807
+ spinner2?.stop();
52808
+ if (opts.json) {
52809
+ printJson(restored);
52810
+ return;
52811
+ }
52812
+ if (restored?.restored === true) {
52813
+ success("Restored. It is offline until you deploy it again.");
52814
+ if (restored.note)
52815
+ info(restored.note);
52816
+ } else {
52817
+ info(restored?.note ?? "This project is not deleted. Nothing changed.");
52818
+ }
52819
+ } catch (err) {
52820
+ spinner2?.stop();
52821
+ renderDeleteError(err, opts.json);
52822
+ process.exit(1);
52823
+ }
52824
+ return;
52825
+ }
52779
52826
  const promptStdout = opts.json ? process.stderr : void 0;
52780
52827
  let project;
52781
52828
  try {
@@ -52796,6 +52843,7 @@ function registerProject(program2) {
52796
52843
  return;
52797
52844
  }
52798
52845
  success("Deleted.");
52846
+ printDeleteNote(deleted2);
52799
52847
  return;
52800
52848
  }
52801
52849
  const code = await requestDeleteConfirmationCode(client, project.id);
@@ -52817,7 +52865,7 @@ function registerProject(program2) {
52817
52865
  const { confirm: confirm2 } = await (0, import_prompts3.default)({
52818
52866
  type: "text",
52819
52867
  name: "confirm",
52820
- message: `This will permanently delete "${projectName}" and all its data.
52868
+ message: `This will delete "${projectName}": it goes offline now, and its data is erased for good after 30 days.
52821
52869
  Type the project name to confirm`,
52822
52870
  stdout: promptStdout
52823
52871
  });
@@ -52838,6 +52886,7 @@ function registerProject(program2) {
52838
52886
  return;
52839
52887
  }
52840
52888
  success("Deleted.");
52889
+ printDeleteNote(deleted);
52841
52890
  } catch (err) {
52842
52891
  spinner?.stop();
52843
52892
  renderDeleteError(err, opts.json);
@@ -52851,6 +52900,8 @@ async function resolveDeleteTarget(client, ref) {
52851
52900
  } catch (err) {
52852
52901
  if (!(err instanceof CliApiError) || err.statusCode !== 404)
52853
52902
  throw err;
52903
+ if (PROJECT_ID_RE.test(ref))
52904
+ throw err;
52854
52905
  }
52855
52906
  const listed = await client.call("GET", "/projects", void 0, { q: ref, fields: "compact" });
52856
52907
  const refLower = ref.toLowerCase();
@@ -52882,6 +52933,11 @@ async function requestDeleteConfirmationCode(client, projectId) {
52882
52933
  }
52883
52934
  throw new CliApiError("DELETE_CONFIRMATION_MISSING", "The server did not require a delete confirmation code, so the CLI refused to continue.", 500);
52884
52935
  }
52936
+ function printDeleteNote(deleted) {
52937
+ const note = deleted && typeof deleted === "object" ? deleted.note : void 0;
52938
+ if (typeof note === "string" && note.trim())
52939
+ info(note);
52940
+ }
52885
52941
  function confirmProjectDelete(client, projectId, code) {
52886
52942
  return client.call("DELETE", `/projects/${encodeURIComponent(projectId)}`, { code });
52887
52943
  }
@@ -52967,7 +53023,7 @@ function printAllowedOrigins(result) {
52967
53023
  info(` ${teal(origin)}`);
52968
53024
  info(dim(" The project's own address and any verified custom domain are always trusted and are not listed here."));
52969
53025
  }
52970
- var import_prompts3;
53026
+ var import_prompts3, PROJECT_ID_RE;
52971
53027
  var init_project = __esm({
52972
53028
  "dist/commands/project.js"() {
52973
53029
  "use strict";
@@ -52984,8 +53040,10 @@ var init_project = __esm({
52984
53040
  init_platform_command();
52985
53041
  init_allowed_origins();
52986
53042
  __name(registerProject, "registerProject");
53043
+ PROJECT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
52987
53044
  __name(resolveDeleteTarget, "resolveDeleteTarget");
52988
53045
  __name(requestDeleteConfirmationCode, "requestDeleteConfirmationCode");
53046
+ __name(printDeleteNote, "printDeleteNote");
52989
53047
  __name(confirmProjectDelete, "confirmProjectDelete");
52990
53048
  __name(renderDeleteError, "renderDeleteError");
52991
53049
  __name(listProjects, "listProjects");
@@ -69514,50 +69572,50 @@ var require_fast_uri = __commonJS({
69514
69572
  return serialize(resolved, schemelessOptions);
69515
69573
  }
69516
69574
  __name(resolve27, "resolve");
69517
- function resolveComponent(base, relative15, options2, skipNormalization) {
69575
+ function resolveComponent(base, relative16, options2, skipNormalization) {
69518
69576
  const target = {};
69519
69577
  if (!skipNormalization) {
69520
69578
  base = parse3(serialize(base, options2), options2);
69521
- relative15 = parse3(serialize(relative15, options2), options2);
69579
+ relative16 = parse3(serialize(relative16, options2), options2);
69522
69580
  }
69523
69581
  options2 = options2 || {};
69524
- if (!options2.tolerant && relative15.scheme) {
69525
- target.scheme = relative15.scheme;
69526
- target.userinfo = relative15.userinfo;
69527
- target.host = relative15.host;
69528
- target.port = relative15.port;
69529
- target.path = removeDotSegments(relative15.path || "");
69530
- target.query = relative15.query;
69582
+ if (!options2.tolerant && relative16.scheme) {
69583
+ target.scheme = relative16.scheme;
69584
+ target.userinfo = relative16.userinfo;
69585
+ target.host = relative16.host;
69586
+ target.port = relative16.port;
69587
+ target.path = removeDotSegments(relative16.path || "");
69588
+ target.query = relative16.query;
69531
69589
  } else {
69532
- if (relative15.userinfo !== void 0 || relative15.host !== void 0 || relative15.port !== void 0) {
69533
- target.userinfo = relative15.userinfo;
69534
- target.host = relative15.host;
69535
- target.port = relative15.port;
69536
- target.path = removeDotSegments(relative15.path || "");
69537
- target.query = relative15.query;
69590
+ if (relative16.userinfo !== void 0 || relative16.host !== void 0 || relative16.port !== void 0) {
69591
+ target.userinfo = relative16.userinfo;
69592
+ target.host = relative16.host;
69593
+ target.port = relative16.port;
69594
+ target.path = removeDotSegments(relative16.path || "");
69595
+ target.query = relative16.query;
69538
69596
  } else {
69539
- if (!relative15.path) {
69597
+ if (!relative16.path) {
69540
69598
  target.path = base.path;
69541
- if (relative15.query !== void 0) {
69542
- target.query = relative15.query;
69599
+ if (relative16.query !== void 0) {
69600
+ target.query = relative16.query;
69543
69601
  } else {
69544
69602
  target.query = base.query;
69545
69603
  }
69546
69604
  } else {
69547
- if (relative15.path[0] === "/") {
69548
- target.path = removeDotSegments(relative15.path);
69605
+ if (relative16.path[0] === "/") {
69606
+ target.path = removeDotSegments(relative16.path);
69549
69607
  } else {
69550
69608
  const baseHasAuthority = base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0;
69551
69609
  if (baseHasAuthority && !base.path) {
69552
- target.path = "/" + relative15.path;
69610
+ target.path = "/" + relative16.path;
69553
69611
  } else if (!base.path) {
69554
- target.path = relative15.path;
69612
+ target.path = relative16.path;
69555
69613
  } else {
69556
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative15.path;
69614
+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative16.path;
69557
69615
  }
69558
69616
  target.path = base.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
69559
69617
  }
69560
- target.query = relative15.query;
69618
+ target.query = relative16.query;
69561
69619
  }
69562
69620
  target.userinfo = base.userinfo;
69563
69621
  target.host = base.host;
@@ -69565,7 +69623,7 @@ var require_fast_uri = __commonJS({
69565
69623
  }
69566
69624
  target.scheme = base.scheme;
69567
69625
  }
69568
- target.fragment = relative15.fragment;
69626
+ target.fragment = relative16.fragment;
69569
69627
  return target;
69570
69628
  }
69571
69629
  __name(resolveComponent, "resolveComponent");
@@ -75912,9 +75970,9 @@ var init_handler = __esm({
75912
75970
  if (this.fsw.closed) {
75913
75971
  return;
75914
75972
  }
75915
- const dirname17 = sysPath.dirname(file);
75973
+ const dirname18 = sysPath.dirname(file);
75916
75974
  const basename13 = sysPath.basename(file);
75917
- const parent = this.fsw._getWatchedDir(dirname17);
75975
+ const parent = this.fsw._getWatchedDir(dirname18);
75918
75976
  let prevStats = stats;
75919
75977
  if (parent.has(basename13))
75920
75978
  return;
@@ -75941,7 +75999,7 @@ var init_handler = __esm({
75941
75999
  prevStats = newStats2;
75942
76000
  }
75943
76001
  } catch (error3) {
75944
- this.fsw._remove(dirname17, basename13);
76002
+ this.fsw._remove(dirname18, basename13);
75945
76003
  }
75946
76004
  } else if (parent.has(basename13)) {
75947
76005
  const at2 = newStats.atimeMs;
@@ -76186,11 +76244,11 @@ function createPattern(matcher) {
76186
76244
  if (matcher.path === string4)
76187
76245
  return true;
76188
76246
  if (matcher.recursive) {
76189
- const relative15 = sysPath2.relative(matcher.path, string4);
76190
- if (!relative15) {
76247
+ const relative16 = sysPath2.relative(matcher.path, string4);
76248
+ if (!relative16) {
76191
76249
  return false;
76192
76250
  }
76193
- return !relative15.startsWith("..") && !sysPath2.isAbsolute(relative15);
76251
+ return !relative16.startsWith("..") && !sysPath2.isAbsolute(relative16);
76194
76252
  }
76195
76253
  return false;
76196
76254
  };
@@ -77018,7 +77076,7 @@ __export(files_exports, {
77018
77076
  testFolderOf: () => testFolderOf
77019
77077
  });
77020
77078
  import { isUtf8 } from "node:buffer";
77021
- import { existsSync as existsSync14, readdirSync as readdirSync3, readFileSync as readFileSync17, statSync as statSync2 } from "node:fs";
77079
+ import { closeSync as closeSync4, existsSync as existsSync14, openSync as openSync4, readdirSync as readdirSync3, readFileSync as readFileSync17, readSync, statSync as statSync2 } from "node:fs";
77022
77080
  import { extname as extname3, isAbsolute as isAbsolute2, join as join18, posix as posix2, relative as relative6 } from "node:path";
77023
77081
  function isTestSourcePath(relPath) {
77024
77082
  return TEST_SOURCE_NAME.test(relPath.slice(relPath.lastIndexOf("/") + 1));
@@ -77084,11 +77142,11 @@ function compilerAssetMatcher(sources) {
77084
77142
  };
77085
77143
  }
77086
77144
  function collectFiles(baseDir, options2 = {}) {
77087
- const out = { dotfilesLeftOut: false, files: {}, binaryFiles: {}, functions: {}, skipped: [], oversize: [], notes: [], excluded: [], sensitive: [], published: [] };
77145
+ const out = { dotfilesLeftOut: false, cliCredentialFiles: [], files: {}, binaryFiles: {}, functions: {}, skipped: [], oversize: [], notes: [], excluded: [], sensitive: [], published: [] };
77088
77146
  const ignore = loadDeployIgnore(baseDir);
77089
77147
  const candidates = [];
77090
77148
  const sizes = /* @__PURE__ */ new Map();
77091
- walk(baseDir, baseDir, out, ignore, candidates, sizes);
77149
+ walk(baseDir, baseDir, out, ignore, candidates, sizes, options2.checkCliCredentials ? Buffer.alloc(512) : null);
77092
77150
  const optIn = new Set((options2.include ?? []).map((p2) => toDeployPath(p2.trim()).replace(/^\.\//, "").replace(/\/+$/, "")).filter(Boolean));
77093
77151
  const publish = [];
77094
77152
  const deferred = [];
@@ -77113,7 +77171,8 @@ function collectFiles(baseDir, options2 = {}) {
77113
77171
  deferred.push(relPath);
77114
77172
  }
77115
77173
  }
77116
- const corpusFiles = /* @__PURE__ */ __name((paths) => paths.filter((relPath) => isReferenceCorpusPath(relPath) && (sizes.get(relPath) ?? 0) <= MAX_FILE_SIZE).map((relPath) => {
77174
+ const inlineFileLimit = options2.inlineFileLimitBytes ?? MAX_FILE_SIZE;
77175
+ const corpusFiles = /* @__PURE__ */ __name((paths) => paths.filter((relPath) => isReferenceCorpusPath(relPath) && (sizes.get(relPath) ?? 0) <= inlineFileLimit).map((relPath) => {
77117
77176
  try {
77118
77177
  return [relPath, readFileSync17(join18(baseDir, relPath), "utf-8")];
77119
77178
  } catch {
@@ -77170,9 +77229,9 @@ function collectFiles(baseDir, options2 = {}) {
77170
77229
  out.published.push(relPath);
77171
77230
  continue;
77172
77231
  }
77173
- if (bytes > MAX_FILE_SIZE) {
77232
+ if (bytes > inlineFileLimit) {
77174
77233
  out.oversize.push({ path: relPath, bytes });
77175
- out.skipped.push({ path: relPath, reason: `${formatBytes(bytes)} exceeds the ${formatBytes(MAX_FILE_SIZE)} per-file limit` });
77234
+ out.skipped.push({ path: relPath, reason: `${formatBytes(bytes)} exceeds the ${formatBytes(inlineFileLimit)} per-file limit` });
77176
77235
  continue;
77177
77236
  }
77178
77237
  classifyInto(out, baseDir, relPath, options2.readBinary !== false);
@@ -77189,7 +77248,34 @@ function collectFiles(baseDir, options2 = {}) {
77189
77248
  }
77190
77249
  return out;
77191
77250
  }
77192
- function walk(baseDir, currentDir, out, ignore, candidates, sizes) {
77251
+ function looksLikeCliCredential(path3, bytes, header) {
77252
+ if (bytes === 0 || bytes > MAX_DEPLOY_BLOB_BYTES)
77253
+ return false;
77254
+ const fd = openSync4(path3, "r");
77255
+ try {
77256
+ const size = readSync(fd, header, 0, header.length, 0);
77257
+ const prefix = header.toString("utf8", 0, size).trimStart();
77258
+ if (!prefix.startsWith("{") && !/^(?:smt|smtr)_/i.test(prefix))
77259
+ return false;
77260
+ } finally {
77261
+ closeSync4(fd);
77262
+ }
77263
+ const text = readFileSync17(path3, "utf8").trim();
77264
+ const cliKey = /^(?:smt|smtr)_[a-z0-9_-]+$/i;
77265
+ if (cliKey.test(text))
77266
+ return true;
77267
+ if (!text.startsWith("{"))
77268
+ return false;
77269
+ try {
77270
+ const value = JSON.parse(text);
77271
+ if (typeof value !== "object" || value === null)
77272
+ return false;
77273
+ return "token" in value && typeof value.token === "string" && cliKey.test(value.token) || "refresh_token" in value && typeof value.refresh_token === "string" && cliKey.test(value.refresh_token);
77274
+ } catch {
77275
+ return false;
77276
+ }
77277
+ }
77278
+ function walk(baseDir, currentDir, out, ignore, candidates, sizes, credentialHeader) {
77193
77279
  for (const entry of readdirSync3(currentDir, { withFileTypes: true })) {
77194
77280
  const fullPath = join18(currentDir, entry.name);
77195
77281
  const relPath = toDeployPath(relative6(baseDir, fullPath));
@@ -77203,7 +77289,7 @@ function walk(baseDir, currentDir, out, ignore, candidates, sizes) {
77203
77289
  continue;
77204
77290
  }
77205
77291
  if (entry.isDirectory()) {
77206
- walk(baseDir, fullPath, out, ignore, candidates, sizes);
77292
+ walk(baseDir, fullPath, out, ignore, candidates, sizes, credentialHeader);
77207
77293
  continue;
77208
77294
  }
77209
77295
  if (!entry.isFile())
@@ -77214,7 +77300,12 @@ function walk(baseDir, currentDir, out, ignore, candidates, sizes) {
77214
77300
  }
77215
77301
  if ((entry.name === DATA_DECLARATION_FILE || entry.name === FILES_DECLARATION_FILE) && readFileSync17(fullPath, "utf8").startsWith(GENERATED_DATA_HEADER))
77216
77302
  continue;
77217
- sizes.set(relPath, statSync2(fullPath).size);
77303
+ const bytes = statSync2(fullPath).size;
77304
+ if (credentialHeader && looksLikeCliCredential(fullPath, bytes, credentialHeader)) {
77305
+ out.cliCredentialFiles.push(relPath);
77306
+ continue;
77307
+ }
77308
+ sizes.set(relPath, bytes);
77218
77309
  candidates.push(relPath);
77219
77310
  }
77220
77311
  }
@@ -77347,11 +77438,12 @@ function globToRegExp(pattern) {
77347
77438
  function escapeRegExp(ch) {
77348
77439
  return /[\\^$+?.()|[\]{}]/.test(ch) ? `\\${ch}` : ch;
77349
77440
  }
77350
- function oversizeRefusal(collected) {
77441
+ function oversizeRefusal(collected, limitBytes = MAX_FILE_SIZE) {
77351
77442
  if (collected.oversize.length === 0)
77352
77443
  return null;
77444
+ const limit = limitBytes === MAX_INLINE_DEPLOY_BYTES ? "20 MiB inline deploy" : `${formatBytes(limitBytes)} per-file`;
77353
77445
  return [
77354
- `Nothing was sent. ${collected.oversize.length === 1 ? "This file is" : "These files are"} over the ${formatBytes(MAX_FILE_SIZE)} per-file limit and would be left out, which removes any copy already live:`,
77446
+ `Nothing was sent. ${collected.oversize.length === 1 ? "This file is" : "These files are"} over the ${limit} limit and would be left out, which removes any copy already live:`,
77355
77447
  ...collected.oversize.map((entry) => ` ${entry.path} (${formatBytes(entry.bytes)})`),
77356
77448
  ...fileStorageRecovery(collected.oversize)
77357
77449
  ].join("\n");
@@ -77486,6 +77578,7 @@ var init_files = __esm({
77486
77578
  SENSITIVE_FILE_REASON = "blocked by the sensitive-path policy \u2014 never uploaded";
77487
77579
  __name(compilerAssetMatcher, "compilerAssetMatcher");
77488
77580
  __name(collectFiles, "collectFiles");
77581
+ __name(looksLikeCliCredential, "looksLikeCliCredential");
77489
77582
  __name(walk, "walk");
77490
77583
  __name(classifyKey, "classifyKey");
77491
77584
  __name(classifyInto, "classifyInto");
@@ -78713,7 +78806,7 @@ function formatChecksReport(check) {
78713
78806
  const coverage = check?.not_checked ?? null;
78714
78807
  if (coverage) {
78715
78808
  if (typeof check?.routes_discovered === "number")
78716
- lines.push(check.routes_checked ? `${check.routes_checked} of ${check.routes_discovered} app routes had a completed read check.` : `Your ${check.routes_discovered} app routes are checked by your own tests (npm test), not here: this check covers your tables, pages and saved checks/ lists.`);
78809
+ lines.push(check.routes_checked ? `${check.routes_checked} of ${check.routes_discovered} app routes had a completed read check.` : `This check called none of your ${check.routes_discovered} app routes: it covers your tables, pages and saved checks/ lists. Check the routes in tests/starter.mjs (npm test).`);
78717
78810
  const { routes_without_read_check: reads, routes_without_write_check: writes, schedules_not_run: schedules, other } = coverage;
78718
78811
  if (reads === null || writes === null)
78719
78812
  lines.push("App route coverage could not be listed.");
@@ -78730,12 +78823,12 @@ function formatChecksReport(check) {
78730
78823
  } else {
78731
78824
  lines.push("Coverage details are unavailable for this run.");
78732
78825
  }
78733
- lines.push("Prove the brief with a check list in checks/<name>.json (users and steps). See somewhere docs test.");
78826
+ lines.push("Prove the brief in tests/starter.mjs (npm test). To rerun a check after every deploy, save it as checks/<name>.json (users and steps). See somewhere docs test.");
78734
78827
  return [...lines, JSON.stringify({
78735
78828
  ...summary,
78736
78829
  not_checked: coverage,
78737
78830
  ...check?.scope === "partial" ? { scope: check.scope, selection: check.selection, checked_parts: check.checked_parts } : {},
78738
- ...coverage ? { routes_checked: check?.routes_checked, routes_discovered: check?.routes_discovered } : {}
78831
+ ...coverage && check?.routes_checked ? { routes_checked: check.routes_checked, routes_discovered: check.routes_discovered } : {}
78739
78832
  })];
78740
78833
  }
78741
78834
  var DEPLOY_CHECKS_RUNNING, TEST_CHECKS_WAIT_MS, selectionLabel, cleanupFindings, functionWarnings;
@@ -80543,12 +80636,14 @@ function uploadInventory(files, binaryFiles, functions, scope) {
80543
80636
  functions: scope === "static" ? [] : sorted(Object.keys(functions).filter((path3) => !path3.split("/").some((segment) => segment.startsWith("_"))))
80544
80637
  };
80545
80638
  }
80546
- function formatUploadInventory(inventory) {
80639
+ function formatUploadInventory(inventory, dryRun = false) {
80547
80640
  const paths = [...inventory.static_files, ...inventory.functions];
80548
80641
  if (paths.length === 0)
80549
80642
  return "Uploaded: nothing";
80550
80643
  if (paths.length <= INLINE_UPLOAD_LIST_MAX)
80551
80644
  return `Uploaded: ${paths.join(", ")}`;
80645
+ if (!dryRun)
80646
+ return `Uploaded ${paths.length} paths.`;
80552
80647
  return `Uploaded ${paths.length} paths; the full list is "uploaded" in the output of ${cliInvocation()} deploy --dry-run --json`;
80553
80648
  }
80554
80649
  var INLINE_UPLOAD_LIST_MAX;
@@ -82463,7 +82558,7 @@ var init_browser = __esm({
82463
82558
 
82464
82559
  // dist/lib/verify-keep.js
82465
82560
  import { createHash as createHash7, randomBytes as randomBytes5 } from "node:crypto";
82466
- import { closeSync as closeSync4, existsSync as existsSync27, openSync as openSync4, readFileSync as readFileSync30, rmSync as rmSync11, statSync as statSync6, writeSync } from "node:fs";
82561
+ import { closeSync as closeSync5, existsSync as existsSync27, openSync as openSync5, readFileSync as readFileSync30, rmSync as rmSync11, statSync as statSync6, writeSync } from "node:fs";
82467
82562
  import { join as join36 } from "node:path";
82468
82563
  function path(root) {
82469
82564
  return join36(stateDir(root), KEEP_FILE);
@@ -82530,9 +82625,9 @@ function lockKeep(root, key, now2 = Date.now()) {
82530
82625
  const lock = join36(stateDir(root), `verify-actors-${key}.lock`);
82531
82626
  for (let attempt = 0; attempt < 2; attempt++) {
82532
82627
  try {
82533
- const fd = openSync4(lock, "wx", 384);
82628
+ const fd = openSync5(lock, "wx", 384);
82534
82629
  writeSync(fd, JSON.stringify({ pid: process.pid, at: now2 }));
82535
- closeSync4(fd);
82630
+ closeSync5(fd);
82536
82631
  return () => {
82537
82632
  try {
82538
82633
  rmSync11(lock, { force: true });
@@ -84486,8 +84581,8 @@ var init_verify = __esm({
84486
84581
  });
84487
84582
 
84488
84583
  // dist/commands/deploy.js
84489
- import { existsSync as existsSync29, readFileSync as readFileSync32 } from "node:fs";
84490
- import { join as join37 } from "node:path";
84584
+ import { existsSync as existsSync29, readFileSync as readFileSync32, realpathSync as realpathSync4 } from "node:fs";
84585
+ import { isAbsolute as isAbsolute6, join as join37, relative as relative10, sep as sep2 } from "node:path";
84491
84586
  import { basename as basename6, resolve as resolve16 } from "node:path";
84492
84587
  function resolveTargetDir(dir, cwd = process.cwd()) {
84493
84588
  return dir ? resolve16(cwd, dir) : cwd;
@@ -84845,8 +84940,29 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84845
84940
  error(message3);
84846
84941
  process.exit(1);
84847
84942
  }
84943
+ const refuseCredential = /* @__PURE__ */ __name((path3) => {
84944
+ const message3 = `Nothing was sent. ${JSON.stringify(path3)} is a CLI login or key location. Move it outside the deploy folder and try again.`;
84945
+ if (opts.json)
84946
+ printJsonError("CLI_CREDENTIAL_IN_DEPLOY", message3);
84947
+ else
84948
+ error(message3);
84949
+ process.exit(1);
84950
+ }, "refuseCredential");
84951
+ const configDir = cliConfigDir();
84952
+ if (existsSync29(configDir) && existsSync29(targetDir)) {
84953
+ const config2 = realpathSync4(configDir);
84954
+ const target = realpathSync4(targetDir);
84955
+ const inside = /* @__PURE__ */ __name((path3) => !isAbsolute6(path3) && path3 !== ".." && !path3.startsWith(".." + sep2), "inside");
84956
+ const configInTarget = relative10(target, config2);
84957
+ if (inside(configInTarget))
84958
+ refuseCredential(join37(configInTarget, "config.json"));
84959
+ if (inside(relative10(config2, target)))
84960
+ refuseCredential(join37(configDir, "config.json"));
84961
+ }
84848
84962
  if (opts.listUnpublished) {
84849
- const { excluded: excluded2, sensitive: sensitive2, skipped: skipped2, dotfilesLeftOut } = collectFiles(targetDir, { include: opts.include ?? [] });
84963
+ const { excluded: excluded2, sensitive: sensitive2, skipped: skipped2, dotfilesLeftOut, cliCredentialFiles } = collectFiles(targetDir, { include: opts.include ?? [], checkCliCredentials: true });
84964
+ if (cliCredentialFiles.length)
84965
+ refuseCredential(cliCredentialFiles.sort()[0]);
84850
84966
  if (dotfilesLeftOut)
84851
84967
  console.error(DOTFILE_NOTICE);
84852
84968
  if (opts.json)
@@ -84875,9 +84991,13 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84875
84991
  const localScaffolds = unchangedPullScaffolds(targetDir, localBase);
84876
84992
  const collected = collectFiles(targetDir, {
84877
84993
  localScaffolds: new Set(Object.keys(localScaffolds)),
84994
+ checkCliCredentials: true,
84878
84995
  include: opts.include ?? [],
84879
- deployBlobs: process.env.SOMEWHERE_DEPLOY_BLOBS === "1" && !opts.dryRun && opts.scope !== "functions"
84996
+ deployBlobs: !opts.dryRun && opts.scope !== "functions",
84997
+ inlineFileLimitBytes: MAX_INLINE_DEPLOY_BYTES
84880
84998
  });
84999
+ if (collected.cliCredentialFiles.length)
85000
+ refuseCredential(collected.cliCredentialFiles.sort()[0]);
84881
85001
  const hashStartedAt = collected.blobs?.size && opts.timing ? performance.now() : void 0;
84882
85002
  const publishedHashes = hashFiles(targetDir, collected.published);
84883
85003
  const collectionEndedAt = performance.now();
@@ -84894,7 +85014,7 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84894
85014
  process.exit(1);
84895
85015
  }
84896
85016
  const tooLargeBlob = [...collected.blobs ?? []].find(([, size]) => size > MAX_DEPLOY_BLOB_BYTES);
84897
- const sizeRefusal = tooLargeBlob ? `"${tooLargeBlob[0]}" exceeds the 25 MiB static file limit. Reduce its size or serve it from file storage.` : oversizeRefusal(collected);
85017
+ const sizeRefusal = tooLargeBlob ? `"${tooLargeBlob[0]}" exceeds the 25 MiB static file limit. Reduce its size or serve it from file storage.` : oversizeRefusal(collected, MAX_INLINE_DEPLOY_BYTES);
84898
85018
  if (sizeRefusal) {
84899
85019
  if (opts.json)
84900
85020
  printJsonError("FILE_TOO_LARGE", sizeRefusal);
@@ -84924,7 +85044,7 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
84924
85044
  process.exit(1);
84925
85045
  }
84926
85046
  if (collected.blobs?.size && collected.published.length > 2e4) {
84927
- const message3 = "A site can contain up to 20,000 files.";
85047
+ const message3 = "A site can contain up to 20,000 files. Move extra assets to file storage.";
84928
85048
  if (opts.json)
84929
85049
  printJsonError("DEPLOY_TOO_MANY_FILES", message3);
84930
85050
  else
@@ -85368,7 +85488,7 @@ Existing app: \`${cliInvocation()} pull <app>\` downloads the live source and li
85368
85488
  printJson({ ...plan, uploaded: inventory });
85369
85489
  } else {
85370
85490
  printDryRun(plan, scope);
85371
- info(dim(formatUploadInventory(inventory)));
85491
+ info(dim(formatUploadInventory(inventory, true)));
85372
85492
  }
85373
85493
  return;
85374
85494
  }
@@ -86366,7 +86486,7 @@ var init_deploys = __esm({
86366
86486
 
86367
86487
  // dist/commands/pull.js
86368
86488
  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";
86369
- import { basename as basename7, dirname as dirname12, join as join38, relative as relative10, resolve as resolve17 } from "node:path";
86489
+ import { basename as basename7, dirname as dirname12, join as join38, relative as relative11, resolve as resolve17 } from "node:path";
86370
86490
  function registerPull(program2) {
86371
86491
  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) => {
86372
86492
  const token = getToken();
@@ -86614,7 +86734,7 @@ function planRemovedFiles(outDir, expected, force, base = null) {
86614
86734
  }
86615
86735
  if (!entry.isFile())
86616
86736
  continue;
86617
- const relPath = normalizeRelPath(relative10(outDir, fullPath));
86737
+ const relPath = normalizeRelPath(relative11(outDir, fullPath));
86618
86738
  if (expected.has(relPath) || !publishable.has(relPath))
86619
86739
  continue;
86620
86740
  const was = base?.files[relPath];
@@ -90170,7 +90290,7 @@ var init_env = __esm({
90170
90290
 
90171
90291
  // dist/commands/run.js
90172
90292
  import { existsSync as existsSync35, readFileSync as readFileSync40 } from "node:fs";
90173
- import { isAbsolute as isAbsolute6, resolve as resolve20 } from "node:path";
90293
+ import { isAbsolute as isAbsolute7, resolve as resolve20 } from "node:path";
90174
90294
  import { createRequire as createRequire8 } from "node:module";
90175
90295
  function parseArgs(values) {
90176
90296
  if (!values.length)
@@ -90204,14 +90324,14 @@ function hasRelativeRuntimeImport(fileName2, code) {
90204
90324
  return false;
90205
90325
  }
90206
90326
  const source = ts2.createSourceFile(fileName2, code, ts2.ScriptTarget.Latest, true);
90207
- const relative15 = /* @__PURE__ */ __name((node2) => node2 !== void 0 && ts2.isStringLiteralLike(node2) && /^\.\.?\//.test(node2.text), "relative");
90327
+ const relative16 = /* @__PURE__ */ __name((node2) => node2 !== void 0 && ts2.isStringLiteralLike(node2) && /^\.\.?\//.test(node2.text), "relative");
90208
90328
  const scan = /* @__PURE__ */ __name((node2) => {
90209
90329
  if (ts2.isImportDeclaration(node2))
90210
- return !node2.importClause?.isTypeOnly && relative15(node2.moduleSpecifier);
90330
+ return !node2.importClause?.isTypeOnly && relative16(node2.moduleSpecifier);
90211
90331
  if (ts2.isExportDeclaration(node2))
90212
- return !node2.isTypeOnly && relative15(node2.moduleSpecifier);
90332
+ return !node2.isTypeOnly && relative16(node2.moduleSpecifier);
90213
90333
  if (ts2.isCallExpression(node2) && node2.expression.kind === ts2.SyntaxKind.ImportKeyword) {
90214
- return relative15(node2.arguments[0]);
90334
+ return relative16(node2.arguments[0]);
90215
90335
  }
90216
90336
  return ts2.forEachChild(node2, (child) => scan(child) || void 0) === true;
90217
90337
  }, "scan");
@@ -90235,7 +90355,7 @@ function registerRun(program2) {
90235
90355
  }
90236
90356
  projectId = config2.project_id;
90237
90357
  }
90238
- const absPath = isAbsolute6(script) ? script : resolve20(process.cwd(), script);
90358
+ const absPath = isAbsolute7(script) ? script : resolve20(process.cwd(), script);
90239
90359
  if (!existsSync35(absPath)) {
90240
90360
  error(`File not found: ${script}`);
90241
90361
  process.exit(1);
@@ -90676,7 +90796,7 @@ var init_claim = __esm({
90676
90796
 
90677
90797
  // dist/lib/frontend-dev.js
90678
90798
  import { createRequire as createRequire9 } from "node:module";
90679
- import { realpathSync as realpathSync4 } from "node:fs";
90799
+ import { realpathSync as realpathSync5 } from "node:fs";
90680
90800
  import { createConnection, createServer as createNetServer } from "node:net";
90681
90801
  import { join as join43 } from "node:path";
90682
90802
  import { pathToFileURL as pathToFileURL3 } from "node:url";
@@ -90770,7 +90890,7 @@ async function relayIpv6Loopback(port) {
90770
90890
  async function startFrontendDev(cwd, target, port = 8787, open4 = false) {
90771
90891
  if (!Number.isInteger(port) || port < 1 || port > 65535)
90772
90892
  throw new Error("Port must be an integer from 1 through 65535.");
90773
- cwd = realpathSync4(cwd);
90893
+ cwd = realpathSync5(cwd);
90774
90894
  const origin = deployedOrigin(target);
90775
90895
  if (missingProjectDependencies(cwd).length)
90776
90896
  throw new Error(INSTALL_PROJECT_DEPENDENCIES);
@@ -90920,7 +91040,7 @@ var init_preview_jobs = __esm({
90920
91040
  // dist/commands/dev.js
90921
91041
  import { randomUUID as randomUUID9 } from "node:crypto";
90922
91042
  import { existsSync as existsSync36 } from "node:fs";
90923
- import { join as join44, relative as relative11 } from "node:path";
91043
+ import { join as join44, relative as relative12 } from "node:path";
90924
91044
  function previewFinishedReason(err) {
90925
91045
  if (!(err instanceof CliApiError) || err.code !== "DRAFT_SESSION_TERMINAL")
90926
91046
  return null;
@@ -91758,7 +91878,7 @@ async function runHotDeploy(opts) {
91758
91878
  const watcher = esm_default.watch(cwd, {
91759
91879
  ignoreInitial: true,
91760
91880
  ignored: /* @__PURE__ */ __name((p2) => {
91761
- const rel = relative11(cwd, p2);
91881
+ const rel = relative12(cwd, p2);
91762
91882
  if (!rel || rel.startsWith(".."))
91763
91883
  return false;
91764
91884
  const segments = rel.split(/[\\/]/);
@@ -91833,7 +91953,7 @@ async function runHotDeploy(opts) {
91833
91953
  }
91834
91954
  }, "flush");
91835
91955
  const onChange = /* @__PURE__ */ __name((abs) => {
91836
- const rel = relative11(cwd, abs);
91956
+ const rel = relative12(cwd, abs);
91837
91957
  if (!WATCH_EXTS.test(rel))
91838
91958
  return;
91839
91959
  pendingChanged.add(rel);
@@ -91841,7 +91961,7 @@ async function runHotDeploy(opts) {
91841
91961
  schedule();
91842
91962
  }, "onChange");
91843
91963
  const onUnlink = /* @__PURE__ */ __name((abs) => {
91844
- const rel = relative11(cwd, abs);
91964
+ const rel = relative12(cwd, abs);
91845
91965
  if (!WATCH_EXTS.test(rel))
91846
91966
  return;
91847
91967
  pendingDeleted.add(rel);
@@ -108610,7 +108730,7 @@ var require_lib5 = __commonJS({
108610
108730
  return `${this.algorithm}-${this.digest}${getOptString(this.options)}`;
108611
108731
  }
108612
108732
  };
108613
- function integrityHashToString(toString, sep2, opts, hashes) {
108733
+ function integrityHashToString(toString, sep3, opts, hashes) {
108614
108734
  const toStringIsNotEmpty = toString !== "";
108615
108735
  let shouldAddFirstSep = false;
108616
108736
  let complement = "";
@@ -108620,7 +108740,7 @@ var require_lib5 = __commonJS({
108620
108740
  if (hashString) {
108621
108741
  shouldAddFirstSep = true;
108622
108742
  complement += hashString;
108623
- complement += sep2;
108743
+ complement += sep3;
108624
108744
  }
108625
108745
  }
108626
108746
  const finalHashString = Hash.prototype.toString.call(hashes[lastIndex], opts);
@@ -108629,7 +108749,7 @@ var require_lib5 = __commonJS({
108629
108749
  complement += finalHashString;
108630
108750
  }
108631
108751
  if (toStringIsNotEmpty && shouldAddFirstSep) {
108632
- return toString + sep2 + complement;
108752
+ return toString + sep3 + complement;
108633
108753
  }
108634
108754
  return toString + complement;
108635
108755
  }
@@ -108648,18 +108768,18 @@ var require_lib5 = __commonJS({
108648
108768
  return Object.keys(this).length === 0;
108649
108769
  }
108650
108770
  toString(opts) {
108651
- let sep2 = opts?.sep || " ";
108771
+ let sep3 = opts?.sep || " ";
108652
108772
  let toString = "";
108653
108773
  if (opts?.strict) {
108654
- sep2 = sep2.replace(/\S+/g, " ");
108774
+ sep3 = sep3.replace(/\S+/g, " ");
108655
108775
  for (const hash of SPEC_ALGORITHMS) {
108656
108776
  if (this[hash]) {
108657
- toString = integrityHashToString(toString, sep2, opts, this[hash]);
108777
+ toString = integrityHashToString(toString, sep3, opts, this[hash]);
108658
108778
  }
108659
108779
  }
108660
108780
  } else {
108661
108781
  for (const hash of Object.keys(this)) {
108662
- toString = integrityHashToString(toString, sep2, opts, this[hash]);
108782
+ toString = integrityHashToString(toString, sep3, opts, this[hash]);
108663
108783
  }
108664
108784
  }
108665
108785
  return toString;
@@ -110544,12 +110664,12 @@ var require_polyfill = __commonJS({
110544
110664
  utimes
110545
110665
  } = __require("fs/promises");
110546
110666
  var {
110547
- dirname: dirname17,
110548
- isAbsolute: isAbsolute7,
110667
+ dirname: dirname18,
110668
+ isAbsolute: isAbsolute8,
110549
110669
  join: join57,
110550
110670
  parse: parse3,
110551
110671
  resolve: resolve27,
110552
- sep: sep2,
110672
+ sep: sep3,
110553
110673
  toNamespacedPath
110554
110674
  } = __require("path");
110555
110675
  var { fileURLToPath: fileURLToPath2 } = __require("url");
@@ -110648,7 +110768,7 @@ var require_polyfill = __commonJS({
110648
110768
  }
110649
110769
  __name(getStats, "getStats");
110650
110770
  async function checkParentDir(destStat, src, dest, opts) {
110651
- const destParent = dirname17(dest);
110771
+ const destParent = dirname18(dest);
110652
110772
  const dirExists = await pathExists(destParent);
110653
110773
  if (dirExists) {
110654
110774
  return getStatsForCopy(destStat, src, dest, opts);
@@ -110666,8 +110786,8 @@ var require_polyfill = __commonJS({
110666
110786
  }
110667
110787
  __name(pathExists, "pathExists");
110668
110788
  async function checkParentPaths(src, srcStat, dest) {
110669
- const srcParent = resolve27(dirname17(src));
110670
- const destParent = resolve27(dirname17(dest));
110789
+ const srcParent = resolve27(dirname18(src));
110790
+ const destParent = resolve27(dirname18(dest));
110671
110791
  if (destParent === srcParent || destParent === parse3(destParent).root) {
110672
110792
  return;
110673
110793
  }
@@ -110691,7 +110811,7 @@ var require_polyfill = __commonJS({
110691
110811
  return checkParentPaths(src, srcStat, destParent);
110692
110812
  }
110693
110813
  __name(checkParentPaths, "checkParentPaths");
110694
- var normalizePathToArray = /* @__PURE__ */ __name((path3) => resolve27(path3).split(sep2).filter(Boolean), "normalizePathToArray");
110814
+ var normalizePathToArray = /* @__PURE__ */ __name((path3) => resolve27(path3).split(sep3).filter(Boolean), "normalizePathToArray");
110695
110815
  function isSrcSubdir(src, dest) {
110696
110816
  const srcArr = normalizePathToArray(src);
110697
110817
  const destArr = normalizePathToArray(dest);
@@ -110836,8 +110956,8 @@ var require_polyfill = __commonJS({
110836
110956
  __name(copyDir, "copyDir");
110837
110957
  async function onLink(destStat, src, dest) {
110838
110958
  let resolvedSrc = await readlink(src);
110839
- if (!isAbsolute7(resolvedSrc)) {
110840
- resolvedSrc = resolve27(dirname17(src), resolvedSrc);
110959
+ if (!isAbsolute8(resolvedSrc)) {
110960
+ resolvedSrc = resolve27(dirname18(src), resolvedSrc);
110841
110961
  }
110842
110962
  if (!destStat) {
110843
110963
  return symlink(resolvedSrc, dest);
@@ -110851,8 +110971,8 @@ var require_polyfill = __commonJS({
110851
110971
  }
110852
110972
  throw err;
110853
110973
  }
110854
- if (!isAbsolute7(resolvedDest)) {
110855
- resolvedDest = resolve27(dirname17(dest), resolvedDest);
110974
+ if (!isAbsolute8(resolvedDest)) {
110975
+ resolvedDest = resolve27(dirname18(dest), resolvedDest);
110856
110976
  }
110857
110977
  if (isSrcSubdir(resolvedSrc, resolvedDest)) {
110858
110978
  throw new ERR_FS_CP_EINVAL({
@@ -110904,7 +111024,7 @@ var require_cp = __commonJS({
110904
111024
  // node_modules/@npmcli/fs/lib/with-temp-dir.js
110905
111025
  var require_with_temp_dir = __commonJS({
110906
111026
  "node_modules/@npmcli/fs/lib/with-temp-dir.js"(exports, module) {
110907
- var { join: join57, sep: sep2 } = __require("path");
111027
+ var { join: join57, sep: sep3 } = __require("path");
110908
111028
  var getOptions = require_get_options();
110909
111029
  var { mkdir, mkdtemp, rm } = __require("fs/promises");
110910
111030
  var withTempDir = /* @__PURE__ */ __name(async (root, fn, opts) => {
@@ -110912,7 +111032,7 @@ var require_with_temp_dir = __commonJS({
110912
111032
  copy: ["tmpPrefix"]
110913
111033
  });
110914
111034
  await mkdir(root, { recursive: true });
110915
- const target = await mkdtemp(join57(`${root}${sep2}`, options2.tmpPrefix || ""));
111035
+ const target = await mkdtemp(join57(`${root}${sep3}`, options2.tmpPrefix || ""));
110916
111036
  let err;
110917
111037
  let result;
110918
111038
  try {
@@ -110958,7 +111078,7 @@ var require_readdir_scoped = __commonJS({
110958
111078
  // node_modules/@npmcli/fs/lib/move-file.js
110959
111079
  var require_move_file = __commonJS({
110960
111080
  "node_modules/@npmcli/fs/lib/move-file.js"(exports, module) {
110961
- var { dirname: dirname17, join: join57, resolve: resolve27, relative: relative15, isAbsolute: isAbsolute7 } = __require("path");
111081
+ var { dirname: dirname18, join: join57, resolve: resolve27, relative: relative16, isAbsolute: isAbsolute8 } = __require("path");
110962
111082
  var fs2 = __require("fs/promises");
110963
111083
  var pathExists = /* @__PURE__ */ __name(async (path3) => {
110964
111084
  try {
@@ -110979,7 +111099,7 @@ var require_move_file = __commonJS({
110979
111099
  if (!options2.overwrite && await pathExists(destination)) {
110980
111100
  throw new Error(`The destination file exists: ${destination}`);
110981
111101
  }
110982
- await fs2.mkdir(dirname17(destination), { recursive: true });
111102
+ await fs2.mkdir(dirname18(destination), { recursive: true });
110983
111103
  try {
110984
111104
  await fs2.rename(source, destination);
110985
111105
  } catch (error3) {
@@ -111002,12 +111122,12 @@ var require_move_file = __commonJS({
111002
111122
  if (root) {
111003
111123
  await Promise.all(symlinks.map(async ({ source: symSource, destination: symDestination }) => {
111004
111124
  let target = await fs2.readlink(symSource);
111005
- if (isAbsolute7(target)) {
111006
- target = resolve27(symDestination, relative15(symSource, target));
111125
+ if (isAbsolute8(target)) {
111126
+ target = resolve27(symDestination, relative16(symSource, target));
111007
111127
  }
111008
111128
  let targetStat = "file";
111009
111129
  try {
111010
- targetStat = await fs2.stat(resolve27(dirname17(symSource), target));
111130
+ targetStat = await fs2.stat(resolve27(dirname18(symSource), target));
111011
111131
  if (targetStat.isDirectory()) {
111012
111132
  targetStat = "junction";
111013
111133
  }
@@ -133179,7 +133299,7 @@ ${GITHUB_REPOSITORY_ID}`,
133179
133299
  // dist/commands/update.js
133180
133300
  import { spawn as spawn6 } from "node:child_process";
133181
133301
  import { randomBytes as randomBytes8 } from "node:crypto";
133182
- 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";
133302
+ import { closeSync as closeSync6, constants as constants2, fstatSync, mkdtempSync as mkdtempSync4, openSync as openSync6, readFileSync as readFileSync42, readSync as readSync2, rmSync as rmSync15, unlinkSync as unlinkSync5, writeFileSync as writeFileSync25 } from "node:fs";
133183
133303
  import { createServer } from "node:http";
133184
133304
  import { tmpdir as tmpdir2 } from "node:os";
133185
133305
  import { join as join48 } from "node:path";
@@ -133254,7 +133374,7 @@ async function runPinnedNpm(args, cwd, ambientEnvironment, userConfigPath, globa
133254
133374
  });
133255
133375
  }
133256
133376
  function snapshotAuthenticatedArtifact(tarballPath) {
133257
- const fd = openSync5(tarballPath, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
133377
+ const fd = openSync6(tarballPath, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
133258
133378
  try {
133259
133379
  const stat7 = fstatSync(fd);
133260
133380
  if (!stat7.isFile() || stat7.size <= 0 || stat7.size > MAX_UPDATE_BYTES) {
@@ -133263,14 +133383,14 @@ function snapshotAuthenticatedArtifact(tarballPath) {
133263
133383
  unlinkSync5(tarballPath);
133264
133384
  return readOpenArtifact(fd, stat7.size);
133265
133385
  } finally {
133266
- closeSync5(fd);
133386
+ closeSync6(fd);
133267
133387
  }
133268
133388
  }
133269
133389
  function readOpenArtifact(fd, size) {
133270
133390
  const bytes = Buffer.allocUnsafe(size);
133271
133391
  let offset = 0;
133272
133392
  while (offset < size) {
133273
- const count2 = readSync(fd, bytes, offset, size - offset, offset);
133393
+ const count2 = readSync2(fd, bytes, offset, size - offset, offset);
133274
133394
  if (count2 === 0)
133275
133395
  throw new Error("the downloaded update artifact ended while being verified");
133276
133396
  offset += count2;
@@ -135904,7 +136024,7 @@ import { randomUUID as randomUUID12 } from "node:crypto";
135904
136024
  import { setDefaultResultOrder } from "node:dns";
135905
136025
  import { lookup } from "node:dns/promises";
135906
136026
  import { existsSync as existsSync38, mkdirSync as mkdirSync20, readFileSync as readFileSync44, writeFileSync as writeFileSync26 } from "node:fs";
135907
- import { basename as basename11, dirname as dirname15, join as join49, relative as relative12, resolve as resolve24 } from "node:path";
136027
+ import { basename as basename11, dirname as dirname15, join as join49, relative as relative13, resolve as resolve24 } from "node:path";
135908
136028
  function launchOptions(extra = {}) {
135909
136029
  return { ...extra, args: ["--disable-features=AsyncDns", ...extra.args ?? []] };
135910
136030
  }
@@ -136132,7 +136252,7 @@ var init_app_test = __esm({
136132
136252
  }
136133
136253
  /** What this run tests: the project, environment, preview, origin and script. */
136134
136254
  identity() {
136135
- const script = process.argv[1] ? relative12(this.root, resolve24(process.argv[1])) : null;
136255
+ const script = process.argv[1] ? relative13(this.root, resolve24(process.argv[1])) : null;
136136
136256
  return {
136137
136257
  project_id: this.control.projectId,
136138
136258
  environment: this.control.environment,
@@ -136326,13 +136446,13 @@ page ${i + 1}: ${state}`).join("");
136326
136446
  ...check,
136327
136447
  ...check.error ? { error: scrub(check.error) } : {}
136328
136448
  }));
136329
- const resultFile = relative12(this.root, this.resultsPath);
136449
+ const resultFile = relative13(this.root, this.resultsPath);
136330
136450
  const handOver = process.env.SW_TEST_REPORT;
136331
136451
  if (handOver)
136332
136452
  writeFileSync26(handOver, JSON.stringify({ checks: reported, resultFile }) + "\n");
136333
136453
  else {
136334
136454
  const verbose = process.argv.includes("--verbose") || process.env.SW_TEST_VERBOSE === "1";
136335
- const script = process.argv[1] ? relative12(this.root, resolve24(process.argv[1])) : "this script";
136455
+ const script = process.argv[1] ? relative13(this.root, resolve24(process.argv[1])) : "this script";
136336
136456
  process.stdout.write(describeReport([{ script, checks: reported, resultFile }], { verbose }).join("\n") + "\n");
136337
136457
  }
136338
136458
  if (live !== this.release) {
@@ -136757,7 +136877,7 @@ var init_test_session = __esm({
136757
136877
 
136758
136878
  // dist/lib/prepared-actor-session.js
136759
136879
  import { createHash as createHash10 } from "node:crypto";
136760
- import { closeSync as closeSync6, openSync as openSync6, rmSync as rmSync16 } from "node:fs";
136880
+ import { closeSync as closeSync7, openSync as openSync7, rmSync as rmSync16 } from "node:fs";
136761
136881
  import { setTimeout as delay2 } from "node:timers/promises";
136762
136882
  async function preparedActorSession(root, target, name) {
136763
136883
  const read = /* @__PURE__ */ __name(() => preparedActorState(root, target, name), "read");
@@ -136770,7 +136890,7 @@ async function preparedActorSession(root, target, name) {
136770
136890
  while (Date.now() < deadline) {
136771
136891
  let fd;
136772
136892
  try {
136773
- fd = openSync6(lock, "wx", 384);
136893
+ fd = openSync7(lock, "wx", 384);
136774
136894
  } catch (error3) {
136775
136895
  if (error3.code !== "EEXIST")
136776
136896
  throw error3;
@@ -136792,7 +136912,7 @@ async function preparedActorSession(root, target, name) {
136792
136912
  writePrivateFile(latest.path, JSON.stringify(renewed, null, 2) + "\n");
136793
136913
  return token;
136794
136914
  } finally {
136795
- closeSync6(fd);
136915
+ closeSync7(fd);
136796
136916
  rmSync16(lock, { force: true });
136797
136917
  }
136798
136918
  }
@@ -136901,7 +137021,7 @@ var init_reference_check_note = __esm({
136901
137021
  // dist/lib/test-scripts.js
136902
137022
  import { createRequire as createRequire10 } from "node:module";
136903
137023
  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";
136904
- import { dirname as dirname16, join as join50, relative as relative13, resolve as resolve25 } from "node:path";
137024
+ import { dirname as dirname16, join as join50, relative as relative14, resolve as resolve25 } from "node:path";
136905
137025
  import { spawn as spawn7, spawnSync as spawnSync5 } from "node:child_process";
136906
137026
  function hasSpecFiles(root) {
136907
137027
  const walk2 = /* @__PURE__ */ __name((dir) => {
@@ -136920,7 +137040,7 @@ function hasSpecFiles(root) {
136920
137040
  }
136921
137041
  function listScripts(root, files) {
136922
137042
  if (files.length)
136923
- return files.map((file) => relative13(root, resolve25(root, file)));
137043
+ return files.map((file) => relative14(root, resolve25(root, file)));
136924
137044
  const dir = join50(root, "tests");
136925
137045
  if (!existsSync39(dir))
136926
137046
  return [];
@@ -138180,7 +138300,7 @@ __export(test_reporter_exports, {
138180
138300
  confirmedRelease: () => confirmedRelease,
138181
138301
  default: () => TestReporter
138182
138302
  });
138183
- import { relative as relative14 } from "node:path";
138303
+ import { relative as relative15 } from "node:path";
138184
138304
  function confirmedRelease(start, seen2, live) {
138185
138305
  if (!start || !live)
138186
138306
  return null;
@@ -138232,7 +138352,7 @@ var init_test_reporter = __esm({
138232
138352
  const location2 = result.errors[i]?.location;
138233
138353
  return location2 ? describeError({ message: "", location: location2 }).replace(/: $/, "") + ": " + message3 : message3;
138234
138354
  }) : result.errors.map((error3) => describeError(error3));
138235
- const file = relative14(process.cwd(), test2.location.file);
138355
+ const file = relative15(process.cwd(), test2.location.file);
138236
138356
  const skipReason = result.status === "skipped" ? scrub(result.annotations.find(({ type, description }) => type === "skip" && description)?.description ?? "no reason given").slice(0, 200) : void 0;
138237
138357
  const entry = { ...details, ...skipReason ? { skipReason } : {}, status: result.status, outcome: test2.outcome(), title: scrub(details.title).slice(0, 200), errors, step: result.steps.find((step2) => step2.error)?.category ?? "test body", file, line: test2.location.line };
138238
138358
  this.entries.push(entry);
@@ -139108,7 +139228,9 @@ var init_testing_jobs = __esm({
139108
139228
  // dist/lib/testing-app.js
139109
139229
  import { resolve as resolve26 } from "node:path";
139110
139230
  import { createRequire as createRequire12 } from "node:module";
139111
- import { join as join56 } from "node:path";
139231
+ import { execFileSync as execFileSync2 } from "node:child_process";
139232
+ import { readdirSync as readdirSync10 } from "node:fs";
139233
+ import { dirname as dirname17, join as join56 } from "node:path";
139112
139234
  async function openTestApp(options2 = {}) {
139113
139235
  const root = resolve26(options2.projectDir ?? process.cwd());
139114
139236
  const projectId = loadProjectConfig(root)?.project_id;
@@ -139158,6 +139280,17 @@ async function openTestApp(options2 = {}) {
139158
139280
  const actor = { name, id, email: email2, roles, session, ...callerOf(session, () => {
139159
139281
  routeWrites++;
139160
139282
  }) };
139283
+ const refusedAs2 = session.expectRefused.bind(session);
139284
+ session.expectRefused = async (...args) => {
139285
+ const what = typeof args[0] === "string" ? args[0] : "";
139286
+ const op = args[1] && typeof args[1] === "object" && "operation" in args[1] ? ` ${args[1].operation}` : "";
139287
+ try {
139288
+ await refusedAs2(...args);
139289
+ results.check(`refused: ${name} ${what}${op}`, true);
139290
+ } catch (error3) {
139291
+ results.check(`refused: ${name} ${what}${op}`, false, error3);
139292
+ }
139293
+ };
139161
139294
  actors.add(actor);
139162
139295
  managedFileSession(session, root, id);
139163
139296
  return actor;
@@ -139367,7 +139500,7 @@ async function openTestApp(options2 = {}) {
139367
139500
  }
139368
139501
  const reply = settled.value;
139369
139502
  const leaked = lacks.findIndex((text) => text && reply.text.includes(text));
139370
- const refused = allowed.includes(reply.status) || request2[0] === "DATA" && options3.status === void 0 && empty(reply);
139503
+ const refused = allowed.includes(reply.status) || request2[0] === "DATA" && options3.status === void 0 && empty(reply) || lacks.length > 0 && reply.ok && leaked < 0;
139371
139504
  if (!refused) {
139372
139505
  results.expect(reply, allowed, line);
139373
139506
  all = false;
@@ -139547,6 +139680,47 @@ function replySummary(reply) {
139547
139680
  const message3 = typeof body.message === "string" ? body.message : void 0;
139548
139681
  return `${reply.status}${reply.requestId ? ` (request ${reply.requestId})` : ""}${code ? ` ${code}` : ""}${message3 ? `: ${cut(message3, 200)}` : ""}`;
139549
139682
  }
139683
+ function findPlaywright(root, given) {
139684
+ if (given && typeof given === "object")
139685
+ return given;
139686
+ const require6 = createRequire12(join56(root, "package.json"));
139687
+ const load2 = /* @__PURE__ */ __name((name) => {
139688
+ try {
139689
+ const pw = require6(name);
139690
+ return pw?.chromium ? pw : void 0;
139691
+ } catch {
139692
+ return void 0;
139693
+ }
139694
+ }, "load");
139695
+ for (const name of [given, process.env.PLAYWRIGHT_MODULE, process.env.PW_PATH, "playwright", "@playwright/test"]) {
139696
+ const pw = name ? load2(name) : void 0;
139697
+ if (pw)
139698
+ return pw;
139699
+ }
139700
+ const dirs = [];
139701
+ const browsers = process.env.PLAYWRIGHT_BROWSERS_PATH;
139702
+ if (browsers) {
139703
+ const parent = dirname17(resolve26(browsers));
139704
+ dirs.push(join56(parent, "node_modules"), ...readdirSafe(parent).map((entry) => join56(parent, entry, "node_modules")));
139705
+ }
139706
+ try {
139707
+ dirs.push(execFileSync2("npm", ["root", "-g"], { encoding: "utf8", timeout: 5e3 }).trim());
139708
+ } catch {
139709
+ }
139710
+ for (const dir of dirs) {
139711
+ const pw = load2(join56(dir, "playwright"));
139712
+ if (pw)
139713
+ return pw;
139714
+ }
139715
+ throw new Error("app.page() needs Playwright and could not find it here, in NODE_PATH, globally or next to PLAYWRIGHT_BROWSERS_PATH. Pass its path: openTestApp({ playwright: '/path/to/node_modules/playwright' }) or set PLAYWRIGHT_MODULE. Or install it: npm install -D playwright && npx playwright install chromium");
139716
+ }
139717
+ function readdirSafe(dir) {
139718
+ try {
139719
+ return readdirSync10(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).slice(0, 50);
139720
+ } catch {
139721
+ return [];
139722
+ }
139723
+ }
139550
139724
  var SECRET_KEY, cut, Results, Pages;
139551
139725
  var init_testing_app = __esm({
139552
139726
  "dist/lib/testing-app.js"() {
@@ -139626,21 +139800,12 @@ var init_testing_app = __esm({
139626
139800
  }
139627
139801
  async open(state, path3) {
139628
139802
  this.browser ??= (() => {
139629
- const require6 = createRequire12(join56(this.root, "package.json"));
139630
- let pw = typeof this.playwright === "object" ? this.playwright : void 0;
139631
- for (const name of pw ? [] : [...typeof this.playwright === "string" ? [this.playwright] : [], "playwright", "@playwright/test"]) {
139632
- try {
139633
- pw = require6(name);
139634
- break;
139635
- } catch {
139636
- }
139637
- }
139638
- if (!pw?.chromium) {
139639
- throw new Error("app.page() needs Playwright. If it is installed outside this folder, pass its path: openTestApp({ playwright: '/path/to/node_modules/playwright' }). Otherwise: npm install -D playwright && npx playwright install chromium");
139640
- }
139641
- return pw.chromium.launch();
139803
+ const pw = findPlaywright(this.root, this.playwright);
139804
+ const { chromium } = pw;
139805
+ return process.platform === "darwin" ? chromium.launch({ channel: "chrome" }).catch(() => chromium.launch()) : chromium.launch();
139642
139806
  })();
139643
139807
  const context = await (await this.browser).newContext({ baseURL: this.origin, storageState: state });
139808
+ context.setDefaultTimeout(1e4);
139644
139809
  const page = await context.newPage();
139645
139810
  await page.goto(path3);
139646
139811
  if (await page.locator("html[data-sw-auth]").count()) {
@@ -139655,6 +139820,8 @@ var init_testing_app = __esm({
139655
139820
  await (await browser).close();
139656
139821
  }
139657
139822
  };
139823
+ __name(findPlaywright, "findPlaywright");
139824
+ __name(readdirSafe, "readdirSafe");
139658
139825
  }
139659
139826
  });
139660
139827