@rebasepro/cli 0.26.0 → 0.27.0

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.
Files changed (34) hide show
  1. package/dist/{apps-CnLDV5b6.js → apps-CdrFm7Y3.js} +2 -2
  2. package/dist/{apps-CnLDV5b6.js.map → apps-CdrFm7Y3.js.map} +1 -1
  3. package/dist/{build-Cza7ZQrp.js → build-D-t5FSg0.js} +10 -10
  4. package/dist/build-D-t5FSg0.js.map +1 -0
  5. package/dist/{bundle-C6yEtMJ-.js → bundle-CrAWbpbG.js} +120 -19
  6. package/dist/bundle-CrAWbpbG.js.map +1 -0
  7. package/dist/bundle.d.ts +25 -11
  8. package/dist/{cloud-BdnmqQaZ.js → cloud-B2_oJmK7.js} +369 -41
  9. package/dist/cloud-B2_oJmK7.js.map +1 -0
  10. package/dist/commands/cloud/auth.d.ts +13 -0
  11. package/dist/commands/cloud/bundle-deploy.d.ts +8 -15
  12. package/dist/commands/cloud/guests.d.ts +11 -0
  13. package/dist/commands/cloud/index.d.ts +1 -0
  14. package/dist/commands/cloud/projects.d.ts +4 -0
  15. package/dist/commands/cloud/resources.d.ts +22 -0
  16. package/dist/{fold-static-BnAK-anQ.js → fold-static-BGlpi22F.js} +2 -2
  17. package/dist/{fold-static-BnAK-anQ.js.map → fold-static-BGlpi22F.js.map} +1 -1
  18. package/dist/index.es.js +10 -10
  19. package/dist/{normalize-imports-D0zXlM6g.js → normalize-imports-CK_Mpcej.js} +2 -2
  20. package/dist/{normalize-imports-D0zXlM6g.js.map → normalize-imports-CK_Mpcej.js.map} +1 -1
  21. package/dist/{start-mVb6upwY.js → start-CflvYL60.js} +2 -2
  22. package/dist/{start-mVb6upwY.js.map → start-CflvYL60.js.map} +1 -1
  23. package/dist/utils/bundle-lock.d.ts +9 -0
  24. package/package.json +8 -8
  25. package/templates/overlays/baas/README.md +2 -2
  26. package/templates/overlays/baas/ai-instructions.md +3 -2
  27. package/templates/overlays/baas/package.json +1 -0
  28. package/templates/overlays/baas/pnpm-workspace.yaml +4 -0
  29. package/templates/template/.env.example +1 -1
  30. package/templates/template/ai-instructions.md +4 -3
  31. package/templates/template/pnpm-workspace.yaml +4 -1
  32. package/dist/build-Cza7ZQrp.js.map +0 -1
  33. package/dist/bundle-C6yEtMJ-.js.map +0 -1
  34. package/dist/cloud-BdnmqQaZ.js.map +0 -1
@@ -2,11 +2,11 @@ import { i as recordEvent, l as durationBucket } from "./telemetry-CgwJPVMO.js";
2
2
  import { C as switchOn, D as unknownCommandMessage, c as findProjectRoot, p as requireProjectRoot } from "./project-CasK56vN.js";
3
3
  import { t as cliUserAgent } from "./version-Buyyo1ut.js";
4
4
  import { _ as selectDeployApp, d as findBackendApp, f as formatAppAddress, l as cmsMountOf, p as loadManifest } from "./manifest-BtzDy7KQ.js";
5
- import { o as buildBundle, x as toolStdio } from "./bundle-C6yEtMJ-.js";
5
+ import { C as toolStdio, n as UNVENDORED_COST, s as buildBundle, x as unvendoredReason } from "./bundle-CrAWbpbG.js";
6
6
  import { $ as resolveCloudUrl, A as lookupProjectId, B as projectLinkPath, C as grantForLink, D as isKnownControlPlane, E as isJsonMode, F as printGroupHelp, G as requireClient, H as refuseDirectLink, I as printJson, J as requireKnownAction, K as requireCloudRow, L as probeToken, M as noteBlank, N as openUrl, O as keyValues, P as parseCloudArgs, Q as resolveCloudTarget, R as projectDotenvSetsAppKey, S as getContextOrg, T as initOutputMode, U as removeLink, V as readLink, W as reportError, X as requireProjectRef, Y as requireProject, Z as requireSessionClient, _ as fail, _t as orgCapabilitiesInScopes, a as billingAccountIdOf, at as storedGrantForLink, b as forgetEphemeralGrant, bt as wantsRawError, c as colorStatus, ct as writeLink, d as displayProjectRef, dt as ORG_CAPABILITY_NAMES, et as resolveProjectRef, f as dotenvSets, ft as TOKEN_CAPABILITIES, g as ephemeralGrantFor, gt as isTokenCapability, h as envToken, ht as isOrgCapability, i as appKeyExpiryNote, it as setCurrentContext, j as note, k as linkedEphemeralGrant, l as confirmDestructive, lt as ALWAYS_SCOPES, m as emitHelp, mt as capabilitiesInScopes, n as GLOBAL_HELP_FLAGS, nt as saveEphemeralGrant, o as cloudRow, ot as success, p as emit, pt as TOKEN_CAPABILITY_NAMES, q as requireInteractive, r as TOKEN_ENV, rt as setContextOrg, s as cloudRows, st as warn, t as GLOBAL_CLOUD_FLAGS, tt as resolveTimeoutMs, u as createCloudClient, ut as ORG_CAPABILITIES, v as fetchDeployTargets, vt as scopesForCapabilities, w as grantProjectOf, x as freshAccessToken, y as fetchTenantBaseDomain, yt as scopesForOrgCapabilities, z as projectHost } from "./context-GUxkZm-S.js";
7
- import { n as foldFrontendIntoBundle, r as foldableApps } from "./fold-static-BnAK-anQ.js";
7
+ import { n as foldFrontendIntoBundle, r as foldableApps } from "./fold-static-BGlpi22F.js";
8
8
  import { n as deriveOptionsFor, r as deriveResourceGraph } from "./derive-ae9UOoOB.js";
9
- import { t as buildAssetApp } from "./build-Cza7ZQrp.js";
9
+ import { t as buildAssetApp } from "./build-D-t5FSg0.js";
10
10
  import chalk from "chalk";
11
11
  import arg from "arg";
12
12
  import fs from "fs";
@@ -16,6 +16,7 @@ import { execFileSync, spawn } from "child_process";
16
16
  import dotenv from "dotenv";
17
17
  import { DEFAULT_STORAGE_SOURCE_KEY } from "@rebasepro/types";
18
18
  import inquirer from "inquirer";
19
+ import { RebaseApiError, createRebaseClient } from "@rebasepro/client";
19
20
  import net from "node:net";
20
21
  import { parse } from "acorn";
21
22
  /**
@@ -731,6 +732,41 @@ async function whoamiToken(client, url) {
731
732
  } : null
732
733
  });
733
734
  }
735
+ /**
736
+ * `rebase cloud access-token` — the bearer this CLI would send right now.
737
+ *
738
+ * For tools that reach the control plane on a person's behalf without a second
739
+ * login: the MCP server reads a project's data through the console's Studio
740
+ * proxy with it, so whoever is signed in to Rebase Cloud reaches every project
741
+ * their organizations hold, and no service key leaves the control plane. It is
742
+ * the same credential `requireClient` resolves — `REBASE_TOKEN`, the token
743
+ * `init --claim` stored for a linked project, or the login, refreshed first when
744
+ * it is close to expiry — so the control plane checks it exactly as it checks
745
+ * this CLI. The token is printed bare, so `$(rebase cloud access-token)` works.
746
+ */
747
+ async function accessTokenCommand(rawArgs) {
748
+ parseCloudArgs({
749
+ spec: {},
750
+ rawArgs,
751
+ commandWords: 2,
752
+ command: "cloud access-token",
753
+ maxPositionals: 0
754
+ });
755
+ const { client, url } = await requireClient(rawArgs);
756
+ let token;
757
+ try {
758
+ token = await freshAccessToken(client);
759
+ } catch {
760
+ fail("The session could not be refreshed.", "Run `rebase cloud login` again.", "session_invalid");
761
+ }
762
+ const session = client.auth.getSession();
763
+ const expiresAt = session?.accessToken === token ? session.expiresAt : null;
764
+ emit(() => console.log(token), {
765
+ host: url,
766
+ accessToken: token,
767
+ expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null
768
+ });
769
+ }
734
770
  //#endregion
735
771
  //#region src/commands/cloud/link.ts
736
772
  /**
@@ -1260,6 +1296,27 @@ async function statusCommand(rawArgs) {
1260
1296
  }
1261
1297
  }
1262
1298
  /**
1299
+ * One row per instance, under a header, for `cloud metrics`.
1300
+ *
1301
+ * Per instance because that is the question: where the sockets landed. A group
1302
+ * that stays on one instance shows as `skipped` climbing while `to bus` stays
1303
+ * flat, and both count from when that instance started.
1304
+ */
1305
+ function realtimeTable(instances) {
1306
+ const row = (name, cells) => `${name.padEnd(34)} ${cells.map((cell, i) => String(cell ?? "—").padStart(i < 2 ? 8 : 9)).join(" ")}`;
1307
+ return [row("", [
1308
+ "sockets",
1309
+ "channels",
1310
+ "to bus",
1311
+ "skipped"
1312
+ ]), ...instances.map(({ name, realtime: r }) => row(name ?? "?", [
1313
+ r?.sockets,
1314
+ r?.channels,
1315
+ r?.busFramesPublished,
1316
+ r?.busFramesSkipped
1317
+ ]))];
1318
+ }
1319
+ /**
1263
1320
  * CPU with the ceiling it is a percentage of.
1264
1321
  *
1265
1322
  * A bare "0.2%" is unreadable without knowing 0.2% of what, and on a burstable
@@ -1287,10 +1344,13 @@ async function metricsCommand(rawArgs) {
1287
1344
  const { client } = await requireClient(rawArgs);
1288
1345
  const projectId = await requireProject(rawArgs, client);
1289
1346
  try {
1290
- const m = await client.functions.invoke("metrics", void 0, {
1347
+ const [m, realtime] = await Promise.all([client.functions.invoke("metrics", void 0, {
1291
1348
  method: "GET",
1292
1349
  path: projectId
1293
- });
1350
+ }), client.functions.invoke("metrics", void 0, {
1351
+ method: "GET",
1352
+ path: `${projectId}/realtime`
1353
+ }).catch(() => null)]);
1294
1354
  const of = m.subject?.workload ? `${m.subject.workload}${m.subject.kind === "deployment" ? " (backend only — not the database)" : ""}` : void 0;
1295
1355
  const sampled = m.subject?.sampledInstances;
1296
1356
  const coverage = sampled === void 0 ? void 0 : sampled === 0 ? chalk.yellow("no instances reported yet") : `${sampled} instance${sampled === 1 ? "" : "s"}`;
@@ -1324,6 +1384,11 @@ async function metricsCommand(rawArgs) {
1324
1384
  if (i.waitingReason) note(chalk.gray(` waiting: ${i.waitingReason}`));
1325
1385
  }
1326
1386
  }
1387
+ if (realtime?.instances?.length) {
1388
+ console.log("");
1389
+ note(" Realtime, since each instance started");
1390
+ for (const line of realtimeTable(realtime.instances)) note(` ${line}`);
1391
+ }
1327
1392
  console.log("");
1328
1393
  }, {
1329
1394
  projectId,
@@ -1335,7 +1400,8 @@ async function metricsCommand(rawArgs) {
1335
1400
  subject: m.subject ?? null,
1336
1401
  allocation: m.allocation ?? null,
1337
1402
  instances: m.instances ?? null,
1338
- condition: m.condition ?? null
1403
+ condition: m.condition ?? null,
1404
+ realtime: realtime?.instances ?? null
1339
1405
  });
1340
1406
  } catch (e) {
1341
1407
  reportError(e, "Failed to fetch metrics");
@@ -2199,6 +2265,8 @@ async function computeCommand(action, rawArgs) {
2199
2265
  ["App CPU", dialLine(project.cpu)],
2200
2266
  ["App memory", dialLine(project.memory)],
2201
2267
  ["App replicas", dialLine(project.replicaCount)],
2268
+ ["Autoscale ceiling", project.autoscaleMaxReplicas === null || project.autoscaleMaxReplicas === void 0 ? chalk.gray("off") : dialLine(project.autoscaleMaxReplicas)],
2269
+ ["Autoscale CPU target", project.autoscaleTargetCpuPercent === null || project.autoscaleTargetCpuPercent === void 0 ? dialLine(void 0) : `${dialLine(project.autoscaleTargetCpuPercent)}%`],
2202
2270
  ["Capacity", dialLine(project.preemptible, {
2203
2271
  true: "spot",
2204
2272
  false: "on demand"
@@ -2227,6 +2295,8 @@ async function computeCommand(action, rawArgs) {
2227
2295
  cpu: project.cpu ?? null,
2228
2296
  memory: project.memory ?? null,
2229
2297
  replicaCount: project.replicaCount ?? null,
2298
+ autoscaleMaxReplicas: project.autoscaleMaxReplicas ?? null,
2299
+ autoscaleTargetCpuPercent: project.autoscaleTargetCpuPercent ?? null,
2230
2300
  preemptible: project.preemptible ?? null,
2231
2301
  scaleToZero: project.scaleToZero ?? null,
2232
2302
  databaseInstances: project.databaseInstances ?? null,
@@ -3253,16 +3323,18 @@ function printDbHelp() {
3253
3323
  /**
3254
3324
  * `rebase cloud projects` — list / create / info / delete.
3255
3325
  */
3326
+ /** Documented in `action-help.ts`, and paired with it by `action-help.test.ts`. */
3327
+ var LIST_PROJECTS_FLAGS = { "--all-orgs": Boolean };
3256
3328
  async function listProjects(rawArgs) {
3257
- parseCloudArgs({
3258
- spec: {},
3329
+ const { flags: args } = parseCloudArgs({
3330
+ spec: LIST_PROJECTS_FLAGS,
3259
3331
  rawArgs,
3260
3332
  commandWords: 3,
3261
3333
  command: "cloud projects",
3262
3334
  maxPositionals: 0
3263
3335
  });
3264
3336
  const { client, url } = await requireClient(rawArgs);
3265
- const org = getContextOrg(url);
3337
+ const org = args["--all-orgs"] ? void 0 : getContextOrg(url);
3266
3338
  try {
3267
3339
  const [projects, baseDomain] = await Promise.all([client.data.collection("projects").find({
3268
3340
  where: org ? { organization: ["==", org] } : void 0,
@@ -6154,7 +6226,7 @@ function readBundleManifest(bundleDir) {
6154
6226
  * The control plane's cap on an uploaded bundle: its `MAX_BUNDLE_BYTES`, which
6155
6227
  * it checks before reading the body.
6156
6228
  */
6157
- var MAX_BUNDLE_UPLOAD_BYTES = 100 * 1024 * 1024;
6229
+ var MAX_BUNDLE_UPLOAD_BYTES = 1024 * 1024 * 1024;
6158
6230
  /**
6159
6231
  * Tar a built bundle into a gzipped archive.
6160
6232
  *
@@ -6184,34 +6256,44 @@ function packBundle(bundleDir, outPath, options = {}) {
6184
6256
  });
6185
6257
  }
6186
6258
  /**
6187
- * Pack a bundle for upload — without `node_modules`, even a vendored tree.
6259
+ * Pack a bundle for upload, with the dependency tree the build vendored for it.
6188
6260
  *
6189
- * Vendoring exists so a pod untars and boots rather than spending 35-55s of
6190
- * every start in `npm install`, and a deploy did carry the tree for one night
6191
- * (c36ea4637). It is left out again because of what the control plane does
6192
- * with the archive: `GET /bundle/:projectId/:bundleId` reads the whole object
6193
- * into memory on every pod start, and a runtime rollout restarts every tenant's
6194
- * pods at once. Bundles it was sized against are a few hundred kB; a vendored
6195
- * one is tens of MB, up to the 100 MB cap — N pods starting together would hold
6196
- * N of them. A slower cold start per pod is the status quo every deploy has
6197
- * shipped with; a control plane out of memory is every tenant's outage. The
6198
- * platform's own rebuilds build with `--no-vendor` for the same shape of
6199
- * reason. When the control plane streams bundles, this is the one switch to
6200
- * flip, and `rebase cloud deploy` builds with `vendor: false` until then.
6261
+ * Vendoring is what lets a pod untar and boot rather than spending 35-55s of
6262
+ * every start in `npm install`, which is the bulk of a new instance's time to
6263
+ * ready. The control plane streams an archive in both directions, so its size
6264
+ * costs that process nothing.
6201
6265
  *
6202
- * `modulesLeftOut` says a tree the build DID vendor was not uploaded — a
6203
- * prebuilt `--bundle-dir` from a plain `rebase build`, which vendors by default.
6266
+ * A vendored tree that takes the archive over the cap is left out rather than
6267
+ * failing the deploy: a bundle without its dependencies still boots, only more
6268
+ * slowly. `modulesLeftOut` says that happened.
6204
6269
  */
6205
6270
  async function packBundleForUpload(bundleDir, outPath, manifest, maxBytes = MAX_BUNDLE_UPLOAD_BYTES) {
6206
- const vendored = manifest.deps?.vendored === true;
6271
+ if (manifest.deps?.vendored === true) {
6272
+ await packBundle(bundleDir, outPath, { withModules: true });
6273
+ const bytes = fs.statSync(outPath).size;
6274
+ if (bytes <= maxBytes) return {
6275
+ bytes,
6276
+ modulesLeftOut: false
6277
+ };
6278
+ fs.rmSync(outPath, { force: true });
6279
+ await packBundle(bundleDir, outPath, { withModules: false });
6280
+ return {
6281
+ bytes: refuseOverCap(outPath, maxBytes),
6282
+ modulesLeftOut: true
6283
+ };
6284
+ }
6207
6285
  await packBundle(bundleDir, outPath, { withModules: false });
6208
- const bytes = fs.statSync(outPath).size;
6209
- if (bytes > maxBytes) throw new Error(`The bundle is ${(bytes / 1024 / 1024).toFixed(1)} MB without its dependencies, over the ${Math.round(maxBytes / 1024 / 1024)} MB upload limit.`);
6210
6286
  return {
6211
- bytes,
6212
- modulesLeftOut: vendored
6287
+ bytes: refuseOverCap(outPath, maxBytes),
6288
+ modulesLeftOut: false
6213
6289
  };
6214
6290
  }
6291
+ /** The archive's size, or a refusal naming the limit: nothing can be left out of it now. */
6292
+ function refuseOverCap(archive, maxBytes) {
6293
+ const bytes = fs.statSync(archive).size;
6294
+ if (bytes > maxBytes) throw new Error(`The bundle is ${(bytes / 1024 / 1024).toFixed(1)} MB without its dependencies, over the ${Math.round(maxBytes / 1024 / 1024)} MB upload limit.`);
6295
+ return bytes;
6296
+ }
6215
6297
  /**
6216
6298
  * The commit HEAD is on, read here because here is the only place it exists.
6217
6299
  *
@@ -6312,14 +6394,13 @@ function declaredAppsFrom(manifest) {
6312
6394
  }
6313
6395
  /** Upload a bundle archive; returns the control-plane bundle id. */
6314
6396
  async function uploadBundle(url, token, projectId, tarPath) {
6315
- const bytes = fs.readFileSync(tarPath);
6316
6397
  const res = await fetch(`${url}/api/functions/deploy/bundle/upload?projectId=${encodeURIComponent(projectId)}`, {
6317
6398
  method: "POST",
6318
6399
  headers: {
6319
6400
  Authorization: `Bearer ${token}`,
6320
6401
  "Content-Type": "application/gzip"
6321
6402
  },
6322
- body: bytes
6403
+ body: await fs.openAsBlob(tarPath)
6323
6404
  });
6324
6405
  if (!res.ok) {
6325
6406
  const body = await res.text().catch(() => "");
@@ -8374,6 +8455,7 @@ async function uploadSource(url, token, projectId, tarPath) {
8374
8455
  async function deployBundle(opts) {
8375
8456
  const projectRoot = requireProjectRoot();
8376
8457
  let bundleDir = opts.bundleDir ? path.resolve(process.cwd(), opts.bundleDir) : path.join(projectRoot, "dist-bundle");
8458
+ let releaseBuild;
8377
8459
  if (!opts.bundleDir) {
8378
8460
  let loaded;
8379
8461
  try {
@@ -8431,7 +8513,6 @@ async function deployBundle(opts) {
8431
8513
  resources: resourceGraph,
8432
8514
  skipTypeCheck: opts.skipTypeCheck,
8433
8515
  skipSchema: opts.skipSchema,
8434
- vendor: false,
8435
8516
  log: (m) => progress(chalk.gray(m)),
8436
8517
  quietStdout: isJsonMode()
8437
8518
  });
@@ -8439,6 +8520,7 @@ async function deployBundle(opts) {
8439
8520
  fail(err instanceof Error ? err.message : String(err), void 0, "build_failed");
8440
8521
  }
8441
8522
  bundleDir = result.outDir;
8523
+ releaseBuild = result.release;
8442
8524
  if (!opts.noStatic) {
8443
8525
  try {
8444
8526
  const folded = await foldFrontendIntoBundle({
@@ -8454,11 +8536,14 @@ async function deployBundle(opts) {
8454
8536
  }
8455
8537
  if (opts.verify) verifyStaticOutput(projectRoot, foldableApps(loaded.manifest).apps);
8456
8538
  }
8539
+ const unvendored = unvendoredReason(result);
8540
+ if (unvendored) warn(`Dependencies not bundled: ${unvendored}`, UNVENDORED_COST);
8457
8541
  }
8458
8542
  await uploadAndTrigger({
8459
8543
  ...opts,
8460
8544
  projectRoot,
8461
- bundleDir
8545
+ bundleDir,
8546
+ onPacked: releaseBuild
8462
8547
  });
8463
8548
  }
8464
8549
  /** Printed under a successful deploy: the way back, where it is needed. */
@@ -8529,7 +8614,8 @@ async function uploadAndTrigger(opts) {
8529
8614
  try {
8530
8615
  bundleId = await withTempArchive("rebase-bundle", async (tarPath) => {
8531
8616
  const packed = await packBundleForUpload(bundleDir, tarPath, manifest);
8532
- if (packed.modulesLeftOut) warn("This bundle's installed dependencies are not uploaded: a managed pod installs them when it starts.", "Build it with `rebase build --no-vendor` to skip installing a tree the upload leaves out.");
8617
+ opts.onPacked?.();
8618
+ if (packed.modulesLeftOut) warn("This bundle's dependencies would take it past the upload limit, so they were left out: each new instance installs them when it starts, which adds about a minute.", "Shrink the declared dependencies to get that minute back.");
8533
8619
  const sizeMb = (packed.bytes / 1024 / 1024).toFixed(1);
8534
8620
  progress(chalk.gray(` Uploading bundle (${sizeMb} MB)...`));
8535
8621
  return uploadBundle(url, await uploadToken(client, url), projectId, tarPath);
@@ -9237,9 +9323,10 @@ async function deployCommand(rawArgs, projectRef) {
9237
9323
  const { client, url } = await requireClient(rawArgs);
9238
9324
  const projectId = await resolveProjectRef(projectRef, client);
9239
9325
  await requirePaymentMethod(client, projectId);
9240
- const declaredManaged = !args["--source"] && !args["--bundle"] && declaresManagedRuntime(appName);
9241
- if (args["--bundle"] || declaredManaged) {
9242
- if (args["--bundle"] && args["--source"]) fail("--bundle and --source cannot be combined: one is a managed bundle, the other a source build.");
9326
+ const bundleFlag = args["--bundle"] ? "--bundle" : args["--bundle-dir"] ? "--bundle-dir" : void 0;
9327
+ const declaredManaged = !args["--source"] && !bundleFlag && declaresManagedRuntime(appName);
9328
+ if (bundleFlag || declaredManaged) {
9329
+ if (bundleFlag && args["--source"]) fail(`${bundleFlag} and --source cannot be combined: one is a managed bundle, the other a source build.`);
9243
9330
  if (declaredManaged && !isJsonMode()) console.log(chalk.gray(" rebase.json declares runtime: managed — deploying a bundle."));
9244
9331
  await deployBundle({
9245
9332
  client,
@@ -11963,6 +12050,202 @@ async function serviceKeyCommand(rawArgs) {
11963
12050
  }, rotation);
11964
12051
  }
11965
12052
  //#endregion
12053
+ //#region src/commands/cloud/guests.ts
12054
+ /**
12055
+ * `rebase cloud guests [delete <id> | prune --older-than <age>]`: the guest
12056
+ * users anonymous sign-in left behind on a project.
12057
+ *
12058
+ * Without an action, counts them and lists the ones last seen longest ago.
12059
+ * `delete` removes one. `prune` removes the ones not seen for an age: a dry run
12060
+ * that prints how many would go, deleting only with `--yes`.
12061
+ *
12062
+ * ## Which rows can go
12063
+ *
12064
+ * The app decides, not this command: `/api/admin/guests` only ever lists and
12065
+ * deletes a row that is anonymous with no password and no linked identity, in
12066
+ * the statement that deletes it. So nothing here can reach an account, even
12067
+ * with a stale list.
12068
+ *
12069
+ * ## How it reaches the app
12070
+ *
12071
+ * Two legs, like `rebase cloud cron`, with the service key where that has a
12072
+ * read-only platform token: deleting users is an administrator's act on the
12073
+ * app's own API. `POST env-vars/reveal` answers the key to an owner or admin of
12074
+ * the project, the same gate as `rebase cloud env reveal REBASE_SERVICE_KEY`;
12075
+ * it stays in memory for this command and goes only to the project's own public
12076
+ * address, which is why there is no `--host`.
12077
+ *
12078
+ * @module
12079
+ */
12080
+ var GUESTS_FLAGS = {
12081
+ "--limit": String,
12082
+ "--older-than": String
12083
+ };
12084
+ var GUESTS_ACTIONS = ["delete", "prune"];
12085
+ var AGE_UNITS_MS = {
12086
+ m: 6e4,
12087
+ h: 36e5,
12088
+ d: 864e5,
12089
+ w: 6048e5
12090
+ };
12091
+ /**
12092
+ * `30d` as milliseconds, or undefined. A unit is required and the age cannot be
12093
+ * zero: `--older-than 30` is a typo for something, and `0d` would be everyone.
12094
+ */
12095
+ function parseAge(value) {
12096
+ const match = /^(\d+)([mhdw])$/.exec(value.trim());
12097
+ if (!match) return void 0;
12098
+ const ms = Number(match[1]) * AGE_UNITS_MS[match[2]];
12099
+ return ms > 0 ? ms : void 0;
12100
+ }
12101
+ /** The instant `--older-than` names, or undefined when it was not given. */
12102
+ function lastSeenBeforeOf(value) {
12103
+ if (value === void 0) return void 0;
12104
+ const ms = parseAge(value);
12105
+ if (ms === void 0) fail(`--older-than takes an age with a unit, e.g. 30d, 12h or 2w (got "${value}").`, void 0, "usage");
12106
+ return new Date(Date.now() - ms);
12107
+ }
12108
+ /** The project's own API, holding its service key. */
12109
+ async function connectToApp(client, origin, projectId) {
12110
+ let serviceKey;
12111
+ try {
12112
+ serviceKey = (await client.functions.invoke("env-vars", {
12113
+ projectId,
12114
+ key: "REBASE_SERVICE_KEY"
12115
+ }, { path: "reveal" })).value;
12116
+ } catch (e) {
12117
+ reportError(e, "Failed to read the project's service key");
12118
+ }
12119
+ return createRebaseClient({
12120
+ baseUrl: origin,
12121
+ token: serviceKey,
12122
+ realtime: false,
12123
+ headers: { "User-Agent": cliUserAgent() },
12124
+ auth: {
12125
+ persistSession: false,
12126
+ autoRefresh: false
12127
+ }
12128
+ });
12129
+ }
12130
+ /**
12131
+ * Report a failed call to the app. An older runtime has no guest routes, and
12132
+ * its 404 is about the route, not about a guest; a repository without them (a
12133
+ * self-hosted Mongo backend) answers 501.
12134
+ */
12135
+ function reportAppError(error, action, origin) {
12136
+ if (error instanceof RebaseApiError) {
12137
+ if (error.status === 404 && isMissingRoute(error.message)) fail(`The app at ${origin} needs a newer runtime: it has no guest routes yet.`, "`rebase cloud status` shows the runtime it is on.", "runtime_too_old");
12138
+ if (error.status === 501) fail(`The app at ${origin} cannot manage guests: ${error.message}`, void 0, "not_supported");
12139
+ if (error.status === 0 || error.code === "NETWORK_ERROR") fail(`Could not reach the app at ${origin}: ${error.message}`, "`rebase cloud debug health` checks whether the deployment is answering at all.", "runtime_unreachable");
12140
+ }
12141
+ reportError(error, action);
12142
+ }
12143
+ function printGuests(guests, total, label) {
12144
+ const count = `${total.toLocaleString()} guest${total === 1 ? "" : "s"}`;
12145
+ console.log("");
12146
+ console.log(chalk.bold(` 👤 ${count} — ${label}`));
12147
+ console.log("");
12148
+ for (const guest of guests) {
12149
+ const created = new Date(guest.createdAt).toLocaleString();
12150
+ const seen = new Date(guest.lastSeenAt).toLocaleString();
12151
+ console.log(` ${guest.uid} ${chalk.gray(`last seen ${seen}, created ${created}`)}`);
12152
+ }
12153
+ if (guests.length < total) console.log(chalk.gray(` … and ${(total - guests.length).toLocaleString()} more, seen more recently.`));
12154
+ if (guests.length > 0) console.log("");
12155
+ }
12156
+ /** Every batch of a prune, until no matching guest is left to try. */
12157
+ async function pruneAll(app, lastSeenBefore) {
12158
+ const pruned = {
12159
+ deleted: 0,
12160
+ skipped: []
12161
+ };
12162
+ let remaining;
12163
+ do {
12164
+ const batch = await app.admin.deleteGuests({
12165
+ lastSeenBefore,
12166
+ offset: pruned.skipped.length
12167
+ });
12168
+ pruned.deleted += batch.deleted;
12169
+ pruned.skipped.push(...batch.skipped);
12170
+ ({remaining} = batch);
12171
+ } while (remaining > 0);
12172
+ return pruned;
12173
+ }
12174
+ async function prune(app, age, lastSeenBefore, yes, label) {
12175
+ const window = {
12176
+ olderThan: age,
12177
+ lastSeenBefore: lastSeenBefore.toISOString()
12178
+ };
12179
+ if (!yes) {
12180
+ const { total } = await app.admin.listGuests({
12181
+ lastSeenBefore,
12182
+ limit: 1
12183
+ });
12184
+ emit(() => {
12185
+ console.log("");
12186
+ console.log(` ${chalk.bold(total.toLocaleString())} guest${total === 1 ? "" : "s"} not seen for ${age} would go from ${label}. Nothing was deleted.`);
12187
+ if (total > 0) note(`Delete them with \`rebase cloud guests prune --older-than ${age} --yes\`.`);
12188
+ console.log("");
12189
+ }, {
12190
+ dryRun: true,
12191
+ ...window,
12192
+ wouldDelete: total
12193
+ });
12194
+ return;
12195
+ }
12196
+ const pruned = await pruneAll(app, lastSeenBefore);
12197
+ emit(() => {
12198
+ success(`Deleted ${pruned.deleted.toLocaleString()} guest${pruned.deleted === 1 ? "" : "s"} not seen for ${age} from ${label}.`);
12199
+ if (pruned.skipped.length > 0) warn(`${pruned.skipped.length.toLocaleString()} could not go. The first: ${pruned.skipped[0].uid}: ${pruned.skipped[0].message}`);
12200
+ }, {
12201
+ dryRun: false,
12202
+ ...window,
12203
+ ...pruned
12204
+ });
12205
+ }
12206
+ async function guestsCommand(rawArgs) {
12207
+ const { flags, positionals } = parseCloudArgs({
12208
+ spec: GUESTS_FLAGS,
12209
+ rawArgs,
12210
+ commandWords: 2,
12211
+ command: "cloud guests",
12212
+ maxPositionals: 2
12213
+ });
12214
+ const [action, id] = positionals;
12215
+ requireKnownAction("guests", action, GUESTS_ACTIONS);
12216
+ if (action === "delete" && !id) fail("Name the guest to delete.", "Usage: rebase cloud guests delete <id>. `rebase cloud guests` lists them.", "usage");
12217
+ if (action !== "delete" && id) fail(`Unexpected argument: ${id}`, "Only `rebase cloud guests delete` takes an id.", "usage");
12218
+ if (action === "prune" && !flags["--older-than"]) fail("Say how old a guest has to be.", "Usage: rebase cloud guests prune --older-than 30d [--yes]", "usage");
12219
+ if (action === "delete" && flags["--older-than"]) fail("`rebase cloud guests delete` removes one guest, by id.", "`rebase cloud guests prune --older-than <age>` removes them by age.", "usage");
12220
+ if (action && flags["--limit"]) fail("--limit only applies to the list.", void 0, "usage");
12221
+ const age = flags["--older-than"];
12222
+ const lastSeenBefore = lastSeenBeforeOf(age);
12223
+ const limit = flags["--limit"] === void 0 ? void 0 : Number(flags["--limit"]);
12224
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1)) fail(`--limit takes a whole number above 0 (got "${flags["--limit"]}").`, void 0, "usage");
12225
+ const { client, url } = await requireClient(rawArgs);
12226
+ const projectId = await requireProject(rawArgs, client);
12227
+ const label = `project ${displayProjectRef(rawArgs) || projectId}`;
12228
+ if (action === "delete") await confirmDestructive({
12229
+ yes: Boolean(flags["--yes"]),
12230
+ prompt: `Delete guest ${id} from ${label}? Its sessions end, and whatever the project's own tables cascade from it goes too.`
12231
+ });
12232
+ const origin = await resolveOrigin(rawArgs, client, url, projectId);
12233
+ const app = await connectToApp(client, origin, projectId);
12234
+ try {
12235
+ if (action === "delete") emit(() => success(`Deleted guest ${id} from ${label}.`), await app.admin.deleteGuest(id));
12236
+ else if (action === "prune" && age && lastSeenBefore) await prune(app, age, lastSeenBefore, Boolean(flags["--yes"]), label);
12237
+ else {
12238
+ const listed = await app.admin.listGuests({
12239
+ limit,
12240
+ lastSeenBefore
12241
+ });
12242
+ emit(() => printGuests(listed.guests, listed.total, label), listed);
12243
+ }
12244
+ } catch (e) {
12245
+ reportAppError(e, "Failed to manage the project's guests", origin);
12246
+ }
12247
+ }
12248
+ //#endregion
11966
12249
  //#region src/commands/cloud/activity.ts
11967
12250
  /**
11968
12251
  * `rebase cloud activity`: the selected organization's audit log — who
@@ -12441,9 +12724,10 @@ var ACTION_HELP = {
12441
12724
  command: "cloud projects",
12442
12725
  usage: "cloud projects <list|create|info|delete> [options]",
12443
12726
  summary: "List, create, inspect and delete projects in the selected organization.",
12444
- flags: [],
12727
+ flags: [["--all-orgs", "list: every organization you belong to, not only the selected one"]],
12445
12728
  examples: [
12446
12729
  "rebase cloud projects list",
12730
+ "rebase cloud projects list --all-orgs --json",
12447
12731
  "rebase cloud projects create --help",
12448
12732
  "rebase cloud projects info shop",
12449
12733
  "rebase cloud projects delete shop --yes"
@@ -12914,6 +13198,24 @@ var ACTION_HELP = {
12914
13198
  "It runs with your login: no access-token capability grants it, so REBASE_TOKEN is refused."
12915
13199
  ]
12916
13200
  },
13201
+ guests: {
13202
+ command: "cloud guests",
13203
+ usage: "cloud guests [delete|prune] [<id>] [--older-than <age>] [--limit <n>]",
13204
+ summary: "The guest users anonymous sign-in left behind on the project. Without an action, counts them and lists the ones last seen longest ago. `delete` removes one. `prune` removes the ones not seen for an age: a dry run that prints how many would go, deleting only with --yes. Only guests can go: an account, or a guest that has become one, is refused by the app itself. Owners and admins.",
13205
+ flags: [["--older-than <age>", "With `prune`, or to count the list: not seen for this long, as 30d, 12h, 2w or 45m"], ["--limit <n>", "How many the list shows. Default: 25"]],
13206
+ examples: [
13207
+ "rebase cloud guests",
13208
+ "rebase cloud guests --older-than 30d --json",
13209
+ "rebase cloud guests delete 3f0c9a7e-1f3b-4c55-9d1e-7a2f4d6b8c10 --yes",
13210
+ "rebase cloud guests prune --older-than 30d",
13211
+ "rebase cloud guests prune --older-than 30d --yes --json"
13212
+ ],
13213
+ notes: [
13214
+ "Last seen is when the guest's session was last issued or refreshed, so a guest who keeps coming back is not old.",
13215
+ "A row of the project's own that references a guest follows its foreign key: `ON DELETE CASCADE` deletes it, `SET NULL` empties it, and a required link (`RESTRICT`) keeps both the row and the guest, reported as skipped. A column without a foreign key keeps the id it holds.",
13216
+ "It reads REBASE_SERVICE_KEY the way `cloud env reveal` does, for this command only. A project on an older runtime is told it needs a newer one."
13217
+ ]
13218
+ },
12917
13219
  usage: {
12918
13220
  command: "cloud usage",
12919
13221
  usage: "cloud usage [org] [--month YYYY-MM]",
@@ -13043,6 +13345,14 @@ var ACTION_HELP = {
13043
13345
  flags: [],
13044
13346
  examples: ["rebase cloud whoami", "rebase cloud whoami --json"]
13045
13347
  },
13348
+ "access-token": {
13349
+ command: "cloud access-token",
13350
+ usage: "cloud access-token",
13351
+ summary: "Print the bearer this CLI would send right now — REBASE_TOKEN, a linked project's claim token, or the login, refreshed first when it is close to expiry. Bare on stdout, so `$(rebase cloud access-token)` works; `--json` adds the host and when it expires.",
13352
+ flags: [],
13353
+ examples: ["rebase cloud access-token", "rebase cloud access-token --json"],
13354
+ notes: ["It is a credential: whoever holds it acts as you until it expires (about an hour for a login).", "The Rebase MCP server uses it to read any of your projects' data through the console's Studio proxy."]
13355
+ },
13046
13356
  tokens: {
13047
13357
  command: "cloud tokens",
13048
13358
  usage: "cloud tokens <list|create|revoke> [options]",
@@ -13197,7 +13507,7 @@ var ACTION_HELP = {
13197
13507
  metrics: {
13198
13508
  command: "cloud metrics",
13199
13509
  usage: "cloud metrics",
13200
- summary: "Live CPU, memory and disk for the project's running units, as the control plane reports them.",
13510
+ summary: "Live CPU, memory and disk for the project's running units, and each instance's realtime counts, as the control plane reports them.",
13201
13511
  flags: [],
13202
13512
  examples: ["rebase cloud metrics", "rebase cloud metrics --json"]
13203
13513
  }
@@ -13309,6 +13619,7 @@ var CLOUD_VALUE_FLAGS = {
13309
13619
  "--message": String,
13310
13620
  "--month": String,
13311
13621
  "--name": String,
13622
+ "--older-than": String,
13312
13623
  "--org": String,
13313
13624
  "--output": String,
13314
13625
  "--password": String,
@@ -13449,6 +13760,9 @@ async function cloudCommand(subcommand, rawArgs) {
13449
13760
  case "whoami":
13450
13761
  await whoamiCommand(rawArgs);
13451
13762
  break;
13763
+ case "access-token":
13764
+ await accessTokenCommand(rawArgs);
13765
+ break;
13452
13766
  case "tokens":
13453
13767
  await tokensCommand(action, rawArgs);
13454
13768
  break;
@@ -13561,6 +13875,9 @@ async function cloudCommand(subcommand, rawArgs) {
13561
13875
  case "service-key":
13562
13876
  await serviceKeyCommand(rawArgs);
13563
13877
  break;
13878
+ case "guests":
13879
+ await guestsCommand(rawArgs);
13880
+ break;
13564
13881
  case "activity":
13565
13882
  await activityCommand(rawArgs);
13566
13883
  break;
@@ -13634,6 +13951,11 @@ var CLOUD_GROUPS = [
13634
13951
  section: "Auth",
13635
13952
  description: "Show the current session, or what REBASE_TOKEN may do"
13636
13953
  },
13954
+ {
13955
+ action: "access-token",
13956
+ section: "Auth",
13957
+ description: "Print the bearer this CLI would send now, refreshed if close to expiry"
13958
+ },
13637
13959
  {
13638
13960
  action: "tokens",
13639
13961
  section: "Auth",
@@ -13795,6 +14117,12 @@ var CLOUD_GROUPS = [
13795
14117
  section: "Data",
13796
14118
  description: "The project's object storage"
13797
14119
  },
14120
+ {
14121
+ action: "guests",
14122
+ section: "Data",
14123
+ args: "[delete|prune]",
14124
+ description: "The guest users anonymous sign-in left behind: count them, delete one, delete the old ones. Owners and admins"
14125
+ },
13798
14126
  {
13799
14127
  action: "notifications",
13800
14128
  section: "Deploy & observe",
@@ -13850,4 +14178,4 @@ function printCloudHelp() {
13850
14178
  //#endregion
13851
14179
  export { CLOUD_GROUP_NAMES, GROUP_ALIASES, cloudCommand };
13852
14180
 
13853
- //# sourceMappingURL=cloud-BdnmqQaZ.js.map
14181
+ //# sourceMappingURL=cloud-B2_oJmK7.js.map