@somewhere-cloud/cli 0.38.160 → 0.38.161

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.38.161
4
+
5
+ - Syncs local runtime declarations with platform consumer contract 43. The declarations document the stop reasons for model refusals in `sw.ai.chat` and `sw.agent.run`.
6
+
3
7
  ## 0.38.160
4
8
 
5
9
  - Find complete examples with `somewhere docs example`. Search returns an outline and the best matching section in full. Add `--include-api` to include API reference topics.
@@ -52507,7 +52507,7 @@ var init_allowed_origins = __esm({
52507
52507
  // dist/commands/project.js
52508
52508
  function registerProject(program2) {
52509
52509
  const proj = program2.command("project").description("Manage projects");
52510
- proj.command("create <name>").description("Create a new project").option("--subdomain <subdomain>", "Custom subdomain").addOption(new Option("--preview").hideHelp()).option("--json", "Print the raw project response as JSON").action(async (name, opts) => {
52510
+ proj.command("create <name>").description("Create a new project").option("--subdomain <subdomain>", "Custom subdomain").option("--json", "Print the raw project response as JSON").action(async (name, opts) => {
52511
52511
  const client = new ApiClient(getToken());
52512
52512
  const spinner = opts.json ? null : ora("Creating project...").start();
52513
52513
  try {
@@ -74331,11 +74331,20 @@ __export(declared_data_exports, {
74331
74331
  FILES_DECLARATION_FILE: () => FILES_DECLARATION_FILE,
74332
74332
  GENERATED_DATA_HEADER: () => GENERATED_DATA_HEADER,
74333
74333
  declaredDataPlugin: () => declaredDataPlugin,
74334
+ localFilesContract: () => localFilesContract,
74334
74335
  prepareDeclaredData: () => prepareDeclaredData
74335
74336
  });
74336
74337
  import { existsSync as existsSync11, readFileSync as readFileSync13, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "node:fs";
74337
74338
  import { createRequire as createRequire4 } from "node:module";
74338
74339
  import { join as join12, resolve as resolve5 } from "node:path";
74340
+ function localFilesContract(projectDir) {
74341
+ const path3 = join12(projectDir, "db", "schema.ts");
74342
+ const generator = require4("./runtime/declared-data.cjs");
74343
+ const digest = existsSync11(path3) && generator.filesContractFromFiles({ "db/schema.ts": readFileSync13(path3, "utf8") });
74344
+ if (!digest)
74345
+ throw new Error("Declare file collections in db/schema.ts and deploy the app before testing files.");
74346
+ return { digest, singleRequestMaxBytes: generator.SINGLE_REQUEST_MAX_BYTES };
74347
+ }
74339
74348
  function generatedContents(path3) {
74340
74349
  const previous = existsSync11(path3) ? readFileSync13(path3, "utf8") : void 0;
74341
74350
  if (previous !== void 0 && !previous.startsWith(GENERATED_DATA_HEADER)) {
@@ -74470,6 +74479,7 @@ var init_declared_data = __esm({
74470
74479
  `;
74471
74480
  require4 = createRequire4(CLI_PACKAGE_ROOT);
74472
74481
  FILES_DECLARATION_FILE = require4("./runtime/declared-data.cjs").FILES_DECLARATION_FILE;
74482
+ __name(localFilesContract, "localFilesContract");
74473
74483
  __name(generatedContents, "generatedContents");
74474
74484
  __name(prepareDeclaredData, "prepareDeclaredData");
74475
74485
  __name(declaredDataPlugin, "declaredDataPlugin");
@@ -78942,7 +78952,9 @@ function messagesAfter(messages, address, since) {
78942
78952
  subject: String(m2.subject ?? ""),
78943
78953
  verification_code: typeof m2.verification_code === "string" && m2.verification_code ? m2.verification_code : null,
78944
78954
  magic_link: typeof m2.magic_link === "string" && m2.magic_link ? m2.magic_link : null,
78945
- created_at: String(m2.created_at ?? "")
78955
+ created_at: String(m2.created_at ?? ""),
78956
+ text: typeof m2.text === "string" ? m2.text : null,
78957
+ html: typeof m2.html === "string" ? m2.html : null
78946
78958
  })).filter((m2) => m2.to.toLowerCase() === want && Date.parse(m2.created_at) > since).sort((a, b2) => Date.parse(b2.created_at) - Date.parse(a.created_at));
78947
78959
  }
78948
78960
  function parseSince(value) {
@@ -79562,14 +79574,14 @@ var init_test_diagnostics = __esm({
79562
79574
 
79563
79575
  // dist/lib/test-control.js
79564
79576
  import { join as join28 } from "node:path";
79565
- function productionControl(client, target) {
79577
+ function productionControl(client, target, options2 = {}) {
79566
79578
  const projectId = target.projectId;
79567
79579
  return {
79568
79580
  environment: "production",
79569
79581
  projectId,
79570
79582
  target,
79571
79583
  async inbox(address, wait) {
79572
- const body = await client.call("GET", "/email/test-inbox", void 0, { project_id: projectId, address, limit: 20, ...wait ? { wait_ms: wait.ms ?? 1e4, since: wait.since } : {} });
79584
+ 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 } : {} });
79573
79585
  return messagesAfter(body.messages, address, 0);
79574
79586
  },
79575
79587
  deleteSignups: /* @__PURE__ */ __name((ids) => deleteAccounts(client, projectId, ids), "deleteSignups"),
@@ -88077,7 +88089,7 @@ async function fetchDocsSearch(query, topic, includeApi) {
88077
88089
  results: results.map(({ content, ...match }) => ({
88078
88090
  ...match,
88079
88091
  snippet: content,
88080
- open: match.section ? `${cliInvocation()} docs ${commandArg(match.topic)} --section ${commandArg(match.section)}` : `${cliInvocation()} docs ${commandArg(match.topic)} --full`
88092
+ open: match.example ? `${cliInvocation()} docs example ${commandArg(match.example)}` : match.section ? `${cliInvocation()} docs ${commandArg(match.topic)} --section ${commandArg(match.section)}` : `${cliInvocation()} docs ${commandArg(match.topic)} --full`
88081
88093
  })),
88082
88094
  total,
88083
88095
  version: docsVersion(version2)
@@ -88261,7 +88273,7 @@ Examples:
88261
88273
  }
88262
88274
  for (const result of results) {
88263
88275
  console.log(`${result.topic}${result.section ? ` \u203A ${result.section}` : ""} ${dim(result.heading ?? result.title)}`);
88264
- console.log(dim(result.open));
88276
+ console.log(dim(result.example ? `Full example: ${result.open}` : result.open));
88265
88277
  }
88266
88278
  if (results[0].snippet)
88267
88279
  console.log(`
@@ -135504,7 +135516,69 @@ var init_test_refusal = __esm({
135504
135516
  }
135505
135517
  });
135506
135518
 
135519
+ // dist/lib/test-files.js
135520
+ function transfer(url3, init) {
135521
+ if (new URL(url3).protocol !== "https:")
135522
+ throw new Error("Expected an HTTPS file transfer URL.");
135523
+ return fetch(url3, { ...init, credentials: "omit", redirect: "error" });
135524
+ }
135525
+ async function transferTestFile(link, file, type, singleRequestMaxBytes) {
135526
+ if (file.size <= singleRequestMaxBytes) {
135527
+ return transfer(link.url, { method: "PUT", headers: { "Content-Type": type }, body: file });
135528
+ }
135529
+ const start = await transfer(link.multipart_url, {
135530
+ method: "POST",
135531
+ headers: { "Content-Type": "application/json" },
135532
+ body: JSON.stringify({ size_bytes: file.size, content_type: type })
135533
+ });
135534
+ if (!start.ok)
135535
+ return start;
135536
+ const { data: data2 } = await start.json();
135537
+ const abort = /* @__PURE__ */ __name(async () => {
135538
+ await transfer(data2.abort_url, { method: "DELETE" }).catch(() => {
135539
+ });
135540
+ }, "abort");
135541
+ try {
135542
+ for (let n = 1; n <= data2.part_count; n++) {
135543
+ const from = (n - 1) * data2.part_size;
135544
+ const part = await transfer(data2.parts_url + "/" + n, {
135545
+ method: "PUT",
135546
+ body: file.slice(from, from + data2.part_size)
135547
+ });
135548
+ if (!part.ok) {
135549
+ await abort();
135550
+ return part;
135551
+ }
135552
+ await part.body?.cancel();
135553
+ }
135554
+ return await transfer(data2.complete_url, { method: "POST" });
135555
+ } catch (error3) {
135556
+ await abort();
135557
+ throw error3;
135558
+ }
135559
+ }
135560
+ var init_test_files = __esm({
135561
+ "dist/lib/test-files.js"() {
135562
+ "use strict";
135563
+ __name(transfer, "transfer");
135564
+ __name(transferTestFile, "transferTestFile");
135565
+ }
135566
+ });
135567
+
135507
135568
  // dist/lib/test-session.js
135569
+ function managedFileSession(session, root, userId) {
135570
+ managedFiles.set(session, { root, userId });
135571
+ }
135572
+ function sessionSubject(token) {
135573
+ const payload = token?.split(".")[1];
135574
+ if (!payload)
135575
+ return void 0;
135576
+ try {
135577
+ return JSON.parse(Buffer.from(payload, "base64url").toString()).sub;
135578
+ } catch {
135579
+ return void 0;
135580
+ }
135581
+ }
135508
135582
  async function expectStatus(response, expected) {
135509
135583
  if (response.status !== expected)
135510
135584
  throw new Error("Expected HTTP " + expected + ", received " + response.status);
@@ -135536,15 +135610,20 @@ async function createUser(baseUrl) {
135536
135610
  throw new Error("Signup did not establish a cookie session");
135537
135611
  return session;
135538
135612
  }
135539
- var UserSession;
135613
+ var managedFiles, UserSession;
135540
135614
  var init_test_session = __esm({
135541
135615
  "dist/lib/test-session.js"() {
135542
135616
  "use strict";
135543
135617
  init_test_refusal();
135618
+ init_declared_data();
135619
+ init_test_files();
135544
135620
  init_client();
135545
135621
  init_config();
135546
135622
  init_test_target();
135547
135623
  init_test_identities();
135624
+ managedFiles = /* @__PURE__ */ new WeakMap();
135625
+ __name(managedFileSession, "managedFileSession");
135626
+ __name(sessionSubject, "sessionSubject");
135548
135627
  UserSession = class {
135549
135628
  static {
135550
135629
  __name(this, "UserSession");
@@ -135664,6 +135743,50 @@ var init_test_session = __esm({
135664
135743
  }), "adapt");
135665
135744
  await assertRefused(adapt(this), target, request2, allowed && adapt(allowed));
135666
135745
  }
135746
+ /** Exercise the declared file door as a managed test user. */
135747
+ async files(collection, request2) {
135748
+ const fixture = managedFiles.get(this);
135749
+ if (!fixture)
135750
+ throw new Error("Choose a session created by openTestApp().users() or signInWithLink().");
135751
+ await this.ensureFresh();
135752
+ if (sessionSubject(this.cookies.get(ACCESS_COOKIE)) !== fixture.userId) {
135753
+ throw new Error("This session no longer belongs to its managed test user.");
135754
+ }
135755
+ const url3 = /* @__PURE__ */ __name((id) => "/__sw/files/" + encodeURIComponent(collection) + "/" + encodeURIComponent(id), "url");
135756
+ if (request2.operation === "url")
135757
+ return this.request(url3(request2.id));
135758
+ const { digest: contract2, singleRequestMaxBytes } = fixture.contract ??= localFilesContract(fixture.root);
135759
+ const post2 = /* @__PURE__ */ __name((operation, fields) => this.post("/__sw/files", { ...fields, contract: contract2, collection, operation }), "post");
135760
+ switch (request2.operation) {
135761
+ case "list":
135762
+ return post2("list", { ...request2.scope, limit: request2.limit, cursor: request2.cursor });
135763
+ case "shareLink":
135764
+ return post2("link", { id: request2.id, expires_in: request2.expiresIn });
135765
+ case "delete":
135766
+ return post2("delete", { id: request2.id });
135767
+ case "upload": {
135768
+ const { file } = request2;
135769
+ const name = request2.name || (file instanceof File ? file.name : "file");
135770
+ const type = (request2.contentType || file.type || "application/octet-stream").split(";")[0].trim().toLowerCase();
135771
+ const minted = await post2("upload", { ...request2.scope, name, size: file.size, content_type: type });
135772
+ if (!minted.ok)
135773
+ return minted;
135774
+ const { data: link } = await minted.json();
135775
+ const uploaded = await transferTestFile(link, file, type, singleRequestMaxBytes);
135776
+ if (!uploaded.ok)
135777
+ return uploaded;
135778
+ const { data: data2 } = await uploaded.json();
135779
+ return Response.json({ ok: true, data: {
135780
+ id: link.id,
135781
+ name: link.name ?? name,
135782
+ size: data2.size_bytes,
135783
+ content_type: data2.content_type,
135784
+ version: data2.version,
135785
+ url: url3(link.id)
135786
+ } }, { status: uploaded.status });
135787
+ }
135788
+ }
135789
+ }
135667
135790
  async data(table2, requestOrContract, request2) {
135668
135791
  if (typeof requestOrContract === "string") {
135669
135792
  return this.post("/__sw/data", { ...request2, table: table2, contract: requestOrContract });
@@ -138032,6 +138155,7 @@ async function openTestApp(options2 = {}) {
138032
138155
  const client = tool ? void 0 : new ApiClient(testingDeveloperToken());
138033
138156
  const target = tool && setup ? await readPreviewTarget(tool, projectId, setup.previewSessionId) : await loadTestTarget(client, projectId);
138034
138157
  const control = tool ? previewControl(tool, target) : void 0;
138158
+ const inbox2 = control ?? productionControl(client, target, { liveInboxOnly: true });
138035
138159
  const origin = target.origin;
138036
138160
  const emptyState = { cookies: [], origins: [] };
138037
138161
  const cookie = await control?.previewCookie?.();
@@ -138049,6 +138173,8 @@ async function openTestApp(options2 = {}) {
138049
138173
  }
138050
138174
  const ids = /* @__PURE__ */ new Set();
138051
138175
  const actors = /* @__PURE__ */ new Set();
138176
+ const recipients = /* @__PURE__ */ new Map();
138177
+ const signInLinks = /* @__PURE__ */ new Map();
138052
138178
  const cleanupSteps = [];
138053
138179
  let closed = false;
138054
138180
  const open4 = /* @__PURE__ */ __name(() => {
@@ -138058,6 +138184,7 @@ async function openTestApp(options2 = {}) {
138058
138184
  const add = /* @__PURE__ */ __name((id, email2, session) => {
138059
138185
  const actor = { id, email: email2, session };
138060
138186
  actors.add(actor);
138187
+ managedFileSession(session, root, id);
138061
138188
  return actor;
138062
138189
  }, "add");
138063
138190
  const onCleanup = /* @__PURE__ */ __name((label, action) => {
@@ -138110,6 +138237,7 @@ async function openTestApp(options2 = {}) {
138110
138237
  open4();
138111
138238
  if (!Number.isInteger(count2) || count2 < 1 || count2 > 25)
138112
138239
  throw new Error("Choose 1 to 25 test users.");
138240
+ const since = Date.now();
138113
138241
  if (control) {
138114
138242
  const out2 = [];
138115
138243
  for (let i = 0; i < count2; i++) {
@@ -138119,6 +138247,7 @@ async function openTestApp(options2 = {}) {
138119
138247
  const login = await session.post("/api/auth/login", { email: user.email, password: user.password });
138120
138248
  if (!login.ok)
138121
138249
  throw new Error(`Could not sign in preview test user ${user.id} (HTTP ${login.status}).`);
138250
+ recipients.set(user.email.toLowerCase(), { id: user.id, email: user.email, since });
138122
138251
  out2.push(add(user.id, user.email, session));
138123
138252
  }
138124
138253
  return out2;
@@ -138131,6 +138260,7 @@ async function openTestApp(options2 = {}) {
138131
138260
  ids.add(identity.user.id);
138132
138261
  for (const identity of issued) {
138133
138262
  const state = buildStorageState(origin, new URL(origin).hostname, identity, expiryOf(identity, receivedAt));
138263
+ recipients.set(identity.user.email.toLowerCase(), { ...identity.user, since });
138134
138264
  out.push(add(identity.user.id, identity.user.email, new UserSession(origin, { target, storageState: state })));
138135
138265
  }
138136
138266
  }
@@ -138144,6 +138274,46 @@ async function openTestApp(options2 = {}) {
138144
138274
  throw error3;
138145
138275
  }
138146
138276
  },
138277
+ async testInbox(email2) {
138278
+ open4();
138279
+ const recipient = recipients.get(email2.toLowerCase());
138280
+ if (!recipient)
138281
+ throw new Error("Choose a test email created by this test app.");
138282
+ const messages = await inbox2.inbox(recipient.email, { since: recipient.since, ms: 3e3 });
138283
+ open4();
138284
+ return messages.filter((message3) => Date.parse(message3.created_at) > recipient.since).map((message3) => {
138285
+ const links = /* @__PURE__ */ new Set();
138286
+ if (message3.magic_link) {
138287
+ links.add(message3.magic_link);
138288
+ const url3 = URL.parse(message3.magic_link);
138289
+ if (url3?.origin === origin && url3.pathname === "/auth/magic" && url3.searchParams.get("token")) {
138290
+ signInLinks.set(message3.magic_link, recipient);
138291
+ }
138292
+ }
138293
+ for (const match of [message3.text, message3.html].join(" ").matchAll(/https?:\/\/[^\s<>"']+/gi)) {
138294
+ links.add(match[0].replaceAll("&amp;", "&").replace(/[.,]+$/, ""));
138295
+ }
138296
+ return { ...message3, links: [...links] };
138297
+ });
138298
+ },
138299
+ async signInWithLink(url3) {
138300
+ open4();
138301
+ const recipient = signInLinks.get(url3);
138302
+ if (!recipient)
138303
+ throw new Error("Use a sign-in link from this test app\u2019s inbox.");
138304
+ signInLinks.delete(url3);
138305
+ const token = new URL(url3).searchParams.get("token");
138306
+ const session = new UserSession(origin, { target, storageState: emptyState });
138307
+ const response = await session.post("/api/auth/magic-link/verify", { token });
138308
+ open4();
138309
+ if (!response.ok)
138310
+ throw new Error(`Could not sign in with the link (HTTP ${response.status}).`);
138311
+ const body = await response.json();
138312
+ if (!body.cookie_session || body.user?.id !== recipient.id || body.user.email?.toLowerCase() !== recipient.email.toLowerCase()) {
138313
+ throw new Error("The link did not sign in the expected test user.");
138314
+ }
138315
+ return add(recipient.id, recipient.email, session);
138316
+ },
138147
138317
  create,
138148
138318
  async plantMarker(user, table2, field2, values = {}) {
138149
138319
  const marker = privateMarker();
@@ -138159,6 +138329,7 @@ async function openTestApp(options2 = {}) {
138159
138329
  if (closed)
138160
138330
  return;
138161
138331
  closed = true;
138332
+ signInLinks.clear();
138162
138333
  const remains = [];
138163
138334
  for (const { label, action } of cleanupSteps.reverse()) {
138164
138335
  try {