@supacloud/cli 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +447 -8
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -238837,8 +238837,9 @@ var ACTION_POLICY = {
238837
238837
  write: ["send", "receive", "ack", "release", "fail", "retry", "delete_message", "update_settings"]
238838
238838
  },
238839
238839
  ai: { local: ["show_skill", "install_skill"] },
238840
- app: { local: ["generate", "compile", "check", "graph", "explain"] },
238841
- db: { local: ["lint", "explain"], read: ["module_check"] }
238840
+ app: { local: ["generate", "compile", "check", "graph", "explain", "export-tools"] },
238841
+ db: { local: ["lint", "explain"], read: ["module_check"] },
238842
+ dev: { read: ["status"], write: ["sync", "watch", "migrate"] }
238842
238843
  };
238843
238844
  function declaredMode(moduleName, action) {
238844
238845
  const policy = ACTION_POLICY[moduleName];
@@ -238857,6 +238858,8 @@ function executionMode(moduleName, action, args) {
238857
238858
  return "read";
238858
238859
  if (moduleName === "supabase" && action === "push" && args.dry_run === true)
238859
238860
  return "read";
238861
+ if (moduleName === "dev" && action === "migrate" && args.apply !== true)
238862
+ return "read";
238860
238863
  return declaredMode(moduleName, action);
238861
238864
  }
238862
238865
  function authorizeExecution(moduleName, args, authorization) {
@@ -247662,6 +247665,120 @@ async function compileProject(options) {
247662
247665
  return { diagnostics, graph, written };
247663
247666
  }
247664
247667
 
247668
+ // src/shared/tools/app-tool-export.ts
247669
+ function sanitizeToolName(name) {
247670
+ const sanitized = name.replace(/[^a-zA-Z0-9_]/g, "_").slice(0, 64);
247671
+ return sanitized || "supacloud_command";
247672
+ }
247673
+ function uniqueToolName(name, moduleName, used) {
247674
+ const base = sanitizeToolName(name);
247675
+ if (!used.has(base)) {
247676
+ used.add(base);
247677
+ return base;
247678
+ }
247679
+ const prefix = sanitizeToolName(moduleName).slice(0, 32);
247680
+ const candidateBase = `${prefix}_${base}`.slice(0, 64);
247681
+ let candidate = candidateBase;
247682
+ let suffix = 2;
247683
+ while (used.has(candidate)) {
247684
+ candidate = `${candidateBase.slice(0, 64 - String(suffix).length - 1)}_${suffix}`;
247685
+ suffix += 1;
247686
+ }
247687
+ used.add(candidate);
247688
+ return candidate;
247689
+ }
247690
+ function findRouteForCommand(manifest, commandClassName) {
247691
+ for (const module of manifest.modules) {
247692
+ for (const controller of module.controllers) {
247693
+ for (const route of controller.routes) {
247694
+ if (route.command !== commandClassName)
247695
+ continue;
247696
+ return {
247697
+ httpMethod: route.method,
247698
+ path: `${controller.path}${route.path}`,
247699
+ bodySchema: route.body,
247700
+ paramsSchema: route.params,
247701
+ querySchema: route.query
247702
+ };
247703
+ }
247704
+ }
247705
+ }
247706
+ return;
247707
+ }
247708
+ function inputSchema(route) {
247709
+ const properties = {};
247710
+ if (route?.bodySchema) {
247711
+ properties.body = {
247712
+ type: "object",
247713
+ description: `Request body. Schema reference: ${route.bodySchema}`,
247714
+ additionalProperties: true
247715
+ };
247716
+ }
247717
+ if (route?.paramsSchema) {
247718
+ properties.params = {
247719
+ type: "object",
247720
+ description: `Path parameters. Schema reference: ${route.paramsSchema}`,
247721
+ additionalProperties: true
247722
+ };
247723
+ }
247724
+ if (route?.querySchema) {
247725
+ properties.query = {
247726
+ type: "object",
247727
+ description: `Query parameters. Schema reference: ${route.querySchema}`,
247728
+ additionalProperties: true
247729
+ };
247730
+ }
247731
+ return {
247732
+ type: "object",
247733
+ properties,
247734
+ required: [],
247735
+ additionalProperties: Object.keys(properties).length === 0
247736
+ };
247737
+ }
247738
+ function descriptionForCommand(command, route) {
247739
+ const parts = [`Command ${command.name}`, `permission ${command.permission}`];
247740
+ if (command.transaction === "required")
247741
+ parts.push("transaction required");
247742
+ if (command.idempotency === "required")
247743
+ parts.push("idempotent");
247744
+ if (command.audit)
247745
+ parts.push(`audit ${command.audit}`);
247746
+ if (route)
247747
+ parts.push(`HTTP ${route.httpMethod} ${route.path}`);
247748
+ return `${parts.join("; ")}.`;
247749
+ }
247750
+ function buildToolDefinitions(manifest) {
247751
+ const openai = [];
247752
+ const mcp = [];
247753
+ const usedNames = new Set;
247754
+ for (const module of manifest.modules) {
247755
+ for (const command of module.commands) {
247756
+ if (!command.permission)
247757
+ continue;
247758
+ const route = findRouteForCommand(manifest, command.className);
247759
+ const name = uniqueToolName(command.name, module.name, usedNames);
247760
+ const description = descriptionForCommand(command, route);
247761
+ const parameters = inputSchema(route);
247762
+ openai.push({
247763
+ type: "function",
247764
+ function: { name, description, parameters }
247765
+ });
247766
+ mcp.push({
247767
+ name,
247768
+ description,
247769
+ inputSchema: parameters,
247770
+ annotations: {
247771
+ readOnly: false,
247772
+ audited: !!command.audit,
247773
+ permission: command.permission,
247774
+ ...route ? { httpPath: route.path, httpMethod: route.httpMethod } : {}
247775
+ }
247776
+ });
247777
+ }
247778
+ }
247779
+ return { openai, mcp };
247780
+ }
247781
+
247665
247782
  // src/shared/tools/app-tools.ts
247666
247783
  function textResult(text, isError = false) {
247667
247784
  return { isError, content: [{ type: "text", text }] };
@@ -247966,19 +248083,43 @@ async function runExplain(args) {
247966
248083
  }
247967
248084
  return textResult(`未找到对象: ${target}`, true);
247968
248085
  }
248086
+ async function runExportTools(args) {
248087
+ const root = resolve7(args.root || process.cwd());
248088
+ const manifest = await readManifest(root);
248089
+ const definitions = buildToolDefinitions(manifest);
248090
+ const outDir = resolve7(args.out_dir || join7(root, "generated"));
248091
+ await mkdir2(outDir, { recursive: true });
248092
+ if (args.format === "json") {
248093
+ return textResult(JSON.stringify(definitions, null, 2));
248094
+ }
248095
+ const openaiPath = join7(outDir, "tool-definitions.openai.json");
248096
+ const mcpPath = join7(outDir, "tool-definitions.mcp.json");
248097
+ await writeFile2(openaiPath, JSON.stringify(definitions.openai, null, 2), "utf8");
248098
+ await writeFile2(mcpPath, JSON.stringify(definitions.mcp, null, 2), "utf8");
248099
+ const summary = [
248100
+ `exported ${definitions.openai.length} tool(s):`,
248101
+ ` openai → ${openaiPath}`,
248102
+ ` mcp → ${mcpPath}`,
248103
+ "",
248104
+ definitions.openai.map((t) => ` ${t.function.name}`).join(`
248105
+ `)
248106
+ ].join(`
248107
+ `);
248108
+ return textResult(summary);
248109
+ }
247969
248110
  function registerAppTools(server2) {
247970
- server2.tool("app", "Local @supacloud/app framework commands: scaffold, compile, check, graph and explain. Actions: generate, compile, check, graph, explain", {
247971
- action: withDescription(stringEnum(["generate", "compile", "check", "graph", "explain"]), "App action"),
248111
+ server2.tool("app", "Local @supacloud/app framework commands: scaffold, compile, check, graph, explain and export-tools. Actions: generate, compile, check, graph, explain, export-tools", {
248112
+ action: withDescription(stringEnum(["generate", "compile", "check", "graph", "explain", "export-tools"]), "App action"),
247972
248113
  kind: optional(stringEnum(["module", "command", "query", "controller"]), "[generate] Scaffold kind"),
247973
248114
  name: optional(Type.String(), "[generate] Object name (module name / command / query name)"),
247974
248115
  module: optional(Type.String(), "[generate] Target feature module (required for command/query/controller)"),
247975
248116
  dir: optional(Type.String(), "[generate] Feature root directory (default: src/features)"),
247976
248117
  force: optional(Type.Boolean(), "[generate] Overwrite existing files"),
247977
- root: optional(Type.String(), "[generate/compile/check/graph/explain] Project root (default: current directory)"),
248118
+ root: optional(Type.String(), "[generate/compile/check/graph/explain/export-tools] Project root (default: current directory)"),
247978
248119
  include: optional(Type.String(), "[compile/check] Comma-separated glob patterns for source files"),
247979
- out_dir: optional(Type.String(), "[compile] Output directory (default: <root>/generated)"),
248120
+ out_dir: optional(Type.String(), "[compile/export-tools] Output directory (default: <root>/generated)"),
247980
248121
  strict: optional(Type.Boolean(), "[compile/check] Promote warnings to errors"),
247981
- format: optional(stringEnum(["text", "json"]), "[graph] Output format (default: text)"),
248122
+ format: optional(stringEnum(["text", "json"]), "[graph/export-tools] Output format (default: text)"),
247982
248123
  target: optional(Type.String(), "[explain] Provider class name / token name / command name")
247983
248124
  }, async (request) => {
247984
248125
  switch (request.action) {
@@ -247992,6 +248133,8 @@ function registerAppTools(server2) {
247992
248133
  return runGraph(request);
247993
248134
  case "explain":
247994
248135
  return runExplain(request);
248136
+ case "export-tools":
248137
+ return runExportTools(request);
247995
248138
  default:
247996
248139
  return textResult(`Unknown app action: ${String(request.action)}`, true);
247997
248140
  }
@@ -250808,10 +250951,282 @@ function registerDeployTools(server2, http, options = {}) {
250808
250951
  }
250809
250952
  });
250810
250953
  }
250954
+
250955
+ // src/shared/tools/remote-dev-tools.ts
250956
+ import { spawn as spawn4 } from "node:child_process";
250957
+ import { existsSync as existsSync11 } from "node:fs";
250958
+ import { readFile as readFile3 } from "node:fs/promises";
250959
+ import { readdir } from "node:fs/promises";
250960
+ import { createHash as createHash5 } from "node:crypto";
250961
+ import { join as join10, resolve as resolve11 } from "node:path";
250962
+ var SAFE_TOKEN = /^[A-Za-z0-9._:@/+,-]+$/;
250963
+ var SAFE_REMOTE_ROOT = /^\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+\/?$/;
250964
+ var remoteDevToolSchema = {
250965
+ action: withDescription(stringEnum(["sync", "watch", "status", "migrate"]), "Remote development action"),
250966
+ target: optional(stringEnum(["db", "functions", "frontend", "project"]), "Sync target (default: project)"),
250967
+ project_dir: optional(Type.String(), "Local project directory (default: current directory)"),
250968
+ remote_root: optional(Type.String(), "Remote development root"),
250969
+ remote_host: optional(Type.String(), "Remote test server host"),
250970
+ remote_user: optional(Type.String(), "SSH user"),
250971
+ remote_port: optional(Type.Number(), "SSH port"),
250972
+ remote_key: optional(Type.String(), "SSH private key path"),
250973
+ function: optional(Type.String(), "Function slug"),
250974
+ delete: optional(Type.Boolean(), "Delete remote files absent locally"),
250975
+ reload: optional(Type.Boolean(), "Reload the affected target after sync (default: true)"),
250976
+ interval_ms: optional(Type.Number(), "Watch debounce interval in milliseconds (default: 300)"),
250977
+ json: optional(Type.Boolean(), "Emit machine-readable JSON"),
250978
+ apply: optional(Type.Boolean(), "Apply generated migrations to the selected test database"),
250979
+ drizzle_config: optional(Type.String(), "Drizzle config path"),
250980
+ migrations_dir: optional(Type.String(), "Migration directory"),
250981
+ drizzle_bin: optional(Type.String(), "drizzle-kit executable")
250982
+ };
250983
+ function runProcess(executable, args, cwd) {
250984
+ return new Promise((resolveResult, reject) => {
250985
+ const child = spawn4(executable, args, { cwd, shell: false, stdio: ["ignore", "pipe", "pipe"] });
250986
+ let stdout = "";
250987
+ let stderr = "";
250988
+ child.stdout?.setEncoding("utf8");
250989
+ child.stderr?.setEncoding("utf8");
250990
+ child.stdout?.on("data", (chunk) => {
250991
+ stdout += String(chunk);
250992
+ });
250993
+ child.stderr?.on("data", (chunk) => {
250994
+ stderr += String(chunk);
250995
+ });
250996
+ child.once("error", reject);
250997
+ child.once("close", (exitCode) => resolveResult({ exitCode: exitCode ?? 1, stdout, stderr }));
250998
+ });
250999
+ }
251000
+ function resolveDrizzleCommand(root, configured) {
251001
+ if (configured?.trim())
251002
+ return configured.trim();
251003
+ const local = join10(root, "node_modules", ".bin", "drizzle-kit");
251004
+ return existsSync11(local) ? local : "drizzle-kit";
251005
+ }
251006
+ function toolFailed(value) {
251007
+ return value?.isError === true || value?.content?.some((chunk) => typeof chunk?.text === "string" && chunk.text.trimStart().startsWith("❌"));
251008
+ }
251009
+ async function migrateDatabase(args, options) {
251010
+ const root = resolve11(String(args.project_dir || options.cwd || process.cwd()));
251011
+ const projectConfig = await readProjectConfig(root);
251012
+ const config = projectConfig.dev || {};
251013
+ const database = config.database || {};
251014
+ const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
251015
+ const drizzleConfig = resolve11(root, String(args.drizzle_config || database.drizzleConfig || "drizzle.config.ts"));
251016
+ const migrationsDir = String(args.migrations_dir || database.migrationsDir || "supabase/migrations");
251017
+ if (!existsSync11(drizzleConfig))
251018
+ throw new Error(`Drizzle config not found: ${drizzleConfig}`);
251019
+ const generated = await execute(resolveDrizzleCommand(root, typeof args.drizzle_bin === "string" ? args.drizzle_bin : database.drizzleBin), ["generate", "--config", drizzleConfig], root);
251020
+ if (generated.exitCode !== 0)
251021
+ throw new Error(`Drizzle migration generation failed: ${generated.stderr.trim() || `exit ${generated.exitCode}`}`);
251022
+ if (!options.runDatabase)
251023
+ throw new Error("dev migrate requires Management API context");
251024
+ const dryRun = await options.runDatabase({ action: "push_migrations", dir: migrationsDir, dry_run: true, strict: database.strict !== false });
251025
+ if (toolFailed(dryRun))
251026
+ throw new Error("SupaCloud migration dry-run failed");
251027
+ if (args.apply !== true)
251028
+ return { ok: true, mode: "dev", action: "migrate", generated: true, applied: false, migrations_dir: migrationsDir, dry_run: dryRun };
251029
+ const applied = await options.runDatabase({ action: "push_migrations", dir: migrationsDir, strict: database.strict !== false });
251030
+ if (toolFailed(applied))
251031
+ throw new Error("SupaCloud migration apply failed");
251032
+ return { ok: true, mode: "dev", action: "migrate", generated: true, applied: true, migrations_dir: migrationsDir, result: applied };
251033
+ }
251034
+ async function readProjectConfig(root) {
251035
+ const file = join10(root, "supacloud.json");
251036
+ if (!existsSync11(file))
251037
+ return {};
251038
+ try {
251039
+ const parsed = JSON.parse(await readFile3(file, "utf8"));
251040
+ return parsed && typeof parsed === "object" ? parsed : {};
251041
+ } catch (error) {
251042
+ throw new Error(`Invalid supacloud.json: ${error instanceof Error ? error.message : String(error)}`);
251043
+ }
251044
+ }
251045
+ async function readDevConfig(root) {
251046
+ const config = await readProjectConfig(root);
251047
+ return config.dev || {};
251048
+ }
251049
+ async function sourceFingerprint(root) {
251050
+ const files = [];
251051
+ const visit = async (directory) => {
251052
+ const entries = await readdir(directory, { withFileTypes: true });
251053
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
251054
+ const path = join10(directory, entry.name);
251055
+ if (entry.isDirectory() && ![".git", "node_modules", "dist", "generated", ".supacloud"].includes(entry.name))
251056
+ await visit(path);
251057
+ else if (entry.isFile())
251058
+ files.push(path);
251059
+ }
251060
+ };
251061
+ await visit(root);
251062
+ const hash2 = createHash5("sha256");
251063
+ for (const file of files) {
251064
+ hash2.update(file.slice(root.length).replace(/\\/g, "/"));
251065
+ hash2.update(await readFile3(file));
251066
+ }
251067
+ return hash2.digest("hex");
251068
+ }
251069
+ function safeToken(value, label) {
251070
+ if (!value || !SAFE_TOKEN.test(value))
251071
+ throw new Error(`Invalid ${label}`);
251072
+ return value;
251073
+ }
251074
+ function remoteRoot(value) {
251075
+ const normalized = value.trim().replace(/\\/g, "/");
251076
+ if (!SAFE_REMOTE_ROOT.test(normalized) || normalized.includes(".."))
251077
+ throw new Error("Invalid remote_root");
251078
+ return normalized.replace(/\/$/, "");
251079
+ }
251080
+ function targetDirectory(root, target, functionSlug, config = {}) {
251081
+ if (target === "db")
251082
+ return join10(root, "supabase", "migrations");
251083
+ if (target === "functions") {
251084
+ const targets = config.targets && typeof config.targets === "object" ? config.targets : {};
251085
+ const match = Object.values(targets).find((entry) => entry?.type === "edge_function" && (!functionSlug || String(entry.slug || "") === functionSlug));
251086
+ const base = match?.root ? resolve11(root, String(match.root)) : join10(root, "supabase", "functions");
251087
+ return match?.root ? base : functionSlug ? join10(base, safeToken(functionSlug, "function")) : base;
251088
+ }
251089
+ if (target === "frontend") {
251090
+ const targets = config.targets && typeof config.targets === "object" ? config.targets : {};
251091
+ const match = Object.values(targets).find((entry) => entry?.type === "frontend");
251092
+ return match?.root ? resolve11(root, String(match.root)) : join10(root, "apps", "web");
251093
+ }
251094
+ return root;
251095
+ }
251096
+ function remoteTargetRoot(root, target, functionSlug) {
251097
+ if (target === "db")
251098
+ return `${root}/database/migrations`;
251099
+ if (target === "functions")
251100
+ return `${root}/functions/${functionSlug ? safeToken(functionSlug, "function") : ""}`.replace(/\/$/, "");
251101
+ if (target === "frontend")
251102
+ return `${root}/frontend`;
251103
+ return `${root}/project`;
251104
+ }
251105
+ function connectionArgs(options, config, args) {
251106
+ const host = String(args.remote_host || config.host || options.host || "").trim();
251107
+ const user = String(args.remote_user || config.user || options.sshUser || "").trim();
251108
+ const port = Number(args.remote_port || config.port || options.sshPort || 22);
251109
+ const key = String(args.remote_key || config.key || options.sshKey || "").trim();
251110
+ if (!host)
251111
+ throw new Error("Remote dev requires SUPACLOUD_HOST or --remote_host");
251112
+ safeToken(host, "remote_host");
251113
+ safeToken(user, "remote_user");
251114
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
251115
+ throw new Error("Invalid remote_port");
251116
+ if (!key || key.includes("\x00") || key.includes(`
251117
+ `))
251118
+ throw new Error("Invalid remote_key");
251119
+ return { host, user, port, key };
251120
+ }
251121
+ function targetConfigPath(target) {
251122
+ return target === "project" ? "project" : target;
251123
+ }
251124
+ function reloadCommand(config, target, projectRef2, functionSlug) {
251125
+ const command = config.reloadCommand?.trim() || "supacloud-dev-agent reload";
251126
+ if (!/^[A-Za-z0-9._/-]+(?: [A-Za-z0-9._:/=-]+)*$/.test(command))
251127
+ throw new Error("Invalid reloadCommand in supacloud.json");
251128
+ return [...command.split(" "), "--project-ref", safeToken(projectRef2 || "test", "project_ref"), "--target", targetConfigPath(target), ...functionSlug ? ["--function", safeToken(functionSlug, "function")] : []];
251129
+ }
251130
+ function sshArgs(connection, remoteCommand) {
251131
+ return ["-p", String(connection.port), "-i", resolve11(connection.key), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", `${connection.user}@${connection.host}`, ...remoteCommand];
251132
+ }
251133
+ function rsyncArgs(connection, source, destination, excludes, deleteRemote) {
251134
+ const args = ["-az", "--checksum", "--partial", "--protect-args", "-e", `ssh -p ${connection.port} -i ${resolve11(connection.key)} -o BatchMode=yes -o StrictHostKeyChecking=yes`];
251135
+ if (deleteRemote)
251136
+ args.push("--delete-delay");
251137
+ for (const exclude of excludes) {
251138
+ if (!/^\/?[A-Za-z0-9._*/-]+$/.test(exclude))
251139
+ throw new Error("Invalid dev exclude pattern");
251140
+ args.push("--exclude", exclude);
251141
+ }
251142
+ args.push(`${source.replace(/\/$/, "")}/`, `${connection.user}@${connection.host}:${destination.replace(/\/$/, "")}/`);
251143
+ return args;
251144
+ }
251145
+ async function syncOnce(args, options) {
251146
+ const root = resolve11(String(args.project_dir || options.cwd || process.cwd()));
251147
+ const projectConfig = await readProjectConfig(root);
251148
+ const config = projectConfig.dev || {};
251149
+ const target = String(args.target || "project");
251150
+ const source = targetDirectory(root, target, typeof args.function === "string" ? args.function : undefined, projectConfig);
251151
+ if (!existsSync11(source))
251152
+ throw new Error(`Dev source directory not found: ${source}`);
251153
+ let compiled = false;
251154
+ if (config.compile === true && target !== "db") {
251155
+ const compileRoot = resolve11(root, config.compileRoot || ".");
251156
+ const compileOutDir = resolve11(root, config.compileOutDir || "generated");
251157
+ const compilation = await compileProject({
251158
+ rootDir: compileRoot,
251159
+ outDir: compileOutDir,
251160
+ strict: config.compileStrict !== false
251161
+ });
251162
+ const errors = compilation.diagnostics.filter((diagnostic) => diagnostic.severity === "error");
251163
+ if (errors.length > 0) {
251164
+ throw new Error(`DI compile failed: ${errors.map((diagnostic) => `${diagnostic.code} ${diagnostic.message}`).join("; ")}`);
251165
+ }
251166
+ compiled = true;
251167
+ }
251168
+ const remoteBase = remoteRoot(String(args.remote_root || config.remoteRoot || `/var/lib/supacloud/dev/${options.projectRef || "project"}`));
251169
+ const slug = typeof args.function === "string" ? args.function : undefined;
251170
+ const destination = remoteTargetRoot(remoteBase, target, slug);
251171
+ const connection = connectionArgs(options, config, args);
251172
+ const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
251173
+ const mkdir3 = await execute("ssh", sshArgs(connection, ["mkdir", "-p", destination]), root);
251174
+ if (mkdir3.exitCode !== 0)
251175
+ throw new Error(`Remote dev prepare failed: ${mkdir3.stderr.trim() || `exit ${mkdir3.exitCode}`}`);
251176
+ const excludes = Array.isArray(config.excludes) ? config.excludes : ["node_modules", ".git", ".env*", "dist", ".supacloud"];
251177
+ const sync = await execute("rsync", rsyncArgs(connection, source, destination, excludes, args.delete === true), root);
251178
+ if (sync.exitCode !== 0)
251179
+ throw new Error(`Remote dev sync failed: ${sync.stderr.trim() || `exit ${sync.exitCode}`}`);
251180
+ const shouldReload = args.reload !== false;
251181
+ let reload = null;
251182
+ if (shouldReload) {
251183
+ reload = await execute("ssh", sshArgs(connection, reloadCommand(config, target, options.projectRef, slug)), root);
251184
+ if (reload.exitCode !== 0)
251185
+ throw new Error(`Remote dev reload failed: ${reload.stderr.trim() || `exit ${reload.exitCode}`}`);
251186
+ }
251187
+ return { ok: true, mode: "dev", action: "sync", environment: options.environment || null, target, source, destination, host: connection.host, compiled, reloaded: shouldReload };
251188
+ }
251189
+ function registerRemoteDevTools(server2, options = {}) {
251190
+ server2.tool("dev", "Remote test-server development sync. It never targets production and never syncs secrets.", remoteDevToolSchema, async (args) => {
251191
+ if (["production", "prod"].includes((options.environment || "").toLowerCase()))
251192
+ throw new Error("Remote dev mode is forbidden for production environments");
251193
+ if (args.action === "status") {
251194
+ const root = resolve11(String(args.project_dir || options.cwd || process.cwd()));
251195
+ const config = await readDevConfig(root);
251196
+ const connection = connectionArgs(options, config, args);
251197
+ const execute = options.execute || ((command, commandArgs, cwd) => runProcess(command, commandArgs, cwd));
251198
+ const status = await execute("ssh", sshArgs(connection, ["supacloud-dev-agent", "status", "--project-ref", safeToken(options.projectRef || "test", "project_ref")]), root);
251199
+ return { content: [{ type: "text", text: JSON.stringify({ ok: status.exitCode === 0, mode: "dev", action: "status", host: connection.host, output: status.stdout.trim(), error: status.stderr.trim() }, null, 2) }], isError: status.exitCode !== 0 };
251200
+ }
251201
+ if (args.action === "sync") {
251202
+ return { content: [{ type: "text", text: JSON.stringify(await syncOnce(args, options), null, 2) }] };
251203
+ }
251204
+ if (args.action === "migrate") {
251205
+ return { content: [{ type: "text", text: JSON.stringify(await migrateDatabase(args, options), null, 2) }] };
251206
+ }
251207
+ if (args.action === "watch") {
251208
+ const root = resolve11(String(args.project_dir || options.cwd || process.cwd()));
251209
+ const interval = Math.max(100, Math.min(1e4, Number(args.interval_ms || 300)));
251210
+ let fingerprint = "";
251211
+ let lastSync = null;
251212
+ for (;; ) {
251213
+ const nextFingerprint = await sourceFingerprint(root);
251214
+ if (nextFingerprint !== fingerprint) {
251215
+ lastSync = await syncOnce(args, options);
251216
+ fingerprint = nextFingerprint;
251217
+ process.stdout.write(`${JSON.stringify({ ...lastSync, watching: true })}
251218
+ `);
251219
+ }
251220
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, interval));
251221
+ }
251222
+ }
251223
+ throw new Error("Unsupported remote dev action");
251224
+ });
251225
+ }
250811
251226
  // package.json
250812
251227
  var package_default = {
250813
251228
  name: "@supacloud/cli",
250814
- version: "0.41.0",
251229
+ version: "0.43.0",
250815
251230
  description: "Project-scoped CLI for SupaCloud users",
250816
251231
  type: "module",
250817
251232
  main: "./dist/index.js",
@@ -251062,6 +251477,11 @@ EXAMPLES
251062
251477
  ${preferredCommand} deploy
251063
251478
  ${preferredCommand} deploy --target web
251064
251479
  ${preferredCommand} deploy --target api
251480
+ ${preferredCommand} dev sync --env test --target functions --function api
251481
+ ${preferredCommand} dev status --env test
251482
+ ${preferredCommand} dev watch --env test --target project
251483
+ ${preferredCommand} dev sync --env test --target db
251484
+ ${preferredCommand} dev migrate --env test
251065
251485
  ${preferredCommand} project get
251066
251486
  ${preferredCommand} project logs --log_type database
251067
251487
  ${preferredCommand} project task_stats
@@ -251228,6 +251648,15 @@ function createCliTools(context, confirmProduction) {
251228
251648
  Object.assign(tools, captureTools((server2) => registerDatabaseTools(server2, undefined, {
251229
251649
  localOnly: true
251230
251650
  })));
251651
+ Object.assign(tools, captureTools((server2) => registerRemoteDevTools(server2, {
251652
+ cwd: process.cwd(),
251653
+ host: process.env.SUPACLOUD_DEV_HOST || context.host,
251654
+ sshUser: context.sshUser,
251655
+ sshPort: context.sshPort,
251656
+ sshKey: context.sshKey,
251657
+ projectRef: context.projectRef || undefined,
251658
+ environment: context.environment
251659
+ })));
251231
251660
  tools.setup_help = {
251232
251661
  schema: {},
251233
251662
  callback: async () => ({
@@ -251280,6 +251709,16 @@ function createCliTools(context, confirmProduction) {
251280
251709
  }));
251281
251710
  pushMigrations = databaseTools.database?.callback;
251282
251711
  assign(databaseTools);
251712
+ assign(captureTools((server2) => registerRemoteDevTools(server2, {
251713
+ cwd: process.cwd(),
251714
+ host: process.env.SUPACLOUD_DEV_HOST || context.host,
251715
+ sshUser: context.sshUser,
251716
+ sshPort: context.sshPort,
251717
+ sshKey: context.sshKey,
251718
+ projectRef: context.projectRef || undefined,
251719
+ environment: context.environment,
251720
+ runDatabase: databaseTools.database?.callback
251721
+ })));
251283
251722
  assign(captureTools((server2) => registerAuthTools(server2, http)));
251284
251723
  assign(captureTools((server2) => registerOAuthClientTools(server2, http)));
251285
251724
  assign(captureTools((server2) => registerStorageTools(server2, http)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/cli",
3
- "version": "0.41.0",
3
+ "version": "0.43.0",
4
4
  "description": "Project-scoped CLI for SupaCloud users",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",