@supacloud/cli 0.121.9 → 0.123.2

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
@@ -9058,6 +9058,42 @@ function parseEnvFile(contents) {
9058
9058
  }
9059
9059
  return values;
9060
9060
  }
9061
+ function projectConfigValues(cwd, environment) {
9062
+ const path = resolve2(cwd, "supacloud.json");
9063
+ if (!existsSync(path))
9064
+ return {};
9065
+ try {
9066
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
9067
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
9068
+ return {};
9069
+ const root = parsed;
9070
+ const context = root.context;
9071
+ if (!context || typeof context !== "object" || Array.isArray(context))
9072
+ return {};
9073
+ const contextRecord = context;
9074
+ const environments = contextRecord.environments;
9075
+ if (!environments || typeof environments !== "object" || Array.isArray(environments))
9076
+ return {};
9077
+ const selected = environments[environment];
9078
+ if (!selected || typeof selected !== "object" || Array.isArray(selected))
9079
+ return {};
9080
+ const values = selected;
9081
+ const output = {};
9082
+ const mappings = {
9083
+ api_url: "SUPACLOUD_API_URL",
9084
+ project_ref: "SUPACLOUD_PROJECT_REF",
9085
+ application_id: "SUPACLOUD_APPLICATION_ID",
9086
+ environment_id: "SUPACLOUD_APPLICATION_ENVIRONMENT_ID"
9087
+ };
9088
+ for (const [source, target] of Object.entries(mappings)) {
9089
+ if (typeof values[source] === "string" && values[source].trim())
9090
+ output[target] = values[source].trim();
9091
+ }
9092
+ return output;
9093
+ } catch {
9094
+ return {};
9095
+ }
9096
+ }
9061
9097
  function readEnvFile(path, required) {
9062
9098
  if (!existsSync(path)) {
9063
9099
  if (required)
@@ -9095,6 +9131,26 @@ function inferProjectRefFromSupabaseUrl(value) {
9095
9131
  return "";
9096
9132
  return new URL(value).hostname.match(/^([a-z0-9-]+)\.api\./i)?.[1] ?? "";
9097
9133
  }
9134
+ function inferManagementApiUrlFromSupabaseUrl(value, projectRef = "") {
9135
+ if (!value)
9136
+ return "";
9137
+ const url = new URL(value);
9138
+ const host = url.hostname;
9139
+ if (host.startsWith("api.")) {
9140
+ url.hostname = `studio.${host.slice("api.".length)}`;
9141
+ return url.origin;
9142
+ }
9143
+ const ref = projectRef.trim();
9144
+ if (ref && host.startsWith(`${ref}.api.`)) {
9145
+ url.hostname = `studio-${ref}.${host.slice(`${ref}.api.`.length)}`;
9146
+ return url.origin;
9147
+ }
9148
+ const managedHost = host.match(/^([a-z0-9-]+)\.api\.(.+)$/i);
9149
+ if (!managedHost)
9150
+ return "";
9151
+ url.hostname = `studio-${managedHost[1]}.${managedHost[2]}`;
9152
+ return url.origin;
9153
+ }
9098
9154
  function sourceCredentialScope(values, explicitApiUrl, supabaseUrl) {
9099
9155
  const hasManagementContext = Boolean(explicitApiUrl.trim() || values.SUPACLOUD_API_TOKEN?.trim() || values.SUPACLOUD_HOST?.trim());
9100
9156
  if (hasManagementContext)
@@ -9106,7 +9162,7 @@ function sourceProjectCore(values) {
9106
9162
  const projectRef = (values.SUPACLOUD_PROJECT_REF || "").trim() || inferProjectRefFromSupabaseUrl(supabaseUrl);
9107
9163
  const explicitApiUrl = values.SUPACLOUD_API_URL || "";
9108
9164
  const credentialScope = sourceCredentialScope(values, explicitApiUrl, supabaseUrl);
9109
- const managementUrl = explicitApiUrl || (values.SUPACLOUD_HOST ? `http://${values.SUPACLOUD_HOST}:9090` : "");
9165
+ const managementUrl = explicitApiUrl || (credentialScope === "management" ? inferManagementApiUrlFromSupabaseUrl(supabaseUrl, projectRef) : "") || (values.SUPACLOUD_HOST ? `http://${values.SUPACLOUD_HOST}:9090` : "");
9110
9166
  const apiUrl = credentialScope === "management" ? canonicalApiOrigin(managementUrl) : "";
9111
9167
  const apiToken = credentialScope === "management" ? values.SUPACLOUD_API_TOKEN || "" : "";
9112
9168
  return { apiUrl, apiToken, projectRef, supabaseUrl, credentialScope };
@@ -9158,17 +9214,31 @@ function explicitEnvironmentSource(cwd, envFile) {
9158
9214
  function contextSource(env, cwd, selection) {
9159
9215
  if (selection.environmentName && selection.envFile)
9160
9216
  throw new Error("Environment selectors are mutually exclusive");
9161
- if (selection.environmentName)
9162
- return namedEnvironmentSource(cwd, selection.environmentName);
9163
- if (selection.envFile)
9164
- return explicitEnvironmentSource(cwd, selection.envFile);
9217
+ if (selection.environmentName) {
9218
+ const source = namedEnvironmentSource(cwd, selection.environmentName);
9219
+ return {
9220
+ ...source,
9221
+ values: { ...projectConfigValues(cwd, source.environment), ...source.values }
9222
+ };
9223
+ }
9224
+ if (selection.envFile) {
9225
+ const source = explicitEnvironmentSource(cwd, selection.envFile);
9226
+ return {
9227
+ ...source,
9228
+ values: { ...projectConfigValues(cwd, source.environment), ...source.values }
9229
+ };
9230
+ }
9165
9231
  if (env.SUPACLOUD_ENV) {
9166
9232
  const environment = normalizeEnvironmentName(env.SUPACLOUD_ENV);
9167
- const values = processValues(env);
9233
+ const values = { ...projectConfigValues(cwd, environment), ...processValues(env) };
9168
9234
  if (completeProjectContext(values)) {
9169
9235
  return { values, kind: "process_env", path: null, environment };
9170
9236
  }
9171
- return namedEnvironmentSource(cwd, env.SUPACLOUD_ENV);
9237
+ const source = namedEnvironmentSource(cwd, env.SUPACLOUD_ENV);
9238
+ return {
9239
+ ...source,
9240
+ values: { ...projectConfigValues(cwd, source.environment), ...source.values }
9241
+ };
9172
9242
  }
9173
9243
  if (hasProcessContext(env)) {
9174
9244
  return { values: processValues(env), kind: "process_env", path: null, environment: "" };
@@ -9176,6 +9246,14 @@ function contextSource(env, cwd, selection) {
9176
9246
  const path = resolve2(cwd, ".env");
9177
9247
  const values = readEnvFile(path, false);
9178
9248
  const environment = values.SUPACLOUD_ENV ? normalizeEnvironmentName(values.SUPACLOUD_ENV) : "";
9249
+ if (environment) {
9250
+ return {
9251
+ values: { ...projectConfigValues(cwd, environment), ...values },
9252
+ kind: "legacy_dotenv",
9253
+ path: existsSync(path) ? path : null,
9254
+ environment
9255
+ };
9256
+ }
9179
9257
  return { values, kind: Object.keys(values).length ? "legacy_dotenv" : "none", path: existsSync(path) ? path : null, environment };
9180
9258
  }
9181
9259
  function resolveSupaCloudContext(env = process.env, cwd = process.cwd(), selection = {}) {
@@ -9267,10 +9345,16 @@ function parseGlobalOptions(args) {
9267
9345
 
9268
9346
  // src/shared/execution-policy.ts
9269
9347
  var ACTION_POLICY = {
9348
+ config: {
9349
+ read: ["doctor", "explain"]
9350
+ },
9351
+ pipeline: {
9352
+ local: ["connect"]
9353
+ },
9270
9354
  deploy: { local: ["init"], write: ["deploy"] },
9271
9355
  applications: {
9272
9356
  read: ["list_releases", "get_release", "get_runtime", "get_deployment_evidence", "get_configuration", "get_release_transfer_plan", "get_promotion_plan", "get_promotion_status", "get_rollback_snapshot", "get_history", "get_deploy_plan", "logs", "get_preview_plan", "list_previews", "get_preview"],
9273
- write: ["upload_release", "put_configuration", "deploy_application", "transfer_release", "promote_application", "reconcile_promotion", "create_preview", "reconcile_preview", "cleanup_preview", "activate_release", "deploy_release", "rollback_release", "reconcile_activation", "retire_activation"]
9357
+ write: ["upload_release", "put_configuration", "deploy_application", "transfer_release", "promote_application", "reconcile_promotion", "create_preview", "reconcile_preview", "cleanup_preview", "preview_pull_request", "activate_release", "deploy_release", "rollback_release", "reconcile_activation", "retire_activation"]
9274
9358
  },
9275
9359
  project: {
9276
9360
  read: ["get", "endpoints", "health", "logs", "api_keys", "settings", "tasks", "task_detail", "task_stats", "dlq", "background_settings"],
@@ -9366,11 +9450,11 @@ var ACTION_POLICY = {
9366
9450
  ai: { local: ["show_skill", "install_skill"] },
9367
9451
  mcp: { local: ["config"] },
9368
9452
  init: { local: ["init"] },
9369
- env: { local: ["list", "check"] },
9453
+ env: { local: ["list", "check", "sync"] },
9370
9454
  app: {
9371
9455
  local: ["init", "generate", "dev", "watch", "verify-plan", "compile", "check", "graph", "explain", "export-tools", "context", "lens", "doctor", "fix", "plan", "build"],
9372
9456
  read: ["status", "evidence", "logs", "transfer-plan", "promote-plan", "rollback-plan", "history", "deploy-plan", "diff", "promote-status", "preview-plan", "previews", "preview-list", "preview-status"],
9373
- write: ["release", "upload", "configure", "transfer", "promote", "promote-reconcile", "deploy", "rollback", "reconcile", "retire", "preview", "preview-create", "preview-reconcile", "preview-cleanup"]
9457
+ write: ["release", "upload", "configure", "transfer", "promote", "promote-reconcile", "deploy", "rollback", "reconcile", "retire", "preview", "preview-create", "preview-reconcile", "preview-cleanup", "preview-pr"]
9374
9458
  },
9375
9459
  db: {
9376
9460
  local: ["context", "lint", "explain", "diff", "role_sql"],
@@ -15857,7 +15941,7 @@ function scaffoldFiles(framework, slug) {
15857
15941
  "package.json": JSON.stringify({
15858
15942
  private: true,
15859
15943
  type: "module",
15860
- dependencies: { elysia: "2.0.0-rc.3" }
15944
+ dependencies: { elysia: "2.0.0-rc.4" }
15861
15945
  }, null, 2) + `
15862
15946
  `,
15863
15947
  "index.ts": `import { Elysia } from "elysia";
@@ -18436,7 +18520,8 @@ var APPLICATION_PREVIEW_ACTIONS = [
18436
18520
  "list_previews",
18437
18521
  "get_preview",
18438
18522
  "reconcile_preview",
18439
- "cleanup_preview"
18523
+ "cleanup_preview",
18524
+ "preview_pull_request"
18440
18525
  ];
18441
18526
  var previewIdSchema = String2({ pattern: "^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$" });
18442
18527
  var branchRefSchema = String2({ pattern: "^[a-z0-9-]{1,20}$" });
@@ -18453,7 +18538,10 @@ var APPLICATION_PREVIEW_FIELDS = {
18453
18538
  data_mode: optional(stringEnum2(["schema_only", "full_clone"]), "[get_preview_plan/create_preview] Default schema_only; full_clone copies rows"),
18454
18539
  ttl_seconds: optional(ttlSecondsSchema, "[get_preview_plan/create_preview] Lifetime from 300 to 604800 seconds; creation defaults to the platform TTL"),
18455
18540
  wait: optional(Boolean2(), "[create_preview/get_preview] Wait for verified readiness of this preview only"),
18456
- timeout_seconds: optional(waitSecondsSchema, "[create_preview/get_preview] Observation budget with wait, from 1 to 3600 seconds (default 300)")
18541
+ timeout_seconds: optional(waitSecondsSchema, "[create_preview/get_preview] Observation budget with wait, from 1 to 3600 seconds (default 300)"),
18542
+ pull_request_action: optional(stringEnum2(["opened", "closed"]), "[preview_pull_request] Pull request lifecycle action"),
18543
+ repository: optional(String2({ pattern: "^[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}$" }), "[preview_pull_request] Repository owner/name"),
18544
+ pull_request_number: optional(Integer({ minimum: 1, maximum: 1e9 }), "[preview_pull_request] Pull request number")
18457
18545
  };
18458
18546
  var strict = { additionalProperties: false };
18459
18547
  var phase2 = stringEnum2(["pending", "ready", "failed", "cleaned"]);
@@ -18518,7 +18606,8 @@ var actionFields = {
18518
18606
  list_previews: [],
18519
18607
  get_preview: ["preview_id", "wait", "timeout_seconds"],
18520
18608
  reconcile_preview: ["preview_id"],
18521
- cleanup_preview: ["preview_id"]
18609
+ cleanup_preview: ["preview_id"],
18610
+ preview_pull_request: ["pull_request_action", "repository", "pull_request_number", "release_id"]
18522
18611
  };
18523
18612
  function timestamp4(value) {
18524
18613
  return Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
@@ -18663,6 +18752,34 @@ async function applicationPreviewAction(http, args, project) {
18663
18752
  const identity = { project_ref: ref, application_id: id, environment_id: environment };
18664
18753
  const applicationPath = `/v1/projects/${project}/applications/${encodeURIComponent(id)}`;
18665
18754
  const path = `${applicationPath}/environments/${encodeURIComponent(environment)}`;
18755
+ if (action === "preview_pull_request") {
18756
+ const lifecycle = required5(args, "pull_request_action");
18757
+ const repository = required5(args, "repository");
18758
+ const releaseId = required5(args, "release_id");
18759
+ const number = args["pull_request_number"];
18760
+ if (!Check2(ApplicationReleaseIdSchema2, releaseId) || !/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/.test(repository) || (typeof number !== "number" || !Number.isSafeInteger(number) || number < 1 || number > 1e9)) {
18761
+ throw new Error("Invalid pull request preview identity");
18762
+ }
18763
+ const result = await http.post(`${path}/preview-pull-requests`, {
18764
+ action: lifecycle,
18765
+ repository,
18766
+ number,
18767
+ release_id: releaseId
18768
+ }, { timeoutMs: 120000, maxJsonBytes: 1048576, responseTimeoutMs: 30000 });
18769
+ const payload = result.data && typeof result.data === "object" && !Array.isArray(result.data) ? result.data : null;
18770
+ if (!result.ok || !payload || payload["action"] !== lifecycle || typeof payload["preview_id"] !== "string" || typeof payload["status"] !== "string" || !Array.isArray(payload["leftovers"])) {
18771
+ return releaseControlFailure(operation, result.ok ? "INVALID_RESPONSE" : "HTTP_ERROR", result.transportError ? null : result.status, identity);
18772
+ }
18773
+ const preview = payload["receipt"] === null || payload["receipt"] === undefined ? null : receipt(payload["receipt"], { ref, id, environment, previewId: payload["preview_id"] });
18774
+ return releaseControlSuccess(operation, {
18775
+ ...identity,
18776
+ action: lifecycle,
18777
+ preview_id: payload["preview_id"],
18778
+ status: payload["status"],
18779
+ leftovers: payload["leftovers"].filter((value) => typeof value === "string").slice(0, 64),
18780
+ receipt: preview
18781
+ });
18782
+ }
18666
18783
  const previewId = action === "get_preview" || action === "reconcile_preview" || action === "cleanup_preview" ? required5(args, "preview_id") : action === "create_preview" ? typeof args["preview_id"] === "string" ? required5(args, "preview_id") : randomUUID() : action === "get_preview_plan" && typeof args["preview_id"] === "string" ? required5(args, "preview_id") : undefined;
18667
18784
  const mutation = action === "create_preview" || action === "reconcile_preview" || action === "cleanup_preview";
18668
18785
  const requestBudget = startedAt === undefined ? 120000 : Math.min(120000, timeoutSeconds * 1000);
@@ -22234,9 +22351,9 @@ function registerMcpTools(server, context) {
22234
22351
  }
22235
22352
 
22236
22353
  // src/shared/tools/app-tools.ts
22237
- import { existsSync as existsSync11, readFileSync as readFileSync9 } from "node:fs";
22238
- import { mkdir as mkdir5, readFile as readFile4, readdir as readdir5, writeFile as writeFile4 } from "node:fs/promises";
22239
- import { basename as basename7, dirname as dirname9, join as join13, relative as relative7, resolve as resolve18 } from "node:path";
22354
+ import { existsSync as existsSync12, readFileSync as readFileSync9 } from "node:fs";
22355
+ import { mkdir as mkdir6, readFile as readFile5, readdir as readdir5, writeFile as writeFile5 } from "node:fs/promises";
22356
+ import { basename as basename7, dirname as dirname9, join as join14, relative as relative7, resolve as resolve19 } from "node:path";
22240
22357
  import {
22241
22358
  applyDiagnosticFix,
22242
22359
  buildDeliveryProject,
@@ -22381,16 +22498,16 @@ var starter_metadata_default = {
22381
22498
  generatedBy: "supacloud/starter-metadata-v1",
22382
22499
  packages: {
22383
22500
  compiler: {
22384
- version: "0.62.6"
22501
+ version: "0.62.7"
22385
22502
  },
22386
22503
  app: {
22387
- version: "0.39.3",
22504
+ version: "0.39.4",
22388
22505
  dependencies: {
22389
22506
  rxjs: "7.8.2"
22390
22507
  }
22391
22508
  },
22392
22509
  elysia: {
22393
- version: "0.42.4"
22510
+ version: "0.42.5"
22394
22511
  },
22395
22512
  commands: {
22396
22513
  version: "0.12.0"
@@ -22399,15 +22516,15 @@ var starter_metadata_default = {
22399
22516
  version: "0.16.2"
22400
22517
  },
22401
22518
  db: {
22402
- version: "0.24.2",
22519
+ version: "0.25.1",
22403
22520
  dependencies: {},
22404
22521
  devDependencies: {},
22405
22522
  peerDependencies: {
22406
- "@supacloud/db-zenstack": "^0.1.0 || ^0.2.0"
22523
+ "@supacloud/db-zenstack": "^0.1.0 || ^0.2.0 || ^0.3.0"
22407
22524
  }
22408
22525
  },
22409
22526
  dbZenstack: {
22410
- version: "0.2.2",
22527
+ version: "0.3.1",
22411
22528
  dependencies: {
22412
22529
  "@zenstackhq/orm": "3.10.0",
22413
22530
  "@zenstackhq/schema": "3.10.0",
@@ -22415,15 +22532,16 @@ var starter_metadata_default = {
22415
22532
  "@zenstackhq/language": "3.10.0",
22416
22533
  "@zenstackhq/sdk": "3.10.0",
22417
22534
  kysely: "0.29.0"
22418
- },
22419
- devDependencies: {
22420
- "@zenstackhq/cli": "3.10.0",
22421
- prisma: "6.19.3",
22422
- pg: "8.23.1"
22535
+ }
22536
+ },
22537
+ modelTooling: {
22538
+ version: "0.1.1",
22539
+ dependencies: {
22540
+ "@supacloud/db-zenstack": "^0.3.0"
22423
22541
  }
22424
22542
  },
22425
22543
  sdk: {
22426
- version: "0.48.3",
22544
+ version: "0.48.4",
22427
22545
  peerDependencies: {
22428
22546
  "@supabase/supabase-js": "^2.118.0"
22429
22547
  }
@@ -22851,7 +22969,7 @@ function baseTemplateFiles(name, sdkDependencies) {
22851
22969
  "@supacloud/app": `^${appMetadata.version}`,
22852
22970
  "@supacloud/elysia": `^${elysiaMetadata.version}`,
22853
22971
  effect: "4.0.5",
22854
- elysia: "2.0.0-rc.3",
22972
+ elysia: "2.0.0-rc.4",
22855
22973
  ...sdkDependencies
22856
22974
  },
22857
22975
  devDependencies: {
@@ -23595,7 +23713,7 @@ GRANT SELECT, INSERT, UPDATE ON supacloud_commands.execution_receipts TO model_o
23595
23713
  GRANT SELECT, INSERT ON supacloud_commands.execution_audit TO model_orders_app;
23596
23714
  `;
23597
23715
  function modelCommandTemplateFiles(name, sdk) {
23598
- const { app, compiler, elysia, commands, contracts, db, dbZenstack } = starter_metadata_default.packages;
23716
+ const { app, compiler, elysia, commands, contracts, db, dbZenstack, modelTooling } = starter_metadata_default.packages;
23599
23717
  const files = baseTemplateFiles(name, sdk);
23600
23718
  delete files["scripts/dev.ts"];
23601
23719
  delete files["scripts/serve.ts"];
@@ -23618,7 +23736,9 @@ function modelCommandTemplateFiles(name, sdk) {
23618
23736
  scripts: {
23619
23737
  "db:generate": "supacloud-model generate && supacloud-db generate",
23620
23738
  "db:check": "supacloud-model check && supacloud-db check",
23621
- "db:diff": "supacloud-model diff",
23739
+ "db:diff": "supacloud db plan --dir migrations",
23740
+ "db:plan": "supacloud db plan --dir migrations",
23741
+ "db:apply": "supacloud db apply --dir migrations",
23622
23742
  "db:pull": "supacloud-model pull",
23623
23743
  compile: "supacloud-compiler compile",
23624
23744
  "check:generated": "supacloud-compiler check",
@@ -23639,10 +23759,10 @@ function modelCommandTemplateFiles(name, sdk) {
23639
23759
  ...dbZenstack.dependencies,
23640
23760
  typebox: "1.4.3",
23641
23761
  effect: "4.0.5",
23642
- elysia: "2.0.0-rc.3",
23762
+ elysia: "2.0.0-rc.4",
23643
23763
  ...sdk
23644
23764
  },
23645
- devDependencies: { "@supacloud/compiler": "^" + compiler.version, ...db.devDependencies, ...dbZenstack.devDependencies, "@types/bun": "^1.4.4", typescript: "7.1.0-beta" }
23765
+ devDependencies: { "@supacloud/compiler": "^" + compiler.version, "@supacloud/model-tooling": "^" + modelTooling.version, "@types/bun": "^1.4.4", typescript: "7.1.0-beta" }
23646
23766
  }),
23647
23767
  "supacloud.config.ts": `import { defineSupacloudConfig } from "@supacloud/compiler";
23648
23768
  export default defineSupacloudConfig({
@@ -23739,7 +23859,7 @@ The receipt migration uses the same supacloud_commands ledger as the platform. I
23739
23859
 
23740
23860
  The model_orders_app role is a trusted-server capability and does not set request.jwt.claims. Its SQL policy is a host bypass, not the model row projection; do not grant that role to PostgREST. Authenticated SELECT, INSERT and UPDATE policies are emitted from the ZModel @@allow rules and must stay in the migration. They do not grant privileges; add a reviewed GRANT before exposing the table through PostgREST.
23741
23861
 
23742
- To change the schema: bun run db:generate, bun run db:check, then bun run db:diff -- --candidate output/database-audit/change.sql against an explicit shadow database. Review forward SQL before promotion. Stop intake and drain HTTP/worker work before host.dispose(), then close the caller-owned pool.
23862
+ To change the schema: bun run db:generate, bun run db:check, then bun run db:plan. Review the Management API's remote plan and run bun run db:apply -- --approved_digest <digest> after approval. The CLI does not receive a database URL. Stop intake and drain HTTP/worker work before host.dispose(), then close the caller-owned pool.
23743
23863
  `
23744
23864
  };
23745
23865
  }
@@ -25019,20 +25139,24 @@ SQL, not the authenticated row-policy projection. Command writes still use the s
25019
25139
  transaction, receipt and audit boundary, not unrestricted CRUD. SQL constraints, RPCs
25020
25140
  and RLS remain explicit reviewed migrations when the model language cannot express them.
25021
25141
 
25022
- Use \`bun run db:diff -- --candidate output/database-audit/change.sql\` with an
25023
- explicit read-only SUPACLOUD_MODEL_DATABASE_URL. Review the SQL, then promote a new
25024
- forward migration through the existing SupaCloud plan/apply ledger. Never run
25025
- zen migrate deploy or db push against a managed production database.
25026
- \`bun run db:pull -- --candidate output/database-audit/schema.zmodel\` writes a
25027
- review candidate only; it never overwrites the maintained model. Add policies
25028
- before adopting introspection output. Keep one migration history and preserve RLS.
25142
+ Use \`bun run db:plan\` to send the reviewed migration directory to the
25143
+ Management API for a remote, read-only plan. Review the returned digest, then run
25144
+ \`bun run db:apply -- --approved_digest <digest>\` to apply the exact same bytes
25145
+ through the project migration ledger. Neither command needs DATABASE_URL or a
25146
+ public PostgreSQL port. Never run zen migrate deploy or db push against a managed
25147
+ production database.
25148
+ \`bun run db:pull -- --candidate output/database-audit/schema.zmodel\` uses the
25149
+ same Management API binding and writes a review candidate only; it never
25150
+ overwrites the maintained model. Add policies before adopting introspection
25151
+ output. Keep one migration history and preserve RLS.
25029
25152
 
25030
25153
  Adopting a database that has no model yet starts with the same command: pull
25031
- introspects through a temporary datasource-only model, so no hand-written ZModel
25032
- is required. Review the candidate, add the policy plugin and @@allow rules, move
25033
- it to zenstack/schema.zmodel, then run \`bun run db:generate\`. Until that file
25034
- exists, \`db:diff\` and \`db:generate\` fail closed instead of building from an
25035
- unreviewed introspection result. Keep the host wiring unchanged: one
25154
+ introspects through a temporary datasource-only model inside the Management API,
25155
+ so no hand-written ZModel is required. Review the candidate, add the policy
25156
+ plugin and @@allow rules, move it to zenstack/schema.zmodel, then run
25157
+ \`bun run db:generate\`. Until that file exists, \`db:plan\` and
25158
+ \`db:generate\` fail closed instead of building from an unreviewed
25159
+ introspection result. Keep the host wiring unchanged: one
25036
25160
  createZenStackDatabase composition root supplies read-only models and the
25037
25161
  transactional command store.
25038
25162
  `;
@@ -26362,7 +26486,7 @@ export async function createReviewTaskAdapters(options: ReviewTaskOptions): Prom
26362
26486
  `;
26363
26487
 
26364
26488
  // src/shared/tools/app-starter.ts
26365
- var { compiler: compilerMetadata2, app: appMetadata2, elysia: elysiaMetadata2, commands: commandsMetadata, contracts: contractsMetadata, db: dbMetadata, dbZenstack: dbZenstackMetadata, sdk: sdkMetadata } = starter_metadata_default.packages;
26489
+ var { compiler: compilerMetadata2, app: appMetadata2, elysia: elysiaMetadata2, commands: commandsMetadata, contracts: contractsMetadata, db: dbMetadata, dbZenstack: dbZenstackMetadata, modelTooling: modelToolingMetadata, sdk: sdkMetadata } = starter_metadata_default.packages;
26366
26490
  var json3 = (value) => `${JSON.stringify(value, null, 2)}
26367
26491
  `;
26368
26492
  function appStarterFiles(name) {
@@ -26386,7 +26510,9 @@ function appStarterFiles(name) {
26386
26510
  "db:generate": "supacloud-model generate && supacloud-db generate",
26387
26511
  "db:check": "supacloud-model check && supacloud-db check",
26388
26512
  "db:assess": "supacloud-db assess",
26389
- "db:diff": "supacloud-model diff",
26513
+ "db:diff": "supacloud db plan --dir migrations",
26514
+ "db:plan": "supacloud db plan --dir migrations",
26515
+ "db:apply": "supacloud db apply --dir migrations",
26390
26516
  "db:pull": "supacloud-model pull",
26391
26517
  check: "bun run db:check && bun run compile && bun run check:generated && bun run typecheck && bun run test",
26392
26518
  test: "bun run compile && bun --no-env-file scripts/environment.ts test bun test",
@@ -26410,13 +26536,12 @@ function appStarterFiles(name) {
26410
26536
  "@supacloud/js": `^${sdkMetadata.version}`,
26411
26537
  "@supabase/supabase-js": sdkMetadata.peerDependencies["@supabase/supabase-js"],
26412
26538
  effect: "4.0.5",
26413
- elysia: "2.0.0-rc.3",
26539
+ elysia: "2.0.0-rc.4",
26414
26540
  rxjs: appMetadata2.dependencies.rxjs
26415
26541
  },
26416
26542
  devDependencies: {
26417
26543
  "@supacloud/compiler": `^${compilerMetadata2.version}`,
26418
- ...dbMetadata.devDependencies,
26419
- ...dbZenstackMetadata.devDependencies,
26544
+ "@supacloud/model-tooling": `^${modelToolingMetadata.version}`,
26420
26545
  "@types/bun": "^1.4.4",
26421
26546
  typescript: "7.1.0-beta"
26422
26547
  }
@@ -29046,6 +29171,137 @@ async function applyScaffoldWrites(plan) {
29046
29171
  }
29047
29172
  }
29048
29173
 
29174
+ // src/shared/tools/configuration-tools.ts
29175
+ import { existsSync as existsSync11 } from "node:fs";
29176
+ import { mkdir as mkdir5, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
29177
+ import { join as join13, resolve as resolve18 } from "node:path";
29178
+ var onboardToolSchema = {
29179
+ root: optional(String2(), "Repository or configuration root (default: current directory)"),
29180
+ profile: optional(stringEnum2(["solo", "podman", "pigsty", "cluster"]), "Deployment profile (default: solo)"),
29181
+ domain: optional(String2(), "Public API domain; studio domain is derived from it"),
29182
+ database: optional(stringEnum2(["local", "external"]), "Database provider (default: local)"),
29183
+ storage: optional(stringEnum2(["juicefs", "external"]), "Storage provider (default: juicefs)"),
29184
+ write: optional(Boolean2(), "Write the generated context into supacloud.json"),
29185
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
29186
+ };
29187
+ var configurationToolSchema = {
29188
+ action: withDescription(stringEnum2(["doctor", "explain"]), "Configuration inspection action"),
29189
+ root: optional(String2(), "Repository or configuration root (default: current directory)"),
29190
+ key: optional(String2(), "[explain] Environment variable name"),
29191
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
29192
+ };
29193
+ var environmentSyncSchema = {
29194
+ action: withDescription(stringEnum2(["list", "check", "sync"]), "Environment profile action"),
29195
+ root: optional(String2(), "Project directory containing .env.supacloud.* files"),
29196
+ environment: optional(String2(), "[sync] Profile name; defaults to the selected environment"),
29197
+ write: optional(Boolean2(), "[sync] Persist derived context and the reduced profile example"),
29198
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
29199
+ };
29200
+ var SECRET_KEY = /(?:PASSWORD|PASS|SECRET|TOKEN|PRIVATE|CREDENTIAL|AUTHORIZATION|COOKIE|SESSION|DATABASE_URL|CONNECTION_STRING|DSN)/i;
29201
+ var PLATFORM_KEY = /^(?:SUPACLOUD|SUPABASE)_(?:API|PROJECT|ENV|HOST|SSH|APPLICATION|SERVICE_ROLE|ACCESS|URL|READ_ONLY|TLS|ANON|PUBLISHABLE)/;
29202
+ function textResult(text, isError = false) {
29203
+ return { isError, content: [{ type: "text", text }] };
29204
+ }
29205
+ function jsonResult(value, isError = false) {
29206
+ return textResult(JSON.stringify(value, null, 2), isError);
29207
+ }
29208
+ function record5(value) {
29209
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
29210
+ }
29211
+ function unquote(value) {
29212
+ const trimmed = value.trim();
29213
+ if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
29214
+ return trimmed.slice(1, -1);
29215
+ }
29216
+ return trimmed;
29217
+ }
29218
+ function parseEnvironment(content) {
29219
+ const values = {};
29220
+ for (const rawLine of content.split(/\r?\n/)) {
29221
+ const line = rawLine.trim();
29222
+ if (!line || line.startsWith("#"))
29223
+ continue;
29224
+ const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
29225
+ if (match)
29226
+ values[match[1]] = unquote(match[2]);
29227
+ }
29228
+ return values;
29229
+ }
29230
+ async function readJsonObject(path) {
29231
+ if (!existsSync11(path))
29232
+ return {};
29233
+ const parsed = JSON.parse(await readFile4(path, "utf8"));
29234
+ const value = record5(parsed);
29235
+ if (!value)
29236
+ throw new Error(`${path} must contain a JSON object`);
29237
+ return value;
29238
+ }
29239
+ async function writeJsonObject(path, value) {
29240
+ await writeFile4(path, `${JSON.stringify(value, null, 2)}
29241
+ `, { encoding: "utf8", mode: 420 });
29242
+ }
29243
+ function contextFromConfig(config) {
29244
+ const context = record5(config.context);
29245
+ return context ?? {};
29246
+ }
29247
+ function environmentContext(config, environment) {
29248
+ const context = contextFromConfig(config);
29249
+ const environments = record5(context.environments);
29250
+ const selected = environments ? record5(environments[environment]) : null;
29251
+ return selected ?? {};
29252
+ }
29253
+ async function syncEnvironmentProfile(args, options) {
29254
+ const root = resolve18(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
29255
+ const environment = typeof args.environment === "string" && args.environment.trim() ? args.environment.trim() : options.activeContext?.environment;
29256
+ if (!environment)
29257
+ throw new Error("env sync requires --env <name> or SUPACLOUD_ENV");
29258
+ const profilePath = join13(root, `.env.supacloud.${environment}`);
29259
+ if (!existsSync11(profilePath))
29260
+ throw new Error(`Environment profile not found: ${profilePath}`);
29261
+ const values = parseEnvironment(await readFile4(profilePath, "utf8"));
29262
+ const configPath = join13(root, "supacloud.json");
29263
+ const config = await readJsonObject(configPath);
29264
+ const context = contextFromConfig(config);
29265
+ const environments = record5(context.environments) ?? {};
29266
+ const publicValues = Object.fromEntries(Object.entries(values).filter(([name]) => !SECRET_KEY.test(name) && !PLATFORM_KEY.test(name)));
29267
+ const secretNames = Object.keys(values).filter((name) => SECRET_KEY.test(name));
29268
+ const nextEnvironment = {
29269
+ api_url: values.SUPACLOUD_API_URL ?? null,
29270
+ project_ref: values.SUPACLOUD_PROJECT_REF ?? null,
29271
+ application_id: values.SUPACLOUD_APPLICATION_ID ?? null,
29272
+ environment_id: values.SUPACLOUD_APPLICATION_ENVIRONMENT_ID ?? environment,
29273
+ public: publicValues,
29274
+ secret_names: secretNames
29275
+ };
29276
+ const result = {
29277
+ schema: "supacloud.environment-sync.v1",
29278
+ environment,
29279
+ profile: profilePath,
29280
+ config: configPath,
29281
+ diff: { changed: nextEnvironment, secret_values_written: false },
29282
+ next: ["Secret values are never copied into supacloud.json", `supacloud --env ${environment} status`]
29283
+ };
29284
+ if (args.write !== true)
29285
+ return jsonResult({ ...result, written: false });
29286
+ config.context = { ...context, environments: { ...environments, [environment]: nextEnvironment } };
29287
+ await writeJsonObject(configPath, config);
29288
+ const reducedExample = [`SUPACLOUD_ENV=${environment}`, "SUPACLOUD_API_TOKEN=<inject-at-runtime>", ""].join(`
29289
+ `);
29290
+ await writeFile4(`${profilePath}.example`, reducedExample, { encoding: "utf8", mode: 384 });
29291
+ return jsonResult({ ...result, written: true, reduced_profile_example: `${profilePath}.example` });
29292
+ }
29293
+ async function readSecretGap(root, environment) {
29294
+ if (!environment)
29295
+ return { environment, required: [], present: [], missing: [] };
29296
+ const config = await readJsonObject(join13(root, "supacloud.json"));
29297
+ const metadata = environmentContext(config, environment);
29298
+ const required = Array.isArray(metadata.secret_names) ? metadata.secret_names.filter((value) => typeof value === "string" && /^[A-Z_][A-Z0-9_]*$/.test(value)).sort() : [];
29299
+ const profilePath = join13(root, `.env.supacloud.${environment}`);
29300
+ const values = existsSync11(profilePath) ? parseEnvironment(await readFile4(profilePath, "utf8")) : {};
29301
+ const present = required.filter((name) => values[name] !== undefined && values[name] !== "" && !/^<[^>]+>$/.test(values[name]));
29302
+ return { environment, required, present, missing: required.filter((name) => !present.includes(name)) };
29303
+ }
29304
+
29049
29305
  // src/shared/tools/app-tools.ts
29050
29306
  var REMOTE_APP_ACTIONS = {
29051
29307
  upload: "upload_release",
@@ -29058,6 +29314,7 @@ var REMOTE_APP_ACTIONS = {
29058
29314
  "preview-create": "create_preview",
29059
29315
  "preview-status": "get_preview",
29060
29316
  "preview-cleanup": "cleanup_preview",
29317
+ "preview-pr": "preview_pull_request",
29061
29318
  transfer: "transfer_release",
29062
29319
  configure: "put_configuration",
29063
29320
  deploy: "deploy_release",
@@ -29126,7 +29383,7 @@ async function initProject(args) {
29126
29383
  ];
29127
29384
  const note = template === "client" ? "Data-plane client only (@supabase/supabase-js). The forced default is app init (minimal compiler/Effect stack)." : template === "model-command" ? "Requires an explicitly selected database, reviewed migrations and trusted HTTP/worker identity authority; see README.md." : "Local demo only. Production requires persistent governance and identity adapters; see README.md.";
29128
29385
  if (args.format === "json")
29129
- return textResult(JSON.stringify({
29386
+ return textResult2(JSON.stringify({
29130
29387
  version: 1,
29131
29388
  ok: true,
29132
29389
  root,
@@ -29136,7 +29393,7 @@ async function initProject(args) {
29136
29393
  next,
29137
29394
  note
29138
29395
  }, null, 2));
29139
- return textResult([
29396
+ return textResult2([
29140
29397
  `Initialized ${name} in ${root} (${files.length} files, template: ${template}).`,
29141
29398
  `cd '${root.replaceAll("'", "'\\''")}'`,
29142
29399
  ...next,
@@ -29144,7 +29401,7 @@ async function initProject(args) {
29144
29401
  ].join(`
29145
29402
  `));
29146
29403
  }
29147
- function textResult(text, isError = false) {
29404
+ function textResult2(text, isError = false) {
29148
29405
  return { isError, content: [{ type: "text", text }] };
29149
29406
  }
29150
29407
  function pascalName(name) {
@@ -29259,7 +29516,7 @@ async function generateScaffold(args) {
29259
29516
  throw new ScaffoldError("SCAFFOLD_OPTION_INVALID", `--${flag.replaceAll("_", "-")} must be boolean`);
29260
29517
  }
29261
29518
  }
29262
- const root = resolve18(args.root || process.cwd());
29519
+ const root = resolve19(args.root || process.cwd());
29263
29520
  const dir = args.dir ?? "src/features";
29264
29521
  if (dir !== ".")
29265
29522
  scaffoldPath(root, dir);
@@ -29288,7 +29545,7 @@ async function generateScaffold(args) {
29288
29545
  let contractName;
29289
29546
  if (kind === "module" || kind === "resource" || kind === "feature") {
29290
29547
  const name = requireIdentifier(args.name, "name");
29291
- modulePath = join13(dir, name, kind === "feature" ? `${name}.feature.ts` : `${name}.module.ts`).replaceAll("\\", "/");
29548
+ modulePath = join14(dir, name, kind === "feature" ? `${name}.feature.ts` : `${name}.module.ts`).replaceAll("\\", "/");
29292
29549
  moduleSymbol = kind === "feature" ? `${pascalName(name)}Feature` : `${pascalName(name)}Module`;
29293
29550
  if (kind === "module")
29294
29551
  writes.push({ path: modulePath, content: moduleScaffold(name), overwrite: args.force === true });
@@ -29296,18 +29553,18 @@ async function generateScaffold(args) {
29296
29553
  for (const [file, content] of Object.entries(kind === "feature" ? featureScaffold(name, pascalName(name), {
29297
29554
  ...featureGovernance,
29298
29555
  databaseImportPath: (() => {
29299
- const source = relative7(join13(root, dir, name), join13(root, featureGovernance.database.source)).replaceAll("\\", "/").replace(/\.(?:[cm]?tsx?|mts|cts)$/, "");
29556
+ const source = relative7(join14(root, dir, name), join14(root, featureGovernance.database.source)).replaceAll("\\", "/").replace(/\.(?:[cm]?tsx?|mts|cts)$/, "");
29300
29557
  return source.startsWith(".") ? source : `./${source}`;
29301
29558
  })()
29302
29559
  }) : resourceScaffold(name, pascalName(name)))) {
29303
- writes.push({ path: join13(dir, name, file).replaceAll("\\", "/"), content });
29560
+ writes.push({ path: join14(dir, name, file).replaceAll("\\", "/"), content });
29304
29561
  }
29305
29562
  } else {
29306
29563
  const moduleName = requireIdentifier(args.module, "module");
29307
29564
  const name = kind === "controller" ? moduleName : requireIdentifier(args.name, "name");
29308
29565
  const subdir = kind === "command" ? "commands" : kind === "query" ? "queries" : kind === "job" ? "jobs" : kind === "contract" ? "contracts" : "";
29309
- const path = join13(dir, moduleName, subdir, `${name}.${kind}.ts`).replaceAll("\\", "/");
29310
- if (kind === "controller" && existsSync11(scaffoldPath(root, path))) {
29566
+ const path = join14(dir, moduleName, subdir, `${name}.${kind}.ts`).replaceAll("\\", "/");
29567
+ if (kind === "controller" && existsSync12(scaffoldPath(root, path))) {
29311
29568
  throw new ScaffoldError("SCAFFOLD_EXISTS", `Controller already exists: ${path}(请手工合并路由到现有 controller)`);
29312
29569
  }
29313
29570
  const content = kind === "command" ? commandScaffold(moduleName, name) : kind === "query" ? queryScaffold(moduleName, name) : kind === "job" ? jobScaffold(moduleName, name) : kind === "contract" ? contractScaffold(moduleName, name) : controllerScaffold(moduleName);
@@ -29325,7 +29582,7 @@ async function generateScaffold(args) {
29325
29582
  if (new RegExp(`\\b${moduleSymbol}\\b`).test(original)) {
29326
29583
  throw new ScaffoldError("SCAFFOLD_REGISTRATION_CONFLICT", `Registration target already references ${moduleSymbol}; review the import manually`);
29327
29584
  }
29328
- let importPath = relative7(dirname9(target), resolve18(root, modulePath)).replaceAll("\\", "/").replace(/\.ts$/, "");
29585
+ let importPath = relative7(dirname9(target), resolve19(root, modulePath)).replaceAll("\\", "/").replace(/\.ts$/, "");
29329
29586
  if (!importPath.startsWith("."))
29330
29587
  importPath = `./${importPath}`;
29331
29588
  const edit = await applyDiagnosticFix({
@@ -29335,7 +29592,7 @@ async function generateScaffold(args) {
29335
29592
  importPath,
29336
29593
  symbol: moduleSymbol
29337
29594
  }, { rootDir: root, dryRun: true });
29338
- if (await readFile4(target, "utf8") !== original)
29595
+ if (await readFile5(target, "utf8") !== original)
29339
29596
  throw new ScaffoldError("SCAFFOLD_CHANGED", "Registration source changed during planning");
29340
29597
  writes.push({ path: args.register_in, content: edit.content, expected: original });
29341
29598
  }
@@ -29348,7 +29605,7 @@ async function generateScaffold(args) {
29348
29605
  ...args.dry_run ? { content: write.content } : {}
29349
29606
  }));
29350
29607
  if (args.format === "json")
29351
- return textResult(JSON.stringify({
29608
+ return textResult2(JSON.stringify({
29352
29609
  version: 1,
29353
29610
  ok: true,
29354
29611
  kind,
@@ -29356,7 +29613,7 @@ async function generateScaffold(args) {
29356
29613
  written: !args.dry_run,
29357
29614
  changes
29358
29615
  }, null, 2));
29359
- const lines = changes.map((change) => `${args.dry_run ? "PREVIEW" : "✅"} ${change.action}: ${join13(plan.root, change.path)}`);
29616
+ const lines = changes.map((change) => `${args.dry_run ? "PREVIEW" : "✅"} ${change.action}: ${join14(plan.root, change.path)}`);
29360
29617
  if (args.dry_run)
29361
29618
  lines.push("No files written. Omit --dry-run to apply this generation.");
29362
29619
  if (kind === "resource")
@@ -29367,7 +29624,7 @@ async function generateScaffold(args) {
29367
29624
  const prefix = pascalName(contractName);
29368
29625
  lines.push("", "Next, bind the contract to a route so the compiler can check route/schema drift:", ` import { ${prefix}Body, ${prefix}Response } from "./contracts/${contractName}.contract";`, ` @Post("/", { body: ${prefix}Body, responses: { 200: ${prefix}Response } })`, "Fill in the schema fields and reuse them in command decoders; never widen them to unknown.");
29369
29626
  }
29370
- return textResult(lines.join(`
29627
+ return textResult2(lines.join(`
29371
29628
  `));
29372
29629
  }
29373
29630
  function formatDiagnostic(diagnostic) {
@@ -29394,17 +29651,17 @@ function parseInclude(include) {
29394
29651
  return patterns && patterns.length > 0 ? patterns : undefined;
29395
29652
  }
29396
29653
  function sourceRoot(args, root, configured) {
29397
- const hasConfig = ["ts", "mts", "js", "mjs"].some((extension) => existsSync11(join13(root, `supacloud.config.${extension}`)));
29654
+ const hasConfig = ["ts", "mts", "js", "mjs"].some((extension) => existsSync12(join14(root, `supacloud.config.${extension}`)));
29398
29655
  return args.root && !hasConfig ? "." : configured;
29399
29656
  }
29400
29657
  async function projectCompileConfig(args) {
29401
- const root = resolve18(args.root || process.cwd());
29402
- const configFile = ["ts", "mts", "js", "mjs"].map((extension) => join13(root, `supacloud.config.${extension}`)).find((candidate) => existsSync11(candidate)) ?? null;
29658
+ const root = resolve19(args.root || process.cwd());
29659
+ const configFile = ["ts", "mts", "js", "mjs"].map((extension) => join14(root, `supacloud.config.${extension}`)).find((candidate) => existsSync12(candidate)) ?? null;
29403
29660
  const loadedConfig = await loadSupacloudConfig(root);
29404
29661
  const defaults = resolveSupacloudConfig(loadedConfig, root);
29405
29662
  const configuredRoot = sourceRoot(args, root, loadedConfig.root);
29406
29663
  const include = parseInclude(args.include) ?? loadedConfig.include;
29407
- const outDir = args.out_dir ? resolve18(root, args.out_dir) : defaults.outDir;
29664
+ const outDir = args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir;
29408
29665
  const compileOptions = compileOptionsFromConfig({
29409
29666
  ...loadedConfig,
29410
29667
  ...configuredRoot === undefined ? {} : { root: configuredRoot },
@@ -29416,12 +29673,12 @@ async function projectCompileConfig(args) {
29416
29673
  return { root, sourceDir: compileOptions.rootDir, configFile, outDir, result };
29417
29674
  }
29418
29675
  async function readAllowedDependencies(root) {
29419
- const path = join13(root, "package.json");
29420
- if (!existsSync11(path)) {
29676
+ const path = join14(root, "package.json");
29677
+ if (!existsSync12(path)) {
29421
29678
  return { dependencies: [], devDependencies: [], optionalDependencies: [], peerDependencies: [] };
29422
29679
  }
29423
29680
  try {
29424
- const parsed = JSON.parse(await readFile4(path, "utf8"));
29681
+ const parsed = JSON.parse(await readFile5(path, "utf8"));
29425
29682
  return {
29426
29683
  dependencies: Object.keys(parsed.dependencies ?? {}).sort(),
29427
29684
  devDependencies: Object.keys(parsed.devDependencies ?? {}).sort(),
@@ -29455,7 +29712,7 @@ async function runContext(args) {
29455
29712
  const subject = args.target?.trim();
29456
29713
  if (subject) {
29457
29714
  const pack = createContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject);
29458
- const execution = args.events === undefined ? undefined : createExecutionContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject, await readExecutionMetadata(resolve18(root, args.events)), args.request_id);
29715
+ const execution = args.events === undefined ? undefined : createExecutionContextPack({ ...result.graph, diagnostics: result.diagnostics }, subject, await readExecutionMetadata(resolve19(root, args.events)), args.request_id);
29459
29716
  const verification = await createVerificationPlan(root, result.graph, pack.subject, sourceDir);
29460
29717
  const repairs = createDiagnosticRepairPlan(pack.diagnostics);
29461
29718
  const workflow = {
@@ -29486,7 +29743,7 @@ async function runContext(args) {
29486
29743
  },
29487
29744
  executed: false
29488
29745
  };
29489
- return textResult(args.format === "json" ? JSON.stringify({ ...pack, ...execution ? { execution } : {}, workflow }, null, 2) : [
29746
+ return textResult2(args.format === "json" ? JSON.stringify({ ...pack, ...execution ? { execution } : {}, workflow }, null, 2) : [
29490
29747
  formatModuleContextPack(pack),
29491
29748
  ` edit files (project-relative): ${workflow.editFiles.join(", ") || "-"}`,
29492
29749
  ` focused tests: ${verification.tests.join(", ") || "-"}`,
@@ -29535,8 +29792,8 @@ async function runContext(args) {
29535
29792
  }
29536
29793
  };
29537
29794
  if (args.format === "json")
29538
- return textResult(JSON.stringify(project, null, 2));
29539
- return textResult([
29795
+ return textResult2(JSON.stringify(project, null, 2));
29796
+ return textResult2([
29540
29797
  `CONTEXT ${root}`,
29541
29798
  ` config: ${configFile ?? "(none)"}`,
29542
29799
  ` generated: ${outDir}`,
@@ -29569,13 +29826,13 @@ async function runLens(args) {
29569
29826
  diagnostics: result.diagnostics
29570
29827
  };
29571
29828
  if (args.format === "json")
29572
- return textResult(JSON.stringify(output, null, 2), lens.conflicts.some((conflict) => conflict.severity === "error"));
29829
+ return textResult2(JSON.stringify(output, null, 2), lens.conflicts.some((conflict) => conflict.severity === "error"));
29573
29830
  const lines = [`LENS ${context?.subject ?? "application"}`, ` semantic hash: ${lens.snapshot.semanticHash}`, ` source hash: ${lens.snapshot.sourceHash}`];
29574
29831
  for (const item of lens.nodes)
29575
29832
  lines.push(` ${item.kind} ${item.id} ${item.hash}`);
29576
29833
  for (const conflict of lens.conflicts)
29577
29834
  lines.push(` ${conflict.severity.toUpperCase()} ${conflict.code}: ${conflict.message}`);
29578
- return textResult(lines.join(`
29835
+ return textResult2(lines.join(`
29579
29836
  `), lens.conflicts.some((conflict) => conflict.severity === "error"));
29580
29837
  }
29581
29838
  function doctorFixPlan(doctor) {
@@ -29597,7 +29854,7 @@ async function findUnwiredContracts(rootDir) {
29597
29854
  for (const entry of entries) {
29598
29855
  if (skip.has(entry.name))
29599
29856
  continue;
29600
- const path = join13(directory, entry.name);
29857
+ const path = join14(directory, entry.name);
29601
29858
  if (entry.isDirectory())
29602
29859
  await walk(path);
29603
29860
  else if (entry.isFile() && entry.name.endsWith(".ts"))
@@ -29608,10 +29865,10 @@ async function findUnwiredContracts(rootDir) {
29608
29865
  const contracts = files.filter((file) => file.endsWith(".contract.ts"));
29609
29866
  if (contracts.length === 0)
29610
29867
  return [];
29611
- const otherSources = await Promise.all(files.filter((file) => !contracts.includes(file)).map(async (file) => await readFile4(file, "utf8").catch(() => "")));
29868
+ const otherSources = await Promise.all(files.filter((file) => !contracts.includes(file)).map(async (file) => await readFile5(file, "utf8").catch(() => "")));
29612
29869
  const unwired = [];
29613
29870
  for (const contract of contracts) {
29614
- const source = await readFile4(contract, "utf8").catch(() => "");
29871
+ const source = await readFile5(contract, "utf8").catch(() => "");
29615
29872
  const symbols = [...source.matchAll(/export\s+const\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)].map((match) => match[1]);
29616
29873
  if (symbols.length === 0)
29617
29874
  continue;
@@ -29627,6 +29884,15 @@ async function runDoctor(args) {
29627
29884
  const target = args.target?.trim();
29628
29885
  const context = target ? createContextPack({ ...result.graph, diagnostics: result.diagnostics }, target) : undefined;
29629
29886
  const doctor = doctorProject(root, outDir, { ...result.graph, ...context ? { modules: context.modules } : {}, diagnostics: [] }, result.upToDate, context?.diagnostics ?? result.diagnostics);
29887
+ const secretGap = await readSecretGap(root, process.env.SUPACLOUD_ENV?.trim() ?? "");
29888
+ if (secretGap.missing.length > 0) {
29889
+ doctor.errors += 1;
29890
+ doctor.diagnostics = [...doctor.diagnostics ?? [], {
29891
+ severity: "error",
29892
+ code: "SUPACLOUD_SECRET_MISSING",
29893
+ message: `Missing environment secrets: ${secretGap.missing.join(", ")}`
29894
+ }];
29895
+ }
29630
29896
  const database = context ? null : checkAppDatabaseSources(root);
29631
29897
  if (database) {
29632
29898
  doctor.checks.push(database);
@@ -29651,7 +29917,7 @@ async function runDoctor(args) {
29651
29917
  generatedArtifactCheck: "project-wide"
29652
29918
  } : undefined;
29653
29919
  if (args.format === "json") {
29654
- return textResult(JSON.stringify({
29920
+ return textResult2(JSON.stringify({
29655
29921
  ok: doctor.errors === 0,
29656
29922
  next,
29657
29923
  autoFixable,
@@ -29659,11 +29925,15 @@ async function runDoctor(args) {
29659
29925
  manualFixes,
29660
29926
  fixPlan,
29661
29927
  unwiredContracts,
29928
+ secretGap,
29662
29929
  ...scope ? { scope } : {},
29663
29930
  ...doctor
29664
29931
  }, null, 2), doctor.errors > 0);
29665
29932
  }
29666
29933
  const lines = doctor.checks.map((check) => formatDoctorCheck(check));
29934
+ if (secretGap.required.length > 0) {
29935
+ lines.push(`Environment secrets (${secretGap.environment}): ${secretGap.missing.length === 0 ? "ready" : `missing ${secretGap.missing.join(", ")}`}`);
29936
+ }
29667
29937
  if (scope)
29668
29938
  lines.unshift(`TARGET ${scope.target}; omitted project diagnostics=${scope.omittedProjectDiagnostics}; generated drift remains project-wide`);
29669
29939
  for (const diagnostic of doctor.diagnostics ?? []) {
@@ -29683,11 +29953,11 @@ async function runDoctor(args) {
29683
29953
  if (unwiredContracts.length > 0) {
29684
29954
  lines.push(`${unwiredContracts.length} unwired contract file(s): ${unwiredContracts.map((contract) => contract.file).join(", ")}. Import their schemas into a controller route or remove them.`);
29685
29955
  }
29686
- return textResult(lines.join(`
29956
+ return textResult2(lines.join(`
29687
29957
  `), doctor.errors > 0);
29688
29958
  }
29689
29959
  async function runFix(args) {
29690
- const root = resolve18(args.root || process.cwd());
29960
+ const root = resolve19(args.root || process.cwd());
29691
29961
  const fixPath = args.fix?.trim();
29692
29962
  const doctorPath = args.from_doctor?.trim();
29693
29963
  if (fixPath && doctorPath)
@@ -29702,7 +29972,7 @@ async function runFix(args) {
29702
29972
  if (!Number.isSafeInteger(rawIndex) || rawIndex === undefined || rawIndex < 0) {
29703
29973
  throw new Error("app fix --from-doctor requires a non-negative --fix-index <n>");
29704
29974
  }
29705
- const doctor = JSON.parse(await readFile4(resolve18(root, doctorPath), "utf8"));
29975
+ const doctor = JSON.parse(await readFile5(resolve19(root, doctorPath), "utf8"));
29706
29976
  if (!doctor || typeof doctor !== "object" || !Array.isArray(doctor.fixPlan)) {
29707
29977
  throw new Error("Invalid doctor output: expected a fixPlan array");
29708
29978
  }
@@ -29721,11 +29991,11 @@ async function runFix(args) {
29721
29991
  parsed = repairEntry.fix;
29722
29992
  source = "doctor";
29723
29993
  } else {
29724
- parsed = JSON.parse(await readFile4(resolve18(root, fixPath), "utf8"));
29994
+ parsed = JSON.parse(await readFile5(resolve19(root, fixPath), "utf8"));
29725
29995
  }
29726
29996
  const write = args.write === true;
29727
29997
  const applied = await applyDiagnosticFix(parsed, { rootDir: root, dryRun: !write });
29728
- return textResult(JSON.stringify({
29998
+ return textResult2(JSON.stringify({
29729
29999
  ok: true,
29730
30000
  source,
29731
30001
  ...source === "doctor" ? {
@@ -29770,7 +30040,7 @@ function devDatabase(profile, explicit) {
29770
30040
  }
29771
30041
  function readManifestModules(outDir) {
29772
30042
  try {
29773
- const parsed = JSON.parse(readFileSync9(join13(outDir, "app.manifest.json"), "utf8"));
30043
+ const parsed = JSON.parse(readFileSync9(join14(outDir, "app.manifest.json"), "utf8"));
29774
30044
  return Array.isArray(parsed.modules) ? parsed.modules.map((module) => module.name) : [];
29775
30045
  } catch {
29776
30046
  return [];
@@ -29804,21 +30074,21 @@ async function runAppDev(args, options) {
29804
30074
  profile: args.profile,
29805
30075
  databaseUrl: args.database_url,
29806
30076
  signal: options.signal,
29807
- onOutput: (text) => options.onDevProgress?.(textResult(args.format === "json" ? JSON.stringify({ version: 1, source: "application", output: text }) : text))
30077
+ onOutput: (text) => options.onDevProgress?.(textResult2(args.format === "json" ? JSON.stringify({ version: 1, source: "application", output: text }) : text))
29808
30078
  });
29809
- return textResult(JSON.stringify({ version: 1, ok: result.exitCode === 0, ...result }), result.exitCode !== 0);
30079
+ return textResult2(JSON.stringify({ version: 1, ok: result.exitCode === 0, ...result }), result.exitCode !== 0);
29810
30080
  }
29811
30081
  const profile = args.profile ?? "fast";
29812
30082
  if (profile !== "fast" && profile !== "integration") {
29813
30083
  throw new ScaffoldError("SCAFFOLD_OPTION_INVALID", "app dev --profile must be fast or integration");
29814
30084
  }
29815
30085
  const database = devDatabase(profile, args.database_url);
29816
- const root = resolve18(args.root || process.cwd());
30086
+ const root = resolve19(args.root || process.cwd());
29817
30087
  const loadedConfig = await loadSupacloudConfig(root);
29818
30088
  const defaults = resolveSupacloudConfig(loadedConfig, root);
29819
30089
  const configuredRoot = sourceRoot(args, root, loadedConfig.root);
29820
30090
  const include = parseInclude(args.include) ?? loadedConfig.include;
29821
- const outDir = args.out_dir ? resolve18(root, args.out_dir) : defaults.outDir;
30091
+ const outDir = args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir;
29822
30092
  const watch = args.once !== true && args.watch !== false;
29823
30093
  const compileOptions = compileOptionsFromConfig({
29824
30094
  ...loadedConfig,
@@ -29833,7 +30103,7 @@ async function runAppDev(args, options) {
29833
30103
  const artifacts = hasError ? "not-current" : "current";
29834
30104
  const notVerified = DEV_NOT_VERIFIED[profile];
29835
30105
  if (args.format === "json") {
29836
- return textResult(JSON.stringify({
30106
+ return textResult2(JSON.stringify({
29837
30107
  version: 1,
29838
30108
  ok: !hasError,
29839
30109
  profile,
@@ -29849,7 +30119,7 @@ async function runAppDev(args, options) {
29849
30119
  notVerified
29850
30120
  }, null, progress ? undefined : 2), hasError);
29851
30121
  }
29852
- return textResult([
30122
+ return textResult2([
29853
30123
  `app watch (compile-only, profile: ${profile}, watch: ${watch ? "on" : "off"}, state: ${state})`,
29854
30124
  ` root: ${root}`,
29855
30125
  ` outDir: ${outDir}`,
@@ -29904,7 +30174,7 @@ async function runAppDev(args, options) {
29904
30174
  return report(lastEvent, "stopped");
29905
30175
  }
29906
30176
  async function runCompile(args) {
29907
- const root = resolve18(args.root || process.cwd());
30177
+ const root = resolve19(args.root || process.cwd());
29908
30178
  const loadedConfig = await loadSupacloudConfig(root);
29909
30179
  const defaults = resolveSupacloudConfig(loadedConfig, root);
29910
30180
  const configuredRoot = sourceRoot(args, root, loadedConfig.root);
@@ -29913,7 +30183,7 @@ async function runCompile(args) {
29913
30183
  ...compileOptionsFromConfig({
29914
30184
  ...loadedConfig,
29915
30185
  ...configuredRoot === undefined ? {} : { root: configuredRoot },
29916
- outDir: args.out_dir ? resolve18(root, args.out_dir) : defaults.outDir,
30186
+ outDir: args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir,
29917
30187
  ...include === undefined ? {} : { include },
29918
30188
  strict: args.strict ?? loadedConfig.strict ?? false
29919
30189
  }, root),
@@ -29921,7 +30191,7 @@ async function runCompile(args) {
29921
30191
  });
29922
30192
  const hasError = result.diagnostics.some((diagnostic) => diagnostic.severity === "error");
29923
30193
  if (args.format === "json")
29924
- return textResult(JSON.stringify({
30194
+ return textResult2(JSON.stringify({
29925
30195
  version: 1,
29926
30196
  ok: !hasError,
29927
30197
  diagnostics: result.diagnostics,
@@ -29934,10 +30204,10 @@ async function runCompile(args) {
29934
30204
  ...result.written.map((path) => ` ${path}`)
29935
30205
  ].join(`
29936
30206
  `);
29937
- return textResult(text, hasError);
30207
+ return textResult2(text, hasError);
29938
30208
  }
29939
30209
  async function runCheck(args) {
29940
- const root = resolve18(args.root || process.cwd());
30210
+ const root = resolve19(args.root || process.cwd());
29941
30211
  const database = checkAppDatabaseSources(root);
29942
30212
  const loadedConfig = await loadSupacloudConfig(root);
29943
30213
  const defaults = resolveSupacloudConfig(loadedConfig, root);
@@ -29946,7 +30216,7 @@ async function runCheck(args) {
29946
30216
  const config = compileOptionsFromConfig({
29947
30217
  ...loadedConfig,
29948
30218
  ...configuredRoot === undefined ? {} : { root: configuredRoot },
29949
- outDir: args.out_dir ? resolve18(root, args.out_dir) : defaults.outDir,
30219
+ outDir: args.out_dir ? resolve19(root, args.out_dir) : defaults.outDir,
29950
30220
  ...include === undefined ? {} : { include },
29951
30221
  strict: args.strict ?? loadedConfig.strict ?? false
29952
30222
  }, root);
@@ -29955,7 +30225,7 @@ async function runCheck(args) {
29955
30225
  const hasError = diagnosticError || result.mismatches.length > 0 || database?.ok === false;
29956
30226
  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>"];
29957
30227
  if (args.format === "json")
29958
- return textResult(JSON.stringify({
30228
+ return textResult2(JSON.stringify({
29959
30229
  version: 1,
29960
30230
  ok: !hasError,
29961
30231
  next,
@@ -29968,7 +30238,7 @@ async function runCheck(args) {
29968
30238
  ...database ? { database } : {}
29969
30239
  }, null, 2), hasError);
29970
30240
  const summary = `checked ${result.graph.modules.length} module(s), no files written`;
29971
- return textResult([
30241
+ return textResult2([
29972
30242
  formatDiagnostics(result.diagnostics),
29973
30243
  ...result.mismatches.map((path) => `generated artifact mismatch: ${path}`),
29974
30244
  ...database ? [formatDoctorCheck(database)] : [],
@@ -29979,12 +30249,12 @@ async function runCheck(args) {
29979
30249
  }
29980
30250
  async function readManifest(root, args) {
29981
30251
  const config = await loadSupacloudConfig(root);
29982
- const outDir = args.out_dir ? resolve18(root, args.out_dir) : resolveSupacloudConfig(config, root).outDir;
29983
- const manifestPath = join13(outDir, "app.manifest.json");
29984
- if (!existsSync11(manifestPath)) {
30252
+ const outDir = args.out_dir ? resolve19(root, args.out_dir) : resolveSupacloudConfig(config, root).outDir;
30253
+ const manifestPath = join14(outDir, "app.manifest.json");
30254
+ if (!existsSync12(manifestPath)) {
29985
30255
  throw new Error(`Manifest not found: ${manifestPath}(先运行 app compile 生成)`);
29986
30256
  }
29987
- const parsed = JSON.parse(await readFile4(manifestPath, "utf8"));
30257
+ const parsed = JSON.parse(await readFile5(manifestPath, "utf8"));
29988
30258
  if (!Array.isArray(parsed.modules)) {
29989
30259
  throw new Error(`Invalid manifest: ${manifestPath}`);
29990
30260
  }
@@ -30024,11 +30294,11 @@ function formatGraphText(manifest) {
30024
30294
  `);
30025
30295
  }
30026
30296
  async function runGraph(args) {
30027
- const root = resolve18(args.root || process.cwd());
30297
+ const root = resolve19(args.root || process.cwd());
30028
30298
  const manifest = await readManifest(root, args);
30029
30299
  if (args.format === "json")
30030
- return textResult(JSON.stringify(manifest, null, 2));
30031
- return textResult(formatGraphText(manifest));
30300
+ return textResult2(JSON.stringify(manifest, null, 2));
30301
+ return textResult2(formatGraphText(manifest));
30032
30302
  }
30033
30303
  function reverseDependencies(manifest, token) {
30034
30304
  const dependents = [];
@@ -30092,7 +30362,7 @@ async function runExplain(args) {
30092
30362
  const target = args.target?.trim();
30093
30363
  if (!target)
30094
30364
  throw new Error("app explain requires --target(provider 类名 / token 名 / command 名 / job 名)");
30095
- const root = resolve18(args.root || process.cwd());
30365
+ const root = resolve19(args.root || process.cwd());
30096
30366
  const manifest = await readManifest(root, args);
30097
30367
  for (const module of manifest.modules) {
30098
30368
  const job = module.jobs?.find((entry) => entry.name === target || entry.className === target);
@@ -30114,15 +30384,15 @@ async function runExplain(args) {
30114
30384
  lines.push(`idempotency: ${job.idempotency}`);
30115
30385
  const dependents = reverseDependencies(manifest, job.className);
30116
30386
  lines.push(`被依赖: ${dependents.length > 0 ? dependents.join(", ") : "(none)"}`);
30117
- return textResult(lines.join(`
30387
+ return textResult2(lines.join(`
30118
30388
  `));
30119
30389
  }
30120
30390
  const providerIndex = module.providers.findIndex((provider) => provider.token === target || provider.useClass === target);
30121
30391
  if (providerIndex >= 0)
30122
- return textResult(explainProvider(manifest, module, providerIndex));
30392
+ return textResult2(explainProvider(manifest, module, providerIndex));
30123
30393
  const controllerIndex = module.controllers.findIndex((controller) => controller.className === target);
30124
30394
  if (controllerIndex >= 0)
30125
- return textResult(explainController(manifest, module, controllerIndex));
30395
+ return textResult2(explainController(manifest, module, controllerIndex));
30126
30396
  const command = module.commands.find((entry) => entry.name === target || entry.className === target);
30127
30397
  if (command) {
30128
30398
  const lines = [
@@ -30141,12 +30411,12 @@ async function runExplain(args) {
30141
30411
  lines.push(`idempotency: ${command.idempotency}`);
30142
30412
  const dependents = reverseDependencies(manifest, command.className);
30143
30413
  lines.push(`被依赖: ${dependents.length > 0 ? dependents.join(", ") : "(none)"}`);
30144
- return textResult(lines.join(`
30414
+ return textResult2(lines.join(`
30145
30415
  `));
30146
30416
  }
30147
30417
  const query = module.queries.find((entry) => entry.name === target || entry.className === target);
30148
30418
  if (query) {
30149
- return textResult([
30419
+ return textResult2([
30150
30420
  `对象: ${query.name}`,
30151
30421
  "类型: query",
30152
30422
  `所属模块: ${module.name}`,
@@ -30157,28 +30427,28 @@ async function runExplain(args) {
30157
30427
  }
30158
30428
  if (manifest.externalTokens.includes(target)) {
30159
30429
  const dependents = reverseDependencies(manifest, target);
30160
- return textResult([
30430
+ return textResult2([
30161
30431
  `对象: ${target}`,
30162
30432
  "类型: externalToken(平台注入,无模块提供)",
30163
30433
  `被依赖: ${dependents.length > 0 ? dependents.join(", ") : "(none)"}`
30164
30434
  ].join(`
30165
30435
  `));
30166
30436
  }
30167
- return textResult(`未找到对象: ${target}`, true);
30437
+ return textResult2(`未找到对象: ${target}`, true);
30168
30438
  }
30169
30439
  async function runExportTools(args) {
30170
- const root = resolve18(args.root || process.cwd());
30440
+ const root = resolve19(args.root || process.cwd());
30171
30441
  const manifest = await readManifest(root, { ...args, out_dir: undefined });
30172
30442
  const definitions = buildToolDefinitions(manifest);
30173
- const outDir = resolve18(args.out_dir || join13(root, "generated"));
30443
+ const outDir = resolve19(args.out_dir || join14(root, "generated"));
30174
30444
  if (args.format === "json") {
30175
- return textResult(JSON.stringify(definitions, null, 2));
30445
+ return textResult2(JSON.stringify(definitions, null, 2));
30176
30446
  }
30177
- await mkdir5(outDir, { recursive: true });
30178
- const openaiPath = join13(outDir, "tool-definitions.openai.json");
30179
- const mcpPath = join13(outDir, "tool-definitions.mcp.json");
30180
- await writeFile4(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
30181
- await writeFile4(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
30447
+ await mkdir6(outDir, { recursive: true });
30448
+ const openaiPath = join14(outDir, "tool-definitions.openai.json");
30449
+ const mcpPath = join14(outDir, "tool-definitions.mcp.json");
30450
+ await writeFile5(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
30451
+ await writeFile5(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
30182
30452
  const summary = [
30183
30453
  `exported ${definitions.openai.length} tool(s):`,
30184
30454
  ` openai → ${openaiPath}`,
@@ -30188,29 +30458,29 @@ async function runExportTools(args) {
30188
30458
  `)
30189
30459
  ].join(`
30190
30460
  `);
30191
- return textResult(summary);
30461
+ return textResult2(summary);
30192
30462
  }
30193
30463
  async function runDelivery(args) {
30194
- const root = resolve18(args.root || process.cwd());
30464
+ const root = resolve19(args.root || process.cwd());
30195
30465
  if (args.action === "build") {
30196
30466
  const database = checkAppDatabaseSources(root);
30197
30467
  if (database && !database.ok) {
30198
- return textResult(JSON.stringify({ ok: false, database, written: [] }, null, 2), true);
30468
+ return textResult2(JSON.stringify({ ok: false, database, written: [] }, null, 2), true);
30199
30469
  }
30200
30470
  }
30201
30471
  const loaded = await loadSupacloudConfig(root);
30202
30472
  const options = compileOptionsFromConfig({
30203
30473
  ...loaded,
30204
- ...args.out_dir === undefined ? {} : { outDir: resolve18(root, args.out_dir) },
30474
+ ...args.out_dir === undefined ? {} : { outDir: resolve19(root, args.out_dir) },
30205
30475
  ...args.include === undefined ? {} : { include: parseInclude(args.include) },
30206
30476
  ...args.strict === undefined ? {} : { strict: args.strict }
30207
30477
  }, root);
30208
30478
  if (args.action === "plan") {
30209
30479
  const result = await planDeliveryProject(options, loaded.delivery);
30210
- return textResult(args.format === "json" ? JSON.stringify(result, null, 2) : formatDeliveryPlan(result), !result.ok);
30480
+ return textResult2(args.format === "json" ? JSON.stringify(result, null, 2) : formatDeliveryPlan(result), !result.ok);
30211
30481
  }
30212
30482
  const result = await buildDeliveryProject(options, loaded.delivery);
30213
- return textResult(JSON.stringify(result, null, 2), !result.ok);
30483
+ return textResult2(JSON.stringify(result, null, 2), !result.ok);
30214
30484
  }
30215
30485
  function resultObject(result) {
30216
30486
  try {
@@ -30250,7 +30520,7 @@ function releasePhaseFailure(phase, result, completed) {
30250
30520
  if (phaseResult?.expected_activation_id !== undefined) {
30251
30521
  payload.expected_activation_id = phaseResult.expected_activation_id;
30252
30522
  }
30253
- return textResult(JSON.stringify(payload, null, 2), true);
30523
+ return textResult2(JSON.stringify(payload, null, 2), true);
30254
30524
  }
30255
30525
  function releaseField(payload, container, field) {
30256
30526
  const value = payload?.[container];
@@ -30278,7 +30548,7 @@ async function runAppRelease(request, options, delegate) {
30278
30548
  if (request.activation_id !== undefined || request.expected_activation_id !== undefined) {
30279
30549
  throw new Error("app release generates one activation identity; use app deploy for an exact retry");
30280
30550
  }
30281
- const root = resolve18(request.root || process.cwd());
30551
+ const root = resolve19(request.root || process.cwd());
30282
30552
  const completed = {};
30283
30553
  let manifestPath;
30284
30554
  let buildReceipt;
@@ -30286,7 +30556,7 @@ async function runAppRelease(request, options, delegate) {
30286
30556
  if (request.manifest_path === undefined) {
30287
30557
  throw new Error("app release --skip_build requires --manifest_path");
30288
30558
  }
30289
- manifestPath = resolve18(root, request.manifest_path);
30559
+ manifestPath = resolve19(root, request.manifest_path);
30290
30560
  completed.build = { skipped: true, manifest_path: manifestPath };
30291
30561
  } else {
30292
30562
  const built = await runDelivery({ ...request, action: "build", root, format: "json" });
@@ -30296,7 +30566,7 @@ async function runAppRelease(request, options, delegate) {
30296
30566
  }
30297
30567
  const loaded = await loadSupacloudConfig(root);
30298
30568
  const resolved = resolveSupacloudConfig(loaded, root);
30299
- manifestPath = join13(resolved.outDir, "delivery", "delivery.manifest.json");
30569
+ manifestPath = join14(resolved.outDir, "delivery", "delivery.manifest.json");
30300
30570
  completed.build = {
30301
30571
  ok: true,
30302
30572
  manifest_path: manifestPath,
@@ -30323,7 +30593,7 @@ async function runAppRelease(request, options, delegate) {
30323
30593
  let configurationWrite;
30324
30594
  const activationId = crypto.randomUUID();
30325
30595
  if (request.configuration_path !== undefined) {
30326
- const configurationPath = resolve18(root, request.configuration_path);
30596
+ const configurationPath = resolve19(root, request.configuration_path);
30327
30597
  try {
30328
30598
  configurationWrite = parseApplicationConfigurationWrite(await Bun.file(configurationPath).json());
30329
30599
  configurationId = configurationWrite.configuration_id;
@@ -30384,7 +30654,7 @@ async function runAppRelease(request, options, delegate) {
30384
30654
  ...typeof deployReceipt.activation_id === "string" ? { activation_id: deployReceipt.activation_id } : {},
30385
30655
  ...deployReceipt.web === undefined ? {} : { web: deployReceipt.web }
30386
30656
  };
30387
- return request.format === "json" ? textResult(JSON.stringify(result, null, 2)) : textResult([
30657
+ return request.format === "json" ? textResult2(JSON.stringify(result, null, 2)) : textResult2([
30388
30658
  `${ref}/${id}/${environmentId}: ${deployReceipt.status === "accepted" ? "accepted" : result.no_op ? "no-op" : "released"}`,
30389
30659
  `Release: ${releaseId}`,
30390
30660
  `Configuration: ${configurationId}`,
@@ -30407,7 +30677,7 @@ function formatReleaseTransfer(result) {
30407
30677
  const data = plan ?? receipt;
30408
30678
  if (!data)
30409
30679
  return result;
30410
- return textResult([
30680
+ return textResult2([
30411
30681
  `${data.project_ref}/${data.application_id}: ${plan ? plan.action === "no-op" ? "No changes" : "Transfer required" : "Artifact transferred"}`,
30412
30682
  `Source: ${data.source.project_ref} / ${data.source.release_id}`,
30413
30683
  `Target release: ${data.candidate_release_id}`,
@@ -30454,7 +30724,7 @@ function historyText(result, request, projectRef) {
30454
30724
  }
30455
30725
  if (history.next_cursor)
30456
30726
  lines.push("", `Next cursor: ${history.next_cursor}`);
30457
- return textResult(lines.join(`
30727
+ return textResult2(lines.join(`
30458
30728
  `));
30459
30729
  } catch {
30460
30730
  return releaseControlFailure("applications.get_history", "INVALID_RESPONSE", null);
@@ -30474,7 +30744,7 @@ function formatRemoteDeployPlan(result) {
30474
30744
  ...names(plan.changes.targets.removed, "-"),
30475
30745
  ...names(plan.changes.targets.changed, "~")
30476
30746
  ];
30477
- return textResult([
30747
+ return textResult2([
30478
30748
  `${plan.project_ref}/${plan.application_id} [${plan.environment_id}]: ${plan.action === "no-op" ? "No changes" : "Activation required"}`,
30479
30749
  `Release: ${plan.candidate.release_id} (${plan.changes.release ? "changed" : "unchanged"})`,
30480
30750
  `Configuration: ${plan.candidate.configuration_id} (${plan.changes.configuration ? "changed" : "unchanged"})`,
@@ -30496,7 +30766,7 @@ function formatPromotionPlan2(result) {
30496
30766
  if (!payload || typeof payload !== "object" || !("plan" in payload))
30497
30767
  return result;
30498
30768
  const plan = parseApplicationPromotionPlan(payload.plan);
30499
- return textResult([
30769
+ return textResult2([
30500
30770
  `${plan.project_ref}/${plan.application_id}/${plan.environment_id}: ${plan.action}`,
30501
30771
  `Source: ${plan.source.project_ref}/${plan.source.environment_id}`,
30502
30772
  ...plan.blockers.length ? [`Blocked: ${plan.blockers.join(", ")}`] : [],
@@ -30523,7 +30793,7 @@ function formatPromotionExecution(result) {
30523
30793
  const receipt = payload.result;
30524
30794
  if (receipt.project_ref !== envelope.project_ref || receipt.application_id !== envelope.application_id || receipt.environment_id !== envelope.environment_id || receipt.mutation_id !== envelope.mutation_id || receipt.plan_sha256 !== envelope.plan_sha256)
30525
30795
  return result;
30526
- return textResult([
30796
+ return textResult2([
30527
30797
  `${String(envelope.project_ref)}/${String(envelope.application_id)}/${String(envelope.environment_id)}: promoted`,
30528
30798
  `Mutation: ${String(envelope.mutation_id)}`,
30529
30799
  `Activation: ${String(receipt.activation_id)}`,
@@ -30554,7 +30824,7 @@ function formatWorkflowObservation(result, action) {
30554
30824
  if (!data.mutation || typeof data.mutation !== "object" || !("mutation_id" in data.mutation) || typeof data.mutation.mutation_id !== "string")
30555
30825
  return result;
30556
30826
  const status = parsePromotionStatus({ ...identity, mutation: data.mutation, promotion: data.promotion }, { ...identity, mutation_id: data.mutation.mutation_id });
30557
- return textResult([
30827
+ return textResult2([
30558
30828
  `${label}: ${status.mutation.status}`,
30559
30829
  `Mutation: ${status.mutation.mutation_id}`,
30560
30830
  `Phase: ${status.promotion.phase ?? "not recorded"}`,
@@ -30564,15 +30834,21 @@ function formatWorkflowObservation(result, action) {
30564
30834
  }
30565
30835
  if (action === "preview-list" || action === "previews") {
30566
30836
  const list = parsePreviewList({ ...identity, previews: data.previews }, identity);
30567
- return textResult([
30837
+ return textResult2([
30568
30838
  `${label}: ${list.previews.length} preview(s)`,
30569
30839
  ...list.previews.map((preview) => `${preview.preview_id} ${preview.status} ${preview.resources.database_branch.branch_ref}`)
30570
30840
  ].join(`
30571
30841
  `));
30572
30842
  }
30573
- if (["preview-plan", "preview-create", "preview-status", "preview-reconcile", "preview-cleanup"].includes(action)) {
30843
+ if (action === "preview-pr") {
30844
+ const status = typeof data.status === "string" ? data.status : "unknown";
30845
+ const previewId = typeof data.preview_id === "string" ? data.preview_id : "unknown";
30846
+ return textResult2(`${label}: PR preview ${status}
30847
+ Preview: ${previewId}`);
30848
+ }
30849
+ if (["preview-plan", "preview-create", "preview-status", "preview-reconcile", "preview-cleanup", "preview-pr"].includes(action)) {
30574
30850
  const preview = parsePreviewReceipt(data.preview ?? data, identity);
30575
- return textResult([
30851
+ return textResult2([
30576
30852
  `${label}: ${preview.status}`,
30577
30853
  `Preview: ${preview.preview_id}`,
30578
30854
  `Branch: ${preview.resources.database_branch.branch_ref} (${preview.resources.database_branch.data_mode})`,
@@ -30601,16 +30877,16 @@ async function runPromotion(request, options, delegate) {
30601
30877
  try {
30602
30878
  payload = JSON.parse(planned.content[0]?.text ?? "");
30603
30879
  } catch {
30604
- return textResult("Promotion plan response was not valid JSON.", true);
30880
+ return textResult2("Promotion plan response was not valid JSON.", true);
30605
30881
  }
30606
30882
  if (!payload || typeof payload !== "object" || !("plan" in payload)) {
30607
- return textResult("Promotion plan response was invalid.", true);
30883
+ return textResult2("Promotion plan response was invalid.", true);
30608
30884
  }
30609
30885
  let plan;
30610
30886
  try {
30611
30887
  plan = parseApplicationPromotionPlan(payload.plan);
30612
30888
  } catch {
30613
- return textResult("Promotion plan failed immutable validation.", true);
30889
+ return textResult2("Promotion plan failed immutable validation.", true);
30614
30890
  }
30615
30891
  const identity = { project_ref: ref, application_id: request.id, environment_id: request.environment_id };
30616
30892
  if (plan.project_ref !== ref || plan.application_id !== request.id || plan.environment_id !== request.environment_id || plan.source.project_ref !== request.source_ref || plan.source.environment_id !== request.source_environment_id || plan.source.release_id !== request.source_release_id || request.configuration_id !== undefined && plan.target.configuration_id !== request.configuration_id) {
@@ -30625,14 +30901,14 @@ async function runPromotion(request, options, delegate) {
30625
30901
  no_op: true,
30626
30902
  execution_performed: false
30627
30903
  });
30628
- return format === "json" ? noOp : textResult(`${plan.project_ref}/${plan.application_id}/${plan.environment_id}: no-op
30904
+ return format === "json" ? noOp : textResult2(`${plan.project_ref}/${plan.application_id}/${plan.environment_id}: no-op
30629
30905
  Execution: skipped`);
30630
30906
  }
30631
30907
  if (plan.blockers.some((code) => !["MIGRATION_PENDING", "BACKUP_REQUIRED"].includes(code))) {
30632
30908
  return releaseControlFailure("applications.promote_application", "MUTATION_NOT_SUCCEEDED", null, { ...identity, plan, execution_performed: false });
30633
30909
  }
30634
30910
  if (!plan.target.configuration_id)
30635
- return textResult("Promotion plan has no target configuration revision.", true);
30911
+ return textResult2("Promotion plan has no target configuration revision.", true);
30636
30912
  const mutationId = crypto.randomUUID();
30637
30913
  const executeArgs = {
30638
30914
  ...remoteRequest,
@@ -30664,19 +30940,19 @@ async function runAppTool(request, options = {}) {
30664
30940
  if (request.action === "promote") {
30665
30941
  const delegate = options.getApplications?.();
30666
30942
  if (!delegate)
30667
- return textResult("App remote actions require a Management API context.", true);
30943
+ return textResult2("App remote actions require a Management API context.", true);
30668
30944
  return runPromotion(request, options, delegate);
30669
30945
  }
30670
30946
  if (request.action === "release") {
30671
30947
  const delegate = options.getApplications?.();
30672
30948
  if (!delegate)
30673
- return textResult("App remote actions require a Management API context.", true);
30949
+ return textResult2("App remote actions require a Management API context.", true);
30674
30950
  return runAppRelease(request, options, delegate);
30675
30951
  }
30676
30952
  if (Object.hasOwn(REMOTE_APP_ACTIONS, request.action)) {
30677
30953
  const delegate = options.getApplications?.();
30678
30954
  if (!delegate)
30679
- return textResult("App remote actions require a Management API context.", true);
30955
+ return textResult2("App remote actions require a Management API context.", true);
30680
30956
  const promotionDiff = request.action === "diff" && request.source_ref !== undefined && request.source_environment_id !== undefined && request.source_release_id !== undefined;
30681
30957
  const action = promotionDiff ? "get_promotion_plan" : REMOTE_APP_ACTIONS[request.action];
30682
30958
  const { format, ...remoteRequest } = request;
@@ -30693,13 +30969,13 @@ async function runAppTool(request, options = {}) {
30693
30969
  if (payload === null || typeof payload !== "object" || !("project_ref" in payload) || payload.project_ref !== args.ref || !("application_id" in payload) || payload.application_id !== request.id || !("environment_id" in payload) || payload.environment_id !== request.environment_id || !("evidence" in payload))
30694
30970
  throw new Error;
30695
30971
  if (payload.evidence === null)
30696
- return textResult("DEPLOYMENT incomplete: no recorded evidence. Read runtime status and obtain authenticated smoke and recovery evidence.");
30972
+ return textResult2("DEPLOYMENT incomplete: no recorded evidence. Read runtime status and obtain authenticated smoke and recovery evidence.");
30697
30973
  const evidence = parseDeploymentEvidence(payload.evidence);
30698
30974
  if (evidence.scope.project_ref !== args.ref || evidence.scope.application_id !== request.id || evidence.scope.environment_id !== request.environment_id)
30699
30975
  throw new Error;
30700
- return textResult(formatDeploymentEvidence(evidence));
30976
+ return textResult2(formatDeploymentEvidence(evidence));
30701
30977
  } catch {
30702
- return textResult("DEPLOYMENT unknown: invalid or mismatched evidence; no mutation was attempted.", true);
30978
+ return textResult2("DEPLOYMENT unknown: invalid or mismatched evidence; no mutation was attempted.", true);
30703
30979
  }
30704
30980
  }
30705
30981
  if (request.action === "history" && format !== "json") {
@@ -30721,7 +30997,7 @@ async function runAppTool(request, options = {}) {
30721
30997
  const { root, sourceDir, result } = await projectCompileConfig(request);
30722
30998
  const plan = await createVerificationPlan(root, result.graph, request.target.trim(), sourceDir);
30723
30999
  const ready = plan.ready && !result.diagnostics.some((item) => item.severity === "error");
30724
- return textResult(JSON.stringify({ ...plan, ready, diagnostics: result.diagnostics }, null, 2), !ready);
31000
+ return textResult2(JSON.stringify({ ...plan, ready, diagnostics: result.diagnostics }, null, 2), !ready);
30725
31001
  }
30726
31002
  case "dev":
30727
31003
  case "watch":
@@ -30737,7 +31013,7 @@ async function runAppTool(request, options = {}) {
30737
31013
  } catch (error) {
30738
31014
  if (request.format !== "json")
30739
31015
  throw error;
30740
- return textResult(JSON.stringify({
31016
+ return textResult2(JSON.stringify({
30741
31017
  version: 1,
30742
31018
  ok: false,
30743
31019
  code: error instanceof ScaffoldError ? error.code : "SCAFFOLD_FAILED",
@@ -30764,7 +31040,7 @@ async function runAppTool(request, options = {}) {
30764
31040
  case "fix":
30765
31041
  return runFix(request);
30766
31042
  default:
30767
- return textResult(`Unknown app action: ${String(request.action)}`, true);
31043
+ return textResult2(`Unknown app action: ${String(request.action)}`, true);
30768
31044
  }
30769
31045
  }
30770
31046
  function registerAppTools(server, options = {}) {
@@ -30811,6 +31087,7 @@ function registerAppTools(server, options = {}) {
30811
31087
  "preview-create",
30812
31088
  "preview-status",
30813
31089
  "preview-cleanup",
31090
+ "preview-pr",
30814
31091
  "preview-reconcile",
30815
31092
  "promote",
30816
31093
  "promote-status",
@@ -30852,8 +31129,8 @@ function registerAppTools(server, options = {}) {
30852
31129
  }
30853
31130
 
30854
31131
  // src/shared/tools/db-governance-tools.ts
30855
- import { existsSync as existsSync13 } from "node:fs";
30856
- import { join as join16, resolve as resolve21 } from "node:path";
31132
+ import { existsSync as existsSync14 } from "node:fs";
31133
+ import { join as join17, resolve as resolve22 } from "node:path";
30857
31134
  import {
30858
31135
  buildDatabaseManifest,
30859
31136
  explainObject,
@@ -30865,9 +31142,9 @@ import { databaseSources } from "@supacloud/db/source-contracts";
30865
31142
 
30866
31143
  // src/shared/tools/db-workflow.ts
30867
31144
  import { createHash as createHash9 } from "node:crypto";
30868
- import { lstat as lstat4, mkdir as mkdir6, mkdtemp, readFile as readFile5, readdir as readdir6, rename as rename3, rm as rm2, writeFile as writeFile5 } from "node:fs/promises";
31145
+ import { lstat as lstat4, mkdir as mkdir7, mkdtemp, readFile as readFile6, readdir as readdir6, rename as rename3, rm as rm2, writeFile as writeFile6 } from "node:fs/promises";
30869
31146
  import { tmpdir as tmpdir2 } from "node:os";
30870
- import { dirname as dirname11, isAbsolute as isAbsolute7, join as join15, relative as relative8, resolve as resolve20 } from "node:path";
31147
+ import { dirname as dirname11, isAbsolute as isAbsolute7, join as join16, relative as relative8, resolve as resolve21 } from "node:path";
30871
31148
  import {
30872
31149
  assertApplicationRoleRestricted,
30873
31150
  readDatabaseRole,
@@ -30878,8 +31155,8 @@ import {
30878
31155
  import { parseDatabaseSourcesConfig } from "@supacloud/db/source-contracts";
30879
31156
 
30880
31157
  // src/shared/tools/supabase-cli-tools.ts
30881
- import { chmodSync as chmodSync2, existsSync as existsSync12, mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync3 } from "node:fs";
30882
- import { dirname as dirname10, isAbsolute as isAbsolute6, join as join14, resolve as resolve19 } from "node:path";
31158
+ import { chmodSync as chmodSync2, existsSync as existsSync13, mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync3 } from "node:fs";
31159
+ import { dirname as dirname10, isAbsolute as isAbsolute6, join as join15, resolve as resolve20 } from "node:path";
30883
31160
  var SENSITIVE_ENV_KEY2 = /(?:^|_)(?:PASSWORD|PASS|SECRET|TOKEN|KEY|CREDENTIALS?|AUTHORIZATION|AUTH|SESSION|COOKIE|BEARER|DB_URI|DB_URL|DSN|DATABASE_URL|DATABASE_URI|CONNECTION_STRING|CONNECTION_URI)(?:_|$)/i;
30884
31161
  var VALID_VERSION2 = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
30885
31162
  var VALID_MIGRATION_NAME2 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,100}$/;
@@ -30939,12 +31216,12 @@ function schemaArguments2(schema) {
30939
31216
  function workdirArguments2(workdir) {
30940
31217
  if (!workdir)
30941
31218
  throw new Error("A workdir is required");
30942
- return ["--workdir", resolve19(workdir)];
31219
+ return ["--workdir", resolve20(workdir)];
30943
31220
  }
30944
31221
  function resolveOutputPath2(workdir, file, label) {
30945
31222
  if (!file || /[\r\n\0]/.test(file))
30946
31223
  throw new Error(`${label} file is required`);
30947
- return isAbsolute6(file) ? resolve19(file) : resolve19(workdir, file);
31224
+ return isAbsolute6(file) ? resolve20(file) : resolve20(workdir, file);
30948
31225
  }
30949
31226
  function databaseTargetArguments2(databaseUrl) {
30950
31227
  return databaseUrl ? ["--db-url", requirePostgresUrl2(databaseUrl)] : ["--local"];
@@ -31119,7 +31396,7 @@ function actionArguments2(request, workdir) {
31119
31396
  function buildOfficialSupabaseArgs2(request) {
31120
31397
  if (request.action === "version")
31121
31398
  return ["--version"];
31122
- const workdir = request.workdir ? resolve19(request.workdir) : undefined;
31399
+ const workdir = request.workdir ? resolve20(request.workdir) : undefined;
31123
31400
  if (!workdir)
31124
31401
  throw new Error("A workdir is required");
31125
31402
  return [...actionArguments2(request, workdir), ...workdirArguments2(workdir)];
@@ -31161,8 +31438,8 @@ function resolveOfficialSupabaseCommand2(workdir, environment = process.env) {
31161
31438
  }
31162
31439
  return ["npx", "--yes", `supabase@${version}`];
31163
31440
  }
31164
- const localPackageEntry = join14(resolve19(workdir), "node_modules", "supabase", "dist", "supabase.js");
31165
- if (existsSync12(localPackageEntry))
31441
+ const localPackageEntry = join15(resolve20(workdir), "node_modules", "supabase", "dist", "supabase.js");
31442
+ if (existsSync13(localPackageEntry))
31166
31443
  return [process.execPath, localPackageEntry];
31167
31444
  return ["supabase"];
31168
31445
  }
@@ -31180,7 +31457,7 @@ async function projectPath2(root, path) {
31180
31457
  }
31181
31458
  let current = root;
31182
31459
  for (const part of path.split("/")) {
31183
- current = join15(current, part);
31460
+ current = join16(current, part);
31184
31461
  try {
31185
31462
  if ((await lstat4(current)).isSymbolicLink())
31186
31463
  throw new Error("Symlink workflow paths are forbidden");
@@ -31202,8 +31479,8 @@ async function exists2(path) {
31202
31479
  }
31203
31480
  }
31204
31481
  async function boundary(root) {
31205
- const config = join15(root, "database.sources.json");
31206
- return await exists2(config) ? parseDatabaseSourcesConfig(JSON.parse(await readFile5(await projectPath2(root, "database.sources.json"), "utf8"))) : undefined;
31482
+ const config = join16(root, "database.sources.json");
31483
+ return await exists2(config) ? parseDatabaseSourcesConfig(JSON.parse(await readFile6(await projectPath2(root, "database.sources.json"), "utf8"))) : undefined;
31207
31484
  }
31208
31485
  var overlaps = (a, b) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
31209
31486
  async function candidatePath(root, path) {
@@ -31296,9 +31573,9 @@ async function runOfficial(root, workdir, args, environment, options) {
31296
31573
  async function initializeCandidate(stage, majorVersion = 18) {
31297
31574
  if (![15, 16, 17, 18].includes(majorVersion))
31298
31575
  throw new Error("Select a supported PostgreSQL major version (15-18)");
31299
- await mkdir6(join15(stage, "supabase/migrations"), { recursive: true });
31300
- await mkdir6(join15(stage, "supabase/schemas"), { recursive: true });
31301
- await writeFile5(join15(stage, "supabase/config.toml"), [
31576
+ await mkdir7(join16(stage, "supabase/migrations"), { recursive: true });
31577
+ await mkdir7(join16(stage, "supabase/schemas"), { recursive: true });
31578
+ await writeFile6(join16(stage, "supabase/config.toml"), [
31302
31579
  `project_id = "supacloud-candidate-${hash4(stage).slice(0, 12)}"`,
31303
31580
  "[db]",
31304
31581
  `major_version = ${majorVersion}`,
@@ -31311,14 +31588,14 @@ async function initializeCandidate(stage, majorVersion = 18) {
31311
31588
  async function copySqlSources(root, source, destination) {
31312
31589
  const path = await projectPath2(root, source);
31313
31590
  let count = 0;
31314
- await mkdir6(destination, { recursive: true });
31591
+ await mkdir7(destination, { recursive: true });
31315
31592
  for (const name of (await readdir6(path)).sort()) {
31316
31593
  const file = await projectPath2(root, `${source}/${name}`);
31317
31594
  const state = await lstat4(file);
31318
31595
  if (state.isDirectory())
31319
- count += await copySqlSources(root, `${source}/${name}`, join15(destination, name));
31596
+ count += await copySqlSources(root, `${source}/${name}`, join16(destination, name));
31320
31597
  else if (state.isFile() && name.endsWith(".sql")) {
31321
- await writeFile5(join15(destination, name), await readFile5(file));
31598
+ await writeFile6(join16(destination, name), await readFile6(file));
31322
31599
  count++;
31323
31600
  }
31324
31601
  }
@@ -31332,8 +31609,8 @@ async function reverse(args, root, options) {
31332
31609
  if (!selectedSchemas.length || selectedSchemas.some((schema) => !/^[a-z_][a-z0-9_$]*$/i.test(schema))) {
31333
31610
  throw new Error("Select valid PostgreSQL schemas");
31334
31611
  }
31335
- await mkdir6(dirname11(out), { recursive: true });
31336
- const stage = await mkdtemp(join15(dirname11(out), ".reverse-"));
31612
+ await mkdir7(dirname11(out), { recursive: true });
31613
+ const stage = await mkdtemp(join16(dirname11(out), ".reverse-"));
31337
31614
  try {
31338
31615
  const snapshot = await withDatabase(args, options, async (executor, url) => {
31339
31616
  const snapshot = await reverseDatabase(executor, selectedSchemas);
@@ -31349,10 +31626,10 @@ async function reverse(args, root, options) {
31349
31626
  }, options.environment ?? process.env, options);
31350
31627
  return snapshot;
31351
31628
  });
31352
- const generated = await readdir6(join15(stage, "supabase/schemas"), { recursive: true });
31629
+ const generated = await readdir6(join16(stage, "supabase/schemas"), { recursive: true });
31353
31630
  if (!generated.some((file) => file.endsWith(".sql")))
31354
31631
  throw new Error("Official reverse did not produce declarative SQL");
31355
- await writeFile5(join15(stage, "catalog.json"), renderReverseSnapshot(snapshot));
31632
+ await writeFile6(join16(stage, "catalog.json"), renderReverseSnapshot(snapshot));
31356
31633
  await rename3(stage, out);
31357
31634
  return result({
31358
31635
  ok: true,
@@ -31377,14 +31654,14 @@ async function diff2(args, root, options) {
31377
31654
  const input = await migrations(root, args.dir ?? (await boundary(root))?.migrations ?? "supabase/migrations");
31378
31655
  if (overlaps(input.dir, out))
31379
31656
  throw new Error("Candidate output overlaps reviewed migration history");
31380
- await mkdir6(dirname11(out), { recursive: true });
31381
- const stage = await mkdtemp(join15(dirname11(out), ".diff-"));
31657
+ await mkdir7(dirname11(out), { recursive: true });
31658
+ const stage = await mkdtemp(join16(dirname11(out), ".diff-"));
31382
31659
  try {
31383
31660
  await initializeCandidate(stage, args.db_major_version);
31384
- if (!await copySqlSources(root, sourcePath, join15(stage, "supabase/schemas")))
31661
+ if (!await copySqlSources(root, sourcePath, join16(stage, "supabase/schemas")))
31385
31662
  throw new Error("No declarative SQL sources");
31386
31663
  for (const { file, text } of input.files)
31387
- await writeFile5(join15(stage, "supabase/migrations", file), text);
31664
+ await writeFile6(join16(stage, "supabase/migrations", file), text);
31388
31665
  await runOfficial(root, stage, {
31389
31666
  action: "db_schema_declarative_sync",
31390
31667
  apply: false,
@@ -31394,15 +31671,15 @@ async function diff2(args, root, options) {
31394
31671
  }, options.environment ?? process.env, options);
31395
31672
  const history = new Map(input.files.map((file) => [file.file, file.text]));
31396
31673
  for (const [file, text] of history) {
31397
- if (await readFile5(join15(stage, "supabase/migrations", file), "utf8") !== text) {
31674
+ if (await readFile6(join16(stage, "supabase/migrations", file), "utf8") !== text) {
31398
31675
  throw new Error("Official diff changed reviewed migration history");
31399
31676
  }
31400
31677
  }
31401
- const names = (await readdir6(join15(stage, "supabase/migrations"))).filter((file) => file.endsWith(".sql") && !history.has(file));
31402
- const candidates = join15(stage, "candidates");
31403
- await mkdir6(candidates);
31678
+ const names = (await readdir6(join16(stage, "supabase/migrations"))).filter((file) => file.endsWith(".sql") && !history.has(file));
31679
+ const candidates = join16(stage, "candidates");
31680
+ await mkdir7(candidates);
31404
31681
  for (const file of names)
31405
- await writeFile5(join15(candidates, file), await readFile5(join15(stage, "supabase/migrations", file)));
31682
+ await writeFile6(join16(candidates, file), await readFile6(join16(stage, "supabase/migrations", file)));
31406
31683
  await rename3(candidates, out);
31407
31684
  } finally {
31408
31685
  await rm2(stage, { force: true, recursive: true });
@@ -31426,7 +31703,7 @@ async function migrations(root, path) {
31426
31703
  throw new Error("No forward migration files");
31427
31704
  const files = [];
31428
31705
  for (const file of names) {
31429
- const text = await readFile5(await projectPath2(root, `${path}/${file}`), "utf8");
31706
+ const text = await readFile6(await projectPath2(root, `${path}/${file}`), "utf8");
31430
31707
  files.push({ file, text, sha256: hash4(text) });
31431
31708
  }
31432
31709
  return { dir, files };
@@ -31440,10 +31717,10 @@ async function migrationAction(args, root, options) {
31440
31717
  throw new Error("Select a Management API and project ref");
31441
31718
  const path = args.dir ?? (await boundary(root))?.migrations ?? "supabase/migrations";
31442
31719
  const input = await migrations(root, path);
31443
- const stage = await mkdtemp(join15(tmpdir2(), "supacloud-reviewed-migrations-"));
31720
+ const stage = await mkdtemp(join16(tmpdir2(), "supacloud-reviewed-migrations-"));
31444
31721
  try {
31445
31722
  for (const { file, text } of input.files)
31446
- await writeFile5(join15(stage, file), text);
31723
+ await writeFile6(join16(stage, file), text);
31447
31724
  const preview = await run({ action: "push_migrations", ref, dir: stage, dry_run: true, strict: true });
31448
31725
  const dryRun = {
31449
31726
  isError: preview.isError === true,
@@ -31470,7 +31747,7 @@ async function migrationAction(args, root, options) {
31470
31747
  }
31471
31748
  }
31472
31749
  async function runDbWorkflow(args, projectRoot, options = {}) {
31473
- const root = resolve20(projectRoot);
31750
+ const root = resolve21(projectRoot);
31474
31751
  if ((await lstat4(root)).isSymbolicLink())
31475
31752
  throw new Error("Workflow root must not be a symlink");
31476
31753
  switch (args.action) {
@@ -31513,7 +31790,7 @@ async function runDbWorkflow(args, projectRoot, options = {}) {
31513
31790
  }
31514
31791
 
31515
31792
  // src/shared/tools/db-governance-tools.ts
31516
- function textResult2(text, isError = false) {
31793
+ function textResult3(text, isError = false) {
31517
31794
  return { isError, content: [{ type: "text", text }] };
31518
31795
  }
31519
31796
  function normalizeModule(candidate, sourcePath) {
@@ -31531,8 +31808,8 @@ function normalizeModule(candidate, sourcePath) {
31531
31808
  };
31532
31809
  }
31533
31810
  async function loadDatabaseModules(root, moduleFile) {
31534
- const filePath = moduleFile ? resolve21(root, moduleFile) : join16(root, "db", "modules.ts");
31535
- if (!existsSync13(filePath)) {
31811
+ const filePath = moduleFile ? resolve22(root, moduleFile) : join17(root, "db", "modules.ts");
31812
+ if (!existsSync14(filePath)) {
31536
31813
  throw new Error(moduleFile ? `Module file not found: ${filePath}` : `Module file not found: ${filePath}(用 --module_file 指定一个导出 defineDatabaseModule(...) 的文件)`);
31537
31814
  }
31538
31815
  let imported;
@@ -31621,7 +31898,7 @@ function buildDatabaseAiContext(modules, root, moduleName, target) {
31621
31898
  const objects = target ? allObjects.filter((object) => objectMatchesTarget(object, target)) : allObjects;
31622
31899
  if (target && objects.length === 0)
31623
31900
  throw new Error(`未找到数据库对象: ${target}`);
31624
- const sqlFirst = !existsSync13(join16(root, "zenstack/schema.zmodel")) && existsSync13(join16(root, "supabase/schemas"));
31901
+ const sqlFirst = !existsSync14(join17(root, "zenstack/schema.zmodel")) && existsSync14(join17(root, "supabase/schemas"));
31625
31902
  return {
31626
31903
  version: 1,
31627
31904
  scope: "database-ai-context",
@@ -31668,7 +31945,7 @@ async function collectLintIssues(args, root) {
31668
31945
  const issues = [];
31669
31946
  for (const module of selected) {
31670
31947
  const readSqlFile = async (path) => {
31671
- const absolute = resolve21(root, path);
31948
+ const absolute = resolve22(root, path);
31672
31949
  try {
31673
31950
  return await Bun.file(absolute).text();
31674
31951
  } catch (error) {
@@ -31686,13 +31963,13 @@ async function runLint(args, root) {
31686
31963
  const header = `linted ${selected.length} module(s): ${selected.map((module) => module.name).join(", ")}`;
31687
31964
  const body = issues.length > 0 ? issues.map(formatLintIssue).join(`
31688
31965
  `) : "no issues";
31689
- return textResult2(`${header}
31966
+ return textResult3(`${header}
31690
31967
  ${body}`, hasError);
31691
31968
  }
31692
31969
  async function runCheck2(args, root, environment, spawn, liteBinary, options) {
31693
31970
  const checks = [];
31694
31971
  let ok = true;
31695
- if (existsSync13(join16(root, "database.sources.json"))) {
31972
+ if (existsSync14(join17(root, "database.sources.json"))) {
31696
31973
  try {
31697
31974
  const source = await databaseSources(root, "check");
31698
31975
  checks.push({ name: "source-contract", ok: source.ok, findings: source.findings });
@@ -31705,8 +31982,8 @@ async function runCheck2(args, root, environment, spawn, liteBinary, options) {
31705
31982
  } else {
31706
31983
  checks.push({ name: "source-contract", skipped: true, reason: "database.sources.json not found" });
31707
31984
  }
31708
- const modulePath = args.module_file ? resolve21(root, args.module_file) : join16(root, "db/modules.ts");
31709
- if (existsSync13(modulePath)) {
31985
+ const modulePath = args.module_file ? resolve22(root, args.module_file) : join17(root, "db/modules.ts");
31986
+ if (existsSync14(modulePath)) {
31710
31987
  try {
31711
31988
  const { selected, issues } = await collectLintIssues(args, root);
31712
31989
  const lintOk = !issues.some((issue) => issue.severity === "error");
@@ -31744,7 +32021,7 @@ async function runCheck2(args, root, environment, spawn, liteBinary, options) {
31744
32021
  } else {
31745
32022
  checks.push({ name: "catalog", skipped: true, reason: "no --database_url, DATABASE_URL, --lite or --remote" });
31746
32023
  }
31747
- return textResult2(JSON.stringify({
32024
+ return textResult3(JSON.stringify({
31748
32025
  version: 1,
31749
32026
  scope: "database-check",
31750
32027
  root,
@@ -31759,11 +32036,11 @@ async function runExplain2(args, root) {
31759
32036
  const modules = await loadDatabaseModules(root, args.module_file);
31760
32037
  const manifest = buildDatabaseManifest(modules);
31761
32038
  const text = explainObject(manifest, target);
31762
- return textResult2(text, text.startsWith("未找到对象"));
32039
+ return textResult3(text, text.startsWith("未找到对象"));
31763
32040
  }
31764
32041
  async function runContext2(args, root) {
31765
32042
  const modules = await loadDatabaseModules(root, args.module_file);
31766
- return textResult2(JSON.stringify(buildDatabaseAiContext(modules, root, args.module, args.target), null, 2));
32043
+ return textResult3(JSON.stringify(buildDatabaseAiContext(modules, root, args.module, args.target), null, 2));
31767
32044
  }
31768
32045
  var defaultLiteSpawn = async (command, cwd) => {
31769
32046
  const proc = Bun.spawn({ cmd: command, cwd, stdout: "pipe", stderr: "pipe" });
@@ -31775,18 +32052,18 @@ var defaultLiteSpawn = async (command, cwd) => {
31775
32052
  return { exitCode, stdout, stderr };
31776
32053
  };
31777
32054
  async function runModuleCheckLite(args, root, spawn, liteBinary) {
31778
- const projectDir = resolve21(args.project_dir?.trim() || root);
32055
+ const projectDir = resolve22(args.project_dir?.trim() || root);
31779
32056
  const binary = liteBinary === undefined ? Bun.which("supacloud-lite") : liteBinary;
31780
32057
  if (!binary) {
31781
32058
  throw new Error("db module_check --lite 需要本机可用的 supacloud-lite(npm i -g @supacloud/lite,或加入 PATH)");
31782
32059
  }
31783
32060
  const command = [binary, "db", "check", "--project-dir", projectDir];
31784
32061
  if (args.module_file?.trim())
31785
- command.push("--module-file", resolve21(root, args.module_file.trim()));
32062
+ command.push("--module-file", resolve22(root, args.module_file.trim()));
31786
32063
  const result = await spawn(command, projectDir);
31787
32064
  const output = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join(`
31788
32065
  `);
31789
- return textResult2(output || "lite db check 无输出", result.exitCode !== 0);
32066
+ return textResult3(output || "lite db check 无输出", result.exitCode !== 0);
31790
32067
  }
31791
32068
  function remoteModuleManifest(modules) {
31792
32069
  return modules.map((module) => ({
@@ -31868,7 +32145,7 @@ async function runModuleCheckAction(args, root, environment, spawn, liteBinary,
31868
32145
  reports.push(await runModuleCheck(module, executor, schemas));
31869
32146
  }
31870
32147
  const hasError = reports.some((report) => !report.ok);
31871
- return textResult2(reports.map(formatReconcileReport).join(`
32148
+ return textResult3(reports.map(formatReconcileReport).join(`
31872
32149
  `), hasError);
31873
32150
  } catch (error) {
31874
32151
  const message = error instanceof Error ? error.message : String(error);
@@ -31902,7 +32179,7 @@ function registerDbGovernanceTools(server, options = {}) {
31902
32179
  migration_role: optional(String2(), "[role_sql] Privileged migration role"),
31903
32180
  database: optional(String2(), "[role_sql] PostgreSQL database name")
31904
32181
  }, async (request) => {
31905
- const root = resolve21(request.root || fallbackRoot);
32182
+ const root = resolve22(request.root || fallbackRoot);
31906
32183
  switch (request.action) {
31907
32184
  case "context":
31908
32185
  return runContext2(request, root);
@@ -31935,7 +32212,7 @@ function registerDbGovernanceTools(server, options = {}) {
31935
32212
  runDatabase: options.runDatabase
31936
32213
  });
31937
32214
  default:
31938
- return textResult2(`Unknown db action: ${String(request.action)}`, true);
32215
+ return textResult3(`Unknown db action: ${String(request.action)}`, true);
31939
32216
  }
31940
32217
  });
31941
32218
  }
@@ -31943,7 +32220,7 @@ function registerDbGovernanceTools(server, options = {}) {
31943
32220
  // src/shared/tools/scheduled-function-tools.ts
31944
32221
  import { randomUUID as randomUUID3 } from "node:crypto";
31945
32222
  import { readFileSync as readFileSync10, statSync as statSync9 } from "node:fs";
31946
- import { resolve as resolve22 } from "node:path";
32223
+ import { resolve as resolve23 } from "node:path";
31947
32224
  import { isDeepStrictEqual } from "node:util";
31948
32225
  var HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
31949
32226
  var ENVIRONMENT_NAME_PATTERN3 = /^[A-Za-z_][A-Za-z0-9_]{0,255}$/;
@@ -32027,7 +32304,7 @@ function validScheduledFunctionCron(expression) {
32027
32304
  function readScheduleBodyFile(bodyPathInput) {
32028
32305
  if (!bodyPathInput.trim())
32029
32306
  throw new Error("'body_file' must be a path");
32030
- const bodyPath = resolve22(bodyPathInput);
32307
+ const bodyPath = resolve23(bodyPathInput);
32031
32308
  const bodyStat = statSync9(bodyPath);
32032
32309
  if (!bodyStat.isFile() || bodyStat.size > MAX_BODY_FILE_BYTES) {
32033
32310
  throw new Error("Scheduled Function body file must be a regular file no larger than 1 MiB");
@@ -32411,8 +32688,8 @@ var MUTATION_TOOL_SCHEMA = {
32411
32688
 
32412
32689
  // src/shared/tools/release-tools.ts
32413
32690
  import { createHash as createHash10 } from "node:crypto";
32414
- import { existsSync as existsSync14, mkdirSync as mkdirSync5, readdirSync as readdirSync5, readFileSync as readFileSync11, writeFileSync as writeFileSync4 } from "node:fs";
32415
- import { dirname as dirname12, join as join17, relative as relative9, resolve as resolve23 } from "node:path";
32691
+ import { existsSync as existsSync15, mkdirSync as mkdirSync5, readdirSync as readdirSync5, readFileSync as readFileSync11, writeFileSync as writeFileSync4 } from "node:fs";
32692
+ import { dirname as dirname12, join as join18, relative as relative9, resolve as resolve24 } from "node:path";
32416
32693
  var SAFE_PROJECT_REF = /^[A-Za-z0-9_-]{1,64}$/;
32417
32694
  var SAFE_ENVIRONMENT_ID = /^[A-Za-z0-9_-]{1,64}$/;
32418
32695
  var BACKUP_ID = /^logical-full_[A-Za-z0-9_-]{1,64}_[a-f0-9]{32}$/;
@@ -32734,15 +33011,15 @@ function collectScopeFiles(cwd, file, files, dir, task) {
32734
33011
  const results = [];
32735
33012
  const resolvePathWithFallbacks = (filePath) => {
32736
33013
  const trimmed = filePath.trim();
32737
- const resolved = resolve23(cwd, trimmed);
32738
- if (existsSync14(resolved))
33014
+ const resolved = resolve24(cwd, trimmed);
33015
+ if (existsSync15(resolved))
32739
33016
  return resolved;
32740
33017
  const candidates = [
32741
- resolve23(cwd, "supacloud/fa/release-scopes", trimmed),
32742
- resolve23(cwd, "release-scopes", trimmed),
32743
- resolve23(cwd, "scopes", trimmed)
33018
+ resolve24(cwd, "supacloud/fa/release-scopes", trimmed),
33019
+ resolve24(cwd, "release-scopes", trimmed),
33020
+ resolve24(cwd, "scopes", trimmed)
32744
33021
  ];
32745
- const found = candidates.find(existsSync14);
33022
+ const found = candidates.find(existsSync15);
32746
33023
  if (found)
32747
33024
  return found;
32748
33025
  throw new Error(`Scope file not found: ${filePath}`);
@@ -32763,18 +33040,18 @@ function collectScopeFiles(cwd, file, files, dir, task) {
32763
33040
  if (!taskFilter && (!dir || typeof dir !== "string" || !dir.trim())) {
32764
33041
  throw new Error("At least one of --file, --files, or --task is required for scope_rebind");
32765
33042
  }
32766
- const candidates = typeof dir === "string" && dir.trim() ? [resolve23(cwd, dir.trim())] : [
32767
- resolve23(cwd, "supacloud/fa/release-scopes"),
32768
- resolve23(cwd, "release-scopes"),
32769
- resolve23(cwd, "scopes")
33043
+ const candidates = typeof dir === "string" && dir.trim() ? [resolve24(cwd, dir.trim())] : [
33044
+ resolve24(cwd, "supacloud/fa/release-scopes"),
33045
+ resolve24(cwd, "release-scopes"),
33046
+ resolve24(cwd, "scopes")
32770
33047
  ];
32771
33048
  for (const directory of candidates) {
32772
- if (existsSync14(directory)) {
33049
+ if (existsSync15(directory)) {
32773
33050
  try {
32774
33051
  const entries = readdirSync5(directory, { withFileTypes: true });
32775
33052
  for (const entry of entries) {
32776
33053
  if (entry.isFile() && entry.name.endsWith(".json")) {
32777
- const fullPath = join17(directory, entry.name);
33054
+ const fullPath = join18(directory, entry.name);
32778
33055
  if (!taskFilter) {
32779
33056
  results.push(fullPath);
32780
33057
  } else if (entry.name.toLowerCase().includes(taskFilter)) {
@@ -32800,7 +33077,7 @@ function collectScopeFiles(cwd, file, files, dir, task) {
32800
33077
  return [...new Set(results)];
32801
33078
  }
32802
33079
  function handleScopeRebind(args) {
32803
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve23(args.cwd.trim()) : process.cwd();
33080
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
32804
33081
  const targetBaseCommit = resolveGitBaseCommit(cwd, args.base_commit);
32805
33082
  const requestedEnvironmentId = requestedScopeEnvironment(args, "scope_rebind");
32806
33083
  const scopeFiles = collectScopeFiles(cwd, args.file, args.files, args.dir, args.task);
@@ -32858,20 +33135,20 @@ function handleScopeRebind(args) {
32858
33135
  });
32859
33136
  }
32860
33137
  function handleScopeInspect(args) {
32861
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve23(args.cwd.trim()) : process.cwd();
33138
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
32862
33139
  const requestedEnvironmentId = requestedScopeEnvironment(args, "scope_inspect");
32863
33140
  if (typeof args.file !== "string" || !args.file.trim()) {
32864
33141
  throw new Error("'file' is required for scope_inspect");
32865
33142
  }
32866
33143
  const trimmed = args.file.trim();
32867
- let filePath = resolve23(cwd, trimmed);
32868
- if (!existsSync14(filePath)) {
33144
+ let filePath = resolve24(cwd, trimmed);
33145
+ if (!existsSync15(filePath)) {
32869
33146
  const candidates = [
32870
- resolve23(cwd, "supacloud/fa/release-scopes", trimmed),
32871
- resolve23(cwd, "release-scopes", trimmed),
32872
- resolve23(cwd, "scopes", trimmed)
33147
+ resolve24(cwd, "supacloud/fa/release-scopes", trimmed),
33148
+ resolve24(cwd, "release-scopes", trimmed),
33149
+ resolve24(cwd, "scopes", trimmed)
32873
33150
  ];
32874
- const found = candidates.find(existsSync14);
33151
+ const found = candidates.find(existsSync15);
32875
33152
  if (found)
32876
33153
  filePath = found;
32877
33154
  else
@@ -32931,15 +33208,15 @@ function releaseComponentView(component) {
32931
33208
  return { kind: component.kind, artifact_sha256: component.artifactSha256 };
32932
33209
  }
32933
33210
  function handleContractPlan(args, fallbackRef) {
32934
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve23(args.cwd.trim()) : process.cwd();
33211
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
32935
33212
  const requestedRef = typeof args.ref === "string" && args.ref.trim() || fallbackRef;
32936
33213
  if (!requestedRef || !validProjectRef(requestedRef)) {
32937
33214
  throw new Error("'ref' is required for contract_plan and must identify one project");
32938
33215
  }
32939
33216
  const requestedEnvironmentId = requestedScopeEnvironment(args, "contract_plan");
32940
33217
  const file = typeof args.file === "string" && args.file.trim() ? args.file.trim() : "supacloud.release.json";
32941
- const filePath = resolve23(cwd, file);
32942
- if (!existsSync14(filePath)) {
33218
+ const filePath = resolve24(cwd, file);
33219
+ if (!existsSync15(filePath)) {
32943
33220
  throw new Error(`Release contract not found: ${file}`);
32944
33221
  }
32945
33222
  let parsedValue;
@@ -33001,7 +33278,7 @@ function parseCommaList(value) {
33001
33278
  return [];
33002
33279
  }
33003
33280
  function handleScopeCreate(args, fallbackRef) {
33004
- const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve23(args.cwd.trim()) : process.cwd();
33281
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? resolve24(args.cwd.trim()) : process.cwd();
33005
33282
  if (typeof args.file !== "string" || !args.file.trim()) {
33006
33283
  throw new Error("'file' is required for scope_create");
33007
33284
  }
@@ -33017,7 +33294,7 @@ function handleScopeCreate(args, fallbackRef) {
33017
33294
  throw new Error("'ref' is invalid for release controls");
33018
33295
  }
33019
33296
  const targetBaseCommit = resolveGitBaseCommit(cwd, args.base_commit);
33020
- const filePath = resolve23(cwd, args.file.trim());
33297
+ const filePath = resolve24(cwd, args.file.trim());
33021
33298
  mkdirSync5(dirname12(filePath), { recursive: true });
33022
33299
  const scope = {
33023
33300
  baseCommit: targetBaseCommit,
@@ -33265,11 +33542,11 @@ function registerReleaseTools(server, http, options = {}) {
33265
33542
  }
33266
33543
 
33267
33544
  // src/shared/tools/deploy-tools.ts
33268
- import { access, lstat as lstat5, mkdtemp as mkdtemp2, opendir, readFile as readFile7, rm as rm3, writeFile as writeFile7 } from "node:fs/promises";
33545
+ import { access, lstat as lstat5, mkdtemp as mkdtemp2, opendir, readFile as readFile8, rm as rm3, writeFile as writeFile8 } from "node:fs/promises";
33269
33546
  import { spawn as spawn2 } from "node:child_process";
33270
33547
  import { createHash as createHash11 } from "node:crypto";
33271
33548
  import { tmpdir as tmpdir3 } from "node:os";
33272
- import { basename as basename8, dirname as dirname14, join as join19, relative as relative10, resolve as resolve26, sep as sep5 } from "node:path";
33549
+ import { basename as basename8, dirname as dirname14, join as join20, relative as relative10, resolve as resolve27, sep as sep5 } from "node:path";
33273
33550
 
33274
33551
  // src/shared/tools/project-deployment.ts
33275
33552
  async function requireProjectDeploymentProtocol(http, projectRef, environmentId) {
@@ -33345,14 +33622,14 @@ async function readProjectDeploymentStatus(http, projectRef, environmentId, depl
33345
33622
  }
33346
33623
 
33347
33624
  // src/shared/tools/developer-experience-tools.ts
33348
- import { existsSync as existsSync16 } from "node:fs";
33349
- import { mkdir as mkdir7, readdir as readdir7, readFile as readFile6, writeFile as writeFile6 } from "node:fs/promises";
33350
- import { dirname as dirname13, join as join18, resolve as resolve25 } from "node:path";
33625
+ import { existsSync as existsSync17 } from "node:fs";
33626
+ import { mkdir as mkdir8, readdir as readdir7, readFile as readFile7, writeFile as writeFile7 } from "node:fs/promises";
33627
+ import { dirname as dirname13, join as join19, resolve as resolve26 } from "node:path";
33351
33628
 
33352
33629
  // src/shared/context.ts
33353
- import { existsSync as existsSync15, readFileSync as readFileSync12 } from "node:fs";
33630
+ import { existsSync as existsSync16, readFileSync as readFileSync12 } from "node:fs";
33354
33631
  import { homedir as homedir3 } from "node:os";
33355
- import { resolve as resolve24 } from "node:path";
33632
+ import { resolve as resolve25 } from "node:path";
33356
33633
  var CORE_CONTEXT_KEYS2 = [
33357
33634
  "SUPABASE_URL",
33358
33635
  "SUPABASE_SERVICE_ROLE_KEY",
@@ -33384,8 +33661,44 @@ function parseEnvFile2(contents) {
33384
33661
  }
33385
33662
  return values;
33386
33663
  }
33664
+ function projectConfigValues2(cwd, environment) {
33665
+ const path = resolve25(cwd, "supacloud.json");
33666
+ if (!existsSync16(path))
33667
+ return {};
33668
+ try {
33669
+ const parsed = JSON.parse(readFileSync12(path, "utf8"));
33670
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
33671
+ return {};
33672
+ const root = parsed;
33673
+ const context = root.context;
33674
+ if (!context || typeof context !== "object" || Array.isArray(context))
33675
+ return {};
33676
+ const contextRecord = context;
33677
+ const environments = contextRecord.environments;
33678
+ if (!environments || typeof environments !== "object" || Array.isArray(environments))
33679
+ return {};
33680
+ const selected = environments[environment];
33681
+ if (!selected || typeof selected !== "object" || Array.isArray(selected))
33682
+ return {};
33683
+ const values = selected;
33684
+ const output = {};
33685
+ const mappings = {
33686
+ api_url: "SUPACLOUD_API_URL",
33687
+ project_ref: "SUPACLOUD_PROJECT_REF",
33688
+ application_id: "SUPACLOUD_APPLICATION_ID",
33689
+ environment_id: "SUPACLOUD_APPLICATION_ENVIRONMENT_ID"
33690
+ };
33691
+ for (const [source, target] of Object.entries(mappings)) {
33692
+ if (typeof values[source] === "string" && values[source].trim())
33693
+ output[target] = values[source].trim();
33694
+ }
33695
+ return output;
33696
+ } catch {
33697
+ return {};
33698
+ }
33699
+ }
33387
33700
  function readEnvFile2(path, required) {
33388
- if (!existsSync15(path)) {
33701
+ if (!existsSync16(path)) {
33389
33702
  if (required)
33390
33703
  throw new Error(`SupaCloud environment file not found: ${path}`);
33391
33704
  return {};
@@ -33421,6 +33734,26 @@ function inferProjectRefFromSupabaseUrl2(value) {
33421
33734
  return "";
33422
33735
  return new URL(value).hostname.match(/^([a-z0-9-]+)\.api\./i)?.[1] ?? "";
33423
33736
  }
33737
+ function inferManagementApiUrlFromSupabaseUrl2(value, projectRef = "") {
33738
+ if (!value)
33739
+ return "";
33740
+ const url = new URL(value);
33741
+ const host = url.hostname;
33742
+ if (host.startsWith("api.")) {
33743
+ url.hostname = `studio.${host.slice("api.".length)}`;
33744
+ return url.origin;
33745
+ }
33746
+ const ref = projectRef.trim();
33747
+ if (ref && host.startsWith(`${ref}.api.`)) {
33748
+ url.hostname = `studio-${ref}.${host.slice(`${ref}.api.`.length)}`;
33749
+ return url.origin;
33750
+ }
33751
+ const managedHost = host.match(/^([a-z0-9-]+)\.api\.(.+)$/i);
33752
+ if (!managedHost)
33753
+ return "";
33754
+ url.hostname = `studio-${managedHost[1]}.${managedHost[2]}`;
33755
+ return url.origin;
33756
+ }
33424
33757
  function sourceCredentialScope2(values, explicitApiUrl, supabaseUrl) {
33425
33758
  const hasManagementContext = Boolean(explicitApiUrl.trim() || values.SUPACLOUD_API_TOKEN?.trim() || values.SUPACLOUD_HOST?.trim());
33426
33759
  if (hasManagementContext)
@@ -33432,7 +33765,7 @@ function sourceProjectCore2(values) {
33432
33765
  const projectRef = (values.SUPACLOUD_PROJECT_REF || "").trim() || inferProjectRefFromSupabaseUrl2(supabaseUrl);
33433
33766
  const explicitApiUrl = values.SUPACLOUD_API_URL || "";
33434
33767
  const credentialScope = sourceCredentialScope2(values, explicitApiUrl, supabaseUrl);
33435
- const managementUrl = explicitApiUrl || (values.SUPACLOUD_HOST ? `http://${values.SUPACLOUD_HOST}:9090` : "");
33768
+ const managementUrl = explicitApiUrl || (credentialScope === "management" ? inferManagementApiUrlFromSupabaseUrl2(supabaseUrl, projectRef) : "") || (values.SUPACLOUD_HOST ? `http://${values.SUPACLOUD_HOST}:9090` : "");
33436
33769
  const apiUrl = credentialScope === "management" ? canonicalApiOrigin2(managementUrl) : "";
33437
33770
  const apiToken = credentialScope === "management" ? values.SUPACLOUD_API_TOKEN || "" : "";
33438
33771
  return { apiUrl, apiToken, projectRef, supabaseUrl, credentialScope };
@@ -33462,7 +33795,7 @@ function parseInsecureTls2(values) {
33462
33795
  }
33463
33796
  function namedEnvironmentSource2(cwd, selector) {
33464
33797
  const environment = normalizeEnvironmentName(selector);
33465
- const path = resolve24(cwd, `.env.supacloud.${selector}`);
33798
+ const path = resolve25(cwd, `.env.supacloud.${selector}`);
33466
33799
  const values = readEnvFile2(path, true);
33467
33800
  if (values.SUPACLOUD_ENV && normalizeEnvironmentName(values.SUPACLOUD_ENV) !== environment) {
33468
33801
  throw new Error(`SUPACLOUD_ENV in ${path} does not match selector ${selector}`);
@@ -33470,7 +33803,7 @@ function namedEnvironmentSource2(cwd, selector) {
33470
33803
  return { values, kind: "named_env_file", path, environment };
33471
33804
  }
33472
33805
  function explicitEnvironmentSource2(cwd, envFile) {
33473
- const path = resolve24(cwd, envFile);
33806
+ const path = resolve25(cwd, envFile);
33474
33807
  const values = readEnvFile2(path, true);
33475
33808
  if (!values.SUPACLOUD_ENV)
33476
33809
  throw new Error(`SUPACLOUD_ENV is required in ${path}`);
@@ -33484,25 +33817,47 @@ function explicitEnvironmentSource2(cwd, envFile) {
33484
33817
  function contextSource2(env, cwd, selection) {
33485
33818
  if (selection.environmentName && selection.envFile)
33486
33819
  throw new Error("Environment selectors are mutually exclusive");
33487
- if (selection.environmentName)
33488
- return namedEnvironmentSource2(cwd, selection.environmentName);
33489
- if (selection.envFile)
33490
- return explicitEnvironmentSource2(cwd, selection.envFile);
33820
+ if (selection.environmentName) {
33821
+ const source = namedEnvironmentSource2(cwd, selection.environmentName);
33822
+ return {
33823
+ ...source,
33824
+ values: { ...projectConfigValues2(cwd, source.environment), ...source.values }
33825
+ };
33826
+ }
33827
+ if (selection.envFile) {
33828
+ const source = explicitEnvironmentSource2(cwd, selection.envFile);
33829
+ return {
33830
+ ...source,
33831
+ values: { ...projectConfigValues2(cwd, source.environment), ...source.values }
33832
+ };
33833
+ }
33491
33834
  if (env.SUPACLOUD_ENV) {
33492
33835
  const environment = normalizeEnvironmentName(env.SUPACLOUD_ENV);
33493
- const values = processValues2(env);
33836
+ const values = { ...projectConfigValues2(cwd, environment), ...processValues2(env) };
33494
33837
  if (completeProjectContext2(values)) {
33495
33838
  return { values, kind: "process_env", path: null, environment };
33496
33839
  }
33497
- return namedEnvironmentSource2(cwd, env.SUPACLOUD_ENV);
33840
+ const source = namedEnvironmentSource2(cwd, env.SUPACLOUD_ENV);
33841
+ return {
33842
+ ...source,
33843
+ values: { ...projectConfigValues2(cwd, source.environment), ...source.values }
33844
+ };
33498
33845
  }
33499
33846
  if (hasProcessContext2(env)) {
33500
33847
  return { values: processValues2(env), kind: "process_env", path: null, environment: "" };
33501
33848
  }
33502
- const path = resolve24(cwd, ".env");
33849
+ const path = resolve25(cwd, ".env");
33503
33850
  const values = readEnvFile2(path, false);
33504
33851
  const environment = values.SUPACLOUD_ENV ? normalizeEnvironmentName(values.SUPACLOUD_ENV) : "";
33505
- return { values, kind: Object.keys(values).length ? "legacy_dotenv" : "none", path: existsSync15(path) ? path : null, environment };
33852
+ if (environment) {
33853
+ return {
33854
+ values: { ...projectConfigValues2(cwd, environment), ...values },
33855
+ kind: "legacy_dotenv",
33856
+ path: existsSync16(path) ? path : null,
33857
+ environment
33858
+ };
33859
+ }
33860
+ return { values, kind: Object.keys(values).length ? "legacy_dotenv" : "none", path: existsSync16(path) ? path : null, environment };
33506
33861
  }
33507
33862
  function resolveSupaCloudContext2(env = process.env, cwd = process.cwd(), selection = {}) {
33508
33863
  const source = contextSource2(env, cwd, selection);
@@ -33514,7 +33869,7 @@ function resolveSupaCloudContext2(env = process.env, cwd = process.cwd(), select
33514
33869
  host,
33515
33870
  sshUser: env.SUPACLOUD_SSH_USER ?? "root",
33516
33871
  sshPort: parseInt(env.SUPACLOUD_SSH_PORT ?? "22", 10),
33517
- sshKey: env.SUPACLOUD_SSH_KEY ?? resolve24(homedir3(), ".ssh", "id_rsa"),
33872
+ sshKey: env.SUPACLOUD_SSH_KEY ?? resolve25(homedir3(), ".ssh", "id_rsa"),
33518
33873
  sshPass: env.SUPACLOUD_SSH_PASS ?? "",
33519
33874
  apiUrl: core.apiUrl,
33520
33875
  apiToken: core.apiToken,
@@ -33543,7 +33898,7 @@ var initToolSchema = {
33543
33898
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
33544
33899
  };
33545
33900
  var environmentToolSchema = {
33546
- action: withDescription(stringEnum2(["list", "check"]), "Environment profile inspection action"),
33901
+ ...environmentSyncSchema,
33547
33902
  root: optional(String2(), "Project directory containing .env.supacloud.* files"),
33548
33903
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
33549
33904
  };
@@ -33565,13 +33920,13 @@ var PRODUCTION_PROFILE = [
33565
33920
  ""
33566
33921
  ].join(`
33567
33922
  `);
33568
- function textResult3(text, isError = false) {
33923
+ function textResult4(text, isError = false) {
33569
33924
  return { isError, content: [{ type: "text", text }] };
33570
33925
  }
33571
- function jsonResult(value, isError = false) {
33572
- return textResult3(JSON.stringify(value, null, 2), isError);
33926
+ function jsonResult2(value, isError = false) {
33927
+ return textResult4(JSON.stringify(value, null, 2), isError);
33573
33928
  }
33574
- function record5(value) {
33929
+ function record6(value) {
33575
33930
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
33576
33931
  }
33577
33932
  function packageDependencies(manifest) {
@@ -33589,17 +33944,17 @@ function outputDirectoryFor(manifest) {
33589
33944
  return "dist";
33590
33945
  }
33591
33946
  async function readPackageManifest(root) {
33592
- const path = join18(root, "package.json");
33593
- if (!existsSync16(path))
33947
+ const path = join19(root, "package.json");
33948
+ if (!existsSync17(path))
33594
33949
  return {};
33595
33950
  try {
33596
- const parsed = JSON.parse(await readFile6(path, "utf8"));
33597
- const value = record5(parsed);
33951
+ const parsed = JSON.parse(await readFile7(path, "utf8"));
33952
+ const value = record6(parsed);
33598
33953
  if (!value)
33599
33954
  throw new Error("package.json must contain an object");
33600
- const scripts = record5(value.scripts);
33601
- const dependencies = record5(value.dependencies);
33602
- const devDependencies = record5(value.devDependencies);
33955
+ const scripts = record6(value.scripts);
33956
+ const dependencies = record6(value.dependencies);
33957
+ const devDependencies = record6(value.devDependencies);
33603
33958
  return {
33604
33959
  scripts: scripts ?? undefined,
33605
33960
  dependencies: dependencies ?? undefined,
@@ -33611,7 +33966,7 @@ async function readPackageManifest(root) {
33611
33966
  }
33612
33967
  async function writeNewFile(path, content) {
33613
33968
  try {
33614
- await writeFile6(path, content, { encoding: "utf8", flag: "wx", mode: 384 });
33969
+ await writeFile7(path, content, { encoding: "utf8", flag: "wx", mode: 384 });
33615
33970
  return true;
33616
33971
  } catch (error) {
33617
33972
  if (error instanceof Error && "code" in error && error.code === "EEXIST")
@@ -33620,8 +33975,8 @@ async function writeNewFile(path, content) {
33620
33975
  }
33621
33976
  }
33622
33977
  async function ensureGitignore(root) {
33623
- const path = join18(root, ".gitignore");
33624
- const existing = existsSync16(path) ? await readFile6(path, "utf8") : "";
33978
+ const path = join19(root, ".gitignore");
33979
+ const existing = existsSync17(path) ? await readFile7(path, "utf8") : "";
33625
33980
  const required = [".env.supacloud.*", "!.env.supacloud.*.example"];
33626
33981
  const missing = required.filter((entry) => !existing.split(/\r?\n/).includes(entry));
33627
33982
  if (missing.length === 0)
@@ -33629,16 +33984,16 @@ async function ensureGitignore(root) {
33629
33984
  const prefix = existing.length > 0 && !existing.endsWith(`
33630
33985
  `) ? `${existing}
33631
33986
  ` : existing;
33632
- await writeFile6(path, `${prefix}${missing.join(`
33987
+ await writeFile7(path, `${prefix}${missing.join(`
33633
33988
  `)}
33634
33989
  `, "utf8");
33635
33990
  return true;
33636
33991
  }
33637
33992
  async function initializeProject(request, options = {}) {
33638
- const root = resolve25(request.root || options.cwd || process.cwd());
33639
- await mkdir7(root, { recursive: true });
33640
- const configPath = join18(root, "supacloud.json");
33641
- if (existsSync16(configPath)) {
33993
+ const root = resolve26(request.root || options.cwd || process.cwd());
33994
+ await mkdir8(root, { recursive: true });
33995
+ const configPath = join19(root, "supacloud.json");
33996
+ if (existsSync17(configPath)) {
33642
33997
  throw new Error(`supacloud.json already exists in ${root}; init never overwrites project configuration`);
33643
33998
  }
33644
33999
  const manifest = await readPackageManifest(root);
@@ -33652,7 +34007,7 @@ async function initializeProject(request, options = {}) {
33652
34007
  };
33653
34008
  const created = [];
33654
34009
  try {
33655
- await writeFile6(configPath, `${JSON.stringify(config, null, 2)}
34010
+ await writeFile7(configPath, `${JSON.stringify(config, null, 2)}
33656
34011
  `, {
33657
34012
  encoding: "utf8",
33658
34013
  flag: "wx",
@@ -33665,10 +34020,10 @@ async function initializeProject(request, options = {}) {
33665
34020
  throw error;
33666
34021
  }
33667
34022
  created.push("supacloud.json");
33668
- if (await writeNewFile(join18(root, ".env.supacloud.test.example"), TEST_PROFILE)) {
34023
+ if (await writeNewFile(join19(root, ".env.supacloud.test.example"), TEST_PROFILE)) {
33669
34024
  created.push(".env.supacloud.test.example");
33670
34025
  }
33671
- if (await writeNewFile(join18(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE)) {
34026
+ if (await writeNewFile(join19(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE)) {
33672
34027
  created.push(".env.supacloud.production.example");
33673
34028
  }
33674
34029
  if (await ensureGitignore(root))
@@ -33679,7 +34034,7 @@ async function initializeProject(request, options = {}) {
33679
34034
  root,
33680
34035
  created,
33681
34036
  detected: {
33682
- package_json: existsSync16(join18(root, "package.json")),
34037
+ package_json: existsSync17(join19(root, "package.json")),
33683
34038
  build_script: hasBuildScript,
33684
34039
  output_directory: outputDirectory
33685
34040
  },
@@ -33691,8 +34046,8 @@ async function initializeProject(request, options = {}) {
33691
34046
  ]
33692
34047
  };
33693
34048
  if (request.format === "json")
33694
- return jsonResult(result);
33695
- return textResult3([
34049
+ return jsonResult2(result);
34050
+ return textResult4([
33696
34051
  `Initialized SupaCloud deployment in ${root}.`,
33697
34052
  `Created: ${created.join(", ")}.`,
33698
34053
  hasBuildScript ? `Detected package.json build script; deploy output defaults to ${outputDirectory}.` : "No package.json build script detected; add one before deploying.",
@@ -33724,7 +34079,7 @@ var deployToolSchema = {
33724
34079
  status: optional(String2({ format: "uuid" }), "Read a backend deployment status without publishing"),
33725
34080
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
33726
34081
  };
33727
- function record6(candidate) {
34082
+ function record7(candidate) {
33728
34083
  return candidate && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : null;
33729
34084
  }
33730
34085
  function requiredString(candidate, field) {
@@ -33734,7 +34089,7 @@ function requiredString(candidate, field) {
33734
34089
  return candidate.trim();
33735
34090
  }
33736
34091
  function frontendDeployment(candidate) {
33737
- const value = record6(candidate);
34092
+ const value = record7(candidate);
33738
34093
  if (!value)
33739
34094
  throw new Error("Invalid frontend deployment response");
33740
34095
  return {
@@ -33748,7 +34103,7 @@ function frontendDeployment(candidate) {
33748
34103
  }
33749
34104
  async function readJson(path) {
33750
34105
  try {
33751
- return JSON.parse(await readFile7(path, "utf8"));
34106
+ return JSON.parse(await readFile8(path, "utf8"));
33752
34107
  } catch (error) {
33753
34108
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
33754
34109
  return null;
@@ -33756,15 +34111,15 @@ async function readJson(path) {
33756
34111
  }
33757
34112
  }
33758
34113
  async function findDeployConfigRoot(startDirectory, environmentName) {
33759
- let directory = resolve26(startDirectory);
34114
+ let directory = resolve27(startDirectory);
33760
34115
  while (true) {
33761
34116
  const environmentFile = environmentName ? `.env.supacloud.${environmentName}` : null;
33762
- if (await pathExists(join19(directory, "supacloud.json")) || await pathExists(join19(directory, "supacloud.config.ts")) || environmentFile !== null && await pathExists(join19(directory, environmentFile))) {
34117
+ if (await pathExists(join20(directory, "supacloud.json")) || await pathExists(join20(directory, "supacloud.config.ts")) || environmentFile !== null && await pathExists(join20(directory, environmentFile))) {
33763
34118
  return directory;
33764
34119
  }
33765
34120
  const parent = dirname14(directory);
33766
34121
  if (parent === directory)
33767
- return resolve26(startDirectory);
34122
+ return resolve27(startDirectory);
33768
34123
  directory = parent;
33769
34124
  }
33770
34125
  }
@@ -33804,7 +34159,7 @@ function optionalStringArray(value, field) {
33804
34159
  });
33805
34160
  }
33806
34161
  function deployTargetConfig(candidate, name) {
33807
- const value = record6(candidate);
34162
+ const value = record7(candidate);
33808
34163
  if (!value || value.type !== "frontend" && value.type !== "edge_function") {
33809
34164
  throw new Error(`supacloud.json targets.${name}.type must be 'frontend' or 'edge_function'`);
33810
34165
  }
@@ -33829,14 +34184,14 @@ function deployTargetConfig(candidate, name) {
33829
34184
  };
33830
34185
  }
33831
34186
  async function readDeployConfig(configRoot) {
33832
- const configPath = join19(configRoot, "supacloud.json");
34187
+ const configPath = join20(configRoot, "supacloud.json");
33833
34188
  const candidate = await readJson(configPath);
33834
34189
  if (candidate === null)
33835
34190
  return {};
33836
- const config = record6(candidate);
33837
- const frontend = record6(config?.frontend);
33838
- const application = record6(config?.application);
33839
- const targetValues = record6(config?.targets);
34191
+ const config = record7(candidate);
34192
+ const frontend = record7(config?.frontend);
34193
+ const application = record7(config?.application);
34194
+ const targetValues = record7(config?.targets);
33840
34195
  if (!config || config.frontend !== undefined && !frontend || config.application !== undefined && !application || config.targets !== undefined && !targetValues) {
33841
34196
  throw new Error("supacloud.json must contain object-valued 'application', 'frontend' or 'targets' configuration");
33842
34197
  }
@@ -33876,16 +34231,16 @@ async function readDeployConfig(configRoot) {
33876
34231
  };
33877
34232
  }
33878
34233
  async function packageName(projectDirectory) {
33879
- const candidate = record6(await readJson(join19(projectDirectory, "package.json")));
34234
+ const candidate = record7(await readJson(join20(projectDirectory, "package.json")));
33880
34235
  return typeof candidate?.name === "string" && candidate.name.trim() ? candidate.name.trim() : null;
33881
34236
  }
33882
34237
  async function pathExists(path) {
33883
34238
  return access(path).then(() => true, () => false);
33884
34239
  }
33885
34240
  async function hasProjectReleaseManifest(root) {
33886
- if (await pathExists(join19(root, "deploy-manifest.json")))
34241
+ if (await pathExists(join20(root, "deploy-manifest.json")))
33887
34242
  return true;
33888
- const directory = await opendir(join19(root, "supacloud")).catch((error) => {
34243
+ const directory = await opendir(join20(root, "supacloud")).catch((error) => {
33889
34244
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
33890
34245
  return null;
33891
34246
  throw error;
@@ -33896,24 +34251,24 @@ async function hasProjectReleaseManifest(root) {
33896
34251
  for await (const entry of directory) {
33897
34252
  if (++entries > 128)
33898
34253
  throw new Error("Too many SupaCloud project roots to resolve a deployment");
33899
- if ((entry.isDirectory() || entry.isSymbolicLink()) && await pathExists(join19(root, "supacloud", entry.name, "deploy-manifest.json")))
34254
+ if ((entry.isDirectory() || entry.isSymbolicLink()) && await pathExists(join20(root, "supacloud", entry.name, "deploy-manifest.json")))
33900
34255
  return true;
33901
34256
  }
33902
34257
  return false;
33903
34258
  }
33904
34259
  async function defaultBuildCommand(projectDirectory, configRoot) {
33905
- const packageJson = record6(await readJson(join19(projectDirectory, "package.json")));
33906
- const scripts = record6(packageJson?.scripts);
34260
+ const packageJson = record7(await readJson(join20(projectDirectory, "package.json")));
34261
+ const scripts = record7(packageJson?.scripts);
33907
34262
  if (typeof scripts?.build !== "string" || !scripts.build.trim()) {
33908
34263
  throw new Error("No build command was configured and package.json has no build script");
33909
34264
  }
33910
34265
  let directory = projectDirectory;
33911
34266
  while (true) {
33912
- if (await pathExists(join19(directory, "bun.lock")) || await pathExists(join19(directory, "bun.lockb")))
34267
+ if (await pathExists(join20(directory, "bun.lock")) || await pathExists(join20(directory, "bun.lockb")))
33913
34268
  return "bun run build";
33914
- if (await pathExists(join19(directory, "pnpm-lock.yaml")))
34269
+ if (await pathExists(join20(directory, "pnpm-lock.yaml")))
33915
34270
  return "pnpm run build";
33916
- if (await pathExists(join19(directory, "yarn.lock")))
34271
+ if (await pathExists(join20(directory, "yarn.lock")))
33917
34272
  return "yarn build";
33918
34273
  if (directory === configRoot)
33919
34274
  break;
@@ -33925,7 +34280,7 @@ async function defaultBuildCommand(projectDirectory, configRoot) {
33925
34280
  return "npm run build";
33926
34281
  }
33927
34282
  function deploymentList(candidate) {
33928
- const values = Array.isArray(candidate) ? candidate : Array.isArray(record6(candidate)?.deployments) ? record6(candidate)?.deployments : null;
34283
+ const values = Array.isArray(candidate) ? candidate : Array.isArray(record7(candidate)?.deployments) ? record7(candidate)?.deployments : null;
33929
34284
  if (!values)
33930
34285
  throw new Error("Invalid frontend deployment list response");
33931
34286
  return values.map(frontendDeployment);
@@ -33985,9 +34340,9 @@ function selectFrontendTarget(configRoot, config) {
33985
34340
  throw new Error(`Multiple frontend deploy targets found (${targets.map(([name]) => name).sort().join(", ")}). Set defaultTarget to the Web target`);
33986
34341
  }
33987
34342
  function targetRoot(configRoot, target, name) {
33988
- const root = resolve26(configRoot, target.root || (name === "frontend" ? "." : name));
33989
- const prefix = `${resolve26(configRoot)}${sep5}`;
33990
- if (root !== resolve26(configRoot) && !root.startsWith(prefix)) {
34343
+ const root = resolve27(configRoot, target.root || (name === "frontend" ? "." : name));
34344
+ const prefix = `${resolve27(configRoot)}${sep5}`;
34345
+ if (root !== resolve27(configRoot) && !root.startsWith(prefix)) {
33991
34346
  throw new Error(`Deploy target '${name}' root must stay inside the repository root`);
33992
34347
  }
33993
34348
  return root;
@@ -34005,8 +34360,8 @@ function defaultOutputDirectory(framework) {
34005
34360
  }
34006
34361
  }
34007
34362
  function resolveInsideProject(projectDirectory, candidate, allowRoot = false) {
34008
- const resolved = resolve26(projectDirectory, candidate);
34009
- const projectRoot = resolve26(projectDirectory);
34363
+ const resolved = resolve27(projectDirectory, candidate);
34364
+ const projectRoot = resolve27(projectDirectory);
34010
34365
  const projectPrefix = `${projectRoot}${sep5}`;
34011
34366
  if (!allowRoot && resolved === projectRoot || resolved !== projectRoot && !resolved.startsWith(projectPrefix)) {
34012
34367
  throw new Error("Frontend output directory must stay inside the project directory");
@@ -34060,7 +34415,7 @@ async function collectArchiveFiles(root) {
34060
34415
  entries.push(entry);
34061
34416
  entries.sort((left, right) => left.name.localeCompare(right.name, "en"));
34062
34417
  for (const entry of entries) {
34063
- const path = join19(directory, entry.name);
34418
+ const path = join20(directory, entry.name);
34064
34419
  const stats = await lstat5(path);
34065
34420
  if (stats.isSymbolicLink())
34066
34421
  throw new Error(`Frontend output cannot contain symbolic links: ${path}`);
@@ -34079,7 +34434,7 @@ async function collectArchiveFiles(root) {
34079
34434
  const files = new Map;
34080
34435
  const digests = [];
34081
34436
  for (const path of paths) {
34082
- const data = new Uint8Array(await readFile7(path));
34437
+ const data = new Uint8Array(await readFile8(path));
34083
34438
  bytes += data.byteLength;
34084
34439
  if (bytes > MAX_SOURCE_BYTES)
34085
34440
  throw new Error(`Frontend output exceeds ${MAX_SOURCE_BYTES} bytes`);
@@ -34098,11 +34453,11 @@ async function collectArchiveFiles(root) {
34098
34453
  return { files, bytes, count: paths.length, treeSha256: tree.digest("hex") };
34099
34454
  }
34100
34455
  async function createCollectedFrontendArchive(outputDirectory, collected) {
34101
- const temporaryDirectory = await mkdtemp2(join19(tmpdir3(), "supacloud-deploy-"));
34102
- const archivePath = join19(temporaryDirectory, `${basename8(outputDirectory)}.tar.zst`);
34456
+ const temporaryDirectory = await mkdtemp2(join20(tmpdir3(), "supacloud-deploy-"));
34457
+ const archivePath = join20(temporaryDirectory, `${basename8(outputDirectory)}.tar.zst`);
34103
34458
  try {
34104
34459
  const archiveBytes = await createFrontendTarZstd(collected.files);
34105
- await writeFile7(archivePath, archiveBytes);
34460
+ await writeFile8(archivePath, archiveBytes);
34106
34461
  const sha256 = createHash11("sha256").update(archiveBytes).digest("hex");
34107
34462
  return {
34108
34463
  archivePath,
@@ -34147,7 +34502,7 @@ async function publishConfiguredFrontend(http, projectRef, configRoot, skipBuild
34147
34502
  }
34148
34503
  function registerDeployTools(server, http, options = {}) {
34149
34504
  registerTool(server, "deploy", "Build and publish the linked project with one command", deployToolSchema, async (args) => {
34150
- const invocationDirectory = resolve26(String(args.cwd || options.cwd || process.cwd()));
34505
+ const invocationDirectory = resolve27(String(args.cwd || options.cwd || process.cwd()));
34151
34506
  if (args.action === "init") {
34152
34507
  return initializeProject({
34153
34508
  ...typeof args.root === "string" ? { root: args.root } : {},
@@ -34228,11 +34583,11 @@ function registerDeployTools(server, http, options = {}) {
34228
34583
  }
34229
34584
 
34230
34585
  // src/shared/tools/remote-dev-tools.ts
34231
- import { existsSync as existsSync17 } from "node:fs";
34232
- import { readFile as readFile8 } from "node:fs/promises";
34586
+ import { existsSync as existsSync18 } from "node:fs";
34587
+ import { readFile as readFile9 } from "node:fs/promises";
34233
34588
  import { readdir as readdir8 } from "node:fs/promises";
34234
34589
  import { createHash as createHash12 } from "node:crypto";
34235
- import { join as join20, resolve as resolve27 } from "node:path";
34590
+ import { join as join21, resolve as resolve28 } from "node:path";
34236
34591
  import { compileProject as compileProject2 } from "@supacloud/compiler";
34237
34592
  var SAFE_TOKEN = /^[A-Za-z0-9._:@/+,-]+$/;
34238
34593
  var SAFE_REMOTE_ROOT = /^\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+\/?$/;
@@ -34260,13 +34615,13 @@ async function runProcess(executable, args, cwd) {
34260
34615
  return { exitCode: exitCode ?? 1, stdout, stderr };
34261
34616
  }
34262
34617
  async function readProjectConfig(root) {
34263
- const file = join20(root, "supacloud.json");
34264
- if (!existsSync17(file))
34618
+ const file = join21(root, "supacloud.json");
34619
+ if (!existsSync18(file))
34265
34620
  return {};
34266
34621
  try {
34267
- const parsed = JSON.parse(await readFile8(file, "utf8"));
34622
+ const parsed = JSON.parse(await readFile9(file, "utf8"));
34268
34623
  if (parsed && typeof parsed === "object" && "dev" in parsed && parsed.dev && typeof parsed.dev === "object" && "database" in parsed.dev) {
34269
- throw new Error("dev.database was removed; use supacloud-model diff and db plan/apply");
34624
+ throw new Error("dev.database was removed; use db:plan/db:apply through the Management API");
34270
34625
  }
34271
34626
  return parsed && typeof parsed === "object" ? parsed : {};
34272
34627
  } catch (error) {
@@ -34282,7 +34637,7 @@ async function sourceFingerprint(root) {
34282
34637
  const visit = async (directory) => {
34283
34638
  const entries = await readdir8(directory, { withFileTypes: true });
34284
34639
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
34285
- const path = join20(directory, entry.name);
34640
+ const path = join21(directory, entry.name);
34286
34641
  if (entry.isDirectory() && ![".git", "node_modules", "dist", "generated", ".supacloud"].includes(entry.name))
34287
34642
  await visit(path);
34288
34643
  else if (entry.isFile())
@@ -34293,7 +34648,7 @@ async function sourceFingerprint(root) {
34293
34648
  const hash = createHash12("sha256");
34294
34649
  for (const file of files) {
34295
34650
  hash.update(file.slice(root.length).replace(/\\/g, "/"));
34296
- hash.update(await readFile8(file));
34651
+ hash.update(await readFile9(file));
34297
34652
  }
34298
34653
  return hash.digest("hex");
34299
34654
  }
@@ -34310,19 +34665,19 @@ function remoteRoot(value) {
34310
34665
  }
34311
34666
  function targetDirectory(root, target, functionSlug, config = {}) {
34312
34667
  if (target === "db")
34313
- return join20(root, "supabase", "migrations");
34668
+ return join21(root, "supabase", "migrations");
34314
34669
  if (target === "functions") {
34315
34670
  const targets = config["targets"];
34316
34671
  const entries = targets && typeof targets === "object" ? Object.values(targets) : [];
34317
34672
  const match = entries.find((entry) => entry !== null && typeof entry === "object" && ("type" in entry) && entry.type === "edge_function" && (!("root" in entry) || typeof entry.root === "string") && (!("slug" in entry) || typeof entry.slug === "string") && (!functionSlug || ("slug" in entry) && entry.slug === functionSlug));
34318
- const base = match?.root ? resolve27(root, match.root) : join20(root, "supabase", "functions");
34319
- return match?.root ? base : functionSlug ? join20(base, safeToken(functionSlug, "function")) : base;
34673
+ const base = match?.root ? resolve28(root, match.root) : join21(root, "supabase", "functions");
34674
+ return match?.root ? base : functionSlug ? join21(base, safeToken(functionSlug, "function")) : base;
34320
34675
  }
34321
34676
  if (target === "frontend") {
34322
34677
  const targets = config["targets"];
34323
34678
  const entries = targets && typeof targets === "object" ? Object.values(targets) : [];
34324
34679
  const match = entries.find((entry) => entry !== null && typeof entry === "object" && ("type" in entry) && entry.type === "frontend" && (!("root" in entry) || typeof entry.root === "string"));
34325
- return match?.root ? resolve27(root, match.root) : join20(root, "apps", "web");
34680
+ return match?.root ? resolve28(root, match.root) : join21(root, "apps", "web");
34326
34681
  }
34327
34682
  return root;
34328
34683
  }
@@ -34361,10 +34716,10 @@ function reloadCommand(config, target, projectRef, functionSlug) {
34361
34716
  return [...command.split(" "), "--project-ref", safeToken(projectRef || "test", "project_ref"), "--target", targetConfigPath(target), ...functionSlug ? ["--function", safeToken(functionSlug, "function")] : []];
34362
34717
  }
34363
34718
  function sshArgs(connection, remoteCommand) {
34364
- return ["-p", String(connection.port), "-i", resolve27(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
34719
+ return ["-p", String(connection.port), "-i", resolve28(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
34365
34720
  }
34366
34721
  function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
34367
- const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve27(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
34722
+ const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve28(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
34368
34723
  if (deleteRemote)
34369
34724
  args.push("--delete-delay");
34370
34725
  for (const exclude of excludes) {
@@ -34376,17 +34731,17 @@ function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
34376
34731
  return args;
34377
34732
  }
34378
34733
  async function syncOnce(args, options) {
34379
- const root = resolve27(String(args.project_dir || options.cwd || process.cwd()));
34734
+ const root = resolve28(String(args.project_dir || options.cwd || process.cwd()));
34380
34735
  const projectConfig = await readProjectConfig(root);
34381
34736
  const config = projectConfig.dev || {};
34382
34737
  const target = String(args.target || "project");
34383
34738
  const source = targetDirectory(root, target, typeof args.function === "string" ? args.function : undefined, projectConfig);
34384
- if (!existsSync17(source))
34739
+ if (!existsSync18(source))
34385
34740
  throw new Error(`Dev source directory not found: ${source}`);
34386
34741
  let compiled = false;
34387
34742
  if (config.compile === true && target !== "db") {
34388
- const compileRoot = resolve27(root, config.compileRoot || ".");
34389
- const compileOutDir = resolve27(root, config.compileOutDir || "generated");
34743
+ const compileRoot = resolve28(root, config.compileRoot || ".");
34744
+ const compileOutDir = resolve28(root, config.compileOutDir || "generated");
34390
34745
  const compilation = await compileProject2({
34391
34746
  rootDir: compileRoot,
34392
34747
  outDir: compileOutDir,
@@ -34424,7 +34779,7 @@ function registerRemoteDevTools(server, options = {}) {
34424
34779
  if (["production", "prod"].includes((options.environment || "").toLowerCase()))
34425
34780
  throw new Error("Remote dev mode is forbidden for production environments");
34426
34781
  if (args.action === "status") {
34427
- const root = resolve27(String(args.project_dir || options.cwd || process.cwd()));
34782
+ const root = resolve28(String(args.project_dir || options.cwd || process.cwd()));
34428
34783
  const config = await readDevConfig(root);
34429
34784
  const connection = connectionArgs(options, config, args);
34430
34785
  const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
@@ -34435,7 +34790,7 @@ function registerRemoteDevTools(server, options = {}) {
34435
34790
  return { content: [{ type: "text", text: JSON.stringify(await syncOnce(args, options), null, 2) }] };
34436
34791
  }
34437
34792
  if (args.action === "watch") {
34438
- const root = resolve27(String(args.project_dir || options.cwd || process.cwd()));
34793
+ const root = resolve28(String(args.project_dir || options.cwd || process.cwd()));
34439
34794
  const interval = Math.max(100, Math.min(1e4, Number(args.interval_ms || 300)));
34440
34795
  let fingerprint = "";
34441
34796
  let lastSync = null;
@@ -34455,15 +34810,15 @@ function registerRemoteDevTools(server, options = {}) {
34455
34810
  }
34456
34811
 
34457
34812
  // src/shared/tools/developer-experience-tools.ts
34458
- import { existsSync as existsSync18 } from "node:fs";
34459
- import { mkdir as mkdir8, readdir as readdir9, readFile as readFile9, writeFile as writeFile8 } from "node:fs/promises";
34460
- import { dirname as dirname15, join as join21, resolve as resolve28 } from "node:path";
34813
+ import { existsSync as existsSync19 } from "node:fs";
34814
+ import { mkdir as mkdir9, readdir as readdir9, readFile as readFile10, writeFile as writeFile9 } from "node:fs/promises";
34815
+ import { dirname as dirname15, join as join22, resolve as resolve29 } from "node:path";
34461
34816
  var initToolSchema2 = {
34462
34817
  root: optional(String2(), "Project directory to initialize (default: current directory)"),
34463
34818
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
34464
34819
  };
34465
34820
  var environmentToolSchema2 = {
34466
- action: withDescription(stringEnum2(["list", "check"]), "Environment profile inspection action"),
34821
+ ...environmentSyncSchema,
34467
34822
  root: optional(String2(), "Project directory containing .env.supacloud.* files"),
34468
34823
  format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
34469
34824
  };
@@ -34485,13 +34840,13 @@ var PRODUCTION_PROFILE2 = [
34485
34840
  ""
34486
34841
  ].join(`
34487
34842
  `);
34488
- function textResult4(text, isError = false) {
34843
+ function textResult5(text, isError = false) {
34489
34844
  return { isError, content: [{ type: "text", text }] };
34490
34845
  }
34491
- function jsonResult2(value, isError = false) {
34492
- return textResult4(JSON.stringify(value, null, 2), isError);
34846
+ function jsonResult3(value, isError = false) {
34847
+ return textResult5(JSON.stringify(value, null, 2), isError);
34493
34848
  }
34494
- function record7(value) {
34849
+ function record8(value) {
34495
34850
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
34496
34851
  }
34497
34852
  function packageDependencies2(manifest) {
@@ -34509,17 +34864,17 @@ function outputDirectoryFor2(manifest) {
34509
34864
  return "dist";
34510
34865
  }
34511
34866
  async function readPackageManifest2(root) {
34512
- const path = join21(root, "package.json");
34513
- if (!existsSync18(path))
34867
+ const path = join22(root, "package.json");
34868
+ if (!existsSync19(path))
34514
34869
  return {};
34515
34870
  try {
34516
- const parsed = JSON.parse(await readFile9(path, "utf8"));
34517
- const value = record7(parsed);
34871
+ const parsed = JSON.parse(await readFile10(path, "utf8"));
34872
+ const value = record8(parsed);
34518
34873
  if (!value)
34519
34874
  throw new Error("package.json must contain an object");
34520
- const scripts = record7(value.scripts);
34521
- const dependencies = record7(value.dependencies);
34522
- const devDependencies = record7(value.devDependencies);
34875
+ const scripts = record8(value.scripts);
34876
+ const dependencies = record8(value.dependencies);
34877
+ const devDependencies = record8(value.devDependencies);
34523
34878
  return {
34524
34879
  scripts: scripts ?? undefined,
34525
34880
  dependencies: dependencies ?? undefined,
@@ -34531,7 +34886,7 @@ async function readPackageManifest2(root) {
34531
34886
  }
34532
34887
  async function writeNewFile2(path, content) {
34533
34888
  try {
34534
- await writeFile8(path, content, { encoding: "utf8", flag: "wx", mode: 384 });
34889
+ await writeFile9(path, content, { encoding: "utf8", flag: "wx", mode: 384 });
34535
34890
  return true;
34536
34891
  } catch (error) {
34537
34892
  if (error instanceof Error && "code" in error && error.code === "EEXIST")
@@ -34540,8 +34895,8 @@ async function writeNewFile2(path, content) {
34540
34895
  }
34541
34896
  }
34542
34897
  async function ensureGitignore2(root) {
34543
- const path = join21(root, ".gitignore");
34544
- const existing = existsSync18(path) ? await readFile9(path, "utf8") : "";
34898
+ const path = join22(root, ".gitignore");
34899
+ const existing = existsSync19(path) ? await readFile10(path, "utf8") : "";
34545
34900
  const required = [".env.supacloud.*", "!.env.supacloud.*.example"];
34546
34901
  const missing = required.filter((entry) => !existing.split(/\r?\n/).includes(entry));
34547
34902
  if (missing.length === 0)
@@ -34549,16 +34904,16 @@ async function ensureGitignore2(root) {
34549
34904
  const prefix = existing.length > 0 && !existing.endsWith(`
34550
34905
  `) ? `${existing}
34551
34906
  ` : existing;
34552
- await writeFile8(path, `${prefix}${missing.join(`
34907
+ await writeFile9(path, `${prefix}${missing.join(`
34553
34908
  `)}
34554
34909
  `, "utf8");
34555
34910
  return true;
34556
34911
  }
34557
34912
  async function initializeProject2(request, options = {}) {
34558
- const root = resolve28(request.root || options.cwd || process.cwd());
34559
- await mkdir8(root, { recursive: true });
34560
- const configPath = join21(root, "supacloud.json");
34561
- if (existsSync18(configPath)) {
34913
+ const root = resolve29(request.root || options.cwd || process.cwd());
34914
+ await mkdir9(root, { recursive: true });
34915
+ const configPath = join22(root, "supacloud.json");
34916
+ if (existsSync19(configPath)) {
34562
34917
  throw new Error(`supacloud.json already exists in ${root}; init never overwrites project configuration`);
34563
34918
  }
34564
34919
  const manifest = await readPackageManifest2(root);
@@ -34572,7 +34927,7 @@ async function initializeProject2(request, options = {}) {
34572
34927
  };
34573
34928
  const created = [];
34574
34929
  try {
34575
- await writeFile8(configPath, `${JSON.stringify(config, null, 2)}
34930
+ await writeFile9(configPath, `${JSON.stringify(config, null, 2)}
34576
34931
  `, {
34577
34932
  encoding: "utf8",
34578
34933
  flag: "wx",
@@ -34585,10 +34940,10 @@ async function initializeProject2(request, options = {}) {
34585
34940
  throw error;
34586
34941
  }
34587
34942
  created.push("supacloud.json");
34588
- if (await writeNewFile2(join21(root, ".env.supacloud.test.example"), TEST_PROFILE2)) {
34943
+ if (await writeNewFile2(join22(root, ".env.supacloud.test.example"), TEST_PROFILE2)) {
34589
34944
  created.push(".env.supacloud.test.example");
34590
34945
  }
34591
- if (await writeNewFile2(join21(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE2)) {
34946
+ if (await writeNewFile2(join22(root, ".env.supacloud.production.example"), PRODUCTION_PROFILE2)) {
34592
34947
  created.push(".env.supacloud.production.example");
34593
34948
  }
34594
34949
  if (await ensureGitignore2(root))
@@ -34599,7 +34954,7 @@ async function initializeProject2(request, options = {}) {
34599
34954
  root,
34600
34955
  created,
34601
34956
  detected: {
34602
- package_json: existsSync18(join21(root, "package.json")),
34957
+ package_json: existsSync19(join22(root, "package.json")),
34603
34958
  build_script: hasBuildScript,
34604
34959
  output_directory: outputDirectory
34605
34960
  },
@@ -34611,8 +34966,8 @@ async function initializeProject2(request, options = {}) {
34611
34966
  ]
34612
34967
  };
34613
34968
  if (request.format === "json")
34614
- return jsonResult2(result);
34615
- return textResult4([
34969
+ return jsonResult3(result);
34970
+ return textResult5([
34616
34971
  `Initialized SupaCloud deployment in ${root}.`,
34617
34972
  `Created: ${created.join(", ")}.`,
34618
34973
  hasBuildScript ? `Detected package.json build script; deploy output defaults to ${outputDirectory}.` : "No package.json build script detected; add one before deploying.",
@@ -34633,7 +34988,7 @@ async function environmentProfiles(root) {
34633
34988
  });
34634
34989
  return entries.filter((entry) => entry.isFile()).map((entry) => {
34635
34990
  const name = profileNameFromFile(entry.name);
34636
- return name ? { name, path: join21(root, entry.name), exists: true } : null;
34991
+ return name ? { name, path: join22(root, entry.name), exists: true } : null;
34637
34992
  }).filter((profile) => profile !== null).sort((left, right) => left.name.localeCompare(right.name));
34638
34993
  }
34639
34994
  function statusMissing(context) {
@@ -34672,14 +35027,14 @@ async function inspectProfile(profile) {
34672
35027
  environmentName: profile.name
34673
35028
  });
34674
35029
  const status = statusMissing(context);
34675
- const configText = await readFile9(join21(dirname15(profile.path), "supacloud.json"), "utf8").catch((error) => {
35030
+ const configText = await readFile10(join22(dirname15(profile.path), "supacloud.json"), "utf8").catch((error) => {
34676
35031
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
34677
35032
  return "{}";
34678
35033
  throw error;
34679
35034
  });
34680
- const config = record7(JSON.parse(configText));
34681
- const hasFrontend = record7(config?.frontend) !== null || Object.values(record7(config?.targets) ?? {}).some((target) => record7(target)?.type === "frontend");
34682
- const deploy = deployMissing(context, record7(config?.application), hasFrontend);
35035
+ const config = record8(JSON.parse(configText));
35036
+ const hasFrontend = record8(config?.frontend) !== null || Object.values(record8(config?.targets) ?? {}).some((target) => record8(target)?.type === "frontend");
35037
+ const deploy = deployMissing(context, record8(config?.application), hasFrontend);
34683
35038
  return {
34684
35039
  name: profile.name,
34685
35040
  path: profile.path,
@@ -34716,7 +35071,7 @@ async function inspectProfile(profile) {
34716
35071
  }
34717
35072
  }
34718
35073
  async function inspectEnvironment(request, options) {
34719
- const root = resolve28(request.root || options.cwd || process.cwd());
35074
+ const root = resolve29(request.root || options.cwd || process.cwd());
34720
35075
  const profiles = await environmentProfiles(root);
34721
35076
  if (request.action === "list") {
34722
35077
  const active = options.activeContext?.environment || null;
@@ -34732,12 +35087,12 @@ async function inspectEnvironment(request, options) {
34732
35087
  }))
34733
35088
  };
34734
35089
  if (request.format === "json")
34735
- return jsonResult2(result);
35090
+ return jsonResult3(result);
34736
35091
  if (profiles.length === 0) {
34737
- return textResult4(`No .env.supacloud.<name> profiles found in ${root}.
35092
+ return textResult5(`No .env.supacloud.<name> profiles found in ${root}.
34738
35093
  Run \`supacloud deploy init\` to create safe examples.`);
34739
35094
  }
34740
- return textResult4([
35095
+ return textResult5([
34741
35096
  `Environment profiles in ${root}:`,
34742
35097
  ...result.environments.map((profile) => `${profile.active ? "*" : " "} ${profile.name} ${profile.path}`)
34743
35098
  ].join(`
@@ -34752,9 +35107,9 @@ Run \`supacloud deploy init\` to create safe examples.`);
34752
35107
  environments: reports
34753
35108
  };
34754
35109
  if (request.format === "json")
34755
- return jsonResult2(result, !result.ok);
35110
+ return jsonResult3(result, !result.ok);
34756
35111
  if (reports.length === 0) {
34757
- return textResult4(`No environment profiles found in ${root}.
35112
+ return textResult5(`No environment profiles found in ${root}.
34758
35113
  Run \`supacloud deploy init\` and copy an example profile.`, true);
34759
35114
  }
34760
35115
  const lines = reports.map((report) => {
@@ -34765,11 +35120,384 @@ Run \`supacloud deploy init\` and copy an example profile.`, true);
34765
35120
  const ref = report.projectRef ? `project=${report.projectRef}` : "project=unknown";
34766
35121
  return `${status} ${report.name} ${deploy} ${ref}`;
34767
35122
  });
34768
- return textResult4(lines.join(`
35123
+ return textResult5(lines.join(`
34769
35124
  `), !result.ok);
34770
35125
  }
34771
35126
  function registerDeveloperExperienceTools(server, options = {}) {
34772
- registerTool(server, "env", "List or locally validate named SupaCloud environment profiles without contacting the platform or printing secrets.", environmentToolSchema2, (request) => inspectEnvironment(request, options));
35127
+ registerTool(server, "env", "List or locally validate named SupaCloud environment profiles without contacting the platform or printing secrets.", environmentToolSchema2, (request) => {
35128
+ const input = request;
35129
+ if (input.action === "sync")
35130
+ return syncEnvironmentProfile(input, options);
35131
+ return inspectEnvironment(input, options);
35132
+ });
35133
+ }
35134
+
35135
+ // src/shared/tools/configuration-tools.ts
35136
+ import { existsSync as existsSync20 } from "node:fs";
35137
+ import { mkdir as mkdir10, readFile as readFile11, writeFile as writeFile10 } from "node:fs/promises";
35138
+ import { join as join23, resolve as resolve30 } from "node:path";
35139
+ var MANAGEMENT_CONFIGURATION_KEYS = ["SUPACLOUD_API_URL", "SUPACLOUD_API_TOKEN", "SUPACLOUD_PROJECT_REF"];
35140
+ var APPLICATION_CONFIGURATION_KEYS = ["SUPABASE_URL", "SUPABASE_SERVICE_ROLE_KEY", "SUPACLOUD_PROJECT_REF"];
35141
+ var onboardToolSchema2 = {
35142
+ root: optional(String2(), "Repository or configuration root (default: current directory)"),
35143
+ profile: optional(stringEnum2(["solo", "podman", "pigsty", "cluster"]), "Deployment profile (default: solo)"),
35144
+ domain: optional(String2(), "Public API domain; studio domain is derived from it"),
35145
+ database: optional(stringEnum2(["local", "external"]), "Database provider (default: local)"),
35146
+ storage: optional(stringEnum2(["juicefs", "external"]), "Storage provider (default: juicefs)"),
35147
+ write: optional(Boolean2(), "Write the generated context into supacloud.json"),
35148
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
35149
+ };
35150
+ var configurationToolSchema2 = {
35151
+ action: withDescription(stringEnum2(["doctor", "explain"]), "Configuration inspection action"),
35152
+ root: optional(String2(), "Repository or configuration root (default: current directory)"),
35153
+ key: optional(String2(), "[explain] Environment variable name"),
35154
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
35155
+ };
35156
+ var environmentSyncSchema2 = {
35157
+ action: withDescription(stringEnum2(["list", "check", "sync"]), "Environment profile action"),
35158
+ root: optional(String2(), "Project directory containing .env.supacloud.* files"),
35159
+ environment: optional(String2(), "[sync] Profile name; defaults to the selected environment"),
35160
+ write: optional(Boolean2(), "[sync] Persist derived context and the reduced profile example"),
35161
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
35162
+ };
35163
+ var SECRET_KEY2 = /(?:PASSWORD|PASS|SECRET|TOKEN|PRIVATE|CREDENTIAL|AUTHORIZATION|COOKIE|SESSION|DATABASE_URL|CONNECTION_STRING|DSN)/i;
35164
+ var PLATFORM_KEY2 = /^(?:SUPACLOUD|SUPABASE)_(?:API|PROJECT|ENV|HOST|SSH|APPLICATION|SERVICE_ROLE|ACCESS|URL|READ_ONLY|TLS|ANON|PUBLISHABLE)/;
35165
+ function textResult6(text, isError = false) {
35166
+ return { isError, content: [{ type: "text", text }] };
35167
+ }
35168
+ function jsonResult4(value, isError = false) {
35169
+ return textResult6(JSON.stringify(value, null, 2), isError);
35170
+ }
35171
+ function record9(value) {
35172
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
35173
+ }
35174
+ function unquote2(value) {
35175
+ const trimmed = value.trim();
35176
+ if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
35177
+ return trimmed.slice(1, -1);
35178
+ }
35179
+ return trimmed;
35180
+ }
35181
+ function parseEnvironment2(content) {
35182
+ const values = {};
35183
+ for (const rawLine of content.split(/\r?\n/)) {
35184
+ const line = rawLine.trim();
35185
+ if (!line || line.startsWith("#"))
35186
+ continue;
35187
+ const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
35188
+ if (match)
35189
+ values[match[1]] = unquote2(match[2]);
35190
+ }
35191
+ return values;
35192
+ }
35193
+ async function readJsonObject2(path) {
35194
+ if (!existsSync20(path))
35195
+ return {};
35196
+ const parsed = JSON.parse(await readFile11(path, "utf8"));
35197
+ const value = record9(parsed);
35198
+ if (!value)
35199
+ throw new Error(`${path} must contain a JSON object`);
35200
+ return value;
35201
+ }
35202
+ async function writeJsonObject2(path, value) {
35203
+ await writeFile10(path, `${JSON.stringify(value, null, 2)}
35204
+ `, { encoding: "utf8", mode: 420 });
35205
+ }
35206
+ function contextFromConfig2(config) {
35207
+ const context = record9(config.context);
35208
+ return context ?? {};
35209
+ }
35210
+ function environmentContext2(config, environment) {
35211
+ const context = contextFromConfig2(config);
35212
+ const environments = record9(context.environments);
35213
+ const selected = environments ? record9(environments[environment]) : null;
35214
+ return selected ?? {};
35215
+ }
35216
+ function derivedValues(values) {
35217
+ const derived = {};
35218
+ const publicDomain = values.SUPABASE_PUBLIC_DOMAIN?.trim();
35219
+ if (publicDomain && !values.SUPABASE_STUDIO_DOMAIN) {
35220
+ derived.SUPABASE_STUDIO_DOMAIN = `studio.${publicDomain.replace(/^api\./, "")}`;
35221
+ }
35222
+ if (publicDomain && !values.SUPABASE_PUBLIC_URL) {
35223
+ derived.SUPABASE_PUBLIC_URL = `https://${publicDomain}`;
35224
+ }
35225
+ const host = values.SUPACLOUD_HOST?.trim();
35226
+ if (host && !values.SUPACLOUD_API_URL) {
35227
+ derived.SUPACLOUD_API_URL = `http://${host}:9090`;
35228
+ }
35229
+ if (values.SUPACLOUD_DEPLOYMENT_PROFILE === undefined) {
35230
+ derived.SUPACLOUD_DEPLOYMENT_PROFILE = "solo";
35231
+ }
35232
+ if (!values.S3_STORAGE_TYPE)
35233
+ derived.S3_STORAGE_TYPE = "juicefs";
35234
+ return derived;
35235
+ }
35236
+ function classify(name, value) {
35237
+ if (SECRET_KEY2.test(name))
35238
+ return "secret";
35239
+ if (PLATFORM_KEY2.test(name))
35240
+ return "platform";
35241
+ if (value === undefined || value === "")
35242
+ return "default";
35243
+ return "override";
35244
+ }
35245
+ function configurationEntries(values) {
35246
+ const derived = derivedValues(values);
35247
+ const names = [...new Set([...Object.keys(values), ...Object.keys(derived)])].sort();
35248
+ return names.map((name) => {
35249
+ const value = values[name] ?? derived[name];
35250
+ const kind = derived[name] !== undefined && values[name] === undefined ? "derived" : classify(name, values[name]);
35251
+ return {
35252
+ name,
35253
+ kind,
35254
+ source: kind === "derived" ? "platform-default" : values[name] === undefined ? "absent" : "profile",
35255
+ configured: value !== undefined && value !== "",
35256
+ value: kind === "secret" ? value ? "********" : null : value ?? null
35257
+ };
35258
+ });
35259
+ }
35260
+ function requiredConfigurationKeys(activeContext) {
35261
+ return activeContext?.credentialScope === "project_application" ? APPLICATION_CONFIGURATION_KEYS : MANAGEMENT_CONFIGURATION_KEYS;
35262
+ }
35263
+ function onboardingPlan(args, root) {
35264
+ const profile = typeof args.profile === "string" ? args.profile : "solo";
35265
+ const database = typeof args.database === "string" ? args.database : "local";
35266
+ const storage = typeof args.storage === "string" ? args.storage : "juicefs";
35267
+ const domain = typeof args.domain === "string" && args.domain.trim() ? args.domain.trim() : null;
35268
+ const required = ["profile"];
35269
+ if (domain === null)
35270
+ required.push("public_domain_or_explicit_ip");
35271
+ if (database === "external")
35272
+ required.push("database_url");
35273
+ if (storage === "external")
35274
+ required.push("s3_endpoint_and_credentials");
35275
+ return {
35276
+ schema: "supacloud.onboarding-plan.v1",
35277
+ root,
35278
+ profile,
35279
+ domain,
35280
+ database,
35281
+ storage,
35282
+ required_inputs: required,
35283
+ derived: {
35284
+ studio_domain: domain ? `studio.${domain.replace(/^api\./, "")}` : null,
35285
+ storage_backend: storage === "juicefs" ? "postgresql-large-object" : "external-s3",
35286
+ internal_service_urls: "allocated by the selected deployment profile",
35287
+ component_versions: "read from the verified release manifest"
35288
+ },
35289
+ writes: ["supacloud.json context metadata"],
35290
+ safety: [
35291
+ "unknown local PostgreSQL is never adopted automatically",
35292
+ "secret values are generated or injected and never printed",
35293
+ "external providers are requested only when selected"
35294
+ ]
35295
+ };
35296
+ }
35297
+ async function runOnboard(args, options) {
35298
+ const root = resolve30(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35299
+ const plan = onboardingPlan(args, root);
35300
+ if (args.write === true) {
35301
+ await mkdir10(root, { recursive: true });
35302
+ const path = join23(root, "supacloud.json");
35303
+ const config = await readJsonObject2(path);
35304
+ if (existsSync20(path) && config.context !== undefined) {
35305
+ throw new Error("supacloud.json already has context metadata; use env sync to update one environment");
35306
+ }
35307
+ config.context = {
35308
+ default_environment: "test",
35309
+ deployment_profile: plan.profile,
35310
+ public_domain: plan.domain,
35311
+ database: plan.database,
35312
+ storage: plan.storage,
35313
+ environments: {}
35314
+ };
35315
+ await writeJsonObject2(path, config);
35316
+ return jsonResult4({ ...plan, ok: true, written: path });
35317
+ }
35318
+ return args.format === "json" ? jsonResult4({ ...plan, ok: true, written: false }) : textResult6([
35319
+ "SupaCloud onboarding plan",
35320
+ `profile: ${String(plan.profile)}`,
35321
+ `database: ${String(plan.database)}`,
35322
+ `storage: ${String(plan.storage)}`,
35323
+ `domain: ${plan.domain ?? "(required)"}`,
35324
+ "",
35325
+ "No files were changed. Re-run with --write after reviewing the plan."
35326
+ ].join(`
35327
+ `));
35328
+ }
35329
+ async function runConfiguration(args, options) {
35330
+ const root = resolve30(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35331
+ const config = await readJsonObject2(join23(root, "supacloud.json"));
35332
+ const environment = options.activeContext?.environment || "";
35333
+ const profileValues = environment && existsSync20(join23(root, `.env.supacloud.${environment}`)) ? parseEnvironment2(await readFile11(join23(root, `.env.supacloud.${environment}`), "utf8")) : {};
35334
+ const metadata = environment ? environmentContext2(config, environment) : {};
35335
+ const values = {
35336
+ ...Object.fromEntries(Object.entries(metadata).filter(([, value]) => typeof value === "string")),
35337
+ ...profileValues
35338
+ };
35339
+ const entries = configurationEntries(Object.fromEntries([
35340
+ ...Object.entries(values),
35341
+ ...requiredConfigurationKeys(options.activeContext).map((name) => [name, values[name] ?? ""])
35342
+ ]));
35343
+ if (args.action === "explain") {
35344
+ const key = typeof args.key === "string" ? args.key.trim() : "";
35345
+ const selected = key ? entries.filter((entry) => entry.name === key) : entries;
35346
+ return jsonResult4({ schema: "supacloud.configuration.explain.v1", root, environment: environment || null, entries: selected });
35347
+ }
35348
+ const missing = entries.filter((entry) => entry.configured === false).map((entry) => entry.name);
35349
+ const secrets = entries.filter((entry) => entry.kind === "secret").map((entry) => entry.name);
35350
+ const result = {
35351
+ schema: "supacloud.configuration.doctor.v1",
35352
+ root,
35353
+ environment: environment || null,
35354
+ ok: missing.length === 0,
35355
+ missing,
35356
+ secret_names: secrets,
35357
+ entries,
35358
+ next: missing.length ? ["supacloud config explain"] : ["supacloud env sync --env test --write"]
35359
+ };
35360
+ return args.format === "json" ? jsonResult4(result, !result.ok) : textResult6([
35361
+ `Configuration: ${result.ok ? "OK" : "BLOCKED"}`,
35362
+ `environment: ${environment || "(none selected)"}`,
35363
+ missing.length ? `missing: ${missing.join(", ")}` : "missing: none",
35364
+ secrets.length ? `secrets: ${secrets.join(", ")}` : "secrets: none"
35365
+ ].join(`
35366
+ `), !result.ok);
35367
+ }
35368
+ function registerConfigurationTools(server, options = {}) {
35369
+ registerTool(server, "onboard", "Preview or write a minimal SupaCloud onboarding plan.", onboardToolSchema2, (args) => runOnboard(args, options));
35370
+ registerTool(server, "config", "Inspect configuration sources, derived values and missing inputs.", configurationToolSchema2, (args) => runConfiguration(args, options));
35371
+ }
35372
+
35373
+ // src/shared/tools/pipeline-tools.ts
35374
+ import { existsSync as existsSync21 } from "node:fs";
35375
+ import { mkdir as mkdir11, readFile as readFile12, writeFile as writeFile11 } from "node:fs/promises";
35376
+ import { join as join24, resolve as resolve31 } from "node:path";
35377
+ var pipelineToolSchema = {
35378
+ action: withDescription(stringEnum2(["connect"]), "Pipeline configuration action"),
35379
+ provider: optional(stringEnum2(["github", "gitlab"]), "[connect] Git provider (default: github)"),
35380
+ root: optional(String2(), "[connect] Repository root (default: current directory)"),
35381
+ write: optional(Boolean2(), "[connect] Write the generated workflow"),
35382
+ preview: optional(Boolean2(), "[connect] Include pull request Preview lifecycle"),
35383
+ format: optional(stringEnum2(["text", "json"]), "Output format (default: text)")
35384
+ };
35385
+ function textResult7(text, isError = false) {
35386
+ return { isError, content: [{ type: "text", text }] };
35387
+ }
35388
+ function jsonResult5(value, isError = false) {
35389
+ return textResult7(JSON.stringify(value, null, 2), isError);
35390
+ }
35391
+ function record10(value) {
35392
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
35393
+ }
35394
+ async function readJson2(path) {
35395
+ if (!existsSync21(path))
35396
+ return {};
35397
+ const parsed = JSON.parse(await readFile12(path, "utf8"));
35398
+ return record10(parsed) ?? {};
35399
+ }
35400
+ function workflow(provider, preview) {
35401
+ if (provider !== "github") {
35402
+ return [
35403
+ "stages:",
35404
+ " - deploy",
35405
+ "",
35406
+ "supacloud_deploy:",
35407
+ " stage: deploy",
35408
+ " image: node:24",
35409
+ " rules:",
35410
+ " - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'",
35411
+ " variables:",
35412
+ " SUPACLOUD_API_URL: $SUPACLOUD_API_URL",
35413
+ " SUPACLOUD_API_TOKEN: $SUPACLOUD_DEPLOY_TOKEN",
35414
+ " SUPACLOUD_PROJECT_REF: $SUPACLOUD_PROJECT_REF",
35415
+ " script:",
35416
+ " - npx @supacloud/cli deploy",
35417
+ ""
35418
+ ].join(`
35419
+ `);
35420
+ }
35421
+ const events = preview ? ` push:
35422
+ branches: [main]
35423
+ pull_request:
35424
+ types: [opened, synchronize, reopened, closed]` : ` push:
35425
+ branches: [main]`;
35426
+ const previewSteps = preview ? [
35427
+ " - name: Provision or reclaim PR Preview",
35428
+ " if: ${{ github.event_name == 'pull_request' }}",
35429
+ " env:",
35430
+ " SUPACLOUD_API_TOKEN: ${{ secrets.SUPACLOUD_DEPLOY_TOKEN }}",
35431
+ " SUPACLOUD_API_URL: ${{ secrets.SUPACLOUD_API_URL }}",
35432
+ " SUPACLOUD_PROJECT_REF: ${{ secrets.SUPACLOUD_PROJECT_REF }}",
35433
+ " run: >-",
35434
+ " npx @supacloud/cli --env test app preview-pr",
35435
+ " --id ${{ vars.SUPACLOUD_APPLICATION_ID }}",
35436
+ " --environment_id ${{ vars.SUPACLOUD_ENVIRONMENT_ID }}",
35437
+ " --pull_request_action ${{ github.event.action == 'closed' && 'closed' || 'opened' }}",
35438
+ " --repository ${{ github.repository }}",
35439
+ " --pull_request_number ${{ github.event.pull_request.number }}",
35440
+ " --release_id ${{ vars.SUPACLOUD_RELEASE_ID }}"
35441
+ ].join(`
35442
+ `) : "";
35443
+ return `name: SupaCloud deploy
35444
+
35445
+ on:
35446
+ ${events}
35447
+
35448
+ jobs:
35449
+ deploy:
35450
+ runs-on: ubuntu-latest
35451
+ steps:
35452
+ - uses: actions/checkout@v4
35453
+ - name: Deploy to SupaCloud
35454
+ if: \${{ github.event_name == 'push' || github.event.action == '' }}
35455
+ env:
35456
+ SUPACLOUD_API_URL: \${{ secrets.SUPACLOUD_API_URL }}
35457
+ SUPACLOUD_API_TOKEN: \${{ secrets.SUPACLOUD_DEPLOY_TOKEN }}
35458
+ SUPACLOUD_PROJECT_REF: \${{ secrets.SUPACLOUD_PROJECT_REF }}
35459
+ run: npx @supacloud/cli deploy
35460
+ ${previewSteps}`;
35461
+ }
35462
+ async function connectPipeline(args, options = {}) {
35463
+ const root = resolve31(typeof args.root === "string" ? args.root : options.cwd ?? process.cwd());
35464
+ const provider = typeof args.provider === "string" ? args.provider : "github";
35465
+ const config = await readJson2(join24(root, "supacloud.json"));
35466
+ const frontend = record10(config.frontend);
35467
+ const packageJson = await readJson2(join24(root, "package.json"));
35468
+ const scripts = record10(packageJson.scripts);
35469
+ const buildCommand = typeof frontend?.buildCommand === "string" ? frontend.buildCommand : typeof scripts?.build === "string" ? scripts.build : "(configure package.json build script)";
35470
+ const outputDirectory = typeof frontend?.outputDirectory === "string" ? frontend.outputDirectory : "dist";
35471
+ const workflowPath = provider === "github" ? join24(root, ".github", "workflows", "supacloud-deploy.yml") : join24(root, ".gitlab-ci.yml");
35472
+ const result = {
35473
+ schema: "supacloud.pipeline-connection.v1",
35474
+ provider,
35475
+ root,
35476
+ detected: { build_command: buildCommand, output_directory: outputDirectory },
35477
+ workflow: workflowPath,
35478
+ secrets: ["SUPACLOUD_DEPLOY_TOKEN", "SUPACLOUD_API_URL", "SUPACLOUD_PROJECT_REF"],
35479
+ variables: args.preview === true ? ["SUPACLOUD_APPLICATION_ID", "SUPACLOUD_ENVIRONMENT_ID", "SUPACLOUD_RELEASE_ID"] : [],
35480
+ preview: args.preview === true,
35481
+ safety: ["workflow contains no secret values", "provider token remains in the provider secret store"]
35482
+ };
35483
+ if (args.write !== true)
35484
+ return args.format === "json" ? jsonResult5({ ...result, written: false }) : textResult7([
35485
+ `Pipeline provider: ${provider}`,
35486
+ `build: ${buildCommand}`,
35487
+ `output: ${outputDirectory}`,
35488
+ `workflow: ${workflowPath}`,
35489
+ "No files were changed. Re-run with --write after reviewing the generated workflow."
35490
+ ].join(`
35491
+ `));
35492
+ if (provider === "gitlab" && existsSync21(workflowPath)) {
35493
+ throw new Error(`Refusing to overwrite existing GitLab workflow: ${workflowPath}`);
35494
+ }
35495
+ await mkdir11(resolve31(workflowPath, ".."), { recursive: true });
35496
+ await writeFile11(workflowPath, workflow(provider, args.preview === true), { encoding: "utf8", mode: 420 });
35497
+ return jsonResult5({ ...result, written: true });
35498
+ }
35499
+ function registerPipelineTools(server, options = {}) {
35500
+ registerTool(server, "pipeline", "Generate a provider workflow for deployment and optional PR Preview lifecycle.", pipelineToolSchema, (args) => connectPipeline(args, options));
34773
35501
  }
34774
35502
 
34775
35503
  // src/shared/tools/project-deployment.ts
@@ -34897,7 +35625,7 @@ async function runProjectDeployment(http, args) {
34897
35625
  // package.json
34898
35626
  var package_default = {
34899
35627
  name: "@supacloud/cli",
34900
- version: "0.121.9",
35628
+ version: "0.123.2",
34901
35629
  description: "Project-scoped CLI for SupaCloud users",
34902
35630
  type: "module",
34903
35631
  main: "./dist/index.js",
@@ -34949,26 +35677,26 @@ var package_default = {
34949
35677
  directory: "packages/cli"
34950
35678
  },
34951
35679
  dependencies: {
34952
- "@supacloud/compiler": "^0.62.6",
35680
+ "@supacloud/compiler": "^0.62.7",
34953
35681
  "@supacloud/delivery": "0.28.0",
34954
- "@supacloud/db": "0.24.2",
35682
+ "@supacloud/db": "0.25.1",
34955
35683
  typebox: "1.4.3"
34956
35684
  },
34957
35685
  overrides: {
34958
35686
  "@supacloud/contracts": "0.16.2",
34959
35687
  "@supacloud/delivery": "0.28.0",
34960
35688
  "@graphql-tools/utils": "^12.0.4",
34961
- "@supacloud/compiler": "^0.62.6",
34962
- "@supacloud/db": "0.24.2",
35689
+ "@supacloud/compiler": "^0.62.7",
35690
+ "@supacloud/db": "0.25.1",
34963
35691
  "deepmerge-ts": "8.0.2",
34964
35692
  prisma: "6.19.3"
34965
35693
  },
34966
35694
  devDependencies: {
34967
35695
  "@supabase/supabase-js": "2.118.0",
34968
- "@supacloud/elysia": "0.42.4",
35696
+ "@supacloud/elysia": "0.42.5",
34969
35697
  "@types/bun": "^1.4.4",
34970
35698
  effect: "4.0.5",
34971
- elysia: "2.0.0-rc.3",
35699
+ elysia: "2.0.0-rc.4",
34972
35700
  typescript: "7.1.0-beta"
34973
35701
  }
34974
35702
  };
@@ -35138,6 +35866,9 @@ USAGE
35138
35866
  ${preferredCommand} [global flags] deploy [--flags]
35139
35867
  ${preferredCommand} [global flags] <module> <action> [--flags]
35140
35868
  ${preferredCommand} deploy init [--root <directory>]
35869
+ ${preferredCommand} onboard [--profile solo] [--domain <domain>] [--write]
35870
+ ${preferredCommand} config <doctor|explain>
35871
+ ${preferredCommand} pipeline connect [--write] [--preview]
35141
35872
  ${preferredCommand} env <list|check> [--root <directory>]
35142
35873
  ${preferredCommand} [global flags] status
35143
35874
  ${preferredCommand} --help
@@ -35172,7 +35903,11 @@ DEFAULT CONTEXT
35172
35903
  EXAMPLES
35173
35904
 
35174
35905
  ${preferredCommand} deploy init
35906
+ ${preferredCommand} onboard
35907
+ ${preferredCommand} config doctor --format json
35908
+ ${preferredCommand} config explain --key SUPACLOUD_API_URL
35175
35909
  ${preferredCommand} env check
35910
+ ${preferredCommand} env sync --env test --write
35176
35911
  ${preferredCommand} env check --format json
35177
35912
  ${preferredCommand} status
35178
35913
  ${preferredCommand} deploy
@@ -35329,6 +36064,13 @@ function createCliTools(context, confirmProduction) {
35329
36064
  cwd: process.cwd(),
35330
36065
  activeContext: context
35331
36066
  })));
36067
+ Object.assign(tools, captureTools((server) => registerConfigurationTools(server, {
36068
+ cwd: process.cwd(),
36069
+ activeContext: context
36070
+ })));
36071
+ Object.assign(tools, captureTools((server) => registerPipelineTools(server, {
36072
+ cwd: process.cwd()
36073
+ })));
35332
36074
  Object.assign(tools, captureTools((server) => registerAppTools(server, { onDevProgress: writeDevProgress })));
35333
36075
  Object.assign(tools, captureTools((server) => registerDbGovernanceTools(server, {
35334
36076
  projectRef: context.projectRef || undefined,