@raybase/cli 0.3.15 → 0.3.16

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/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import { STARTER_DESCRIPTION_FILE, StarterDescriptionError, checkProjectSkills,
13
13
  import { applyEdits, modify, parse } from "jsonc-parser";
14
14
  import { register } from "tsx/esm/api";
15
15
  import { defaultAiDefaults, defaultAiLimits, signToken, storageHardMaxSizeBytes } from "@raybase/core/cli";
16
- import { generateVapidKeys, parseRaybaseSignupAllowlist, raybaseSignupAllowlistEnvName, resolveRaybaseSignInRateLimits, validateHandoffConfig } from "@raybase/core";
16
+ import { generateVapidKeys, noPartitionDefault, parseRaybaseSignupAllowlist, raybaseSignupAllowlistEnvName, resolveRaybaseSignInRateLimits, validateHandoffConfig } from "@raybase/core";
17
17
  import { errorMessage, run, runWithOutput } from "./shared.js";
18
18
  import { resolveContentSiteDevPort, resolveSpineDevPort, spineOriginForPort } from "./dev-ports.js";
19
19
  import { acquireProjectDevLock } from "./dev-project-lock.js";
@@ -30,6 +30,7 @@ import { FRAMEWORK_KINDS, FrameworkResolutionError, resolveFrameworkProfile } fr
30
30
  import { checkRaybaseAdminAssets, syncRaybaseAdminAssets, verifyBuiltRaybaseAdminAssets } from "./admin-assets.js";
31
31
  import { activateLicense, assertProAuthorization, createBillingPortal, hostedAuthAddOrigin, hostedAuthAppStatus, hostedAuthCreateToken, hostedAuthDisableApp, hostedAuthRegisterApp, hostedAuthUsage, hostedAuthVerifyOrigin, listAccounts, logoutLocalCredentials, needsRegistryRefresh, onlineBillingStatus, onlineLicenseStatus, pollDeviceLogin, readAccountState, readLocalLicenseStatus, readRegistryState, refreshLicense, requestRegistryToken, startDeviceLogin, storeCredentialBundle, submitSupportTicket, updateBillingSeats, useAccount, writeProjectNpmrc, writeUserNpmrc } from "./licensing.js";
32
32
  import { readWranglerVar } from "./env-files.js";
33
+ import { partitionDoctorIssues } from "./partition-doctor.js";
33
34
  import { agentDoctor, agentPreflight, checkUpdates as checkAgentUpdates, confirmAgentPlugin, latestBundleVersion, maybeRunAsyncUpdateCheck, updateInstructions as agentUpdateInstructions, versions as agentVersions } from "./agent.js";
34
35
  import { addKit, doctorKits, formatKitDoctor, formatKitInfo, formatKitInstall, formatKitList, formatKitRemoveGuidance, formatKitSearch, formatKitUpdate, infoKit, listKits, removeKitGuidance, searchKits, updateInstalledKits } from "./kits.js";
35
36
  import { addTemplate, addTemplateTheme, addTemplateShell, activateTemplateShell, matchShells, matchThemes, doctorInstalledTemplates, formatTemplateDoctor, formatTemplateInfo, formatTemplateInstall, formatTemplateList, formatTemplateSearch, formatTemplateThemeInstall, formatTemplateShellInstall, formatTemplateShellActivate, formatShellMatch, formatThemeMatch, formatTemplateUpdate, infoTemplate, listTemplates, searchTemplates, updateInstalledTemplates } from "./templates.js";
@@ -53,11 +54,8 @@ const FRAMEWORK_HELP = `Frameworks (each has a built-in starter):
53
54
  // through the pro plugin (reapplyProSkillsOverlay).
54
55
  const PRO_PROJECT_COMMANDS = new Set(["doctor", "check", "jobs", "ai", "retrieval", "search", "migrate", "dev", "connect", "deploy", "backup", "backups", "export", "restore", "invite", "update", "modules"]);
55
56
  const PRO_NAMESPACE_DELEGATE_COMMANDS = new Set(["upgrade", "provision", "skills", "attach", "install", "control-plane", "dev", "deploy"]);
56
- const CLI_VERSION = "0.3.15";
57
- // Pro's package took its own scope in 0.3.4. An app made before then declares
58
- // the old name; the CLI finds Pro under either, and doctor says which to move to.
57
+ const CLI_VERSION = "0.3.16";
59
58
  const PRO_PACKAGE = "@raybase-pro/pro";
60
- const PRO_PACKAGE_BEFORE_0_3_4 = "@raybase/pro";
61
59
  program
62
60
  .name("raybase")
63
61
  .description("Build, verify, and deploy secure internal apps on Cloudflare.")
@@ -518,8 +516,6 @@ program
518
516
  .option("--dry-run", "Resolve and plan the install without writing files")
519
517
  .option("--offline", "Use bundled, cached, or file registry data without network access")
520
518
  .option("--json", "Print machine-readable JSON output")
521
- .option("--skip-install", "Deprecated no-op; kits print manual package changes in v1")
522
- .option("--migrate", "Deprecated no-op; kits print migration guidance in v1")
523
519
  .option("--accept-risk", "Acknowledge security-sensitive kit install or update behavior")
524
520
  .action(runAddKitCommand);
525
521
  const kitsCommand = program.command("kits").description("Discover, install, update, and inspect Raybase Kits.");
@@ -531,8 +527,6 @@ kitsCommand
531
527
  .option("--dry-run", "Resolve and plan the install without writing files")
532
528
  .option("--offline", "Use bundled, cached, or file registry data without network access")
533
529
  .option("--json", "Print machine-readable JSON output")
534
- .option("--skip-install", "Deprecated no-op; kits print manual package changes in v1")
535
- .option("--migrate", "Deprecated no-op; kits print migration guidance in v1")
536
530
  .option("--accept-risk", "Acknowledge security-sensitive kit install behavior")
537
531
  .action(runAddKitCommand);
538
532
  kitsCommand
@@ -591,7 +585,6 @@ kitsCommand
591
585
  offline: Boolean(options.offline),
592
586
  overwrite: Boolean(options.overwrite),
593
587
  acceptRisk: Boolean(options.acceptRisk),
594
- skipInstall: true,
595
588
  framework: profile.kind,
596
589
  cliVersion: CLI_VERSION
597
590
  });
@@ -1051,8 +1044,6 @@ async function runAddKitCommand(spec, options) {
1051
1044
  registry: options.registry,
1052
1045
  dryRun: Boolean(options.dryRun),
1053
1046
  offline: Boolean(options.offline),
1054
- skipInstall: Boolean(options.skipInstall),
1055
- migrate: Boolean(options.migrate),
1056
1047
  overwrite: false,
1057
1048
  acceptRisk: Boolean(options.acceptRisk),
1058
1049
  framework: profile.kind,
@@ -1217,7 +1208,7 @@ backupsCommand
1217
1208
  });
1218
1209
  backupsCommand
1219
1210
  .command("restore <key>")
1220
- .description("Restore an encrypted R2 archive or legacy SQL backup through the admin API.")
1211
+ .description("Restore an encrypted R2 archive through the admin API.")
1221
1212
  .requiredOption("--url <url>", "Base URL of the app")
1222
1213
  .option("--cookie <cookie>", "Admin session cookie for the app")
1223
1214
  .requiredOption("--confirm <text>", "Must be exactly: restore")
@@ -1228,7 +1219,7 @@ backupsCommand
1228
1219
  });
1229
1220
  backupsCommand
1230
1221
  .command("restore-upload <file>")
1231
- .description("Restore an uploaded .rbb archive or legacy .sql backup through the admin API.")
1222
+ .description("Restore an uploaded encrypted .rbb archive through the admin API.")
1232
1223
  .requiredOption("--url <url>", "Base URL of the app")
1233
1224
  .option("--cookie <cookie>", "Admin session cookie for the app")
1234
1225
  .requiredOption("--confirm <text>", "Must be exactly: restore")
@@ -2082,9 +2073,49 @@ program
2082
2073
  const result = await exportApp(options.url, options.cookie, options.output);
2083
2074
  output(options, result, `App export written to ${result.file}`);
2084
2075
  });
2076
+ const partitionsCommand = program
2077
+ .command("partitions")
2078
+ .description("Operate a deployed app's host partitions (one customer's several host accounts). The host platform installs them; these commands never create one.");
2079
+ partitionsCommand
2080
+ .command("list")
2081
+ .description("List partitions with their status, rows per partitioned table and host users.")
2082
+ .requiredOption("--url <url>", "Base URL of the app")
2083
+ .option("--cookie <cookie>", "Admin session cookie for the app")
2084
+ .option("--json", "Print machine-readable JSON output")
2085
+ .action(async (options) => {
2086
+ const result = await partitionsList(options.url, options.cookie);
2087
+ output(options, result, result.partitions.length
2088
+ ? result.partitions.map((partition) => `${partition.key} ${partition.status} ${partition.name}`).join("\n")
2089
+ : `No ${result.label?.other?.toLowerCase() ?? "partitions"} installed.`);
2090
+ });
2091
+ partitionsCommand
2092
+ .command("export <key>")
2093
+ .description("Export one partition (its partitioned rows, files, audit, settings and host users) as NDJSON.")
2094
+ .requiredOption("--url <url>", "Base URL of the app")
2095
+ .option("--cookie <cookie>", "Admin session cookie for the app")
2096
+ .option("--output <file>", "Output file path")
2097
+ .option("--include-transcripts", "Also include the partition's agent conversation transcripts")
2098
+ .option("--json", "Print machine-readable JSON output")
2099
+ .action(async (key, options) => {
2100
+ const result = await partitionsExport(options.url, options.cookie, key, { output: options.output, includeTranscripts: Boolean(options.includeTranscripts) });
2101
+ output(options, result, `Partition ${key} exported to ${result.file}`);
2102
+ });
2103
+ partitionsCommand
2104
+ .command("erase <key>")
2105
+ .description("Erase one partition: every partitioned row, file, conversation, job and index entry. Its audit becomes one erasure record. Cannot be undone.")
2106
+ .requiredOption("--url <url>", "Base URL of the app")
2107
+ .option("--cookie <cookie>", "Admin session cookie for the app")
2108
+ .requiredOption("--confirm <key>", "Must repeat the partition key")
2109
+ .option("--json", "Print machine-readable JSON output")
2110
+ .action(async (key, options) => {
2111
+ if (options.confirm !== key)
2112
+ throw new Error("--confirm must repeat the partition key.");
2113
+ const result = await fetchAdminJson(`${String(options.url).replace(/\/$/, "")}/api/admin/partitions/${encodeURIComponent(key)}/erase`, { method: "POST", cookie: options.cookie, body: JSON.stringify({ confirm: key }) });
2114
+ output(options, result, `Partition ${key} erasure ${result.erasureId} is ${result.status}. It drains in the background; raybase partitions list shows when it is erased.`);
2115
+ });
2085
2116
  program
2086
2117
  .command("restore <file>")
2087
- .description("Restore an encrypted .rbb archive or legacy .sql dump through the admin endpoint.")
2118
+ .description("Restore an encrypted .rbb archive through the admin endpoint.")
2088
2119
  .requiredOption("--url <url>", "Base URL of the app")
2089
2120
  .option("--cookie <cookie>", "Admin session cookie for the app")
2090
2121
  .requiredOption("--confirm <text>", "Must be exactly: restore")
@@ -2210,10 +2241,7 @@ async function maybeDelegateToPro(argv) {
2210
2241
  return false;
2211
2242
  throw new Error(shouldDelegateProNamespace
2212
2243
  ? "Install @raybase-pro/pro in this project before running this Raybase Pro command."
2213
- : `This project declares ${(projectRoot && declaredProPackage(projectRoot)) || PRO_PACKAGE}, but the package is not installed. Run your package manager install command, then retry.`);
2214
- }
2215
- if (projectRoot && declaredProPackage(projectRoot) === PRO_PACKAGE_BEFORE_0_3_4) {
2216
- console.warn(`This app declares ${PRO_PACKAGE_BEFORE_0_3_4}, Pro's name before 0.3.4; later releases are ${PRO_PACKAGE}. The steps to move are in Raybase's 0.3.4 changelog.`);
2244
+ : `This project declares ${PRO_PACKAGE}, but the package is not installed. Run your package manager install command, then retry.`);
2217
2245
  }
2218
2246
  const module = (await import(pathToFileURL(entry).href));
2219
2247
  const plugin = pluginMetadata(module);
@@ -2326,22 +2354,18 @@ function isRaybaseAppProject(cwd) {
2326
2354
  return false;
2327
2355
  try {
2328
2356
  const parsed = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
2329
- const declaresRaybase = [parsed.dependencies, parsed.devDependencies, parsed.peerDependencies, parsed.optionalDependencies].some((deps) => Boolean(deps?.["@raybase/core"] || deps?.["@raybase/cli"] || deps?.[PRO_PACKAGE] || deps?.[PRO_PACKAGE_BEFORE_0_3_4]));
2357
+ const declaresRaybase = [parsed.dependencies, parsed.devDependencies, parsed.peerDependencies, parsed.optionalDependencies].some((deps) => Boolean(deps?.["@raybase/core"] || deps?.["@raybase/cli"] || deps?.[PRO_PACKAGE]));
2330
2358
  return declaresRaybase;
2331
2359
  }
2332
2360
  catch {
2333
2361
  return false;
2334
2362
  }
2335
2363
  }
2336
- function declaredProPackage(projectRoot) {
2337
- return [PRO_PACKAGE, PRO_PACKAGE_BEFORE_0_3_4].find((name) => packageDeclaredVersion(projectRoot, name)) ?? null;
2338
- }
2339
2364
  function projectDeclaresPro(projectRoot) {
2340
- return declaredProPackage(projectRoot) !== null;
2365
+ return Boolean(packageDeclaredVersion(projectRoot, PRO_PACKAGE));
2341
2366
  }
2342
2367
  function proDeclaredVersion(projectRoot) {
2343
- const name = declaredProPackage(projectRoot);
2344
- return name ? packageDeclaredVersion(projectRoot, name) : null;
2368
+ return packageDeclaredVersion(projectRoot, PRO_PACKAGE);
2345
2369
  }
2346
2370
  function packageDeclaredVersion(projectRoot, name) {
2347
2371
  try {
@@ -2463,26 +2487,26 @@ function templateFrameworkForProfile(profile) {
2463
2487
  }
2464
2488
  function resolveProCliEntry(projectRoot) {
2465
2489
  const require = createRequire(join(projectRoot, "package.json"));
2466
- const declared = declaredProPackage(projectRoot);
2467
- for (const name of declared ? [declared] : [PRO_PACKAGE, PRO_PACKAGE_BEFORE_0_3_4]) {
2468
- try {
2469
- return require.resolve(`${name}/cli-entry`);
2470
- }
2471
- catch {
2472
- // not installed under this name
2473
- }
2490
+ try {
2491
+ return require.resolve(`${PRO_PACKAGE}/cli-entry`);
2492
+ }
2493
+ catch {
2494
+ return null;
2474
2495
  }
2475
- return null;
2476
2496
  }
2477
2497
  async function readProPluginMetadata(entry) {
2478
2498
  const module = (await import(pathToFileURL(entry).href));
2479
2499
  return pluginMetadata(module);
2480
2500
  }
2481
2501
  function pluginMetadata(module) {
2502
+ const plugin = module.raybaseCliPlugin;
2503
+ if (!plugin?.compatibleRaybaseCli) {
2504
+ throw new Error("Installed @raybase-pro/pro declares no raybaseCliPlugin compatibility range. Upgrade @raybase/cli and @raybase-pro/pro together, then retry.");
2505
+ }
2482
2506
  return {
2483
- name: module.raybaseCliPlugin?.name ?? "pro",
2484
- compatibleRaybaseCli: module.raybaseCliPlugin?.compatibleRaybaseCli ?? module.RAYBASE_PRO_CLI_COMPATIBILITY ?? "*",
2485
- commandPolicies: { ...defaultProCommandPolicies(), ...(module.raybaseCliPlugin?.commandPolicies ?? {}) }
2507
+ name: plugin.name ?? "pro",
2508
+ compatibleRaybaseCli: plugin.compatibleRaybaseCli,
2509
+ commandPolicies: { ...defaultProCommandPolicies(), ...(plugin.commandPolicies ?? {}) }
2486
2510
  };
2487
2511
  }
2488
2512
  function ensurePluginCompatible(plugin) {
@@ -2595,23 +2619,14 @@ async function proDoctor(cwd) {
2595
2619
  const registry = readRegistryState();
2596
2620
  if (!declaresPro && !entry && !license.ok && !registry)
2597
2621
  return issues;
2598
- const declaredName = declaredProPackage(cwd);
2599
2622
  if (declaresPro && !entry) {
2600
2623
  issues.push({
2601
2624
  level: "error",
2602
2625
  check: "pro-package",
2603
- message: `package.json declares ${declaredName}, but ${declaredName}/cli-entry cannot be resolved.`,
2626
+ message: `package.json declares ${PRO_PACKAGE}, but ${PRO_PACKAGE}/cli-entry cannot be resolved.`,
2604
2627
  fix: "Run your package manager install command, then retry raybase doctor."
2605
2628
  });
2606
2629
  }
2607
- if (declaredName === PRO_PACKAGE_BEFORE_0_3_4) {
2608
- issues.push({
2609
- level: "warning",
2610
- check: "pro-package-name",
2611
- message: `package.json declares ${PRO_PACKAGE_BEFORE_0_3_4}, Pro's name before 0.3.4. Pro 0.3.4 and later are published as ${PRO_PACKAGE}.`,
2612
- fix: `Rename ${PRO_PACKAGE_BEFORE_0_3_4} to ${PRO_PACKAGE} and @raybase/pro-control-plane to @raybase-pro/control-plane in package.json and in imports, add "@raybase-pro:registry=" with the registry your @raybase line names to .npmrc, then install.`
2613
- });
2614
- }
2615
2630
  if (!license.ok) {
2616
2631
  issues.push({
2617
2632
  level: declaresPro ? "error" : "warning",
@@ -4001,7 +4016,7 @@ async function doctor(cwd, options = {}, resolvedProfile) {
4001
4016
  level: "error",
4002
4017
  check: "tenant-column",
4003
4018
  message: `${table.name} declares a tenant id column.`,
4004
- fix: "Do not add tenant scoping columns to app tables. Core uses one app database."
4019
+ fix: "Do not add tenant scoping columns to app tables. Separate customers (tenants, clients, merchants you sell to) need Raybase Pro, which gives each its own database. One customer's several host accounts (one merchant's stores) use host partitions: appConfig.partitions with { partition: \"partitioned\" } tables."
4005
4020
  });
4006
4021
  }
4007
4022
  const manifestTable = appManifest.ok ? manifestTableByName(appManifest.manifest, table.name) : undefined;
@@ -4017,6 +4032,7 @@ async function doctor(cwd, options = {}, resolvedProfile) {
4017
4032
  });
4018
4033
  }
4019
4034
  }
4035
+ issues.push(...partitionDoctorIssues({ cwd, summary, schemaModule: profile.schemaModule, appManifest }));
4020
4036
  issues.push(...actionRoutePolicyIssues(appManifest));
4021
4037
  issues.push(...actionOutputSchemaIssues(appManifest));
4022
4038
  issues.push(...agentCapabilityIssues(cwd, profile, appManifest));
@@ -4575,6 +4591,14 @@ async function doctor(cwd, options = {}, resolvedProfile) {
4575
4591
  fix: "Add the RAYBASE_THREAD_ARCHIVE binding from the framework's current built-in starter; raybase deploy creates the bucket."
4576
4592
  });
4577
4593
  }
4594
+ for (const shared of sharedBackupsBuckets(config.parsed)) {
4595
+ issues.push({
4596
+ level: "error",
4597
+ check: "backups-shared-bucket",
4598
+ message: `Wrangler environments ${shared.environments.join(" and ")} share the RAYBASE_BACKUPS bucket ${shared.bucket}: their backups, restores and partition erasure tombstones would act on each other's databases.`,
4599
+ fix: "Give each environment its own RAYBASE_BACKUPS bucket_name."
4600
+ });
4601
+ }
4578
4602
  if (backups.invalidRetention) {
4579
4603
  issues.push({
4580
4604
  level: "error",
@@ -6737,6 +6761,8 @@ async function migrate(cwd, options, profile = resolveFrameworkProfile(cwd)) {
6737
6761
  }
6738
6762
  const after = new Set(readdirSync(migrationsDir).filter((file) => file.endsWith(".sql")));
6739
6763
  const generated = [...after].filter((file) => !before.has(file));
6764
+ for (const file of generated)
6765
+ repairGeneratedPartitionMigration(migrationsDir, file);
6740
6766
  // A changed schema that produced neither a migration file nor drizzle-kit's
6741
6767
  // own "No schema changes" verdict is that swallowed failure. Claiming
6742
6768
  // success here would compile a bundle missing the change and rewrite the
@@ -6809,8 +6835,36 @@ async function exportApp(baseUrl, cookie, outputFile) {
6809
6835
  writeFileSync(file, text);
6810
6836
  return { ok: true, file, url: baseUrl };
6811
6837
  }
6838
+ async function partitionsList(baseUrl, cookie) {
6839
+ return fetchAdminJson(`${String(baseUrl).replace(/\/$/, "")}/api/admin/partitions`, { cookie });
6840
+ }
6841
+ /** Starts a partition export, waits for it to complete, and downloads its NDJSON. */
6842
+ async function partitionsExport(baseUrl, cookie, key, options) {
6843
+ const base = String(baseUrl).replace(/\/$/, "");
6844
+ const started = await fetchAdminJson(`${base}/api/admin/partitions/${encodeURIComponent(key)}/export`, {
6845
+ method: "POST",
6846
+ cookie,
6847
+ body: JSON.stringify({ includeTranscripts: options.includeTranscripts })
6848
+ });
6849
+ const deadline = Date.now() + (options.timeoutMs ?? 10 * 60_000);
6850
+ let status = started.status;
6851
+ while (status !== "complete") {
6852
+ if (status === "failed")
6853
+ throw new Error(`Partition export ${started.exportId} failed`);
6854
+ if (Date.now() > deadline)
6855
+ throw new Error(`Partition export ${started.exportId} is still ${status}; download it later from the admin`);
6856
+ await new Promise((resolveWait) => setTimeout(resolveWait, options.pollMs ?? 2000));
6857
+ status = (await fetchAdminJson(`${base}/api/admin/partitions/exports/${encodeURIComponent(started.exportId)}`, { cookie })).status;
6858
+ }
6859
+ const safeKey = key.replace(/[^A-Za-z0-9._-]+/g, "_");
6860
+ const file = options.output ? resolve(options.output) : resolve(`raybase-partition-${safeKey}-${new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "")}.ndjson`);
6861
+ await downloadAdminFile(`${base}/api/admin/partitions/exports/${encodeURIComponent(started.exportId)}/download`, file, { cookie, accept: "application/x-ndjson" });
6862
+ return { ok: true, file, url: baseUrl, partitionKey: key, exportId: started.exportId };
6863
+ }
6812
6864
  async function restore(baseUrl, cookie, file) {
6813
- const contentType = file.toLowerCase().endsWith(".sql") ? "application/sql" : "application/vnd.raybase.backup";
6865
+ if (!file.toLowerCase().endsWith(".rbb"))
6866
+ throw new Error("Only encrypted .rbb archives can be restored.");
6867
+ const contentType = "application/vnd.raybase.backup";
6814
6868
  await fetchAdminText(`${String(baseUrl).replace(/\/$/, "")}/api/deployment/backups/restore-upload?confirm=restore`, {
6815
6869
  method: "POST",
6816
6870
  cookie,
@@ -6832,8 +6886,7 @@ async function backupsCreate(baseUrl, cookie) {
6832
6886
  return fetchAdminJson(`${String(baseUrl).replace(/\/$/, "")}/api/deployment/backups`, { method: "POST", cookie, body: "{}" });
6833
6887
  }
6834
6888
  async function backupsDownload(baseUrl, cookie, key, outputFile) {
6835
- const fallbackExtension = key.endsWith(".sql") ? "sql" : "rbb";
6836
- const file = outputFile ? resolve(outputFile) : resolve(key.split("/").pop() || `raybase-backup-${new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "")}.${fallbackExtension}`);
6889
+ const file = outputFile ? resolve(outputFile) : resolve(key.split("/").pop() || `raybase-backup-${new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "")}.rbb`);
6837
6890
  await downloadAdminFile(`${String(baseUrl).replace(/\/$/, "")}/api/deployment/backups/download?key=${encodeURIComponent(key)}`, file, { cookie, accept: "application/octet-stream" });
6838
6891
  return { ok: true, file, key, url: baseUrl };
6839
6892
  }
@@ -6850,7 +6903,9 @@ async function backupsRestore(baseUrl, cookie, key, confirm) {
6850
6903
  async function backupsRestoreUpload(baseUrl, cookie, file, confirm) {
6851
6904
  if (confirm !== "restore")
6852
6905
  throw new Error('--confirm must be exactly "restore".');
6853
- const contentType = file.toLowerCase().endsWith(".sql") ? "application/sql" : "application/vnd.raybase.backup";
6906
+ if (!file.toLowerCase().endsWith(".rbb"))
6907
+ throw new Error("Only encrypted .rbb archives can be restored.");
6908
+ const contentType = "application/vnd.raybase.backup";
6854
6909
  const result = await fetchAdminJson(`${String(baseUrl).replace(/\/$/, "")}/api/deployment/backups/restore-upload?confirm=restore`, {
6855
6910
  method: "POST",
6856
6911
  cookie,
@@ -6879,7 +6934,7 @@ function formatBackupsStatus(status) {
6879
6934
  `PITR restore safety: ${restore?.pitrAvailable === true ? "available" : restore?.pitrAvailable === false ? "unavailable" : "unknown"}`,
6880
6935
  `Restore maintenance: ${maintenance?.active ? `active (${maintenance.phase ?? "unknown"})` : "inactive"}`,
6881
6936
  `Retention: ${status.retention ?? "unknown"} per target`,
6882
- `Latest backup: ${latest?.date ? `${latest.date} (${latest.key}, ${latest.encrypted ? "encrypted" : "legacy plaintext"})` : "none"}`
6937
+ `Latest backup: ${latest?.date ? `${latest.date} (${latest.key})` : "none"}`
6883
6938
  ];
6884
6939
  const caveats = Array.isArray(status.caveats) ? status.caveats.map(String) : [];
6885
6940
  if (caveats.length)
@@ -6896,7 +6951,7 @@ function formatBackupsList(result) {
6896
6951
  entry.date ?? "unknown",
6897
6952
  entry.key,
6898
6953
  `${entry.bytes ?? "?"} bytes`,
6899
- entry.encrypted ? `encrypted format-${entry.archiveFormat ?? 2}` : "legacy plaintext",
6954
+ `encrypted format-${entry.archiveFormat ?? 2}`,
6900
6955
  entry.providerId ? `${entry.providerId}/${entry.kekKeyId ?? "unknown-key"}` : null,
6901
6956
  entry.trigger ?? "unknown"
6902
6957
  ].filter(Boolean).join(" "));
@@ -7697,20 +7752,22 @@ async function loadProjectCoreCli(cwd) {
7697
7752
  const entry = projectRequire.resolve("@raybase/core/cli");
7698
7753
  return (await import(pathToFileURL(entry).href));
7699
7754
  }
7700
- export async function loadSchema(cwd, profile) {
7701
- const schemaPath = join(cwd, profile.schemaModule);
7702
- const storagePath = join(cwd, profile.storageModule);
7703
- const { getReferenceName, schemaSql } = await loadProjectCoreCli(cwd);
7704
- const schemaModule = await importProjectModule(schemaPath);
7705
- const schema = schemaModule.schema;
7706
- const appConfig = schemaModule.appConfig;
7707
- const storageConfig = existsSync(storagePath)
7708
- ? ((await importProjectModule(storagePath)).storage ?? null)
7709
- : null;
7710
- const tables = Object.fromEntries(Object.entries(schema.tables).map(([key, table]) => [
7755
+ /** The plain-data summary of the app's tables that doctor, migrate and drizzle emission read. */
7756
+ export function summarizeSchemaTables(schemaTables, getReferenceName) {
7757
+ const tablesByName = new Map(Object.values(schemaTables).map((table) => [table.name, table]));
7758
+ const referencePartition = (column) => {
7759
+ const target = typeof column.references === "function" ? column.references() : undefined;
7760
+ if (!target)
7761
+ return undefined;
7762
+ if (typeof target === "string")
7763
+ return tablesByName.get(target)?.partition;
7764
+ return target.partition;
7765
+ };
7766
+ return Object.fromEntries(Object.entries(schemaTables).map(([key, table]) => [
7711
7767
  key,
7712
7768
  {
7713
7769
  name: table.name,
7770
+ ...(table.partition ? { partition: table.partition } : {}),
7714
7771
  columns: Object.fromEntries(Object.entries(table.columns).map(([columnName, column]) => [
7715
7772
  columnName,
7716
7773
  {
@@ -7719,13 +7776,28 @@ export async function loadSchema(cwd, profile) {
7719
7776
  primaryKey: column.primaryKey,
7720
7777
  unique: column.unique,
7721
7778
  default: column.default,
7722
- reference: getReferenceName(column)
7779
+ reference: getReferenceName(column),
7780
+ ...(column.auto ? { auto: column.auto } : {}),
7781
+ ...(column.referencesColumn ? { referencesColumn: column.referencesColumn } : {}),
7782
+ ...(referencePartition(column) === "partitioned" ? { referencePartitioned: true } : {})
7723
7783
  }
7724
7784
  ])),
7725
7785
  policies: Object.keys(table.policies || {}),
7726
7786
  invariants: (table.invariants || []).map((invariant) => invariant.name)
7727
7787
  }
7728
7788
  ]));
7789
+ }
7790
+ export async function loadSchema(cwd, profile) {
7791
+ const schemaPath = join(cwd, profile.schemaModule);
7792
+ const storagePath = join(cwd, profile.storageModule);
7793
+ const { getReferenceName, schemaSql } = await loadProjectCoreCli(cwd);
7794
+ const schemaModule = await importProjectModule(schemaPath);
7795
+ const schema = schemaModule.schema;
7796
+ const appConfig = schemaModule.appConfig;
7797
+ const storageConfig = existsSync(storagePath)
7798
+ ? ((await importProjectModule(storagePath)).storage ?? null)
7799
+ : null;
7800
+ const tables = summarizeSchemaTables(schema.tables, getReferenceName);
7729
7801
  const storageBuckets = Object.fromEntries(Object.entries(storageConfig?.buckets || {}).map(([key, bucket]) => [
7730
7802
  key,
7731
7803
  {
@@ -7753,29 +7825,118 @@ function writeDrizzleSchema(cwd, summary) {
7753
7825
  const dir = join(cwd, ".raybase", "drizzle");
7754
7826
  mkdirSync(dir, { recursive: true });
7755
7827
  const file = join(dir, "app-schema.ts");
7756
- const used = new Set();
7828
+ writeFileSync(file, drizzleSchemaSource(summary));
7829
+ return file;
7830
+ }
7831
+ /**
7832
+ * The drizzle-kit input for the app's tables. A partitioned table gets its
7833
+ * Core-owned `partitionKey` (NOT NULL, default '' for rows written before the
7834
+ * table was partitioned, referencing the `_partitions` registry), a unique
7835
+ * (partitionKey, id), per-partition uniques, and a composite foreign key for
7836
+ * each reference to another partitioned table, so no path can join rows
7837
+ * across partitions. The registry table is declared but not exported, so
7838
+ * drizzle-kit references it without ever creating it: Core owns it.
7839
+ */
7840
+ export function drizzleSchemaSource(summary) {
7841
+ const used = new Set(["raybase_partitions"]);
7757
7842
  const tableIdentifiers = new Map();
7843
+ const partitionedTables = new Set();
7758
7844
  for (const key of summary.tableKeys) {
7759
7845
  const table = summary.tables[key];
7760
7846
  const identifier = uniqueIdentifier(`app_${key}`, used);
7761
7847
  tableIdentifiers.set(table.name, identifier);
7848
+ if (table.partition === "partitioned")
7849
+ partitionedTables.add(table.name);
7762
7850
  }
7851
+ let needsPartitions = false;
7852
+ let needsExtras = false;
7763
7853
  const appExports = summary.tableKeys.map((key) => {
7764
7854
  const table = summary.tables[key];
7765
7855
  const identifier = tableIdentifiers.get(table.name);
7766
7856
  if (!identifier)
7767
7857
  throw new Error(`Missing generated identifier for table ${table.name}`);
7858
+ const partitioned = table.partition === "partitioned";
7859
+ const extras = [];
7768
7860
  const columns = Object.entries(table.columns)
7769
- .map(([columnName, column]) => ` ${JSON.stringify(columnName)}: ${drizzleColumnExpression(columnName, column, tableIdentifiers)}`)
7861
+ .map(([columnName, column]) => {
7862
+ if (partitioned && column.auto === "partition") {
7863
+ needsPartitions = true;
7864
+ return ` ${JSON.stringify(columnName)}: text(${JSON.stringify(columnName)}).notNull().references(() => raybase_partitions.key)`;
7865
+ }
7866
+ const compositeReference = partitioned && column.reference && partitionedTables.has(column.reference);
7867
+ if (partitioned && column.unique && !column.primaryKey) {
7868
+ extras.push(`unique(${JSON.stringify(`${table.name}_partitionKey_${columnName}_unique`)}).on(table.partitionKey, table[${JSON.stringify(columnName)}])`);
7869
+ }
7870
+ if (compositeReference) {
7871
+ const target = tableIdentifiers.get(column.reference);
7872
+ extras.push(`foreignKey({ name: ${JSON.stringify(`${table.name}_${columnName}_partition_fk`)}, columns: [table.partitionKey, table[${JSON.stringify(columnName)}]], foreignColumns: [${target}.partitionKey, ${target}.id] })`);
7873
+ }
7874
+ return ` ${JSON.stringify(columnName)}: ${drizzleColumnExpression(columnName, { ...column, unique: partitioned ? false : column.unique, reference: compositeReference ? null : column.reference }, tableIdentifiers)}`;
7875
+ })
7770
7876
  .join(",\n");
7771
- return `export const ${identifier} = sqliteTable(${JSON.stringify(table.name)}, {\n${columns}\n});`;
7877
+ if (partitioned)
7878
+ extras.unshift(`unique(${JSON.stringify(`${table.name}_partitionKey_id_unique`)}).on(table.partitionKey, table.id)`);
7879
+ if (extras.length)
7880
+ needsExtras = true;
7881
+ const extraConfig = extras.length ? `, (table) => [\n ${extras.join(",\n ")}\n]` : "";
7882
+ return `export const ${identifier} = sqliteTable(${JSON.stringify(table.name)}, {\n${columns}\n}${extraConfig});`;
7772
7883
  });
7773
- writeFileSync(file, `import { sql } from "drizzle-orm";
7774
- import { integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
7884
+ const imports = ["integer", "real", "sqliteTable", "text", ...(needsExtras ? ["foreignKey", "unique"] : [])].sort();
7885
+ const registry = needsPartitions
7886
+ ? `// Core's partition registry. Referenced, never exported: Raybase creates it, migrations do not.
7887
+ const raybase_partitions = sqliteTable("_partitions", { key: text("key").primaryKey() });
7775
7888
 
7776
- ${appExports.join("\n\n")}
7777
- `);
7778
- return file;
7889
+ `
7890
+ : "";
7891
+ return `import { sql } from "drizzle-orm";
7892
+ import { ${imports.join(", ")} } from "drizzle-orm/sqlite-core";
7893
+
7894
+ ${registry}${appExports.join("\n\n")}
7895
+ `;
7896
+ }
7897
+ /**
7898
+ * Partitions start from empty tables. drizzle-kit (0.31) turns an existing
7899
+ * table partitioned in one of two ways, and Raybase rewrites each so it
7900
+ * works for an empty table and fails, at migration time, for one with rows:
7901
+ *
7902
+ * - a rebuild, which copies rows with `SELECT ..., "partitionKey" FROM` the
7903
+ * old table (which has no such column): the copy selects NULL, so a row
7904
+ * fails the column's NOT NULL;
7905
+ * - `ALTER TABLE ... ADD "partitionKey" ... NOT NULL`, which SQLite refuses
7906
+ * without a default: it gets one that names no partition, so a row fails
7907
+ * the migration's foreign-key check.
7908
+ *
7909
+ * `previousTables` holds each table's columns before this migration (from
7910
+ * drizzle's previous snapshot).
7911
+ */
7912
+ export function repairPartitionAdoptionSql(sql, previousTables) {
7913
+ return sql
7914
+ .replace(/INSERT INTO [`"]__new_([^`"]+)[`"]\(([^)]*)\) SELECT ([^;]*?) FROM [`"]([^`"]+)[`"];/g, (statement, newName, columns, selected, source) => {
7915
+ const before = previousTables[source];
7916
+ if (newName !== source || !before || before.includes("partitionKey"))
7917
+ return statement;
7918
+ const selection = selected.split(",").map((part) => (part.trim() === '"partitionKey"' ? "NULL" : part.trim()));
7919
+ return `INSERT INTO \`__new_${newName}\`(${columns}) SELECT ${selection.join(", ")} FROM \`${source}\`;`;
7920
+ })
7921
+ .replace(/(ALTER TABLE [`"][^`"]+[`"] ADD [`"]partitionKey[`"] text NOT NULL)( REFERENCES)/gi, `$1 DEFAULT '${noPartitionDefault}'$2`);
7922
+ }
7923
+ /** Each table's columns in a drizzle-kit snapshot file. */
7924
+ export function drizzleSnapshotColumns(snapshotJson) {
7925
+ const snapshot = JSON.parse(snapshotJson);
7926
+ return Object.fromEntries(Object.values(snapshot.tables ?? {}).map((table) => [table.name, Object.values(table.columns ?? {}).map((column) => column.name)]));
7927
+ }
7928
+ /** Applies repairPartitionAdoptionSql to one freshly generated migration file, against drizzle's previous snapshot. */
7929
+ function repairGeneratedPartitionMigration(migrationsDir, file) {
7930
+ const index = Number(/^(\d+)_/.exec(file)?.[1] ?? NaN);
7931
+ const previousSnapshot = Number.isInteger(index) && index > 0
7932
+ ? join(migrationsDir, "meta", `${String(index - 1).padStart(4, "0")}_snapshot.json`)
7933
+ : null;
7934
+ const previousTables = previousSnapshot && existsSync(previousSnapshot) ? drizzleSnapshotColumns(readFileSync(previousSnapshot, "utf8")) : {};
7935
+ const path = join(migrationsDir, file);
7936
+ const sql = readFileSync(path, "utf8");
7937
+ const repaired = repairPartitionAdoptionSql(sql, previousTables);
7938
+ if (repaired !== sql)
7939
+ writeFileSync(path, repaired);
7779
7940
  }
7780
7941
  function drizzleColumnExpression(columnName, column, tableIdentifiers) {
7781
7942
  const args = column.kind === "integer"
@@ -8458,8 +8619,7 @@ function enableAi(cwd, options = {}) {
8458
8619
  };
8459
8620
  }
8460
8621
  function enableAppConfigAi(cwd, profile) {
8461
- // Older apps keep appConfig in the schema module.
8462
- const configModule = existsSync(join(cwd, profile.appConfigModule)) ? profile.appConfigModule : profile.schemaModule;
8622
+ const configModule = profile.appConfigModule;
8463
8623
  const file = join(cwd, configModule);
8464
8624
  if (!existsSync(file))
8465
8625
  return null;
@@ -9470,12 +9630,6 @@ function ensureAuthSecret(cwd) {
9470
9630
  mkdirSync(dir, { recursive: true });
9471
9631
  if (existsSync(file))
9472
9632
  return readFileSync(file, "utf8").trim();
9473
- const legacy = join(dir, "auth-secret");
9474
- if (existsSync(legacy)) {
9475
- const value = readFileSync(legacy, "utf8").trim();
9476
- writeFileSync(file, `${value}\n`, { mode: 0o600 });
9477
- return value;
9478
- }
9479
9633
  const value = generateRandom32Secret();
9480
9634
  writeFileSync(file, `${value}\n`, { mode: 0o600 });
9481
9635
  return value;
@@ -10878,6 +11032,31 @@ function wranglerJobsStatus(config) {
10878
11032
  function wranglerSendEmailBindings(config) {
10879
11033
  return Array.isArray(config.send_email) ? config.send_email : [];
10880
11034
  }
11035
+ /** RAYBASE_BACKUPS buckets bound by more than one Wrangler environment (the top level counts as one). */
11036
+ function sharedBackupsBuckets(config) {
11037
+ const sections = [["the top level", config]];
11038
+ const environments = config.env && typeof config.env === "object" ? config.env : {};
11039
+ for (const [name, section] of Object.entries(environments)) {
11040
+ if (section && typeof section === "object")
11041
+ sections.push([`env.${name}`, section]);
11042
+ }
11043
+ // A bucket is its name within a jurisdiction: "eu" and the default are different buckets.
11044
+ const byBucket = new Map();
11045
+ for (const [name, section] of sections) {
11046
+ const buckets = Array.isArray(section.r2_buckets) ? section.r2_buckets : [];
11047
+ for (const bucket of buckets) {
11048
+ if (bucket.binding !== "RAYBASE_BACKUPS" || typeof bucket.bucket_name !== "string")
11049
+ continue;
11050
+ const jurisdiction = typeof bucket.jurisdiction === "string" && bucket.jurisdiction ? bucket.jurisdiction : null;
11051
+ const label = jurisdiction ? `${bucket.bucket_name} (jurisdiction ${jurisdiction})` : bucket.bucket_name;
11052
+ const id = `${jurisdiction ?? ""}/${bucket.bucket_name}`;
11053
+ const entry = byBucket.get(id) ?? { bucket: label, names: [] };
11054
+ entry.names.push(name);
11055
+ byBucket.set(id, entry);
11056
+ }
11057
+ }
11058
+ return [...byBucket.values()].filter((entry) => entry.names.length > 1).map((entry) => ({ bucket: entry.bucket, environments: entry.names }));
11059
+ }
10881
11060
  function wranglerBackupsStatus(config) {
10882
11061
  const r2Buckets = Array.isArray(config.r2_buckets) ? config.r2_buckets : [];
10883
11062
  const vars = (config.vars && typeof config.vars === "object" ? config.vars : {});
@@ -10920,7 +11099,7 @@ function localDevBackupNotice(config) {
10920
11099
  return [
10921
11100
  "Raybase dev notice: automated R2 backups are production-only in local development.",
10922
11101
  "Wrangler may warn that the top-level RAYBASE_BACKUPS bucket or backup vars are not inherited by env.local-dev; that is expected.",
10923
- "The local admin supports encrypted manual backup download when a local R2 binding and RAYBASE_BACKUPS_KEY are available; legacy SQL remains restore-only."
11102
+ "The local admin supports encrypted manual backup download when a local R2 binding and RAYBASE_BACKUPS_KEY are available."
10924
11103
  ].join("\n");
10925
11104
  }
10926
11105
  function wranglerAiStatus(config) {