sagacloud 0.3.0 → 0.3.1

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 +394 -109
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -6,7 +6,6 @@ import pc8 from "picocolors";
6
6
 
7
7
  // src/commands/auth.ts
8
8
  import crypto from "crypto";
9
- import { execFile } from "child_process";
10
9
  import http from "http";
11
10
  import os2 from "os";
12
11
  import * as p from "@clack/prompts";
@@ -34,7 +33,7 @@ var SagaCloudJsoncSchema = z.object({
34
33
  app_name: z.string().min(1).optional(),
35
34
  name: z.string().min(1).optional(),
36
35
  site_id: z.string().optional(),
37
- type: z.enum(["static", "spa", "php", "node", "nextjs"]).optional(),
36
+ type: z.enum(["static", "html", "spa", "php", "node", "nextjs"]).optional(),
38
37
  base_directory: z.string().optional(),
39
38
  install_command: z.string().optional(),
40
39
  build_command: z.string().optional(),
@@ -285,12 +284,102 @@ async function exchangeCliCode(apiUrl, code) {
285
284
  return parsed.message || parsed;
286
285
  }
287
286
 
288
- // src/commands/auth.ts
289
- function openBrowser(url) {
287
+ // src/lib/browser.ts
288
+ import { execFile } from "child_process";
289
+ async function openBrowser(url) {
290
290
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
291
291
  const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
292
- execFile(cmd, args, () => {
292
+ return await new Promise((resolve) => {
293
+ let settled = false;
294
+ const finish = (ok) => {
295
+ if (settled) return;
296
+ settled = true;
297
+ resolve(ok);
298
+ };
299
+ try {
300
+ const child = execFile(cmd, args, (err) => {
301
+ finish(!err);
302
+ });
303
+ child.once("error", () => finish(false));
304
+ setTimeout(() => {
305
+ if (child.exitCode === null) {
306
+ child.unref();
307
+ finish(true);
308
+ }
309
+ }, 400);
310
+ } catch {
311
+ finish(false);
312
+ }
313
+ });
314
+ }
315
+ function isHeadlessOrRemoteShell() {
316
+ if (!process.stdin.isTTY) return true;
317
+ if (process.env.SSH_CONNECTION || process.env.SSH_TTY || process.env.SSH_CLIENT) return true;
318
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
319
+ return true;
320
+ }
321
+ return false;
322
+ }
323
+
324
+ // src/commands/auth.ts
325
+ async function authenticateWithToken(rawToken, apiUrl, panelUrl) {
326
+ const spin = p.spinner();
327
+ spin.start("Verifying SagaCloud API token...");
328
+ const client = new SagaCloudClient({ token: rawToken.trim(), apiUrl });
329
+ const info = await client.rpc("saga_cloud.api.cli_auth.get_cli_session_info");
330
+ writeAuthProfile({
331
+ token: rawToken.trim(),
332
+ apiUrl,
333
+ panelUrl,
334
+ user: info.user,
335
+ tenant: info.tenant,
336
+ tenantName: info.tenant_name,
337
+ tokenName: info.token_name
338
+ });
339
+ spin.stop(`Authenticated as ${pc.green(info.user)} (Workspace: ${pc.cyan(info.tenant_name)})`);
340
+ }
341
+ async function promptManualLogin(apiUrl, panelBase, tryOpenBrowser) {
342
+ const manualUrl = new URL(`${panelBase}/hosting/cli-auth`);
343
+ manualUrl.searchParams.set("mode", "manual");
344
+ manualUrl.searchParams.set("device", os2.hostname());
345
+ console.log(pc.bold("Manual CLI authorization (SSH / headless / container):"));
346
+ console.log(`1. Open this URL in any browser:
347
+ ${pc.cyan(manualUrl.toString())}`);
348
+ console.log(`2. Click ${pc.bold("Authorize CLI Access")} and copy the one-time code (or an ${pc.dim("sc_live_...")} API token).
349
+ `);
350
+ if (tryOpenBrowser) {
351
+ await openBrowser(manualUrl.toString());
352
+ }
353
+ const pasted = await p.password({
354
+ message: "Paste authorization code or sc_live_... token",
355
+ validate(val) {
356
+ if (!val || !val.trim()) return "Authorization code or token is required.";
357
+ }
358
+ });
359
+ if (p.isCancel(pasted)) {
360
+ p.cancel("Login cancelled.");
361
+ process.exit(1);
362
+ }
363
+ const secret = String(pasted).trim();
364
+ if (secret.startsWith("sc_live_")) {
365
+ await authenticateWithToken(secret, apiUrl, panelBase);
366
+ return;
367
+ }
368
+ const spin = p.spinner();
369
+ spin.start("Exchanging one-time authorization code...");
370
+ const exchanged = await exchangeCliCode(apiUrl, secret);
371
+ writeAuthProfile({
372
+ token: exchanged.token,
373
+ apiUrl,
374
+ panelUrl: panelBase,
375
+ user: exchanged.user,
376
+ tenant: exchanged.tenant,
377
+ tenantName: exchanged.tenant_name,
378
+ tokenName: exchanged.token_name
293
379
  });
380
+ spin.stop(
381
+ `Logged in as ${pc.green(exchanged.user)} \xB7 Workspace: ${pc.cyan(exchanged.tenant_name)} (${pc.dim(exchanged.token_prefix)}...)`
382
+ );
294
383
  }
295
384
  function escapeHtml(value) {
296
385
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
@@ -423,23 +512,15 @@ function renderCallbackHtml(opts) {
423
512
  </html>`;
424
513
  }
425
514
  function registerAuthCommands(program2) {
426
- program2.command("login").description("Authenticate CLI via browser approval or --token").option("--token <token>", "Store an existing sc_live_... API token directly").option("--url <apiUrl>", "SagaCloud API base URL", DEFAULT_API_BASE_URL).option("--panel-url <panelUrl>", "SagaCloud Dashboard URL for browser login", DEFAULT_PANEL_BASE_URL).action(async (opts) => {
515
+ program2.command("login").description("Authenticate CLI via browser approval, manual code paste, or --token").option("--token <token>", "Store an existing sc_live_... API token directly").option("--manual", "Prompt to paste an authorization code or token instead of waiting for 127.0.0.1 callback", false).option("--no-browser", "Do not launch a local browser automatically").option("--url <apiUrl>", "SagaCloud API base URL", DEFAULT_API_BASE_URL).option("--panel-url <panelUrl>", "SagaCloud Dashboard URL for browser login", DEFAULT_PANEL_BASE_URL).action(async (opts) => {
427
516
  const apiUrl = (opts.url || DEFAULT_API_BASE_URL).replace(/\/+$/, "");
517
+ const panelBase = (opts.panelUrl || DEFAULT_PANEL_BASE_URL).replace(/\/+$/, "");
428
518
  if (opts.token) {
429
- const spin2 = p.spinner();
430
- spin2.start("Verifying SagaCloud API token...");
431
- const client = new SagaCloudClient({ token: opts.token.trim(), apiUrl });
432
- const info = await client.rpc("saga_cloud.api.cli_auth.get_cli_session_info");
433
- writeAuthProfile({
434
- token: opts.token.trim(),
435
- apiUrl,
436
- panelUrl: opts.panelUrl,
437
- user: info.user,
438
- tenant: info.tenant,
439
- tenantName: info.tenant_name,
440
- tokenName: info.token_name
441
- });
442
- spin2.stop(`Authenticated as ${pc.green(info.user)} (Workspace: ${pc.cyan(info.tenant_name)})`);
519
+ await authenticateWithToken(opts.token, apiUrl, opts.panelUrl);
520
+ return;
521
+ }
522
+ if (opts.manual || opts.browser === false || isHeadlessOrRemoteShell()) {
523
+ await promptManualLogin(apiUrl, panelBase, Boolean(opts.browser !== false && !isHeadlessOrRemoteShell()));
443
524
  return;
444
525
  }
445
526
  const state = crypto.randomBytes(24).toString("hex");
@@ -450,7 +531,6 @@ function registerAuthCommands(program2) {
450
531
  throw new Error("Could not bind local loopback port for login.");
451
532
  }
452
533
  const callbackUrl = `http://127.0.0.1:${addr.port}/callback`;
453
- const panelBase = (opts.panelUrl || DEFAULT_PANEL_BASE_URL).replace(/\/+$/, "");
454
534
  const authUrl = new URL(`${panelBase}/hosting/cli-auth`);
455
535
  authUrl.searchParams.set("callback", callbackUrl);
456
536
  authUrl.searchParams.set("state", state);
@@ -459,7 +539,13 @@ function registerAuthCommands(program2) {
459
539
  console.log(`If your browser doesn't open, visit:
460
540
  ${pc.cyan(authUrl.toString())}
461
541
  `);
462
- openBrowser(authUrl.toString());
542
+ const opened = await openBrowser(authUrl.toString());
543
+ if (!opened) {
544
+ server.close();
545
+ console.log(pc.yellow("No working local browser opener detected; switching to manual authorization mode.\n"));
546
+ await promptManualLogin(apiUrl, panelBase, false);
547
+ return;
548
+ }
463
549
  const code = await new Promise((resolve, reject) => {
464
550
  const timeout = setTimeout(() => {
465
551
  server.close();
@@ -530,6 +616,7 @@ function registerAuthCommands(program2) {
530
616
  );
531
617
  });
532
618
  program2.command("logout").description("Revoke active CLI token on server and remove local credentials").action(async () => {
619
+ const envToken = process.env.SAGACLOUD_TOKEN?.trim();
533
620
  const profile = readAuthProfile();
534
621
  if (!profile) {
535
622
  console.log(pc.yellow("No local CLI credentials found."));
@@ -543,6 +630,13 @@ function registerAuthCommands(program2) {
543
630
  }
544
631
  clearAuthProfile();
545
632
  console.log(pc.green(`Logged out and removed ${getAuthFilePath()}`));
633
+ if (envToken) {
634
+ console.log(
635
+ pc.yellow(
636
+ "Warning: SAGACLOUD_TOKEN is set in your shell environment and its token was just revoked. Run `unset SAGACLOUD_TOKEN` in your terminal."
637
+ )
638
+ );
639
+ }
546
640
  });
547
641
  program2.command("whoami").description("Display active CLI user, workspace, and token scopes").action(async () => {
548
642
  const client = new SagaCloudClient();
@@ -799,28 +893,32 @@ async function streamRuntimeLogs(client, siteId, lines = 100, follow = false) {
799
893
  void stop().then(() => process.exit(0));
800
894
  });
801
895
  let ticks = 0;
802
- while (running) {
803
- const res = await client.rpc("saga_cloud.api.hosting.get_site_logs", {
804
- query: { site_id: siteId, lines }
805
- });
806
- const current = (res.logs || "").split(/\r?\n/).filter(Boolean);
807
- if (previousLines.length === 0) {
808
- for (const ln of current) console.log(ln);
809
- } else {
810
- const lastPrev = previousLines[previousLines.length - 1];
811
- const matchIdx = current.lastIndexOf(lastPrev);
812
- const added = matchIdx >= 0 ? current.slice(matchIdx + 1) : current;
813
- for (const ln of added) console.log(ln);
814
- }
815
- previousLines = current;
816
- ticks += 1;
817
- if (ticks % 5 === 0) {
818
- await client.rpc("saga_cloud.api.hosting.heartbeat_site_log_stream", {
819
- method: "POST",
820
- body: { site_id: siteId }
896
+ try {
897
+ while (running) {
898
+ const res = await client.rpc("saga_cloud.api.hosting.get_site_logs", {
899
+ query: { site_id: siteId, lines }
821
900
  });
901
+ const current = (res.logs || "").split(/\r?\n/).filter(Boolean);
902
+ if (previousLines.length === 0) {
903
+ for (const ln of current) console.log(ln);
904
+ } else {
905
+ const lastPrev = previousLines[previousLines.length - 1];
906
+ const matchIdx = current.lastIndexOf(lastPrev);
907
+ const added = matchIdx >= 0 ? current.slice(matchIdx + 1) : current;
908
+ for (const ln of added) console.log(ln);
909
+ }
910
+ previousLines = current;
911
+ ticks += 1;
912
+ if (ticks % 5 === 0) {
913
+ await client.rpc("saga_cloud.api.hosting.heartbeat_site_log_stream", {
914
+ method: "POST",
915
+ body: { site_id: siteId }
916
+ });
917
+ }
918
+ await new Promise((r) => setTimeout(r, 2500));
822
919
  }
823
- await new Promise((r) => setTimeout(r, 2500));
920
+ } finally {
921
+ await stop();
824
922
  }
825
923
  }
826
924
 
@@ -843,22 +941,52 @@ var ALWAYS_IGNORED = [
843
941
  ".env",
844
942
  ".env.*",
845
943
  "sagacloud.jsonc",
846
- "sagacloud.json"
944
+ "sagacloud.json",
945
+ ".sagacloudignore"
946
+ ];
947
+ var STATIC_NON_WEB_IGNORES = [
948
+ "**/*.d.ts",
949
+ "**/*.d.mts",
950
+ "**/*.d.cts",
951
+ "*.d.ts",
952
+ "*.d.mts",
953
+ "*.d.cts",
954
+ ".editorconfig",
955
+ ".gitignore",
956
+ ".gitattributes",
957
+ ".browserslistrc",
958
+ ".npmrc",
959
+ ".prettierrc",
960
+ ".prettierignore",
961
+ ".eslintrc",
962
+ ".eslintignore",
963
+ ".stylelintrc"
847
964
  ];
848
- async function createArchiveFromDirectory(targetDir, extraIgnorePatterns = [], includeGitignore = false) {
965
+ async function createArchiveFromDirectory(targetDir, extraOrOptions = [], includeGitignoreArg = false) {
849
966
  if (!fs3.existsSync(targetDir) || !fs3.statSync(targetDir).isDirectory()) {
850
967
  throw new Error(`Directory not found: ${targetDir}`);
851
968
  }
969
+ const opts = Array.isArray(extraOrOptions) ? { extraIgnorePatterns: extraOrOptions, includeGitignore: includeGitignoreArg } : extraOrOptions;
852
970
  const ig = ignore().add(ALWAYS_IGNORED);
853
- if (extraIgnorePatterns.length > 0) {
854
- ig.add(extraIgnorePatterns);
971
+ if (opts.staticSiteFilter) {
972
+ ig.add(STATIC_NON_WEB_IGNORES);
855
973
  }
856
- if (includeGitignore) {
857
- for (const ignoreFile of [".gitignore", ".sagacloudignore"]) {
858
- const fp = path3.join(targetDir, ignoreFile);
859
- if (fs3.existsSync(fp)) {
860
- ig.add(fs3.readFileSync(fp, "utf8"));
861
- }
974
+ if (opts.extraIgnorePatterns && opts.extraIgnorePatterns.length > 0) {
975
+ ig.add(opts.extraIgnorePatterns);
976
+ }
977
+ const searchDirs = Array.from(
978
+ /* @__PURE__ */ new Set([targetDir, ...opts.projectRootDir ? [opts.projectRootDir] : []])
979
+ );
980
+ for (const baseDir of searchDirs) {
981
+ const sagaIgnore = path3.join(baseDir, ".sagacloudignore");
982
+ if (fs3.existsSync(sagaIgnore)) {
983
+ ig.add(fs3.readFileSync(sagaIgnore, "utf8"));
984
+ }
985
+ }
986
+ if (opts.includeGitignore) {
987
+ const gitIgnore = path3.join(targetDir, ".gitignore");
988
+ if (fs3.existsSync(gitIgnore)) {
989
+ ig.add(fs3.readFileSync(gitIgnore, "utf8"));
862
990
  }
863
991
  }
864
992
  return await new Promise((resolve, reject) => {
@@ -911,16 +1039,57 @@ async function resolveWranglerStyleTargetSite(client, optsSite, configuredName,
911
1039
  return link?.site_id || "";
912
1040
  }
913
1041
  function parseDotEnvText(raw) {
1042
+ const trimmed = raw.trim();
1043
+ if (trimmed.startsWith("[")) {
1044
+ const parsed = JSON.parse(trimmed);
1045
+ return parsed.filter((r) => Boolean(r?.key)).map((r) => ({
1046
+ key: String(r.key).trim(),
1047
+ value: String(r.value ?? ""),
1048
+ isBuildTime: r.is_build_time
1049
+ }));
1050
+ }
914
1051
  const rows = [];
915
- for (const line of raw.split(/\r?\n/)) {
916
- const trimmed = line.trim();
917
- if (!trimmed || trimmed.startsWith("#")) continue;
918
- const eq = trimmed.indexOf("=");
1052
+ const lines = raw.split(/\r?\n/);
1053
+ for (let i = 0; i < lines.length; i += 1) {
1054
+ let line = lines[i].trim();
1055
+ if (!line || line.startsWith("#")) continue;
1056
+ if (/^export\s+/i.test(line)) {
1057
+ line = line.replace(/^export\s+/i, "").trim();
1058
+ }
1059
+ const eq = line.indexOf("=");
919
1060
  if (eq <= 0) continue;
920
- const key = trimmed.slice(0, eq).trim();
921
- let val = trimmed.slice(eq + 1).trim();
922
- if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
923
- val = val.slice(1, -1);
1061
+ const key = line.slice(0, eq).trim();
1062
+ const rawVal = line.slice(eq + 1).trimStart();
1063
+ let val = "";
1064
+ if (rawVal.startsWith('"') || rawVal.startsWith("'")) {
1065
+ const quote = rawVal[0];
1066
+ let buf = rawVal.slice(1);
1067
+ while (true) {
1068
+ let closeIdx = -1;
1069
+ for (let j = 0; j < buf.length; j += 1) {
1070
+ if (buf[j] === "\\" && quote === '"' && j + 1 < buf.length) {
1071
+ j += 1;
1072
+ continue;
1073
+ }
1074
+ if (buf[j] === quote) {
1075
+ closeIdx = j;
1076
+ break;
1077
+ }
1078
+ }
1079
+ if (closeIdx !== -1 || i + 1 >= lines.length) {
1080
+ val = closeIdx !== -1 ? buf.slice(0, closeIdx) : buf;
1081
+ if (quote === '"') {
1082
+ val = val.replaceAll("\\n", "\n").replaceAll('\\"', '"').replaceAll("\\\\", "\\");
1083
+ }
1084
+ break;
1085
+ }
1086
+ i += 1;
1087
+ buf += `
1088
+ ${lines[i]}`;
1089
+ }
1090
+ } else {
1091
+ const hashIdx = rawVal.indexOf(" #");
1092
+ val = (hashIdx !== -1 ? rawVal.slice(0, hashIdx) : rawVal).trim();
924
1093
  }
925
1094
  if (key) rows.push({ key, value: val });
926
1095
  }
@@ -977,7 +1146,7 @@ async function reconcileConfiguredDomains(client, site, specs) {
977
1146
  return latestSite;
978
1147
  }
979
1148
  function registerDeployCommands(program2) {
980
- program2.command("deploy").alias("up").description("Deploy local static/SPA output, Express/Node source, or Git site to SagaCloud").option("--site <siteId>", "Target Site ID (overrides .sagacloud/project.json)").option("--name <siteName>", "Site name when creating a new site").option("--dir <outputDir>", "Pre-built static output directory (e.g. ./dist)").option("--build", "Run local build command before packaging static output").option("--no-build", "Skip running local build command").option("--static", "Deploy as static HTML/PHP site").option("--spa", "Deploy as Single Page App (Nginx try_files /index.html)").option("--node", "Deploy as Node.js / Express / SSR application").option("--port <port>", "Listening HTTP port for Node.js app", "3000").option("--start <cmd>", "Start command for Node.js app").option("--git", "Trigger remote Git redeploy instead of uploading local files").option("--force", "Bypass build cache on remote rebuild", false).option("--with-env <file>", "Load and push .env file variables before building").option("--detach", "Queue deployment and exit without streaming build logs", false).option("--yes", "Skip interactive prompts", false).action(
1149
+ program2.command("deploy").alias("up").description("Deploy local static/SPA output, Express/Node source, or Git site to SagaCloud").option("--site <siteId>", "Target Site ID (overrides .sagacloud/project.json)").option("--name <siteName>", "Site name when creating a new site").option("--dir <outputDir>", "Pre-built static output directory (e.g. ./dist)").option("--build", "Run local build command before packaging static output").option("--no-build", "Skip running local build command").option("--static", "Deploy as static HTML/PHP site").option("--spa", "Deploy as Single Page App (Nginx try_files /index.html)").option("--node", "Deploy as Node.js / Express / SSR application").option("--port <port>", "Listening HTTP port for Node.js app").option("--start <cmd>", "Start command for Node.js app").option("--git", "Trigger remote Git redeploy instead of uploading local files").option("--force", "Bypass build cache on remote rebuild", false).option("--with-env <file>", "Load and push .env file variables before building").option("--detach", "Queue deployment and exit without streaming build logs", false).option("--yes", "Skip interactive prompts", false).action(
981
1150
  async (opts) => {
982
1151
  const cwd = process.cwd();
983
1152
  const client = new SagaCloudClient();
@@ -1027,7 +1196,7 @@ function registerDeployCommands(program2) {
1027
1196
  runtimeVariant = jsonc.type;
1028
1197
  } else {
1029
1198
  siteType = "static";
1030
- runtimeVariant = jsonc.type === "static" || jsonc.type === "spa" && jsonc.spa_fallback === false ? "html" : jsonc.type;
1199
+ runtimeVariant = jsonc.type === "static" || jsonc.type === "html" || jsonc.type === "spa" && jsonc.spa_fallback === false ? "html" : jsonc.type;
1031
1200
  }
1032
1201
  } else if (link?.site_type) {
1033
1202
  siteType = link.site_type;
@@ -1048,14 +1217,20 @@ function registerDeployCommands(program2) {
1048
1217
  }
1049
1218
  const spin = p2.spinner();
1050
1219
  spin.start(`Packaging ${siteType === "node" ? "Node.js source" : outputRel}...`);
1051
- const archive = await createArchiveFromDirectory(
1052
- uploadDir,
1053
- jsonc?.ignore || [],
1054
- siteType === "node"
1055
- );
1220
+ const archive = await createArchiveFromDirectory(uploadDir, {
1221
+ extraIgnorePatterns: jsonc?.ignore || [],
1222
+ includeGitignore: siteType === "node" || path4.resolve(uploadDir) === path4.resolve(cwd),
1223
+ staticSiteFilter: siteType === "static",
1224
+ projectRootDir: cwd
1225
+ });
1056
1226
  spin.stop(
1057
1227
  `Packaged ${archive.fileCount} files (${(archive.sizeBytes / 1024).toFixed(1)} KB)`
1058
1228
  );
1229
+ if (archive.fileCount === 0) {
1230
+ throw new Error(
1231
+ `No deployable files found in '${outputRel}'. Check your output directory or ignore patterns.`
1232
+ );
1233
+ }
1059
1234
  const uploadSpin = p2.spinner();
1060
1235
  uploadSpin.start("Uploading bundle to SagaCloud...");
1061
1236
  const zipName = `${(jsonc?.app_name || jsonc?.name || path4.basename(cwd) || "bundle").replace(/[^a-z0-9-]+/gi, "-")}.zip`;
@@ -1064,7 +1239,7 @@ function registerDeployCommands(program2) {
1064
1239
  const mergedVars = /* @__PURE__ */ new Map();
1065
1240
  if (jsonc?.vars) {
1066
1241
  for (const [k, v] of Object.entries(jsonc.vars)) {
1067
- mergedVars.set(k, String(v));
1242
+ mergedVars.set(k, { value: String(v) });
1068
1243
  }
1069
1244
  }
1070
1245
  const envFilesToLoad = [jsonc?.env_file, opts.withEnv].filter((f) => Boolean(f));
@@ -1072,13 +1247,13 @@ function registerDeployCommands(program2) {
1072
1247
  const envPath = path4.resolve(cwd, relEnv);
1073
1248
  if (!fs4.existsSync(envPath)) throw new Error(`Env file not found: ${envPath}`);
1074
1249
  for (const item of parseDotEnvText(fs4.readFileSync(envPath, "utf8"))) {
1075
- mergedVars.set(item.key, item.value);
1250
+ mergedVars.set(item.key, { value: item.value, isBuildTime: item.isBuildTime });
1076
1251
  }
1077
1252
  }
1078
- const envPayload = Array.from(mergedVars.entries()).map(([key, value]) => ({
1253
+ const envPayload = Array.from(mergedVars.entries()).map(([key, item]) => ({
1079
1254
  key,
1080
- value,
1081
- is_build_time: siteType === "static"
1255
+ value: item.value,
1256
+ is_build_time: item.isBuildTime ?? siteType === "static"
1082
1257
  }));
1083
1258
  const forceRebuild = opts.force || Boolean(jsonc?.deploy?.force_rebuild);
1084
1259
  const detachMode = opts.detach || Boolean(jsonc?.deploy?.detach);
@@ -1086,6 +1261,61 @@ function registerDeployCommands(program2) {
1086
1261
  let targetSite;
1087
1262
  let dep;
1088
1263
  if (existingSiteId) {
1264
+ const settingsPatch = {
1265
+ site_id: existingSiteId
1266
+ };
1267
+ let hasSettingsUpdate = false;
1268
+ if (siteType === "node") {
1269
+ const nextPort = opts.port || (jsonc?.port !== void 0 ? String(jsonc.port) : "");
1270
+ if (nextPort) {
1271
+ settingsPatch.ports_exposes = nextPort;
1272
+ hasSettingsUpdate = true;
1273
+ }
1274
+ const nextStart = opts.start || jsonc?.start_command;
1275
+ if (nextStart) {
1276
+ settingsPatch.start_command = nextStart;
1277
+ hasSettingsUpdate = true;
1278
+ }
1279
+ if (jsonc?.install_command !== void 0) {
1280
+ settingsPatch.install_command = jsonc.install_command;
1281
+ hasSettingsUpdate = true;
1282
+ }
1283
+ if (jsonc?.build_command !== void 0) {
1284
+ settingsPatch.build_command = jsonc.build_command;
1285
+ hasSettingsUpdate = true;
1286
+ }
1287
+ } else {
1288
+ if (opts.spa || opts.static || jsonc?.spa_fallback !== void 0) {
1289
+ settingsPatch.is_spa = runtimeVariant === "spa" ? 1 : 0;
1290
+ hasSettingsUpdate = true;
1291
+ }
1292
+ if (opts.dir || jsonc?.output_dir) {
1293
+ settingsPatch.publish_directory = outputRel;
1294
+ hasSettingsUpdate = true;
1295
+ }
1296
+ }
1297
+ if (jsonc?.base_directory !== void 0) {
1298
+ settingsPatch.base_directory = jsonc.base_directory;
1299
+ hasSettingsUpdate = true;
1300
+ }
1301
+ if (jsonc?.healthcheck_path !== void 0) {
1302
+ settingsPatch.healthcheck_path = jsonc.healthcheck_path;
1303
+ hasSettingsUpdate = true;
1304
+ }
1305
+ if (jsonc?.resources?.memory !== void 0) {
1306
+ settingsPatch.limits_memory = String(jsonc.resources.memory);
1307
+ hasSettingsUpdate = true;
1308
+ }
1309
+ if (jsonc?.resources?.cpus !== void 0) {
1310
+ settingsPatch.limits_cpus = String(jsonc.resources.cpus);
1311
+ hasSettingsUpdate = true;
1312
+ }
1313
+ if (hasSettingsUpdate) {
1314
+ await client.rpc("saga_cloud.api.hosting.update_site_settings", {
1315
+ method: "POST",
1316
+ body: settingsPatch
1317
+ });
1318
+ }
1089
1319
  if (envPayload.length > 0) {
1090
1320
  await client.rpc("saga_cloud.api.hosting.save_site_envs", {
1091
1321
  method: "POST",
@@ -1258,21 +1488,55 @@ function registerEnvCommands(program2) {
1258
1488
  );
1259
1489
  console.log(pc4.green(`Synced ${res.envs?.length || 0} variables from ${filePath}. Redeploy to apply changes.`));
1260
1490
  });
1261
- env.command("pull [filePath]").description("Download remote environment variables to a local file").option("--site <siteId>", "Site ID").action(async (filePath = ".env.local", opts) => {
1491
+ env.command("pull [filePath]").description("Download remote environment variables to a local file").option("--site <siteId>", "Site ID").option("--json", "Write JSON including is_build_time metadata", false).action(async (filePath = ".env.local", opts) => {
1262
1492
  const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1263
1493
  const client = new SagaCloudClient();
1264
1494
  const res = await client.rpc("saga_cloud.api.hosting.get_site_envs", {
1265
1495
  query: { site_id: siteId }
1266
1496
  });
1497
+ const envs = res.envs || [];
1267
1498
  const outPath = path5.resolve(process.cwd(), filePath);
1268
- const lines = (res.envs || []).map((item) => {
1499
+ if (opts.json) {
1500
+ fs5.writeFileSync(
1501
+ outPath,
1502
+ `${JSON.stringify(
1503
+ envs.map((e) => ({
1504
+ key: e.key,
1505
+ value: e.value ?? "",
1506
+ is_build_time: Boolean(e.is_build_time)
1507
+ })),
1508
+ null,
1509
+ 2
1510
+ )}
1511
+ `,
1512
+ { mode: 384 }
1513
+ );
1514
+ console.log(pc4.green(`Wrote ${envs.length} variables (JSON with metadata) to ${filePath}`));
1515
+ return;
1516
+ }
1517
+ const buildTimeKeys = [];
1518
+ const lines = [];
1519
+ for (const item of envs) {
1269
1520
  const val = String(item.value ?? "");
1270
- const needsQuotes = /[\s#'"]/.test(val);
1271
- return `${item.key}=${needsQuotes ? JSON.stringify(val) : val}`;
1272
- });
1521
+ const needsQuotes = /[\s#'"\\]/.test(val);
1522
+ const formatted = `${item.key}=${needsQuotes ? JSON.stringify(val) : val}`;
1523
+ if (item.is_build_time) {
1524
+ buildTimeKeys.push(item.key);
1525
+ lines.push(`# build-time`, formatted);
1526
+ } else {
1527
+ lines.push(formatted);
1528
+ }
1529
+ }
1273
1530
  fs5.writeFileSync(outPath, `${lines.join("\n")}
1274
1531
  `, { mode: 384 });
1275
- console.log(pc4.green(`Wrote ${lines.length} variables to ${filePath}`));
1532
+ console.log(pc4.green(`Wrote ${envs.length} variables to ${filePath}`));
1533
+ if (buildTimeKeys.length > 0) {
1534
+ console.log(
1535
+ pc4.dim(
1536
+ `Note: ${buildTimeKeys.length} build-time variable(s) (${buildTimeKeys.join(", ")}); use \`env pull --json\` to preserve flags cleanly.`
1537
+ )
1538
+ );
1539
+ }
1276
1540
  });
1277
1541
  env.command("set <pairs...>").description("Set one or more KEY=VALUE variables").option("--site <siteId>", "Site ID").option("--build-time", "Mark variables as build-time", false).action(async (pairs, opts) => {
1278
1542
  const siteId = resolveActiveSiteId(process.cwd(), opts.site);
@@ -1337,7 +1601,10 @@ function registerOpsCommands(program2) {
1337
1601
  console.log(pc5.yellow("No deployments found for this site."));
1338
1602
  return;
1339
1603
  }
1340
- await streamBuildUntilDone(client, siteId, targetDep);
1604
+ const finalStatus = await streamBuildUntilDone(client, siteId, targetDep);
1605
+ if (finalStatus !== "finished") {
1606
+ process.exit(1);
1607
+ }
1341
1608
  }
1342
1609
  );
1343
1610
  program2.command("deployments").description("List deployment version history for a site").option("--site <siteId>", "Site ID").option("--limit <limit>", "Rows to fetch", "15").action(async (opts) => {
@@ -1366,25 +1633,20 @@ function registerOpsCommands(program2) {
1366
1633
  program2.command("rollback <versionOrId>").description("Roll back site to a previous version (e.g. `v2` or deployment ID)").option("--site <siteId>", "Site ID").action(async (versionOrId, opts) => {
1367
1634
  const siteId = resolveActiveSiteId(process.cwd(), opts.site);
1368
1635
  const client = new SagaCloudClient();
1369
- let depId = versionOrId.trim();
1370
- const vMatch = depId.match(/^v?(\d+)$/i);
1371
- if (vMatch) {
1372
- const ver = Number(vMatch[1]);
1373
- const list = await client.rpc(
1374
- "saga_cloud.api.hosting.list_deployments",
1375
- { query: { site_id: siteId, limit: 50 } }
1376
- );
1377
- const found = (list.deployments || []).find((d) => d.version_number === ver);
1378
- if (!found) throw new Error(`Version v${ver} not found.`);
1379
- depId = found.name;
1380
- }
1636
+ const raw = versionOrId.trim();
1637
+ const vMatch = raw.match(/^v?(\d+)$/i);
1638
+ const rollbackBody = vMatch ? { site_id: siteId, target_version: Number(vMatch[1]) } : { site_id: siteId, target_deployment_id: raw };
1381
1639
  const res = await client.rpc(
1382
1640
  "saga_cloud.api.hosting.rollback_site",
1383
- { method: "POST", body: { site_id: siteId, target_deployment_id: depId } }
1641
+ { method: "POST", body: rollbackBody }
1384
1642
  );
1385
1643
  console.log(pc5.green(`Queued rollback v${res.deployment.version_number} (${res.rollback_mode || "instant"})`));
1386
1644
  if (res.deployment.deployment_uuid) {
1387
- await streamBuildUntilDone(client, siteId, res.deployment.deployment_uuid);
1645
+ const finalStatus = await streamBuildUntilDone(client, siteId, res.deployment.deployment_uuid);
1646
+ if (finalStatus !== "finished") {
1647
+ console.log(pc5.red(`\u2717 Rollback v${res.deployment.version_number} ${finalStatus}`));
1648
+ process.exit(1);
1649
+ }
1388
1650
  }
1389
1651
  });
1390
1652
  const domains = program2.command("domains").description("Manage custom domains & Edge SSL");
@@ -1481,6 +1743,38 @@ function registerOpsCommands(program2) {
1481
1743
  const ci = program2.command("ci").description("CI/CD helpers");
1482
1744
  ci.command("init").description("Generate .github/workflows/sagacloud.yml").action(() => {
1483
1745
  const cwd = process.cwd();
1746
+ const detected = detectProject(cwd);
1747
+ const { config: jsonc } = readRepoJsoncConfig(cwd);
1748
+ const hasPackageJson = fs6.existsSync(path6.join(cwd, "package.json"));
1749
+ const hasLockfile = fs6.existsSync(path6.join(cwd, "package-lock.json"));
1750
+ const buildCmd = (jsonc?.build_command || detected.buildCommand || "").trim();
1751
+ const siteType = jsonc?.type === "node" || jsonc?.type === "nextjs" ? "node" : jsonc?.type ? "static" : detected.siteType;
1752
+ const outDir = jsonc?.output_dir || detected.outputDir || ".";
1753
+ const steps = [" - uses: actions/checkout@v4"];
1754
+ if (hasPackageJson && (siteType === "static" || Boolean(buildCmd))) {
1755
+ steps.push(
1756
+ " - uses: actions/setup-node@v4",
1757
+ " with:",
1758
+ " node-version: 22",
1759
+ ` - run: ${hasLockfile ? "npm ci" : "npm install"}`
1760
+ );
1761
+ if (buildCmd && siteType === "static") {
1762
+ steps.push(` - run: ${buildCmd}`);
1763
+ }
1764
+ }
1765
+ let deployCmd = "npx sagacloud deploy --yes";
1766
+ if (siteType === "node") {
1767
+ deployCmd = "npx sagacloud deploy --node --yes";
1768
+ } else if (outDir && outDir !== ".") {
1769
+ deployCmd = `npx sagacloud deploy --dir ${outDir} --no-build --yes`;
1770
+ } else {
1771
+ deployCmd = "npx sagacloud deploy --no-build --yes";
1772
+ }
1773
+ steps.push(
1774
+ ` - run: ${deployCmd}`,
1775
+ " env:",
1776
+ " SAGACLOUD_TOKEN: ${{ secrets.SAGACLOUD_TOKEN }}"
1777
+ );
1484
1778
  const wfDir = path6.join(cwd, ".github", "workflows");
1485
1779
  fs6.mkdirSync(wfDir, { recursive: true });
1486
1780
  const outPath = path6.join(wfDir, "sagacloud.yml");
@@ -1493,15 +1787,7 @@ function registerOpsCommands(program2) {
1493
1787
  " deploy:",
1494
1788
  " runs-on: ubuntu-latest",
1495
1789
  " steps:",
1496
- " - uses: actions/checkout@v4",
1497
- " - uses: actions/setup-node@v4",
1498
- " with:",
1499
- " node-version: 22",
1500
- " - run: npm ci",
1501
- " - run: npm run build",
1502
- " - run: npx sagacloud deploy --no-build --yes",
1503
- " env:",
1504
- " SAGACLOUD_TOKEN: ${{ secrets.SAGACLOUD_TOKEN }}",
1790
+ ...steps,
1505
1791
  ""
1506
1792
  ].join("\n");
1507
1793
  fs6.writeFileSync(outPath, yml);
@@ -1512,7 +1798,6 @@ function registerOpsCommands(program2) {
1512
1798
  // src/commands/project.ts
1513
1799
  import fs7 from "fs";
1514
1800
  import path7 from "path";
1515
- import { execFile as execFile2 } from "child_process";
1516
1801
  import * as p4 from "@clack/prompts";
1517
1802
  import Table4 from "cli-table3";
1518
1803
  import pc6 from "picocolors";
@@ -1595,7 +1880,7 @@ function registerProjectCommands(program2) {
1595
1880
  "{",
1596
1881
  ` // Auto-detected: ${detected.frameworkLabel}`,
1597
1882
  ` "app_name": ${JSON.stringify(siteName)},`,
1598
- ` "type": ${JSON.stringify(detected.runtimeVariant)},`,
1883
+ ` "type": ${JSON.stringify(detected.runtimeVariant === "html" ? "static" : detected.runtimeVariant)},`,
1599
1884
  ...detected.buildCommand ? [` "build_command": ${JSON.stringify(detected.buildCommand)},`] : [],
1600
1885
  ...detected.siteType === "static" ? [
1601
1886
  ` "output_dir": ${JSON.stringify(outDir || ".")},`,
@@ -1641,10 +1926,10 @@ function registerProjectCommands(program2) {
1641
1926
  });
1642
1927
  const url = res.site.live_url || `https://${res.site.domain}`;
1643
1928
  console.log(`Opening ${pc6.cyan(url)}`);
1644
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1645
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1646
- execFile2(cmd, args, () => {
1647
- });
1929
+ const opened = await openBrowser(url);
1930
+ if (!opened) {
1931
+ console.log(pc6.yellow("Browser opener is unavailable in this environment; open the URL above manually."));
1932
+ }
1648
1933
  });
1649
1934
  }
1650
1935
 
@@ -1757,7 +2042,7 @@ function registerSkillCommands(program2) {
1757
2042
 
1758
2043
  // src/index.ts
1759
2044
  var program = new Command();
1760
- program.name("sagacloud").description("SagaCloud CLI \u2014 deploy Static, SPA, Express & Node.js apps cleanly").version("0.3.0");
2045
+ program.name("sagacloud").description("SagaCloud CLI \u2014 deploy Static, SPA, Express & Node.js apps cleanly").version("0.3.1");
1761
2046
  registerAuthCommands(program);
1762
2047
  registerProjectCommands(program);
1763
2048
  registerDeployCommands(program);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sagacloud",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Official CLI for SagaCloud Web & App Hosting",
5
5
  "license": "MIT",
6
6
  "author": "SagaSoft",