@supacloud/cli 0.130.0 → 0.132.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.
package/dist/index.js CHANGED
@@ -19565,7 +19565,7 @@ var ACTION_POLICY = {
19565
19565
  init: { local: ["init"] },
19566
19566
  env: { local: ["list", "check", "sync"] },
19567
19567
  app: {
19568
- local: ["init", "generate", "infer", "dev", "watch", "verify-plan", "verify", "compile", "check", "graph", "explain", "export-tools", "context", "lens", "doctor", "fix", "plan", "build"],
19568
+ local: ["init", "generate", "infer", "dev", "watch", "verify-plan", "verify", "compile", "check", "graph", "explain", "export-tools", "context", "lens", "doctor", "fix", "upgrade", "client-sdk", "contract-diff", "sql-prepare", "plan", "build"],
19569
19569
  read: ["status", "evidence", "logs", "transfer-plan", "promote-plan", "rollback-plan", "history", "deploy-plan", "diff", "promote-status", "preview-plan", "previews", "preview-list", "preview-status"],
19570
19570
  write: ["release", "upload", "configure", "transfer", "promote", "promote-reconcile", "deploy", "rollback", "reconcile", "retire", "preview", "preview-create", "preview-reconcile", "preview-cleanup", "preview-pr"]
19571
19571
  },
@@ -24818,6 +24818,19 @@ function rejectActionSpecificFlags(action, args) {
24818
24818
  throw new Error(`'--bundle-dir' is not supported for '${action}'`);
24819
24819
  }
24820
24820
  }
24821
+ function databaseSecretName(action, value, projectApi) {
24822
+ if (action !== "deploy" && (value !== undefined || projectApi !== undefined)) {
24823
+ const flag = value !== undefined ? "--database-secret" : "--project-api";
24824
+ throw new Error(`'${flag}' is not supported for '${action}'`);
24825
+ }
24826
+ if (value === undefined) {
24827
+ if (projectApi !== undefined)
24828
+ throw new Error("'--project-api' requires '--database-secret'");
24829
+ } else if (typeof value !== "string" || value.length > 64 || !/^APP_[A-Z][A-Z0-9_]*_DATABASE_URL$/u.test(value)) {
24830
+ throw new Error("'--database-secret' expects an APP_*_DATABASE_URL secret name (max 64 characters), not a connection string");
24831
+ }
24832
+ return value;
24833
+ }
24821
24834
  function resolveEntrypoint(pathArg) {
24822
24835
  const resolved = resolve8(pathArg);
24823
24836
  const stat = statSync4(resolved);
@@ -25175,6 +25188,26 @@ async function readFunctionIdentity(http, projectRef, slug) {
25175
25188
  const identity = projectedFunctionIdentity(response.data, projectRef, slug);
25176
25189
  return identity ? { content: [{ type: "text", text: JSON.stringify(identity, null, 2) }] } : releaseControlFailure("edge_functions.get_config", "INVALID_RESPONSE", response.status);
25177
25190
  }
25191
+ async function databaseDeployCapabilities(http, target, secret, projectApi, base) {
25192
+ if (base === undefined && target.expectedActiveVersion !== "absent") {
25193
+ const response = await http.get(`${edgeFunctionResourcePath(target.projectRef, target.slug)}/config`, { maxJsonBytes: 128 * 1024 });
25194
+ const current = response.ok && projectedFunctionIdentity(response.data, target.projectRef, target.slug);
25195
+ if (!current)
25196
+ throw new Error("Could not read the current Function configuration for '--database-secret'");
25197
+ if (current.active_version !== target.expectedActiveVersion || current.activation_id !== target.expectedActivationId) {
25198
+ throw new Error("Function activation changed. Run 'edge_functions list' before deploying again.");
25199
+ }
25200
+ base = current.capabilities;
25201
+ }
25202
+ const { secrets = [], outbound_hosts, bindings, background } = base ?? {};
25203
+ const selectedBindings = projectApi === true ? [...new Set([...bindings ?? ["pgredis"], "project_api"])] : projectApi === false ? bindings?.filter((name) => name !== "project_api") : bindings;
25204
+ return {
25205
+ secrets: [...new Set([...secrets, secret])],
25206
+ ...outbound_hosts === undefined ? {} : { outbound_hosts },
25207
+ ...selectedBindings === undefined ? {} : { bindings: selectedBindings },
25208
+ ...background === undefined ? {} : { background }
25209
+ };
25210
+ }
25178
25211
  async function updateFunctionConfiguration(http, request) {
25179
25212
  const response = await http.patchReleaseMutation(`${edgeFunctionResourcePath(request.projectRef, request.slug)}/config`, { ...request.config, expected_activation_id: request.expectedActivationId });
25180
25213
  if (!response.ok)
@@ -25313,6 +25346,8 @@ Actions: list, get_config, deploy, deploy_bundle, deploy_manifest, config, sourc
25313
25346
  path: optional(String2(), "[deploy/check] Source path; [scaffold] optional target directory"),
25314
25347
  "prebundled-path": optional(String2(), "[deploy] Prebuilt runtime bundle to upload without rebuilding; requires expected-sha256"),
25315
25348
  "expected-sha256": optional(String2({ pattern: SHA256_HEX_PATTERN.source, minLength: 64, maxLength: 64 }), "[deploy] Required lowercase SHA-256 of the exact prebundled-path bytes"),
25349
+ "database-secret": optional(String2(), "[deploy] Bind an APP_*_DATABASE_URL project secret by name"),
25350
+ "project-api": optional(Boolean2(), "[deploy] With database-secret, explicitly grant or revoke project API access (includes the service-role key)"),
25316
25351
  output: optional(String2(), "[source] Write source to this local file instead of stdout; the file must not already exist"),
25317
25352
  files: optional(functionFilesSchema, "[deploy_bundle] File map as a JSON object: { 'index.ts': '...', '_shared/x.ts': '...' }"),
25318
25353
  "bundle-dir": optional(String2(), "[deploy_bundle] Local self-contained UTF-8 bundle directory; excludes node_modules, .git, AppleDouble, symlinks, and special files"),
@@ -25342,6 +25377,7 @@ Actions: list, get_config, deploy, deploy_bundle, deploy_manifest, config, sourc
25342
25377
  };
25343
25378
  }
25344
25379
  validateFunctionAot(args);
25380
+ const databaseSecret = databaseSecretName(args.action, args["database-secret"], args["project-api"]);
25345
25381
  if (args.action === "activate")
25346
25382
  return activateFunctionVersion(http, args, options.readOnly);
25347
25383
  if (args.action === "deploy_manifest")
@@ -25445,6 +25481,13 @@ ${checkRes.err}`;
25445
25481
  case "deploy":
25446
25482
  need("ref", ref);
25447
25483
  need("slug", slug);
25484
+ need("expected-active-version", expectedActiveVersion);
25485
+ need("expected-activation-id", expectedActivationId);
25486
+ const target = { projectRef: ref, slug, expectedActiveVersion, expectedActivationId };
25487
+ const deployConfig = functionConfig();
25488
+ if (databaseSecret !== undefined) {
25489
+ deployConfig.capabilities = await databaseDeployCapabilities(http, target, databaseSecret, args["project-api"], capabilities);
25490
+ }
25448
25491
  const deployCode = await preparedDeployCode(args);
25449
25492
  if (!deployCode.prebundled) {
25450
25493
  const deployCheck = await checkSyntax(deployCode.code);
@@ -25459,15 +25502,12 @@ ${deployCheck.err}`;
25459
25502
  ...deployCode.prebundled ? { prebundled: true, expected_sha256: deployCode.expectedSha256 } : { minify },
25460
25503
  expected_active_version: expectedActiveVersion,
25461
25504
  expected_activation_id: expectedActivationId,
25462
- ...functionConfig()
25505
+ ...deployConfig
25463
25506
  }, { timeoutMs: EDGE_FUNCTION_DEPLOY_TIMEOUT_MS });
25464
25507
  return functionMutationResponse({
25465
25508
  operation: "edge_functions.deploy",
25466
- projectRef: ref,
25467
- slug,
25468
- expectedActiveVersion,
25469
- expectedActivationId,
25470
- config: functionConfig()
25509
+ ...target,
25510
+ config: deployConfig
25471
25511
  }, deploymentResponse);
25472
25512
  case "deploy_bundle":
25473
25513
  need("ref", ref);
@@ -30033,6 +30073,7 @@ import { basename as basename8, dirname as dirname9, isAbsolute as isAbsolute6,
30033
30073
  import { promisify as promisify2 } from "node:util";
30034
30074
  import {
30035
30075
  applyDiagnosticFix,
30076
+ assessMigration,
30036
30077
  buildDeliveryProject,
30037
30078
  checkProject,
30038
30079
  compileProject,
@@ -30041,17 +30082,32 @@ import {
30041
30082
  createExecutionContextPack,
30042
30083
  createDiagnosticRepairPlan,
30043
30084
  createInferencePlan,
30085
+ diffProjectContracts,
30044
30086
  formatInferencePlan,
30045
30087
  doctorProject,
30088
+ extractStaticSqlQueriesFromSource,
30089
+ formatContractDiffReport,
30046
30090
  formatDoctorCheck,
30091
+ formatMigrationAssessment,
30092
+ generateMultiLangClient,
30093
+ lintArchitectureRules,
30094
+ lintAspectUsage,
30095
+ lintEffectErrorExhaustiveness,
30096
+ lintEnvContract,
30097
+ lintRlsIndexes,
30098
+ lintSqlAgainstCatalog,
30047
30099
  loadSupacloudConfig,
30100
+ migrateProject,
30101
+ parseDataCatalogDocument,
30048
30102
  formatDeliveryPlan,
30049
30103
  planDeliveryProject,
30104
+ readOpenApiJson,
30050
30105
  resolveSupacloudConfig,
30051
30106
  readExecutionMetadata,
30052
30107
  createProjectSemanticSnapshot,
30053
30108
  createSemanticLens,
30054
- watchProject
30109
+ watchProject,
30110
+ verifySqlQueriesAgainstPostgres
30055
30111
  } from "@supacloud/compiler";
30056
30112
 
30057
30113
  // src/shared/tools/app-tool-export.ts
@@ -30177,25 +30233,25 @@ var starter_metadata_default = {
30177
30233
  generatedBy: "supacloud/starter-metadata-v1",
30178
30234
  packages: {
30179
30235
  compiler: {
30180
- version: "0.68.0"
30236
+ version: "0.70.0"
30181
30237
  },
30182
30238
  app: {
30183
- version: "0.40.1",
30239
+ version: "0.41.0",
30184
30240
  dependencies: {
30185
30241
  rxjs: "7.8.2"
30186
30242
  }
30187
30243
  },
30188
30244
  elysia: {
30189
- version: "0.44.0"
30245
+ version: "0.45.0"
30190
30246
  },
30191
30247
  commands: {
30192
- version: "0.14.0"
30248
+ version: "0.15.0"
30193
30249
  },
30194
30250
  contracts: {
30195
30251
  version: "0.17.0"
30196
30252
  },
30197
30253
  db: {
30198
- version: "0.28.0",
30254
+ version: "0.29.0",
30199
30255
  dependencies: {},
30200
30256
  devDependencies: {},
30201
30257
  peerDependencies: {
@@ -30220,7 +30276,7 @@ var starter_metadata_default = {
30220
30276
  }
30221
30277
  },
30222
30278
  sdk: {
30223
- version: "0.49.1",
30279
+ version: "0.50.0",
30224
30280
  peerDependencies: {
30225
30281
  "@supabase/supabase-js": "^2.118.0"
30226
30282
  }
@@ -36559,6 +36615,58 @@ Scenario: Delivery
36559
36615
  `
36560
36616
  };
36561
36617
  }
36618
+ function featureTestingScaffold(name, className, table) {
36619
+ const [schemaName, tableName] = table.includes(".") ? table.split(".", 2) : ["public", table];
36620
+ return {
36621
+ [`${name}.governance.test.ts`]: `import { describe, test } from "bun:test";
36622
+ import { SQL } from "bun";
36623
+ import { assertRlsMatrix, runDurableCommandContractSuite, type SqlExecutor } from "@supacloud/testing";
36624
+
36625
+ const PG_URL = process.env["SUPACLOUD_TEST_PG_URL"];
36626
+ const runIfPg = PG_URL ? test : test.skip;
36627
+
36628
+ function adaptSql(db: SQL): SqlExecutor {
36629
+ return {
36630
+ async query<T = Record<string, unknown>>(statement: string, params?: unknown[]): Promise<T[]> {
36631
+ if (params && params.length > 0) return (await db.unsafe(statement, params)) as unknown as T[];
36632
+ return (await db.unsafe(statement)) as unknown as T[];
36633
+ },
36634
+ };
36635
+ }
36636
+
36637
+ describe("${className} governance contract", () => {
36638
+ runIfPg("enforces multi-role RLS matrix on ${schemaName}.${tableName}", async () => {
36639
+ const db = new SQL(PG_URL!);
36640
+ try {
36641
+ await assertRlsMatrix(adaptSql(db), {
36642
+ roles: [
36643
+ { label: "anon", role: "anon" },
36644
+ { label: "authenticated", role: "authenticated", jwtClaims: { sub: "00000000-0000-4000-8000-000000000001" } },
36645
+ ],
36646
+ tables: [
36647
+ {
36648
+ schema: ${JSON.stringify(schemaName)},
36649
+ table: ${JSON.stringify(tableName)},
36650
+ probes: {},
36651
+ expectations: {
36652
+ anon: { select: "deny" },
36653
+ authenticated: { select: "empty" },
36654
+ },
36655
+ },
36656
+ ],
36657
+ });
36658
+ } finally {
36659
+ await db.close();
36660
+ }
36661
+ });
36662
+
36663
+ test.skip("verifies ${name}.approve idempotency and rollback atomicity (wire runner)", async () => {
36664
+ void runDurableCommandContractSuite;
36665
+ });
36666
+ });
36667
+ `
36668
+ };
36669
+ }
36562
36670
 
36563
36671
  // src/shared/tools/app-local-dev.ts
36564
36672
  import { spawn } from "node:child_process";
@@ -37339,6 +37447,11 @@ async function generateScaffold(args) {
37339
37447
  }) : resourceScaffold(name, pascalName(name)))) {
37340
37448
  writes.push({ path: join15(dir, name, file).replaceAll("\\", "/"), content });
37341
37449
  }
37450
+ if (kind === "feature" && args.with_tests) {
37451
+ for (const [file, content] of Object.entries(featureTestingScaffold(name, pascalName(name), featureGovernance.database.table))) {
37452
+ writes.push({ path: join15(dir, name, file).replaceAll("\\", "/"), content });
37453
+ }
37454
+ }
37342
37455
  } else {
37343
37456
  if (!moduleName?.trim()) {
37344
37457
  throw new ScaffoldError("SCAFFOLD_MODULE_REQUIRED", "app generate requires --module; no unique top-level module was inferred");
@@ -38127,7 +38240,77 @@ async function runCheck(args) {
38127
38240
  strict: args.strict ?? loadedConfig.strict ?? false
38128
38241
  }, root);
38129
38242
  const result = await checkProject(config);
38130
- const diagnosticError = result.diagnostics.some((diagnostic) => diagnostic.severity === "error");
38243
+ const aspectDiagnostics = lintAspectUsage(result.graph);
38244
+ const effectDiagnostics = lintEffectErrorExhaustiveness(result.graph);
38245
+ const collectSourceFiles = async (dirPath) => {
38246
+ const out = [];
38247
+ const skipDirs = new Set(["node_modules", ".git", basename8(config.outDir)]);
38248
+ const walk = async (current) => {
38249
+ const entries = await readdir5(current, { withFileTypes: true }).catch(() => []);
38250
+ for (const entry of entries) {
38251
+ const full = join15(current, entry.name);
38252
+ if (entry.isDirectory()) {
38253
+ if (!skipDirs.has(entry.name))
38254
+ await walk(full);
38255
+ continue;
38256
+ }
38257
+ if (entry.isFile() && /\.(?:ts|mts|svelte)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
38258
+ const relToSource = relative8(config.rootDir, full).replaceAll("\\", "/");
38259
+ out.push({
38260
+ file: relToSource,
38261
+ content: await readFile5(full, "utf8")
38262
+ });
38263
+ }
38264
+ }
38265
+ };
38266
+ await walk(config.rootDir);
38267
+ return out;
38268
+ };
38269
+ const sourceFiles = await collectSourceFiles(config.rootDir);
38270
+ const catalogCandidates = [
38271
+ join15(defaults.outDir, "data-catalog.json"),
38272
+ join15(root, "data-catalog.json"),
38273
+ join15(root, "generated", "data-catalog.json")
38274
+ ];
38275
+ const catalogPath = catalogCandidates.find((candidate) => existsSync13(candidate));
38276
+ const sqlDiagnostics = [];
38277
+ if (catalogPath) {
38278
+ try {
38279
+ const catalogDoc = parseDataCatalogDocument(JSON.parse(await readFile5(catalogPath, "utf8")));
38280
+ for (const src of sourceFiles) {
38281
+ sqlDiagnostics.push(...lintSqlAgainstCatalog({ sourceText: src.content, file: src.file, catalog: catalogDoc }));
38282
+ }
38283
+ } catch {}
38284
+ }
38285
+ const archDiagnostics = loadedConfig.architectureRules?.length ? lintArchitectureRules({
38286
+ graph: result.graph,
38287
+ rules: loadedConfig.architectureRules,
38288
+ sourceFiles
38289
+ }) : [];
38290
+ const envDiagnostics = loadedConfig.envSchema ? lintEnvContract({
38291
+ envSchema: loadedConfig.envSchema,
38292
+ sourceFiles
38293
+ }) : [];
38294
+ const zmodelCandidates = [
38295
+ join15(root, "zenstack", "schema.zmodel"),
38296
+ join15(root, "prisma", "schema.zmodel"),
38297
+ join15(root, "schema.zmodel")
38298
+ ];
38299
+ const zmodelPath = zmodelCandidates.find((candidate) => existsSync13(candidate));
38300
+ const rlsDiagnostics = zmodelPath ? lintRlsIndexes({
38301
+ file: projectRelativePath(root, zmodelPath) ?? "schema.zmodel",
38302
+ zmodelText: await readFile5(zmodelPath, "utf8")
38303
+ }) : [];
38304
+ const combinedDiagnostics = [
38305
+ ...result.diagnostics,
38306
+ ...aspectDiagnostics,
38307
+ ...effectDiagnostics,
38308
+ ...sqlDiagnostics,
38309
+ ...archDiagnostics,
38310
+ ...envDiagnostics,
38311
+ ...rlsDiagnostics
38312
+ ];
38313
+ const diagnosticError = combinedDiagnostics.some((diagnostic) => diagnostic.severity === "error");
38131
38314
  const hasError = diagnosticError || result.mismatches.length > 0 || database?.ok === false;
38132
38315
  const next = hasError ? diagnosticError || database?.ok === false ? ["supacloud app doctor --format json"] : ["supacloud app compile", "supacloud app check --format json"] : ["supacloud app verify-plan --target <module>"];
38133
38316
  if (args.format === "json")
@@ -38136,7 +38319,7 @@ async function runCheck(args) {
38136
38319
  ok: !hasError,
38137
38320
  next,
38138
38321
  source: "declaration",
38139
- diagnostics: result.diagnostics,
38322
+ diagnostics: combinedDiagnostics,
38140
38323
  mismatches: result.mismatches,
38141
38324
  upToDate: result.upToDate,
38142
38325
  written: [],
@@ -38145,7 +38328,7 @@ async function runCheck(args) {
38145
38328
  }, null, 2), hasError);
38146
38329
  const summary = `checked ${result.graph.modules.length} module(s), no files written`;
38147
38330
  return textResult2([
38148
- formatDiagnostics(result.diagnostics),
38331
+ formatDiagnostics(combinedDiagnostics),
38149
38332
  ...result.mismatches.map((path) => `generated artifact mismatch: ${path}`),
38150
38333
  ...database ? [formatDoctorCheck(database)] : [],
38151
38334
  "",
@@ -38153,6 +38336,197 @@ async function runCheck(args) {
38153
38336
  ].join(`
38154
38337
  `), hasError);
38155
38338
  }
38339
+ async function runUpgrade(args) {
38340
+ const root = resolve20(args.root || process.cwd());
38341
+ const loadedConfig = await loadSupacloudConfig(root);
38342
+ const defaults = resolveSupacloudConfig(loadedConfig, root);
38343
+ const configuredRoot = sourceRoot(args, root, loadedConfig.root);
38344
+ const include = parseInclude(args.include) ?? loadedConfig.include;
38345
+ const compile = compileOptionsFromConfig({
38346
+ ...loadedConfig,
38347
+ ...configuredRoot === undefined ? {} : { root: configuredRoot },
38348
+ outDir: args.out_dir ? resolve20(root, args.out_dir) : defaults.outDir,
38349
+ ...include === undefined ? {} : { include },
38350
+ strict: args.strict ?? loadedConfig.strict ?? false
38351
+ }, root);
38352
+ const assessment = await assessMigration({ projectDir: root, compile });
38353
+ const migrated = await migrateProject({ rootDir: compile.rootDir, include, write: args.write === true });
38354
+ const ok = assessment.ok && migrated.issues.length === 0;
38355
+ const payload = {
38356
+ version: 1,
38357
+ ok,
38358
+ dryRun: args.write !== true,
38359
+ status: assessment.status,
38360
+ findings: assessment.findings,
38361
+ migrations: migrated
38362
+ };
38363
+ if (args.format === "json") {
38364
+ return textResult2(JSON.stringify(payload, null, 2), !ok);
38365
+ }
38366
+ return textResult2([
38367
+ formatMigrationAssessment(assessment),
38368
+ "",
38369
+ `Migration ${args.write === true ? "applied" : "preview"}: ${migrated.files.length} file(s) scanned, ${migrated.changedFiles.length} changed.`
38370
+ ].join(`
38371
+ `), !ok);
38372
+ }
38373
+ async function runClientSdk(args) {
38374
+ const root = resolve20(args.root || process.cwd());
38375
+ const language = args.lang;
38376
+ if (language !== "python" && language !== "go" && language !== "dart") {
38377
+ return textResult2("app client-sdk requires --lang python|go|dart", true);
38378
+ }
38379
+ const catalogFile = args.catalog ? resolve20(root, args.catalog) : undefined;
38380
+ const openapiFile = args.openapi ? resolve20(root, args.openapi) : undefined;
38381
+ const catalog = catalogFile && existsSync13(catalogFile) ? parseDataCatalogDocument(JSON.parse(await readFile5(catalogFile, "utf8"))) : undefined;
38382
+ const openapi = openapiFile && existsSync13(openapiFile) ? await readOpenApiJson(openapiFile) : undefined;
38383
+ const generated = generateMultiLangClient({
38384
+ language,
38385
+ catalog,
38386
+ openapi,
38387
+ packageName: args.package_name
38388
+ });
38389
+ if (args.out_dir) {
38390
+ const targetDir = resolve20(root, args.out_dir);
38391
+ await mkdir6(targetDir, { recursive: true });
38392
+ const targetFile = join15(targetDir, generated.filename);
38393
+ await writeFile5(targetFile, generated.content, "utf8");
38394
+ if (args.format === "json") {
38395
+ return textResult2(JSON.stringify({ ok: true, language, file: targetFile, summary: generated.summary }, null, 2));
38396
+ }
38397
+ return textResult2(`Generated ${language} SDK -> ${targetFile}`);
38398
+ }
38399
+ if (args.format === "json") {
38400
+ return textResult2(JSON.stringify({ ok: true, ...generated }, null, 2));
38401
+ }
38402
+ return textResult2(generated.content);
38403
+ }
38404
+ async function runContractDiff(args) {
38405
+ const root = resolve20(args.root || process.cwd());
38406
+ const loadedConfig = await loadSupacloudConfig(root);
38407
+ const defaults = resolveSupacloudConfig(loadedConfig, root);
38408
+ const outDir = args.out_dir ? resolve20(root, args.out_dir) : defaults.outDir;
38409
+ const resolveOptionalJson = async (explicitPath, fallbackPath) => {
38410
+ const candidate = explicitPath ? resolve20(root, explicitPath) : fallbackPath;
38411
+ if (!candidate || !existsSync13(candidate))
38412
+ return;
38413
+ return JSON.parse(await readFile5(candidate, "utf8"));
38414
+ };
38415
+ const resolveOptionalText = async (explicitPath, fallbackPath) => {
38416
+ const candidate = explicitPath ? resolve20(root, explicitPath) : fallbackPath;
38417
+ if (!candidate || !existsSync13(candidate))
38418
+ return;
38419
+ return await readFile5(candidate, "utf8");
38420
+ };
38421
+ const baselineOpenApi = args.baseline_openapi ? await readOpenApiJson(resolve20(root, args.baseline_openapi)) : undefined;
38422
+ const currentOpenApi = baselineOpenApi ? await resolveOptionalJson(args.current_openapi, join15(outDir, "openapi.json")) : undefined;
38423
+ const baselineAsyncApi = await resolveOptionalJson(args.baseline_asyncapi);
38424
+ const currentAsyncApi = baselineAsyncApi ? await resolveOptionalJson(args.current_asyncapi, join15(outDir, "asyncapi.json")) : undefined;
38425
+ const baselineCatalog = await resolveOptionalJson(args.baseline_catalog);
38426
+ const currentCatalog = baselineCatalog ? await resolveOptionalJson(args.current_catalog, join15(outDir, "data-catalog.json")) : undefined;
38427
+ const baselineRls = await resolveOptionalJson(args.baseline_rls);
38428
+ const currentRls = baselineRls ? await resolveOptionalJson(args.current_rls) : undefined;
38429
+ const baselineGraphqlSdl = await resolveOptionalText(args.baseline_graphql);
38430
+ const currentGraphqlSdl = baselineGraphqlSdl ? await resolveOptionalText(args.current_graphql, join15(outDir, "catalog.graphql")) : undefined;
38431
+ if (!baselineOpenApi && !baselineAsyncApi && !baselineCatalog && !baselineRls && !baselineGraphqlSdl) {
38432
+ return textResult2("app contract-diff requires at least one baseline contract (--baseline_openapi, --baseline_asyncapi, --baseline_catalog, --baseline_rls, or --baseline_graphql)", true);
38433
+ }
38434
+ const report = diffProjectContracts({
38435
+ ...baselineOpenApi && currentOpenApi ? { baselineOpenApi, currentOpenApi } : {},
38436
+ ...baselineAsyncApi && currentAsyncApi ? { baselineAsyncApi, currentAsyncApi } : {},
38437
+ ...baselineCatalog && currentCatalog ? { baselineCatalog, currentCatalog } : {},
38438
+ ...baselineRls && currentRls ? { baselineRls, currentRls } : {},
38439
+ ...baselineGraphqlSdl && currentGraphqlSdl ? { baselineGraphqlSdl, currentGraphqlSdl } : {}
38440
+ });
38441
+ if (args.format === "json") {
38442
+ return textResult2(JSON.stringify(report, null, 2), !report.ok);
38443
+ }
38444
+ return textResult2(formatContractDiffReport(report), !report.ok);
38445
+ }
38446
+ async function collectTsFilesRecursive(dir, rootDir, out) {
38447
+ if (!existsSync13(dir))
38448
+ return;
38449
+ const entries = await readdir5(dir, { withFileTypes: true });
38450
+ for (const entry of entries) {
38451
+ if (entry.name === "node_modules" || entry.name === "generated" || entry.name.startsWith("."))
38452
+ continue;
38453
+ const full = join15(dir, entry.name);
38454
+ if (entry.isDirectory()) {
38455
+ await collectTsFilesRecursive(full, rootDir, out);
38456
+ } else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {
38457
+ out.push({
38458
+ file: relative8(rootDir, full).replaceAll("\\", "/"),
38459
+ content: await readFile5(full, "utf8")
38460
+ });
38461
+ }
38462
+ }
38463
+ }
38464
+ async function runSqlPrepare(args) {
38465
+ const root = resolve20(args.root || process.cwd());
38466
+ const srcFiles = [];
38467
+ await collectTsFilesRecursive(join15(root, "src"), root, srcFiles);
38468
+ const queries = extractStaticSqlQueriesFromSource(srcFiles);
38469
+ const cacheFile = args.cache_path ? resolve20(root, args.cache_path) : join15(root, ".supacloud", "sql-prepare-cache.json");
38470
+ const offline = args.offline === true || !args.database_url;
38471
+ if (offline) {
38472
+ const cache = existsSync13(cacheFile) ? JSON.parse(await readFile5(cacheFile, "utf8")) : undefined;
38473
+ const report = await verifySqlQueriesAgainstPostgres({
38474
+ queries,
38475
+ cache,
38476
+ offline: true,
38477
+ ...args.schema_hash ? { schemaHash: args.schema_hash } : {}
38478
+ });
38479
+ if (args.format === "json") {
38480
+ return textResult2(JSON.stringify(report, null, 2), !report.ok);
38481
+ }
38482
+ return textResult2(report.ok ? `SQL prepare offline verification passed (${report.verifiedCount} query/queries).` : report.diagnostics.map((d) => `${d.errorCode ?? d.code}: ${d.message}`).join(`
38483
+ `), !report.ok);
38484
+ }
38485
+ const dbUrl = args.database_url;
38486
+ const pgClient = new Bun.SQL(dbUrl);
38487
+ let seq = 0;
38488
+ const executor = {
38489
+ async prepare(sqlText) {
38490
+ const cleanSql = sqlText.trim().replace(/;+$/, "").trim();
38491
+ if (!cleanSql)
38492
+ return { ok: false, error: "SQL statement must not be empty" };
38493
+ seq += 1;
38494
+ const stmt = `supacloud_cli_prepare_${seq}`;
38495
+ try {
38496
+ await pgClient.unsafe(`PREPARE ${stmt} AS ${cleanSql}`);
38497
+ const meta = await pgClient.unsafe("SELECT parameter_types::text[] AS param_types FROM pg_prepared_statements WHERE name = $1", [stmt]);
38498
+ const firstRow = Array.isArray(meta) ? meta[0] : undefined;
38499
+ const paramTypes = Array.isArray(firstRow?.param_types) ? firstRow.param_types.filter((t) => typeof t === "string") : [];
38500
+ return { ok: true, paramTypes, columns: [] };
38501
+ } catch (err) {
38502
+ const msg = err instanceof Error ? err.message : String(err);
38503
+ const code = err && typeof err === "object" && "code" in err && typeof err.code === "string" ? err.code : undefined;
38504
+ return { ok: false, error: msg, ...code ? { code } : {} };
38505
+ } finally {
38506
+ await pgClient.unsafe(`DEALLOCATE ${stmt}`).catch(() => {});
38507
+ }
38508
+ }
38509
+ };
38510
+ try {
38511
+ const report = await verifySqlQueriesAgainstPostgres({
38512
+ queries,
38513
+ executor,
38514
+ ...args.schema_hash ? { schemaHash: args.schema_hash } : {}
38515
+ });
38516
+ if (report.ok && args.write === true) {
38517
+ await mkdir6(dirname9(cacheFile), { recursive: true });
38518
+ await writeFile5(cacheFile, `${JSON.stringify(report.cache, null, 2)}
38519
+ `, "utf8");
38520
+ }
38521
+ if (args.format === "json") {
38522
+ return textResult2(JSON.stringify(report, null, 2), !report.ok);
38523
+ }
38524
+ return textResult2(report.ok ? `SQL prepare live verification passed (${report.verifiedCount} query/queries).` : report.diagnostics.map((d) => `${d.errorCode ?? d.code}: ${d.message}`).join(`
38525
+ `), !report.ok);
38526
+ } finally {
38527
+ await pgClient.close();
38528
+ }
38529
+ }
38156
38530
  function projectRelativePath(root, path) {
38157
38531
  const value = relative8(root, path).replaceAll("\\", "/");
38158
38532
  return value === ".." || value.startsWith("../") || value.startsWith("/") ? undefined : value;
@@ -39069,6 +39443,14 @@ async function runAppTool(request, options = {}) {
39069
39443
  return runDoctor(request);
39070
39444
  case "fix":
39071
39445
  return runFix(request);
39446
+ case "upgrade":
39447
+ return runUpgrade(request);
39448
+ case "client-sdk":
39449
+ return runClientSdk(request);
39450
+ case "contract-diff":
39451
+ return runContractDiff(request);
39452
+ case "sql-prepare":
39453
+ return runSqlPrepare(request);
39072
39454
  default:
39073
39455
  return textResult2(`Unknown app action: ${String(request.action)}`, true);
39074
39456
  }
@@ -39093,6 +39475,10 @@ function registerAppTools(server, options = {}) {
39093
39475
  "lens",
39094
39476
  "doctor",
39095
39477
  "fix",
39478
+ "upgrade",
39479
+ "client-sdk",
39480
+ "contract-diff",
39481
+ "sql-prepare",
39096
39482
  "plan",
39097
39483
  "build",
39098
39484
  "release",
@@ -39156,8 +39542,26 @@ function registerAppTools(server, options = {}) {
39156
39542
  fix: optional(String2(), "[fix] Path to a DiagnosticFix JSON file produced by `doctor --format json`"),
39157
39543
  from_doctor: optional(String2(), "[fix] Read one fix from a doctor --format json output"),
39158
39544
  fix_index: optional(Number2({ minimum: 0, multipleOf: 1 }), "[fix] Zero-based fixPlan index used with --from-doctor"),
39159
- write: optional(Boolean2(), "[fix] Write the fix to disk (default: preview only)"),
39160
- skip_build: optional(Boolean2(), "[release] Reuse --manifest_path instead of running the local delivery build")
39545
+ write: optional(Boolean2(), "[fix/upgrade/client-sdk] Write changes or generated SDK files to disk (default: preview only)"),
39546
+ skip_build: optional(Boolean2(), "[release] Reuse --manifest_path instead of running the local delivery build"),
39547
+ lang: optional(stringEnum2(["python", "go", "dart"]), "[client-sdk] Target client language"),
39548
+ catalog: optional(String2(), "[client-sdk] Path to data-catalog.json"),
39549
+ openapi: optional(String2(), "[client-sdk] Path to OpenAPI JSON document"),
39550
+ baseline_openapi: optional(String2(), "[contract-diff] Baseline OpenAPI JSON path"),
39551
+ current_openapi: optional(String2(), "[contract-diff] Current OpenAPI JSON path"),
39552
+ baseline_asyncapi: optional(String2(), "[contract-diff] Baseline AsyncAPI JSON path"),
39553
+ current_asyncapi: optional(String2(), "[contract-diff] Current AsyncAPI JSON path"),
39554
+ baseline_catalog: optional(String2(), "[contract-diff] Baseline DataCatalog JSON path"),
39555
+ current_catalog: optional(String2(), "[contract-diff] Current DataCatalog JSON path"),
39556
+ baseline_graphql: optional(String2(), "[contract-diff] Baseline GraphQL SDL path"),
39557
+ current_graphql: optional(String2(), "[contract-diff] Current GraphQL SDL path"),
39558
+ baseline_rls: optional(String2(), "[contract-diff] Baseline RLS snapshot JSON path"),
39559
+ current_rls: optional(String2(), "[contract-diff] Current RLS snapshot JSON path"),
39560
+ cache_path: optional(String2(), "[sql-prepare] SQL prepare cache path (default: .supacloud/sql-prepare-cache.json)"),
39561
+ offline: optional(Boolean2(), "[sql-prepare] Verify SQL against offline cache without connecting to PostgreSQL"),
39562
+ schema_hash: optional(String2(), "[sql-prepare] Expected ZModel schema hash for drift check"),
39563
+ package_name: optional(String2(), "[client-sdk] Package/module name for generated client"),
39564
+ with_tests: optional(Boolean2(), "[generate feature] Also scaffold a @supacloud/testing test file")
39161
39565
  }, (request) => runAppTool(request, options));
39162
39566
  }
39163
39567
 
@@ -44770,7 +45174,7 @@ async function runProjectDeployment(http, args) {
44770
45174
  // package.json
44771
45175
  var package_default = {
44772
45176
  name: "@supacloud/cli",
44773
- version: "0.130.0",
45177
+ version: "0.132.0",
44774
45178
  description: "Project-scoped CLI for SupaCloud users",
44775
45179
  type: "module",
44776
45180
  main: "./dist/index.js",
@@ -44822,23 +45226,23 @@ var package_default = {
44822
45226
  directory: "packages/cli"
44823
45227
  },
44824
45228
  dependencies: {
44825
- "@supacloud/compiler": "^0.68.0",
45229
+ "@supacloud/compiler": "^0.70.0",
44826
45230
  "@supacloud/delivery": "0.30.1",
44827
- "@supacloud/db": "0.28.0",
45231
+ "@supacloud/db": "0.29.0",
44828
45232
  typebox: "1.4.3"
44829
45233
  },
44830
45234
  overrides: {
44831
45235
  "@supacloud/contracts": "0.17.0",
44832
45236
  "@supacloud/delivery": "0.30.1",
44833
45237
  "@graphql-tools/utils": "^12.0.4",
44834
- "@supacloud/compiler": "^0.68.0",
44835
- "@supacloud/db": "0.28.0",
45238
+ "@supacloud/compiler": "^0.70.0",
45239
+ "@supacloud/db": "0.29.0",
44836
45240
  "deepmerge-ts": "8.0.2",
44837
45241
  prisma: "6.19.3"
44838
45242
  },
44839
45243
  devDependencies: {
44840
45244
  "@supabase/supabase-js": "2.118.0",
44841
- "@supacloud/elysia": "0.44.0",
45245
+ "@supacloud/elysia": "0.45.0",
44842
45246
  "@types/bun": "^1.4.5",
44843
45247
  effect: "4.0.5",
44844
45248
  elysia: "2.0.0-rc.6",
@@ -13,3 +13,8 @@ export declare function featureScaffold(name: string, className: string, governa
13
13
  };
14
14
  databaseImportPath?: string;
15
15
  }): Record<string, string>;
16
+ /**
17
+ * Generates an executable `@supacloud/testing` multi-role RLS matrix & Durable
18
+ * Command contract verification test template alongside a feature slice.
19
+ */
20
+ export declare function featureTestingScaffold(name: string, className: string, table: string): Record<string, string>;
@@ -1,4 +1,5 @@
1
1
  import type { ApplicationDeployRequest } from "@supacloud/delivery";
2
+ import { type MultiLangTarget } from "@supacloud/compiler";
2
3
  import { type ToolServer } from "../tool-server";
3
4
  import { type AppManifest } from "./app-tool-export";
4
5
  declare const REMOTE_APP_ACTIONS: {
@@ -40,7 +41,25 @@ export interface AppToolOptions {
40
41
  onDevProgress?: (result: ToolResult) => void;
41
42
  }
42
43
  export interface AppToolArguments {
43
- action: "init" | "generate" | "infer" | "dev" | "watch" | "verify-plan" | "verify" | "compile" | "check" | "graph" | "explain" | "export-tools" | "context" | "lens" | "doctor" | "fix" | "plan" | "build" | "release" | "promote" | keyof typeof REMOTE_APP_ACTIONS;
44
+ action: "init" | "generate" | "infer" | "dev" | "watch" | "verify-plan" | "verify" | "compile" | "check" | "graph" | "explain" | "export-tools" | "context" | "lens" | "doctor" | "fix" | "upgrade" | "client-sdk" | "contract-diff" | "sql-prepare" | "plan" | "build" | "release" | "promote" | keyof typeof REMOTE_APP_ACTIONS;
45
+ lang?: MultiLangTarget;
46
+ catalog?: string;
47
+ openapi?: string;
48
+ baseline_openapi?: string;
49
+ current_openapi?: string;
50
+ baseline_asyncapi?: string;
51
+ current_asyncapi?: string;
52
+ baseline_catalog?: string;
53
+ current_catalog?: string;
54
+ baseline_graphql?: string;
55
+ current_graphql?: string;
56
+ baseline_rls?: string;
57
+ current_rls?: string;
58
+ cache_path?: string;
59
+ offline?: boolean;
60
+ schema_hash?: string;
61
+ package_name?: string;
62
+ with_tests?: boolean;
44
63
  ref?: string;
45
64
  id?: string;
46
65
  environment_id?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/cli",
3
- "version": "0.130.0",
3
+ "version": "0.132.0",
4
4
  "description": "Project-scoped CLI for SupaCloud users",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -52,23 +52,23 @@
52
52
  "directory": "packages/cli"
53
53
  },
54
54
  "dependencies": {
55
- "@supacloud/compiler": "^0.68.0",
55
+ "@supacloud/compiler": "^0.70.0",
56
56
  "@supacloud/delivery": "0.30.1",
57
- "@supacloud/db": "0.28.0",
57
+ "@supacloud/db": "0.29.0",
58
58
  "typebox": "1.4.3"
59
59
  },
60
60
  "overrides": {
61
61
  "@supacloud/contracts": "0.17.0",
62
62
  "@supacloud/delivery": "0.30.1",
63
63
  "@graphql-tools/utils": "^12.0.4",
64
- "@supacloud/compiler": "^0.68.0",
65
- "@supacloud/db": "0.28.0",
64
+ "@supacloud/compiler": "^0.70.0",
65
+ "@supacloud/db": "0.29.0",
66
66
  "deepmerge-ts": "8.0.2",
67
67
  "prisma": "6.19.3"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@supabase/supabase-js": "2.118.0",
71
- "@supacloud/elysia": "0.44.0",
71
+ "@supacloud/elysia": "0.45.0",
72
72
  "@types/bun": "^1.4.5",
73
73
  "effect": "4.0.5",
74
74
  "elysia": "2.0.0-rc.6",