@temps-sdk/cli 0.1.10 → 0.1.11

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 (3) hide show
  1. package/README.md +331 -6
  2. package/dist/index.js +2154 -1421
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -34829,14 +34829,14 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
34829
34829
  prevActScopeDepth !== actScopeDepth - 1 && console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ");
34830
34830
  actScopeDepth = prevActScopeDepth;
34831
34831
  }
34832
- function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
34832
+ function recursivelyFlushAsyncActWork(returnValue, resolve2, reject) {
34833
34833
  var queue = ReactSharedInternals.actQueue;
34834
34834
  if (queue !== null)
34835
34835
  if (queue.length !== 0)
34836
34836
  try {
34837
34837
  flushActQueue(queue);
34838
34838
  enqueueTask(function() {
34839
- return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
34839
+ return recursivelyFlushAsyncActWork(returnValue, resolve2, reject);
34840
34840
  });
34841
34841
  return;
34842
34842
  } catch (error3) {
@@ -34844,7 +34844,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
34844
34844
  }
34845
34845
  else
34846
34846
  ReactSharedInternals.actQueue = null;
34847
- 0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue);
34847
+ 0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve2(returnValue);
34848
34848
  }
34849
34849
  function flushActQueue(queue) {
34850
34850
  if (!isFlushing) {
@@ -35020,14 +35020,14 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
35020
35020
  didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"));
35021
35021
  });
35022
35022
  return {
35023
- then: function(resolve, reject) {
35023
+ then: function(resolve2, reject) {
35024
35024
  didAwaitActCall = true;
35025
35025
  thenable.then(function(returnValue) {
35026
35026
  popActScope(prevActQueue, prevActScopeDepth);
35027
35027
  if (prevActScopeDepth === 0) {
35028
35028
  try {
35029
35029
  flushActQueue(queue), enqueueTask(function() {
35030
- return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
35030
+ return recursivelyFlushAsyncActWork(returnValue, resolve2, reject);
35031
35031
  });
35032
35032
  } catch (error$0) {
35033
35033
  ReactSharedInternals.thrownErrors.push(error$0);
@@ -35038,7 +35038,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
35038
35038
  reject(_thrownError);
35039
35039
  }
35040
35040
  } else
35041
- resolve(returnValue);
35041
+ resolve2(returnValue);
35042
35042
  }, function(error3) {
35043
35043
  popActScope(prevActQueue, prevActScopeDepth);
35044
35044
  0 < ReactSharedInternals.thrownErrors.length ? (error3 = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(error3)) : reject(error3);
@@ -35054,11 +35054,11 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
35054
35054
  if (0 < ReactSharedInternals.thrownErrors.length)
35055
35055
  throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
35056
35056
  return {
35057
- then: function(resolve, reject) {
35057
+ then: function(resolve2, reject) {
35058
35058
  didAwaitActCall = true;
35059
35059
  prevActScopeDepth === 0 ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
35060
- return recursivelyFlushAsyncActWork(returnValue$jscomp$0, resolve, reject);
35061
- })) : resolve(returnValue$jscomp$0);
35060
+ return recursivelyFlushAsyncActWork(returnValue$jscomp$0, resolve2, reject);
35061
+ })) : resolve2(returnValue$jscomp$0);
35062
35062
  }
35063
35063
  };
35064
35064
  };
@@ -37900,8 +37900,8 @@ It can also happen if the client has a browser extension installed which messes
37900
37900
  currentEntangledActionThenable = {
37901
37901
  status: "pending",
37902
37902
  value: undefined,
37903
- then: function(resolve) {
37904
- entangledListeners.push(resolve);
37903
+ then: function(resolve2) {
37904
+ entangledListeners.push(resolve2);
37905
37905
  }
37906
37906
  };
37907
37907
  }
@@ -37925,8 +37925,8 @@ It can also happen if the client has a browser extension installed which messes
37925
37925
  status: "pending",
37926
37926
  value: null,
37927
37927
  reason: null,
37928
- then: function(resolve) {
37929
- listeners.push(resolve);
37928
+ then: function(resolve2) {
37929
+ listeners.push(resolve2);
37930
37930
  }
37931
37931
  };
37932
37932
  thenable.then(function() {
@@ -72424,6 +72424,9 @@ async function setupClient() {
72424
72424
  return request;
72425
72425
  });
72426
72426
  }
72427
+ function getWebUrl() {
72428
+ return config.get("apiUrl").replace(/\/+$/, "").replace(/\/api$/, "");
72429
+ }
72427
72430
  function getErrorMessage(error3) {
72428
72431
  if (!error3)
72429
72432
  return "Unknown error";
@@ -72533,7 +72536,7 @@ async function loginWithEmail(emailArg) {
72533
72536
  return true;
72534
72537
  }
72535
72538
  });
72536
- const apiUrl = config.get("apiUrl");
72539
+ const apiUrl = normalizeApiUrl(config.get("apiUrl"));
72537
72540
  const authResponse = await withSpinner("Logging in...", async () => {
72538
72541
  const response = await fetch(`${apiUrl}/auth/login`, {
72539
72542
  method: "POST",
@@ -72624,7 +72627,7 @@ async function loginWithEmail(emailArg) {
72624
72627
  }
72625
72628
  async function loginWithMagicLink(emailArg) {
72626
72629
  const email = emailArg ?? await promptEmail("Email");
72627
- const apiUrl = config.get("apiUrl");
72630
+ const apiUrl = normalizeApiUrl(config.get("apiUrl"));
72628
72631
  await withSpinner("Sending magic link...", async () => {
72629
72632
  const response = await fetch(`${apiUrl}/auth/magic-link/request`, {
72630
72633
  method: "POST",
@@ -72868,14 +72871,35 @@ async function runConfigureWizard(options) {
72868
72871
  console.log(colors.bold(`${icons.sparkles} Temps CLI Configuration`));
72869
72872
  console.log(colors.muted(`This wizard will help you configure the CLI.
72870
72873
  `));
72871
- const apiUrl = options.apiUrl ?? await promptUrl(`API URL [${colors.muted(currentConfig.apiUrl)}]`, currentConfig.apiUrl);
72872
- config.set("apiUrl", apiUrl);
72874
+ const envApiUrl = process.env.TEMPS_API_URL;
72875
+ let apiUrl;
72876
+ if (options.apiUrl) {
72877
+ apiUrl = options.apiUrl;
72878
+ } else if (envApiUrl) {
72879
+ console.log(` API URL: ${colors.bold(envApiUrl)} ${colors.muted("(env: TEMPS_API_URL)")}`);
72880
+ console.log(colors.muted(` To change, unset TEMPS_API_URL or use --api-url flag
72881
+ `));
72882
+ apiUrl = envApiUrl;
72883
+ } else {
72884
+ apiUrl = await promptUrl(`API URL [${colors.muted(currentConfig.apiUrl)}]`, currentConfig.apiUrl);
72885
+ }
72886
+ if (!envApiUrl || options.apiUrl) {
72887
+ config.set("apiUrl", apiUrl);
72888
+ }
72873
72889
  let authStatus = "Not authenticated";
72890
+ const envApiToken = process.env.TEMPS_TOKEN || process.env.TEMPS_API_TOKEN || process.env.TEMPS_API_KEY;
72891
+ const envApiTokenName = process.env.TEMPS_TOKEN ? "TEMPS_TOKEN" : process.env.TEMPS_API_TOKEN ? "TEMPS_API_TOKEN" : process.env.TEMPS_API_KEY ? "TEMPS_API_KEY" : null;
72874
72892
  if (options.apiToken) {
72875
72893
  const tokenValid = await validateAndSaveToken(options.apiToken, apiUrl);
72876
72894
  if (tokenValid) {
72877
72895
  authStatus = `Authenticated as ${await credentials.get("email") ?? "unknown"}`;
72878
72896
  }
72897
+ } else if (envApiToken) {
72898
+ const email = await credentials.get("email");
72899
+ authStatus = `Authenticated as ${email ?? "unknown"} ${colors.muted(`(env: ${envApiTokenName})`)}`;
72900
+ console.log(`
72901
+ API Token: ${colors.muted("***")} ${colors.muted(`(env: ${envApiTokenName})`)}`);
72902
+ console.log(colors.muted(` To change, unset ${envApiTokenName} or use --api-token flag`));
72879
72903
  } else if (isAuthenticated) {
72880
72904
  console.log(colors.muted(`
72881
72905
  Currently authenticated as: ${colors.bold(currentEmail ?? "unknown")}`));
@@ -72934,11 +72958,11 @@ Currently authenticated as: ${colors.bold(currentEmail ?? "unknown")}`));
72934
72958
  message: "Enable colored output?",
72935
72959
  default: currentConfig.colorEnabled
72936
72960
  });
72937
- config.setAll({
72938
- apiUrl,
72939
- outputFormat,
72940
- colorEnabled
72941
- });
72961
+ const configToSave = { outputFormat, colorEnabled };
72962
+ if (!envApiUrl || options.apiUrl) {
72963
+ configToSave.apiUrl = apiUrl;
72964
+ }
72965
+ config.setAll(configToSave);
72942
72966
  newline();
72943
72967
  box(`API URL: ${apiUrl}
72944
72968
  ` + `API Token: ${authStatus}
@@ -72985,11 +73009,18 @@ function setConfigValue(key, value) {
72985
73009
  success(`Set ${key} = ${value}`);
72986
73010
  }
72987
73011
  function listConfig() {
72988
- const allConfig = config.getAll();
73012
+ const storedConfig = config.getAll();
72989
73013
  newline();
72990
73014
  header(`${icons.folder} Configuration`);
72991
- for (const [key, value] of Object.entries(allConfig)) {
72992
- keyValue(key, value);
73015
+ for (const [key, storedValue] of Object.entries(storedConfig)) {
73016
+ const effectiveValue = config.get(key);
73017
+ const isOverridden = key === "apiUrl" && process.env.TEMPS_API_URL;
73018
+ if (isOverridden) {
73019
+ keyValue(key, `${effectiveValue} ${colors.muted("(env: TEMPS_API_URL)")}`);
73020
+ keyValue(` ${colors.muted("stored")}`, colors.muted(String(storedValue)));
73021
+ } else {
73022
+ keyValue(key, effectiveValue);
73023
+ }
72993
73024
  }
72994
73025
  newline();
72995
73026
  info(`Configuration file: ${colors.muted(config.path)}`);
@@ -73001,8 +73032,9 @@ async function showConfig(options) {
73001
73032
  const envApiUrl = process.env.TEMPS_API_URL;
73002
73033
  const apiUrlSource = envApiUrl ? "env" : "config";
73003
73034
  const apiUrl = envApiUrl || allConfig.apiUrl;
73004
- const envApiKey = process.env.TEMPS_API_TOKEN || process.env.TEMPS_API_KEY;
73035
+ const envApiKey = process.env.TEMPS_TOKEN || process.env.TEMPS_API_TOKEN || process.env.TEMPS_API_KEY;
73005
73036
  const apiKeySource = envApiKey ? "env" : "config";
73037
+ const apiKeyEnvName = process.env.TEMPS_TOKEN ? "TEMPS_TOKEN" : process.env.TEMPS_API_TOKEN ? "TEMPS_API_TOKEN" : process.env.TEMPS_API_KEY ? "TEMPS_API_KEY" : null;
73006
73038
  let maskedApiKey = "Not configured";
73007
73039
  if (apiKey) {
73008
73040
  if (apiKey.length > 8) {
@@ -73030,12 +73062,12 @@ async function showConfig(options) {
73030
73062
  header(`${icons.sparkles} Temps CLI Configuration`);
73031
73063
  newline();
73032
73064
  if (apiUrlSource === "env") {
73033
- keyValue("API URL", `${apiUrl} ${colors.muted("(from TEMPS_API_URL)")}`);
73065
+ keyValue("API URL", `${apiUrl} ${colors.muted("(env: TEMPS_API_URL)")}`);
73034
73066
  } else {
73035
73067
  keyValue("API URL", apiUrl);
73036
73068
  }
73037
73069
  if (apiKey) {
73038
- const sourceNote = apiKeySource === "env" ? colors.muted("(from TEMPS_API_TOKEN)") : colors.muted("(from config)");
73070
+ const sourceNote = apiKeySource === "env" ? colors.muted(`(env: ${apiKeyEnvName})`) : colors.muted("(config)");
73039
73071
  keyValue("API Key", `${maskedApiKey} ${sourceNote}`);
73040
73072
  } else {
73041
73073
  keyValue("API Key", colors.warning("Not configured"));
@@ -73305,6 +73337,52 @@ init_prompts();
73305
73337
  init_output();
73306
73338
  init_sdk_gen();
73307
73339
 
73340
+ // src/lib/env-file.ts
73341
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
73342
+ import { resolve } from "node:path";
73343
+ function parseEnvFile(content) {
73344
+ const variables = {};
73345
+ for (const line of content.split(`
73346
+ `)) {
73347
+ const trimmed = line.trim();
73348
+ if (!trimmed || trimmed.startsWith("#"))
73349
+ continue;
73350
+ const match = trimmed.match(/^([^=]+)=(.*)$/);
73351
+ if (!match)
73352
+ continue;
73353
+ const [, key, rawValue] = match;
73354
+ if (!key || rawValue === undefined)
73355
+ continue;
73356
+ let value = rawValue.trim();
73357
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
73358
+ value = value.slice(1, -1).replace(/\\n/g, `
73359
+ `).replace(/\\"/g, '"').replace(/\\'/g, "'");
73360
+ }
73361
+ variables[key.trim()] = value;
73362
+ }
73363
+ return variables;
73364
+ }
73365
+ function readEnvFile(filePath) {
73366
+ const resolved = resolve(filePath);
73367
+ if (!existsSync2(resolved)) {
73368
+ return null;
73369
+ }
73370
+ const content = readFileSync2(resolved, "utf-8");
73371
+ return parseEnvFile(content);
73372
+ }
73373
+ function findEnvFiles(dir) {
73374
+ const cwd = dir ?? process.cwd();
73375
+ const candidates = [".env", ".env.local", ".env.development", ".env.example"];
73376
+ const found = [];
73377
+ for (const name of candidates) {
73378
+ const fullPath = resolve(cwd, name);
73379
+ if (existsSync2(fullPath)) {
73380
+ found.push(name);
73381
+ }
73382
+ }
73383
+ return found;
73384
+ }
73385
+
73308
73386
  // src/lib/git-connection.ts
73309
73387
  init_sdk_gen();
73310
73388
  init_prompts();
@@ -73655,6 +73733,32 @@ async function createNewService() {
73655
73733
  });
73656
73734
  return createNewServiceOfType(serviceType);
73657
73735
  }
73736
+ function sanitizeToIdentifier(name) {
73737
+ let sanitized = name.replace(/[^a-zA-Z0-9_]/g, "_").toLowerCase();
73738
+ if (sanitized && !/^[a-z]/.test(sanitized)) {
73739
+ sanitized = `svc_${sanitized}`;
73740
+ }
73741
+ return sanitized || "default";
73742
+ }
73743
+ var KNOWN_REQUIRED_FIELDS = {
73744
+ postgres: ["database", "username"],
73745
+ mongodb: ["database", "username"]
73746
+ };
73747
+ function autoGenerateRequiredParams(serviceType, serviceName, requiredFields) {
73748
+ const params = {};
73749
+ const identifier = sanitizeToIdentifier(serviceName);
73750
+ for (const field of requiredFields) {
73751
+ switch (field) {
73752
+ case "database":
73753
+ params.database = identifier;
73754
+ break;
73755
+ case "username":
73756
+ params.username = identifier;
73757
+ break;
73758
+ }
73759
+ }
73760
+ return params;
73761
+ }
73658
73762
  async function createNewServiceOfType(serviceType) {
73659
73763
  const typeLabel = SERVICE_TYPES.find((t) => t.id === serviceType)?.name || serviceType;
73660
73764
  const serviceName = await promptText({
@@ -73662,22 +73766,52 @@ async function createNewServiceOfType(serviceType) {
73662
73766
  default: `${serviceType}-${Date.now().toString(36)}`,
73663
73767
  required: true
73664
73768
  });
73665
- const { data, error: apiError } = await withSpinner(`Creating ${typeLabel} service...`, async () => {
73666
- return await createService({
73769
+ let requiredFields = [];
73770
+ try {
73771
+ const { data: schemaData, error: schemaError } = await getServiceTypeParameters({
73667
73772
  client,
73668
- body: {
73669
- name: serviceName,
73670
- service_type: serviceType,
73671
- parameters: {}
73773
+ path: { service_type: serviceType }
73774
+ });
73775
+ if (!schemaError && schemaData) {
73776
+ const schema = schemaData;
73777
+ if (schema.required && Array.isArray(schema.required)) {
73778
+ requiredFields = schema.required;
73672
73779
  }
73780
+ }
73781
+ } catch {}
73782
+ if (requiredFields.length === 0) {
73783
+ requiredFields = KNOWN_REQUIRED_FIELDS[serviceType] ?? [];
73784
+ }
73785
+ const parameters = autoGenerateRequiredParams(serviceType, serviceName, requiredFields);
73786
+ const MAX_RETRIES = 2;
73787
+ for (let attempt = 1;attempt <= MAX_RETRIES; attempt++) {
73788
+ const { data, error: apiError } = await withSpinner(`Creating ${typeLabel} service...`, async () => {
73789
+ return await createService({
73790
+ client,
73791
+ body: {
73792
+ name: serviceName,
73793
+ service_type: serviceType,
73794
+ parameters
73795
+ }
73796
+ });
73673
73797
  });
73674
- });
73675
- if (apiError || !data) {
73676
- error(`Failed to create service: ${getErrorMessage(apiError)}`);
73677
- return null;
73798
+ if (data?.id) {
73799
+ success(`Service "${serviceName}" created`);
73800
+ return data.id;
73801
+ }
73802
+ const errorMsg = getErrorMessage(apiError);
73803
+ error(`Failed to create service: ${errorMsg}`);
73804
+ if (attempt < MAX_RETRIES) {
73805
+ const retry = await promptConfirm({
73806
+ message: "Retry creating this service?",
73807
+ default: true
73808
+ });
73809
+ if (!retry) {
73810
+ return null;
73811
+ }
73812
+ }
73678
73813
  }
73679
- success(`Service "${serviceName}" created`);
73680
- return data.id;
73814
+ return null;
73681
73815
  }
73682
73816
 
73683
73817
  // src/commands/projects/create.ts
@@ -73785,41 +73919,195 @@ async function configureEnvironmentVariables() {
73785
73919
  return [];
73786
73920
  }
73787
73921
  const envVars = [];
73788
- let addMore = true;
73789
- while (addMore) {
73790
- newline();
73791
- const key = await promptText({
73792
- message: "Variable name (e.g., DATABASE_URL)",
73793
- required: true,
73794
- validate: (v) => {
73795
- if (!v)
73796
- return "Variable name is required";
73797
- if (!/^[A-Z_][A-Z0-9_]*$/i.test(v)) {
73798
- return "Variable name must start with a letter or underscore and contain only letters, numbers, and underscores";
73922
+ const envFiles = findEnvFiles();
73923
+ const methodChoices = [];
73924
+ if (envFiles.length > 0) {
73925
+ methodChoices.push({
73926
+ name: `Import from file (${envFiles.join(", ")} found)`,
73927
+ value: "file",
73928
+ description: "Load variables from a .env file"
73929
+ });
73930
+ }
73931
+ methodChoices.push({
73932
+ name: "Enter manually",
73933
+ value: "manual",
73934
+ description: "Type key-value pairs one by one"
73935
+ }, {
73936
+ name: "Specify file path",
73937
+ value: "path",
73938
+ description: "Provide a custom path to a .env file"
73939
+ });
73940
+ const method = methodChoices.length === 1 ? "manual" : await promptSelect({ message: "How to add variables?", choices: methodChoices });
73941
+ if (method === "file" || method === "path") {
73942
+ let filePath;
73943
+ if (method === "file") {
73944
+ if (envFiles.length === 1) {
73945
+ filePath = envFiles[0];
73946
+ } else {
73947
+ filePath = await promptSelect({
73948
+ message: "Select .env file",
73949
+ choices: envFiles.map((f) => ({ name: f, value: f }))
73950
+ });
73951
+ }
73952
+ } else {
73953
+ filePath = await promptText({
73954
+ message: "Path to .env file",
73955
+ default: ".env",
73956
+ required: true
73957
+ });
73958
+ }
73959
+ const parsed = readEnvFile(filePath);
73960
+ if (!parsed || Object.keys(parsed).length === 0) {
73961
+ warning(`No variables found in ${filePath}`);
73962
+ } else {
73963
+ const entries = Object.entries(parsed);
73964
+ newline();
73965
+ info(`Found ${entries.length} variable(s) in ${colors.bold(filePath)}:`);
73966
+ newline();
73967
+ for (const [key, value] of entries) {
73968
+ const masked = value.length > 30 ? `${value.substring(0, 30)}...` : value;
73969
+ keyValue(` ${key}`, colors.muted(masked));
73970
+ }
73971
+ newline();
73972
+ const confirm = await promptConfirm({
73973
+ message: `Import ${entries.length} variable(s)?`,
73974
+ default: true
73975
+ });
73976
+ if (confirm) {
73977
+ for (const [key, value] of entries) {
73978
+ envVars.push([key, value]);
73799
73979
  }
73800
- return true;
73980
+ success(`Imported ${entries.length} variable(s) from ${filePath}`);
73801
73981
  }
73802
- });
73803
- const value = await promptText({
73804
- message: `Value for ${key}`,
73805
- required: true
73806
- });
73807
- envVars.push([key, value]);
73808
- addMore = await promptConfirm({
73809
- message: "Add another environment variable?",
73982
+ }
73983
+ }
73984
+ if (method === "manual" || envVars.length > 0) {
73985
+ const shouldAddManual = method === "manual" || await promptConfirm({
73986
+ message: "Add more variables manually?",
73810
73987
  default: false
73811
73988
  });
73989
+ if (shouldAddManual) {
73990
+ let addMore = true;
73991
+ while (addMore) {
73992
+ newline();
73993
+ const key = await promptText({
73994
+ message: "Variable name (e.g., DATABASE_URL)",
73995
+ required: true,
73996
+ validate: (v) => {
73997
+ if (!v)
73998
+ return "Variable name is required";
73999
+ if (!/^[A-Z_][A-Z0-9_]*$/i.test(v)) {
74000
+ return "Variable name must start with a letter or underscore and contain only letters, numbers, and underscores";
74001
+ }
74002
+ return true;
74003
+ }
74004
+ });
74005
+ const value = await promptText({
74006
+ message: `Value for ${key}`,
74007
+ required: true
74008
+ });
74009
+ envVars.push([key, value]);
74010
+ addMore = await promptConfirm({
74011
+ message: "Add another variable?",
74012
+ default: false
74013
+ });
74014
+ }
74015
+ }
73812
74016
  }
73813
74017
  return envVars;
73814
74018
  }
73815
74019
 
74020
+ // src/config/project-config.ts
74021
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "node:fs/promises";
74022
+ import { existsSync as existsSync3 } from "node:fs";
74023
+ import { join, dirname as dirname2 } from "node:path";
74024
+ var CONFIG_DIR = ".temps";
74025
+ var CONFIG_FILE = "config.json";
74026
+ var GITIGNORE_FILE = ".gitignore";
74027
+ function findProjectConfigDir(startDir) {
74028
+ let dir = startDir ?? process.cwd();
74029
+ while (true) {
74030
+ const configPath = join(dir, CONFIG_DIR, CONFIG_FILE);
74031
+ if (existsSync3(configPath)) {
74032
+ return join(dir, CONFIG_DIR);
74033
+ }
74034
+ const parent = dirname2(dir);
74035
+ if (parent === dir)
74036
+ break;
74037
+ dir = parent;
74038
+ }
74039
+ return null;
74040
+ }
74041
+ async function readProjectConfig() {
74042
+ const configDir = findProjectConfigDir();
74043
+ if (!configDir)
74044
+ return null;
74045
+ try {
74046
+ const configPath = join(configDir, CONFIG_FILE);
74047
+ const content = await readFile2(configPath, "utf-8");
74048
+ return JSON.parse(content);
74049
+ } catch {
74050
+ return null;
74051
+ }
74052
+ }
74053
+ async function writeProjectConfig(config2) {
74054
+ const configDir = join(process.cwd(), CONFIG_DIR);
74055
+ await mkdir2(configDir, { recursive: true });
74056
+ const configPath = join(configDir, CONFIG_FILE);
74057
+ await writeFile2(configPath, JSON.stringify(config2, null, 2) + `
74058
+ `, "utf-8");
74059
+ const gitignorePath = join(configDir, GITIGNORE_FILE);
74060
+ if (!existsSync3(gitignorePath)) {
74061
+ await writeFile2(gitignorePath, `*
74062
+ `, "utf-8");
74063
+ }
74064
+ return configPath;
74065
+ }
74066
+ function hasProjectConfig() {
74067
+ return findProjectConfigDir() !== null;
74068
+ }
74069
+
74070
+ // src/config/resolve-project.ts
74071
+ async function resolveProjectSlug(flagValue) {
74072
+ if (flagValue) {
74073
+ return { slug: flagValue, source: "flag" };
74074
+ }
74075
+ const localConfig = await readProjectConfig();
74076
+ if (localConfig?.projectSlug) {
74077
+ return { slug: localConfig.projectSlug, source: "local-config" };
74078
+ }
74079
+ const envProject = process.env.TEMPS_PROJECT;
74080
+ if (envProject) {
74081
+ return { slug: envProject, source: "env-var" };
74082
+ }
74083
+ const defaultProject = config.get("defaultProject");
74084
+ if (defaultProject) {
74085
+ return { slug: defaultProject, source: "global-config" };
74086
+ }
74087
+ return null;
74088
+ }
74089
+ async function requireProjectSlug(flagValue) {
74090
+ const resolved = await resolveProjectSlug(flagValue);
74091
+ if (resolved)
74092
+ return resolved;
74093
+ throw new Error(`No project specified. You can:
74094
+ ` + ` • Pass --project <slug> flag
74095
+ ` + ` • Run "temps link" to link this directory to a project
74096
+ ` + ` • Set TEMPS_PROJECT environment variable
74097
+ ` + ' • Run "temps configure" to set a default project');
74098
+ }
74099
+
73816
74100
  // src/commands/projects/show.ts
73817
74101
  init_output();
73818
74102
  init_sdk_gen();
73819
74103
  async function show(options) {
73820
74104
  await requireAuth();
73821
74105
  await setupClient();
73822
- const projectIdOrName = options.project;
74106
+ const resolved = await requireProjectSlug(options.project);
74107
+ if (resolved.source !== "flag") {
74108
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
74109
+ }
74110
+ const projectIdOrName = resolved.slug;
73823
74111
  const project = await withSpinner("Fetching project...", async () => {
73824
74112
  const id = parseInt(projectIdOrName, 10);
73825
74113
  if (!isNaN(id)) {
@@ -73866,7 +74154,11 @@ init_sdk_gen();
73866
74154
  async function remove(options) {
73867
74155
  await requireAuth();
73868
74156
  await setupClient();
73869
- const projectIdOrName = options.project;
74157
+ const resolved = await requireProjectSlug(options.project);
74158
+ if (resolved.source !== "flag") {
74159
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
74160
+ }
74161
+ const projectIdOrName = resolved.slug;
73870
74162
  newline();
73871
74163
  if (!options.force && !options.yes) {
73872
74164
  warning(`You are about to delete project "${colors.bold(projectIdOrName)}"`);
@@ -73908,7 +74200,11 @@ init_output();
73908
74200
  async function updateProjectAction(options) {
73909
74201
  await requireAuth();
73910
74202
  await setupClient();
73911
- const projectIdOrSlug = options.project;
74203
+ const resolved = await requireProjectSlug(options.project);
74204
+ if (resolved.source !== "flag") {
74205
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
74206
+ }
74207
+ const projectIdOrSlug = resolved.slug;
73912
74208
  const project = await withSpinner("Fetching project...", async () => {
73913
74209
  const id = parseInt(projectIdOrSlug, 10);
73914
74210
  if (!isNaN(id)) {
@@ -73966,77 +74262,85 @@ async function updateProjectAction(options) {
73966
74262
  async function updateSettingsAction(options) {
73967
74263
  await requireAuth();
73968
74264
  await setupClient();
73969
- const projectIdOrSlug = options.project;
73970
- const project = await withSpinner("Fetching project...", async () => {
73971
- const id = parseInt(projectIdOrSlug, 10);
73972
- if (!isNaN(id)) {
73973
- const { data: data2, error: error4 } = await getProject({
73974
- client,
73975
- path: { id }
73976
- });
73977
- if (error4 || !data2) {
73978
- throw new Error(getErrorMessage(error4) ?? `Project "${projectIdOrSlug}" not found`);
73979
- }
73980
- return data2;
73981
- }
73982
- const { data, error: error3 } = await getProjectBySlug({
73983
- client,
73984
- path: { slug: projectIdOrSlug }
73985
- });
73986
- if (error3 || !data) {
73987
- throw new Error(getErrorMessage(error3) ?? `Project "${projectIdOrSlug}" not found`);
73988
- }
73989
- return data;
73990
- });
73991
- let slug = options.slug;
73992
- let attackMode = options.attackMode;
73993
- let previewEnvs = options.previewEnvs;
73994
- if (slug === undefined && attackMode === undefined && previewEnvs === undefined && !options.yes) {
73995
- newline();
73996
- header("Update Project Settings");
73997
- info(`Current settings for "${project.name}"`);
73998
- newline();
73999
- slug = await promptText({
74000
- message: "Project slug (URL-friendly identifier)",
74001
- default: project.slug
74002
- });
74003
- attackMode = await promptConfirm({
74004
- message: "Enable attack mode (CAPTCHA protection)?",
74005
- default: project.attack_mode ?? false
74006
- });
74007
- previewEnvs = await promptConfirm({
74008
- message: "Enable preview environments for branches?",
74009
- default: project.enable_preview_environments ?? false
74010
- });
74011
- }
74012
- const updated = await withSpinner("Updating project settings...", async () => {
74013
- const { data, error: error3 } = await updateProjectSettings({
74014
- client,
74015
- path: { project_id: project.id },
74016
- body: {
74017
- slug: slug ?? undefined,
74018
- attack_mode: attackMode ?? undefined,
74019
- enable_preview_environments: previewEnvs ?? undefined
74020
- }
74021
- });
74022
- if (error3) {
74023
- throw new Error(getErrorMessage(error3));
74024
- }
74025
- return data;
74026
- });
74027
- if (options.json) {
74028
- json(updated);
74029
- return;
74265
+ const resolved = await requireProjectSlug(options.project);
74266
+ if (resolved.source !== "flag") {
74267
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
74030
74268
  }
74031
- success("Project settings updated successfully");
74032
- keyValue("Slug", slug ?? project.slug);
74033
- keyValue("Attack Mode", attackMode ? colors.success("Enabled") : colors.muted("Disabled"));
74034
- keyValue("Preview Environments", previewEnvs ? colors.success("Enabled") : colors.muted("Disabled"));
74035
- }
74036
- async function updateGitAction(options) {
74037
- await requireAuth();
74038
- await setupClient();
74039
- const projectIdOrSlug = options.project;
74269
+ const projectIdOrSlug = resolved.slug;
74270
+ const project = await withSpinner("Fetching project...", async () => {
74271
+ const id = parseInt(projectIdOrSlug, 10);
74272
+ if (!isNaN(id)) {
74273
+ const { data: data2, error: error4 } = await getProject({
74274
+ client,
74275
+ path: { id }
74276
+ });
74277
+ if (error4 || !data2) {
74278
+ throw new Error(getErrorMessage(error4) ?? `Project "${projectIdOrSlug}" not found`);
74279
+ }
74280
+ return data2;
74281
+ }
74282
+ const { data, error: error3 } = await getProjectBySlug({
74283
+ client,
74284
+ path: { slug: projectIdOrSlug }
74285
+ });
74286
+ if (error3 || !data) {
74287
+ throw new Error(getErrorMessage(error3) ?? `Project "${projectIdOrSlug}" not found`);
74288
+ }
74289
+ return data;
74290
+ });
74291
+ let slug = options.slug;
74292
+ let attackMode = options.attackMode;
74293
+ let previewEnvs = options.previewEnvs;
74294
+ if (slug === undefined && attackMode === undefined && previewEnvs === undefined && !options.yes) {
74295
+ newline();
74296
+ header("Update Project Settings");
74297
+ info(`Current settings for "${project.name}"`);
74298
+ newline();
74299
+ slug = await promptText({
74300
+ message: "Project slug (URL-friendly identifier)",
74301
+ default: project.slug
74302
+ });
74303
+ attackMode = await promptConfirm({
74304
+ message: "Enable attack mode (CAPTCHA protection)?",
74305
+ default: project.attack_mode ?? false
74306
+ });
74307
+ previewEnvs = await promptConfirm({
74308
+ message: "Enable preview environments for branches?",
74309
+ default: project.enable_preview_environments ?? false
74310
+ });
74311
+ }
74312
+ const updated = await withSpinner("Updating project settings...", async () => {
74313
+ const { data, error: error3 } = await updateProjectSettings({
74314
+ client,
74315
+ path: { project_id: project.id },
74316
+ body: {
74317
+ slug: slug ?? undefined,
74318
+ attack_mode: attackMode ?? undefined,
74319
+ enable_preview_environments: previewEnvs ?? undefined
74320
+ }
74321
+ });
74322
+ if (error3) {
74323
+ throw new Error(getErrorMessage(error3));
74324
+ }
74325
+ return data;
74326
+ });
74327
+ if (options.json) {
74328
+ json(updated);
74329
+ return;
74330
+ }
74331
+ success("Project settings updated successfully");
74332
+ keyValue("Slug", slug ?? project.slug);
74333
+ keyValue("Attack Mode", attackMode ? colors.success("Enabled") : colors.muted("Disabled"));
74334
+ keyValue("Preview Environments", previewEnvs ? colors.success("Enabled") : colors.muted("Disabled"));
74335
+ }
74336
+ async function updateGitAction(options) {
74337
+ await requireAuth();
74338
+ await setupClient();
74339
+ const resolved = await requireProjectSlug(options.project);
74340
+ if (resolved.source !== "flag") {
74341
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
74342
+ }
74343
+ const projectIdOrSlug = resolved.slug;
74040
74344
  const project = await withSpinner("Fetching project...", async () => {
74041
74345
  const id = parseInt(projectIdOrSlug, 10);
74042
74346
  if (!isNaN(id)) {
@@ -74141,7 +74445,11 @@ async function updateGitAction(options) {
74141
74445
  async function updateConfigAction(options) {
74142
74446
  await requireAuth();
74143
74447
  await setupClient();
74144
- const projectIdOrSlug = options.project;
74448
+ const resolved = await requireProjectSlug(options.project);
74449
+ if (resolved.source !== "flag") {
74450
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
74451
+ }
74452
+ const projectIdOrSlug = resolved.slug;
74145
74453
  const project = await withSpinner("Fetching project...", async () => {
74146
74454
  const id = parseInt(projectIdOrSlug, 10);
74147
74455
  if (!isNaN(id)) {
@@ -74228,194 +74536,18 @@ function registerProjectsCommands(program2) {
74228
74536
  const projects = program2.command("projects").alias("project").alias("p").description("Manage projects");
74229
74537
  projects.command("list").alias("ls").description("List all projects").option("--json", "Output in JSON format").option("--page <n>", "Page number").option("--per-page <n>", "Items per page").action(list);
74230
74538
  projects.command("create").alias("new").description("Create a new project").option("-n, --name <name>", "Project name").option("-d, --description <description>", "Project description").option("--repo <repository>", "Git repository URL").action(create);
74231
- projects.command("show").alias("get").description("Show project details").requiredOption("-p, --project <project>", "Project slug or ID").option("--json", "Output in JSON format").action(show);
74232
- projects.command("update").alias("edit").description("Update project name and description").requiredOption("-p, --project <project>", "Project slug or ID").option("-n, --name <name>", "New project name").option("-d, --description <description>", "New project description").option("--json", "Output in JSON format").option("-y, --yes", "Skip prompts, use provided values (for automation)").action(updateProjectAction);
74233
- projects.command("settings").description("Update project settings (slug, attack mode, preview environments)").requiredOption("-p, --project <project>", "Project slug or ID").option("--slug <slug>", "Project URL slug").option("--attack-mode", "Enable attack mode (CAPTCHA protection)").option("--no-attack-mode", "Disable attack mode").option("--preview-envs", "Enable preview environments").option("--no-preview-envs", "Disable preview environments").option("--json", "Output in JSON format").option("-y, --yes", "Skip prompts (for automation)").action(updateSettingsAction);
74234
- projects.command("git").description("Update git repository settings").requiredOption("-p, --project <project>", "Project slug or ID").option("--owner <owner>", "Repository owner").option("--repo <repo>", "Repository name").option("--branch <branch>", "Main branch").option("--directory <directory>", "App directory path").option("--preset <preset>", "Build preset (auto, nextjs, nodejs, static, docker, rust, go, python)").option("--json", "Output in JSON format").option("-y, --yes", "Skip prompts, use provided/existing values (for automation)").action(updateGitAction);
74235
- projects.command("config").description("Update deployment configuration (resources, replicas)").requiredOption("-p, --project <project>", "Project slug or ID").option("--replicas <n>", "Number of container replicas").option("--cpu-limit <limit>", "CPU limit in cores (e.g., 0.5, 1, 2)").option("--memory-limit <limit>", "Memory limit in MB").option("--auto-deploy", "Enable automatic deployments").option("--no-auto-deploy", "Disable automatic deployments").option("--json", "Output in JSON format").option("-y, --yes", "Skip prompts (for automation)").action(updateConfigAction);
74236
- projects.command("delete").alias("rm").description("Delete a project").requiredOption("-p, --project <project>", "Project slug or ID").option("-f, --force", "Skip confirmation").option("-y, --yes", "Skip confirmation (alias for --force)").action(remove);
74539
+ projects.command("show").alias("get").description("Show project details").option("-p, --project <project>", "Project slug or ID").option("--json", "Output in JSON format").action(show);
74540
+ projects.command("update").alias("edit").description("Update project name and description").option("-p, --project <project>", "Project slug or ID").option("-n, --name <name>", "New project name").option("-d, --description <description>", "New project description").option("--json", "Output in JSON format").option("-y, --yes", "Skip prompts, use provided values (for automation)").action(updateProjectAction);
74541
+ projects.command("settings").description("Update project settings (slug, attack mode, preview environments)").option("-p, --project <project>", "Project slug or ID").option("--slug <slug>", "Project URL slug").option("--attack-mode", "Enable attack mode (CAPTCHA protection)").option("--no-attack-mode", "Disable attack mode").option("--preview-envs", "Enable preview environments").option("--no-preview-envs", "Disable preview environments").option("--json", "Output in JSON format").option("-y, --yes", "Skip prompts (for automation)").action(updateSettingsAction);
74542
+ projects.command("git").description("Update git repository settings").option("-p, --project <project>", "Project slug or ID").option("--owner <owner>", "Repository owner").option("--repo <repo>", "Repository name").option("--branch <branch>", "Main branch").option("--directory <directory>", "App directory path").option("--preset <preset>", "Build preset (auto, nextjs, nodejs, static, docker, rust, go, python)").option("--json", "Output in JSON format").option("-y, --yes", "Skip prompts, use provided/existing values (for automation)").action(updateGitAction);
74543
+ projects.command("config").description("Update deployment configuration (resources, replicas)").option("-p, --project <project>", "Project slug or ID").option("--replicas <n>", "Number of container replicas").option("--cpu-limit <limit>", "CPU limit in cores (e.g., 0.5, 1, 2)").option("--memory-limit <limit>", "Memory limit in MB").option("--auto-deploy", "Enable automatic deployments").option("--no-auto-deploy", "Disable automatic deployments").option("--json", "Output in JSON format").option("-y, --yes", "Skip prompts (for automation)").action(updateConfigAction);
74544
+ projects.command("delete").alias("rm").description("Delete a project").option("-p, --project <project>", "Project slug or ID").option("-f, --force", "Skip confirmation").option("-y, --yes", "Skip confirmation (alias for --force)").action(remove);
74237
74545
  }
74238
74546
 
74239
74547
  // src/commands/deploy/deploy.ts
74240
74548
  init_sdk_gen();
74241
74549
  init_prompts();
74242
74550
  init_output();
74243
- async function deploy(options) {
74244
- await requireAuth();
74245
- await setupClient();
74246
- newline();
74247
- const projectName = options.project ?? config.get("defaultProject");
74248
- if (!projectName) {
74249
- warning("No project specified");
74250
- info("Use: temps deploy --project <project> or set a default with temps configure");
74251
- return;
74252
- }
74253
- startSpinner("Fetching project details...");
74254
- let projectData;
74255
- let environments = [];
74256
- try {
74257
- const { data, error: error3 } = await getProjectBySlug({
74258
- client,
74259
- path: { slug: projectName }
74260
- });
74261
- if (error3 || !data) {
74262
- failSpinner(`Project "${projectName}" not found`);
74263
- return;
74264
- }
74265
- projectData = data;
74266
- succeedSpinner(`Found project: ${projectData.name}`);
74267
- const { data: envData } = await getEnvironments({
74268
- client,
74269
- path: { project_id: projectData.id }
74270
- });
74271
- environments = envData ?? [];
74272
- } catch (err) {
74273
- failSpinner("Failed to fetch project");
74274
- throw err;
74275
- }
74276
- let environmentId;
74277
- let environmentName = options.environment || "production";
74278
- if (environments.length > 0) {
74279
- if (options.environmentId) {
74280
- environmentId = parseInt(options.environmentId, 10);
74281
- const env3 = environments.find((e) => e.id === environmentId);
74282
- if (env3) {
74283
- environmentName = env3.name;
74284
- }
74285
- } else if (options.environment) {
74286
- const env3 = environments.find((e) => e.name === options.environment);
74287
- if (env3) {
74288
- environmentId = env3.id;
74289
- environmentName = env3.name;
74290
- }
74291
- } else if (!options.yes) {
74292
- const selectedEnv = await promptSelect({
74293
- message: "Select environment",
74294
- choices: environments.map((env3) => ({
74295
- name: env3.name,
74296
- value: String(env3.id),
74297
- description: env3.is_preview ? "Preview environment" : undefined
74298
- })),
74299
- default: String(environments.find((e) => e.name === "production")?.id ?? environments[0]?.id ?? "")
74300
- });
74301
- environmentId = parseInt(selectedEnv, 10);
74302
- environmentName = environments.find((e) => e.id === environmentId)?.name ?? "production";
74303
- } else {
74304
- const prodEnv = environments.find((e) => e.name === "production");
74305
- if (prodEnv) {
74306
- environmentId = prodEnv.id;
74307
- environmentName = prodEnv.name;
74308
- } else if (environments[0]) {
74309
- environmentId = environments[0].id;
74310
- environmentName = environments[0].name;
74311
- }
74312
- }
74313
- }
74314
- let branch = options.branch;
74315
- if (!branch) {
74316
- if (options.yes) {
74317
- branch = "main";
74318
- } else {
74319
- branch = await promptText({
74320
- message: "Branch to deploy",
74321
- default: "main"
74322
- });
74323
- }
74324
- }
74325
- newline();
74326
- box(`Project: ${colors.bold(projectName)}
74327
- ` + `Environment: ${colors.bold(environmentName)}
74328
- ` + `Branch: ${colors.bold(branch)}`, `${icons.rocket} Deployment Preview`);
74329
- newline();
74330
- startSpinner("Starting deployment...");
74331
- try {
74332
- const { data, error: error3 } = await triggerProjectPipeline({
74333
- client,
74334
- path: { id: projectData.id },
74335
- body: {
74336
- branch,
74337
- environment_id: environmentId
74338
- }
74339
- });
74340
- if (error3 || !data) {
74341
- failSpinner("Failed to start deployment");
74342
- return;
74343
- }
74344
- succeedSpinner(`Deployment started`);
74345
- info(data.message ?? "Pipeline triggered successfully");
74346
- if (options.wait !== false) {
74347
- await waitForDeployment(projectData.id, environmentId);
74348
- } else {
74349
- newline();
74350
- info("Deployment running in background");
74351
- info(`Check status with: temps deployments list --project ${projectName}`);
74352
- }
74353
- } catch (err) {
74354
- failSpinner("Deployment failed");
74355
- throw err;
74356
- }
74357
- }
74358
- async function waitForDeployment(projectId, environmentId) {
74359
- const statusMessages = {
74360
- pending: "Waiting in queue...",
74361
- building: "Building application...",
74362
- deploying: "Deploying to servers...",
74363
- running: "Starting containers..."
74364
- };
74365
- startSpinner("Waiting for deployment...");
74366
- let lastStatus = "";
74367
- let attempts = 0;
74368
- const maxAttempts = 180;
74369
- while (attempts < maxAttempts) {
74370
- attempts++;
74371
- const { data: deployment, error: error3 } = await getLastDeployment({
74372
- client,
74373
- path: { id: projectId }
74374
- });
74375
- if (error3 || !deployment) {
74376
- await new Promise((resolve) => setTimeout(resolve, 2000));
74377
- continue;
74378
- }
74379
- if (environmentId && deployment.environment_id !== environmentId) {
74380
- await new Promise((resolve) => setTimeout(resolve, 2000));
74381
- continue;
74382
- }
74383
- if (deployment.status !== lastStatus) {
74384
- lastStatus = deployment.status;
74385
- updateSpinner(statusMessages[deployment.status] ?? `Status: ${deployment.status}`);
74386
- }
74387
- if (deployment.status === "success" || deployment.status === "completed" || deployment.status === "deployed") {
74388
- succeedSpinner(`${icons.rocket} Deployment successful!`);
74389
- newline();
74390
- header(`${icons.check} Deployment Complete`);
74391
- keyValue("Deployment ID", deployment.id);
74392
- keyValue("Commit", deployment.commit_hash?.substring(0, 7) ?? "-");
74393
- if (deployment.url) {
74394
- keyValue("URL", colors.primary(deployment.url));
74395
- }
74396
- const envDomains = deployment.environment?.domains || [];
74397
- const firstDomain = envDomains[0];
74398
- if (firstDomain) {
74399
- const envUrl = firstDomain.startsWith("http") ? firstDomain : `https://${firstDomain}`;
74400
- keyValue("Environment", colors.primary(envUrl));
74401
- }
74402
- newline();
74403
- return;
74404
- }
74405
- if (deployment.status === "failed" || deployment.status === "error" || deployment.status === "cancelled") {
74406
- failSpinner("Deployment failed");
74407
- newline();
74408
- if (deployment.cancelled_reason) {
74409
- info(`Reason: ${deployment.cancelled_reason}`);
74410
- }
74411
- info(`View logs with: temps logs ${projectId}`);
74412
- return;
74413
- }
74414
- await new Promise((resolve) => setTimeout(resolve, 2000));
74415
- }
74416
- failSpinner("Deployment timed out");
74417
- info("Deployment is still running. Check status with: temps deployments list");
74418
- }
74419
74551
 
74420
74552
  // src/lib/deployment-watcher.tsx
74421
74553
  var import_react27 = __toESM(require_react(), 1);
@@ -79110,8 +79242,8 @@ class Ink {
79110
79242
  }
79111
79243
  }
79112
79244
  async waitUntilExit() {
79113
- this.exitPromise ||= new Promise((resolve, reject) => {
79114
- this.resolveExitPromise = resolve;
79245
+ this.exitPromise ||= new Promise((resolve2, reject) => {
79246
+ this.resolveExitPromise = resolve2;
79115
79247
  this.rejectExitPromise = reject;
79116
79248
  });
79117
79249
  return this.exitPromise;
@@ -79307,6 +79439,8 @@ var build_default = Spinner;
79307
79439
 
79308
79440
  // src/lib/deployment-watcher.tsx
79309
79441
  var jsx_dev_runtime = __toESM(require_jsx_dev_runtime(), 1);
79442
+ var TERMINAL_STATUSES = ["success", "completed", "deployed", "failed", "error", "cancelled"];
79443
+ var FAILURE_STATUSES = ["failed", "error", "cancelled"];
79310
79444
  function toMs(timestamp) {
79311
79445
  if (timestamp < 946684800000) {
79312
79446
  return timestamp * 1000;
@@ -79341,7 +79475,7 @@ function StatusIcon({ status }) {
79341
79475
  case "deployed":
79342
79476
  return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79343
79477
  color: "green",
79344
- children: "●"
79478
+ children: "✓"
79345
79479
  }, undefined, false, undefined, this);
79346
79480
  case "failed":
79347
79481
  case "error":
@@ -79393,7 +79527,7 @@ function LogEntryRow({ entry }) {
79393
79527
  icon = "!";
79394
79528
  break;
79395
79529
  }
79396
- const message = entry.message.replace(/^[✅❌⏳📦📋📂🚀📍🔄⬇️🐳🏷️]\s*/, "");
79530
+ const message = entry.message.replace(/^[\u{1F300}-\u{1F9FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]\s*/u, "");
79397
79531
  return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79398
79532
  marginLeft: 4,
79399
79533
  children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
@@ -79406,11 +79540,11 @@ function LogEntryRow({ entry }) {
79406
79540
  }, undefined, true, undefined, this)
79407
79541
  }, undefined, false, undefined, this);
79408
79542
  }
79409
- function JobRow({ jobState, showAllLogs }) {
79543
+ function JobRow({ jobState, isFinished }) {
79410
79544
  const { job, logs } = jobState;
79411
79545
  const duration = job.started_at ? formatDuration(job.started_at, job.finished_at ?? undefined) : "";
79412
79546
  const statusColor = getStatusColor(job.status);
79413
- const maxLogs = showAllLogs ? 20 : job.status === "running" ? 10 : 5;
79547
+ const maxLogs = isFinished ? 3 : job.status === "running" ? 10 : 5;
79414
79548
  const recentLogs = logs.slice(-maxLogs);
79415
79549
  return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79416
79550
  flexDirection: "column",
@@ -79435,18 +79569,10 @@ function JobRow({ jobState, showAllLogs }) {
79435
79569
  duration,
79436
79570
  ")"
79437
79571
  ]
79438
- }, undefined, true, undefined, this),
79439
- logs.length > 0 && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79440
- color: "gray",
79441
- children: [
79442
- " [",
79443
- logs.length,
79444
- " logs]"
79445
- ]
79446
79572
  }, undefined, true, undefined, this)
79447
79573
  ]
79448
79574
  }, undefined, true, undefined, this),
79449
- (job.status === "failed" || job.status === "error") && job.error_message && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79575
+ FAILURE_STATUSES.includes(job.status) && job.error_message && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79450
79576
  marginLeft: 2,
79451
79577
  children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79452
79578
  color: "red",
@@ -79456,10 +79582,9 @@ function JobRow({ jobState, showAllLogs }) {
79456
79582
  ]
79457
79583
  }, undefined, true, undefined, this)
79458
79584
  }, undefined, false, undefined, this),
79459
- recentLogs.length > 0 && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79585
+ recentLogs.length > 0 && !isFinished && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79460
79586
  flexDirection: "column",
79461
79587
  marginLeft: 2,
79462
- marginTop: 0,
79463
79588
  children: recentLogs.map((log, i) => /* @__PURE__ */ jsx_dev_runtime.jsxDEV(LogEntryRow, {
79464
79589
  entry: log
79465
79590
  }, `${job.job_id}-log-${i}`, false, undefined, this))
@@ -79471,7 +79596,7 @@ function DeploymentWatcher({
79471
79596
  projectId,
79472
79597
  deploymentId,
79473
79598
  timeoutSecs,
79474
- projectName: _projectName,
79599
+ projectName,
79475
79600
  apiUrl,
79476
79601
  apiKey,
79477
79602
  onComplete
@@ -79481,7 +79606,10 @@ function DeploymentWatcher({
79481
79606
  const [startTime] = import_react27.useState(Date.now());
79482
79607
  const [elapsed, setElapsed] = import_react27.useState("0s");
79483
79608
  const [error3, setError] = import_react27.useState(null);
79609
+ const [result, setResult] = import_react27.useState(null);
79484
79610
  import_react27.useEffect(() => {
79611
+ if (result)
79612
+ return;
79485
79613
  const timer = setInterval(() => {
79486
79614
  const seconds = Math.floor((Date.now() - startTime) / 1000);
79487
79615
  if (seconds < 60) {
@@ -79493,98 +79621,109 @@ function DeploymentWatcher({
79493
79621
  }
79494
79622
  }, 1000);
79495
79623
  return () => clearInterval(timer);
79496
- }, [startTime]);
79624
+ }, [startTime, result]);
79625
+ import_react27.useEffect(() => {
79626
+ if (!result)
79627
+ return;
79628
+ const timer = setTimeout(() => onComplete(result), 200);
79629
+ return () => clearTimeout(timer);
79630
+ }, [result, onComplete]);
79631
+ const fetchJobs = import_react27.useCallback(async (currentJobStates) => {
79632
+ const jobsRes = await fetch(`${apiUrl}/projects/${projectId}/deployments/${deploymentId}/jobs`, { headers: { Authorization: `Bearer ${apiKey}` } });
79633
+ if (!jobsRes.ok)
79634
+ return currentJobStates;
79635
+ const jobsData = await jobsRes.json();
79636
+ const jobs = jobsData.jobs || [];
79637
+ jobs.sort((a, b) => a.id - b.id);
79638
+ const newJobStates = new Map(currentJobStates);
79639
+ for (const job of jobs) {
79640
+ let state = newJobStates.get(job.job_id);
79641
+ if (!state) {
79642
+ state = { job, logs: [], lastLogLine: 0 };
79643
+ } else {
79644
+ state = { ...state, job };
79645
+ }
79646
+ if (job.status !== "pending" && job.status !== "queued") {
79647
+ try {
79648
+ const logsRes = await fetch(`${apiUrl}/projects/${projectId}/deployments/${deploymentId}/jobs/${job.id}/logs`, { headers: { Authorization: `Bearer ${apiKey}` } });
79649
+ if (logsRes.ok) {
79650
+ const logsText = await logsRes.text();
79651
+ if (logsText.trim()) {
79652
+ const newLogs = [];
79653
+ for (const line of logsText.trim().split(`
79654
+ `)) {
79655
+ if (!line.trim())
79656
+ continue;
79657
+ try {
79658
+ const entry = JSON.parse(line);
79659
+ if (entry.line > state.lastLogLine) {
79660
+ newLogs.push(entry);
79661
+ state.lastLogLine = entry.line;
79662
+ }
79663
+ } catch {}
79664
+ }
79665
+ if (newLogs.length > 0) {
79666
+ state = { ...state, logs: [...state.logs, ...newLogs] };
79667
+ }
79668
+ }
79669
+ }
79670
+ } catch {}
79671
+ }
79672
+ newJobStates.set(job.job_id, state);
79673
+ }
79674
+ return newJobStates;
79675
+ }, [apiUrl, apiKey, projectId, deploymentId]);
79497
79676
  import_react27.useEffect(() => {
79498
79677
  let cancelled = false;
79499
79678
  const timeoutMs = timeoutSecs * 1000;
79679
+ let latestJobStates = jobStates;
79500
79680
  async function poll() {
79501
79681
  while (!cancelled && Date.now() - startTime < timeoutMs) {
79502
79682
  try {
79503
79683
  const deploymentRes = await fetch(`${apiUrl}/projects/${projectId}/deployments/${deploymentId}`, { headers: { Authorization: `Bearer ${apiKey}` } });
79684
+ let dep = null;
79504
79685
  if (deploymentRes.ok) {
79505
- const dep = await deploymentRes.json();
79686
+ dep = await deploymentRes.json();
79506
79687
  setDeployment(dep);
79507
- const isDeploymentTerminal = ["success", "completed", "deployed", "failed", "error", "cancelled"].includes(dep.status);
79508
- if (isDeploymentTerminal) {
79509
- if (["failed", "error", "cancelled"].includes(dep.status)) {
79510
- onComplete({
79511
- success: false,
79512
- deployment: dep,
79513
- error: dep.cancelled_reason || "Deployment failed"
79514
- });
79515
- return;
79516
- }
79517
- const markCompleteJob = Array.from(jobStates.values()).find((js) => js.job.name.toLowerCase().includes("mark deployment complete"));
79518
- const isMarkCompleteDone = markCompleteJob && ["success", "completed"].includes(markCompleteJob.job.status);
79519
- if (dep.url || isMarkCompleteDone) {
79520
- onComplete({ success: true, deployment: dep });
79521
- return;
79522
- }
79523
- }
79524
79688
  } else {
79525
79689
  const errorText = await deploymentRes.text();
79526
79690
  setError(`API Error ${deploymentRes.status}: ${errorText.substring(0, 200)}`);
79527
79691
  }
79528
- const jobsRes = await fetch(`${apiUrl}/projects/${projectId}/deployments/${deploymentId}/jobs`, { headers: { Authorization: `Bearer ${apiKey}` } });
79529
- if (jobsRes.ok) {
79530
- const jobsData = await jobsRes.json();
79531
- const jobs = jobsData.jobs || [];
79532
- jobs.sort((a, b) => a.id - b.id);
79533
- const newJobStates = new Map(jobStates);
79534
- for (const job of jobs) {
79535
- let state = newJobStates.get(job.job_id);
79536
- if (!state) {
79537
- state = { job, logs: [], lastLogLine: 0 };
79538
- } else {
79539
- state = { ...state, job };
79540
- }
79541
- if (job.status !== "pending" && job.status !== "queued") {
79542
- try {
79543
- const logsRes = await fetch(`${apiUrl}/projects/${projectId}/deployments/${deploymentId}/jobs/${job.id}/logs`, { headers: { Authorization: `Bearer ${apiKey}` } });
79544
- if (logsRes.ok) {
79545
- const logsText = await logsRes.text();
79546
- if (logsText.trim()) {
79547
- const newLogs = [];
79548
- for (const line of logsText.trim().split(`
79549
- `)) {
79550
- if (!line.trim())
79551
- continue;
79552
- try {
79553
- const entry = JSON.parse(line);
79554
- if (entry.line > state.lastLogLine) {
79555
- newLogs.push(entry);
79556
- state.lastLogLine = entry.line;
79557
- }
79558
- } catch {}
79559
- }
79560
- if (newLogs.length > 0) {
79561
- state = { ...state, logs: [...state.logs, ...newLogs] };
79562
- }
79563
- }
79564
- }
79565
- } catch {}
79566
- }
79567
- newJobStates.set(job.job_id, state);
79692
+ latestJobStates = await fetchJobs(latestJobStates);
79693
+ if (!cancelled) {
79694
+ setJobStates(latestJobStates);
79695
+ }
79696
+ if (dep && TERMINAL_STATUSES.includes(dep.status)) {
79697
+ if (FAILURE_STATUSES.includes(dep.status)) {
79698
+ setResult({
79699
+ success: false,
79700
+ deployment: dep,
79701
+ error: dep.cancelled_reason || "Deployment failed"
79702
+ });
79703
+ return;
79568
79704
  }
79569
- setJobStates(newJobStates);
79705
+ setResult({ success: true, deployment: dep });
79706
+ return;
79570
79707
  }
79571
- await new Promise((r) => setTimeout(r, 1000));
79708
+ await new Promise((r) => setTimeout(r, 1500));
79572
79709
  } catch (err) {
79573
79710
  setError(`Exception: ${err instanceof Error ? err.message : String(err)}`);
79574
- await new Promise((r) => setTimeout(r, 1000));
79711
+ await new Promise((r) => setTimeout(r, 2000));
79575
79712
  }
79576
79713
  }
79577
79714
  if (!cancelled) {
79578
- onComplete({ success: false, error: "Timeout" });
79715
+ setResult({ success: false, error: "Timeout waiting for deployment to complete" });
79579
79716
  }
79580
79717
  }
79581
79718
  poll();
79582
79719
  return () => {
79583
79720
  cancelled = true;
79584
79721
  };
79585
- }, [projectId, deploymentId, timeoutSecs, startTime, onComplete]);
79722
+ }, []);
79586
79723
  const sortedJobs = Array.from(jobStates.values()).sort((a, b) => a.job.id - b.job.id);
79587
79724
  const statusColor = deployment ? getStatusColor(deployment.status) : "gray";
79725
+ const isFinished = !!result;
79726
+ const webUrl = getWebUrl();
79588
79727
  return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79589
79728
  flexDirection: "column",
79590
79729
  paddingTop: 1,
@@ -79594,7 +79733,8 @@ function DeploymentWatcher({
79594
79733
  bold: true,
79595
79734
  children: [
79596
79735
  " ",
79597
- "\uD83D\uDE80 Deployment Progress"
79736
+ "\uD83D\uDE80 Deployment #",
79737
+ deploymentId
79598
79738
  ]
79599
79739
  }, undefined, true, undefined, this)
79600
79740
  }, undefined, false, undefined, this),
@@ -79637,7 +79777,7 @@ function DeploymentWatcher({
79637
79777
  ]
79638
79778
  }, undefined, true, undefined, this)
79639
79779
  }, undefined, false, undefined, this),
79640
- error3 && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79780
+ error3 && !result && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79641
79781
  marginLeft: 1,
79642
79782
  marginTop: 1,
79643
79783
  children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
@@ -79650,181 +79790,699 @@ function DeploymentWatcher({
79650
79790
  }, undefined, false, undefined, this),
79651
79791
  /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Newline, {}, undefined, false, undefined, this),
79652
79792
  sortedJobs.map((jobState) => /* @__PURE__ */ jsx_dev_runtime.jsxDEV(JobRow, {
79653
- jobState
79793
+ jobState,
79794
+ isFinished
79654
79795
  }, jobState.job.job_id, false, undefined, this)),
79655
- sortedJobs.length === 0 && deployment && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79796
+ sortedJobs.length === 0 && deployment && !result && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79656
79797
  marginLeft: 2,
79657
79798
  children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79658
79799
  color: "gray",
79659
79800
  children: "Waiting for jobs..."
79660
79801
  }, undefined, false, undefined, this)
79661
79802
  }, undefined, false, undefined, this),
79662
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Newline, {}, undefined, false, undefined, this)
79663
- ]
79664
- }, undefined, true, undefined, this);
79665
- }
79666
- function DeploymentResult({
79667
- result,
79668
- projectName
79669
- }) {
79670
- if (result.success) {
79671
- const deployment = result.deployment;
79672
- const envDomains = deployment?.environment?.domains || [];
79673
- const firstDomain = envDomains[0];
79674
- const envUrl = firstDomain ? firstDomain.startsWith("http") ? firstDomain : `https://${firstDomain}` : null;
79675
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79676
- flexDirection: "column",
79677
- paddingTop: 1,
79678
- children: [
79679
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79680
- children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79681
- color: "green",
79803
+ result && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
79804
+ children: [
79805
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Newline, {}, undefined, false, undefined, this),
79806
+ result.success ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79807
+ flexDirection: "column",
79682
79808
  children: [
79683
- " ",
79684
- "✓ Deployment completed successfully!"
79809
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79810
+ marginLeft: 1,
79811
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79812
+ color: "green",
79813
+ bold: true,
79814
+ children: "✓ Deployment completed successfully!"
79815
+ }, undefined, false, undefined, this)
79816
+ }, undefined, false, undefined, this),
79817
+ deployment?.url && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79818
+ marginLeft: 3,
79819
+ children: [
79820
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79821
+ children: "URL: "
79822
+ }, undefined, false, undefined, this),
79823
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79824
+ color: "cyan",
79825
+ bold: true,
79826
+ children: deployment.url
79827
+ }, undefined, false, undefined, this)
79828
+ ]
79829
+ }, undefined, true, undefined, this),
79830
+ deployment?.environment?.domains?.[0] && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79831
+ marginLeft: 3,
79832
+ children: [
79833
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79834
+ children: "Domain: "
79835
+ }, undefined, false, undefined, this),
79836
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79837
+ color: "cyan",
79838
+ bold: true,
79839
+ children: deployment.environment.domains[0].startsWith("http") ? deployment.environment.domains[0] : `https://${deployment.environment.domains[0]}`
79840
+ }, undefined, false, undefined, this)
79841
+ ]
79842
+ }, undefined, true, undefined, this)
79685
79843
  ]
79686
- }, undefined, true, undefined, this)
79687
- }, undefined, false, undefined, this),
79688
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Newline, {}, undefined, false, undefined, this),
79689
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79690
- marginLeft: 2,
79691
- children: [
79692
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79693
- children: "Deployment ID: "
79694
- }, undefined, false, undefined, this),
79695
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79696
- bold: true,
79697
- children: deployment?.id
79698
- }, undefined, false, undefined, this)
79699
- ]
79700
- }, undefined, true, undefined, this),
79701
- deployment?.url && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79702
- marginLeft: 2,
79703
- children: [
79704
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79705
- children: "Deployment URL: "
79706
- }, undefined, false, undefined, this),
79707
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79708
- color: "cyan",
79709
- bold: true,
79710
- children: deployment.url
79711
- }, undefined, false, undefined, this)
79712
- ]
79713
- }, undefined, true, undefined, this),
79714
- envUrl && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79715
- marginLeft: 2,
79716
- children: [
79717
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79718
- children: "Environment URL: "
79719
- }, undefined, false, undefined, this),
79720
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79721
- color: "cyan",
79722
- bold: true,
79723
- children: envUrl
79724
- }, undefined, false, undefined, this)
79725
- ]
79726
- }, undefined, true, undefined, this),
79727
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Newline, {}, undefined, false, undefined, this)
79728
- ]
79729
- }, undefined, true, undefined, this);
79730
- }
79731
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79732
- flexDirection: "column",
79733
- paddingTop: 1,
79734
- children: [
79735
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79736
- children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79737
- color: "red",
79738
- children: [
79739
- " ",
79740
- "✗ Deployment failed"
79741
- ]
79742
- }, undefined, true, undefined, this)
79743
- }, undefined, false, undefined, this),
79744
- result.error && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79745
- marginLeft: 2,
79746
- children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79747
- color: "red",
79748
- children: [
79749
- "Reason: ",
79750
- result.error
79751
- ]
79752
- }, undefined, true, undefined, this)
79753
- }, undefined, false, undefined, this),
79754
- projectName && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79755
- marginLeft: 2,
79756
- children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79757
- color: "gray",
79758
- children: [
79759
- "View full logs: temps logs ",
79760
- projectName
79761
- ]
79762
- }, undefined, true, undefined, this)
79763
- }, undefined, false, undefined, this),
79764
- /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Newline, {}, undefined, false, undefined, this)
79844
+ }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79845
+ flexDirection: "column",
79846
+ children: [
79847
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79848
+ marginLeft: 1,
79849
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79850
+ color: "red",
79851
+ bold: true,
79852
+ children: "✗ Deployment failed"
79853
+ }, undefined, false, undefined, this)
79854
+ }, undefined, false, undefined, this),
79855
+ result.error && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79856
+ marginLeft: 3,
79857
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79858
+ color: "red",
79859
+ children: result.error
79860
+ }, undefined, false, undefined, this)
79861
+ }, undefined, false, undefined, this)
79862
+ ]
79863
+ }, undefined, true, undefined, this),
79864
+ projectName && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Box_default, {
79865
+ marginLeft: 3,
79866
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Text, {
79867
+ color: "gray",
79868
+ children: [
79869
+ "Dashboard: ",
79870
+ webUrl,
79871
+ "/projects/",
79872
+ projectName,
79873
+ "/deployments"
79874
+ ]
79875
+ }, undefined, true, undefined, this)
79876
+ }, undefined, false, undefined, this),
79877
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Newline, {}, undefined, false, undefined, this)
79878
+ ]
79879
+ }, undefined, true, undefined, this)
79765
79880
  ]
79766
79881
  }, undefined, true, undefined, this);
79767
79882
  }
79768
79883
  async function watchDeployment(options) {
79769
- const apiUrl = config.get("apiUrl");
79884
+ const apiUrl = normalizeApiUrl(config.get("apiUrl"));
79770
79885
  const apiKey = await credentials.getApiKey() || "";
79771
79886
  if (!apiKey) {
79772
79887
  return { success: false, error: "No API key found. Please run: temps login" };
79773
79888
  }
79774
- return new Promise((resolve) => {
79775
- let instance = null;
79776
- const handleComplete = (res) => {
79777
- if (instance) {
79778
- instance.unmount();
79779
- }
79780
- const resultInstance = render_default(/* @__PURE__ */ jsx_dev_runtime.jsxDEV(DeploymentResult, {
79781
- result: res,
79782
- projectName: options.projectName
79783
- }, undefined, false, undefined, this));
79784
- setTimeout(() => {
79785
- resultInstance.unmount();
79786
- resolve(res);
79787
- }, 100);
79788
- };
79789
- instance = render_default(/* @__PURE__ */ jsx_dev_runtime.jsxDEV(DeploymentWatcher, {
79889
+ return new Promise((resolve2) => {
79890
+ const instance = render_default(/* @__PURE__ */ jsx_dev_runtime.jsxDEV(DeploymentWatcher, {
79790
79891
  ...options,
79791
79892
  apiUrl,
79792
79893
  apiKey,
79793
- onComplete: handleComplete
79894
+ onComplete: (res) => {
79895
+ setTimeout(() => {
79896
+ instance.unmount();
79897
+ resolve2(res);
79898
+ }, 300);
79899
+ }
79794
79900
  }, undefined, false, undefined, this));
79795
79901
  });
79796
79902
  }
79797
79903
 
79798
- // src/commands/deploy/deploy-static.ts
79904
+ // src/commands/deploy/deploy-local-image.ts
79799
79905
  init_sdk_gen();
79800
79906
  init_prompts();
79801
79907
  init_output();
79802
- import { existsSync as existsSync3, statSync } from "node:fs";
79803
- import { readFile as readFile2 } from "node:fs/promises";
79804
- import { basename, extname, resolve } from "node:path";
79805
79908
  import { spawn as spawn2 } from "node:child_process";
79806
- async function deployStatic(options) {
79909
+ import { existsSync as existsSync5, createWriteStream, writeFileSync as writeFileSync3, mkdirSync } from "node:fs";
79910
+ import { unlink } from "node:fs/promises";
79911
+ import { resolve as resolve2, basename, join as join2 } from "node:path";
79912
+ import { tmpdir as tmpdir2 } from "node:os";
79913
+ async function deployLocalImage(options) {
79807
79914
  await requireAuth();
79808
79915
  await setupClient();
79809
79916
  newline();
79810
- const resolvedPath = resolve(options.path);
79811
- if (!existsSync3(resolvedPath)) {
79812
- warning(`Path does not exist: ${resolvedPath}`);
79813
- return;
79814
- }
79815
- const stat = statSync(resolvedPath);
79816
- const isDirectory = stat.isDirectory();
79817
- const isArchive = !isDirectory && isValidArchive(resolvedPath);
79818
- if (!isDirectory && !isArchive) {
79819
- warning("Path must be a directory or a .tar.gz/.tgz/.zip archive");
79820
- return;
79821
- }
79822
- const projectName = options.project ?? config.get("defaultProject");
79823
- if (!projectName) {
79917
+ const resolved = await resolveProjectSlug(options.project);
79918
+ if (!resolved) {
79824
79919
  warning("No project specified");
79825
- info("Use: temps deploy static --project <project> or set a default with temps configure");
79920
+ info("Use: bunx @temps-sdk/cli deploy:local-image --project <slug>");
79921
+ info("Or link this directory: bunx @temps-sdk/cli link <slug>");
79826
79922
  return;
79827
79923
  }
79924
+ const projectName = resolved.slug;
79925
+ if (resolved.source !== "flag") {
79926
+ info(`Using project ${colors.bold(projectName)} (from ${resolved.source})`);
79927
+ }
79928
+ startSpinner("Fetching project details...");
79929
+ let projectData;
79930
+ let environments = [];
79931
+ try {
79932
+ const isNumericId = /^\d+$/.test(projectName);
79933
+ if (isNumericId) {
79934
+ const result = await getProject({
79935
+ client,
79936
+ path: { id: parseInt(projectName, 10) }
79937
+ });
79938
+ if (result.error || !result.data) {
79939
+ failSpinner(`Project with ID "${projectName}" not found`);
79940
+ info(`Debug: ${JSON.stringify(result)}`);
79941
+ return;
79942
+ }
79943
+ const responseData = result.data;
79944
+ if (responseData.id !== undefined) {
79945
+ projectData = result.data;
79946
+ } else if (responseData.data && typeof responseData.data === "object") {
79947
+ projectData = responseData.data;
79948
+ } else {
79949
+ failSpinner("Unexpected project response format");
79950
+ info(`Debug: ${JSON.stringify(result.data)}`);
79951
+ return;
79952
+ }
79953
+ } else {
79954
+ const { data, error: error3 } = await getProjectBySlug({
79955
+ client,
79956
+ path: { slug: projectName }
79957
+ });
79958
+ if (error3 || !data) {
79959
+ failSpinner(`Project "${projectName}" not found`);
79960
+ return;
79961
+ }
79962
+ projectData = data;
79963
+ }
79964
+ succeedSpinner(`Found project: ${projectData.name || projectData.slug}`);
79965
+ const { data: envData } = await getEnvironments({
79966
+ client,
79967
+ path: { project_id: projectData.id }
79968
+ });
79969
+ if (Array.isArray(envData)) {
79970
+ environments = envData;
79971
+ } else if (envData && typeof envData === "object") {
79972
+ const wrapped = envData;
79973
+ if (Array.isArray(wrapped.data)) {
79974
+ environments = wrapped.data;
79975
+ } else if (Array.isArray(wrapped.environments)) {
79976
+ environments = wrapped.environments;
79977
+ }
79978
+ }
79979
+ } catch (err) {
79980
+ failSpinner("Failed to fetch project");
79981
+ throw err;
79982
+ }
79983
+ let environmentId;
79984
+ let environmentName = options.environment || "production";
79985
+ if (options.environmentId) {
79986
+ environmentId = parseInt(options.environmentId, 10);
79987
+ if (environments.length > 0) {
79988
+ const env4 = environments.find((e) => e.id === environmentId);
79989
+ if (env4) {
79990
+ environmentName = env4.name;
79991
+ }
79992
+ } else {
79993
+ environmentName = `Environment #${environmentId}`;
79994
+ }
79995
+ } else if (environments.length > 0) {
79996
+ if (options.environment) {
79997
+ const env4 = environments.find((e) => e.name === options.environment);
79998
+ if (env4) {
79999
+ environmentId = env4.id;
80000
+ environmentName = env4.name;
80001
+ }
80002
+ } else if (!options.yes) {
80003
+ const selectedEnv = await promptSelect({
80004
+ message: "Select environment",
80005
+ choices: environments.map((env4) => ({
80006
+ name: env4.name,
80007
+ value: String(env4.id),
80008
+ description: env4.is_preview ? "Preview environment" : undefined
80009
+ })),
80010
+ default: String(environments.find((e) => e.name === "production")?.id ?? environments[0]?.id ?? "")
80011
+ });
80012
+ environmentId = parseInt(selectedEnv, 10);
80013
+ environmentName = environments.find((e) => e.id === environmentId)?.name ?? "production";
80014
+ } else {
80015
+ const prodEnv = environments.find((e) => e.name === "production");
80016
+ if (prodEnv) {
80017
+ environmentId = prodEnv.id;
80018
+ environmentName = prodEnv.name;
80019
+ } else if (environments[0]) {
80020
+ environmentId = environments[0].id;
80021
+ environmentName = environments[0].name;
80022
+ }
80023
+ }
80024
+ } else if (!options.environmentId) {
80025
+ warning("No environments found for this project");
80026
+ info("Create an environment first or specify --environment-id directly");
80027
+ return;
80028
+ }
80029
+ info(`Environment: ${colors.bold(environmentName)}`);
80030
+ let imageName;
80031
+ let didBuild = false;
80032
+ const shouldBuild = !options.noBuild && !options.image;
80033
+ if (shouldBuild) {
80034
+ let dockerfilePath = options.dockerfile || "Dockerfile";
80035
+ const contextPath = options.context || ".";
80036
+ let resolvedDockerfile = resolve2(dockerfilePath);
80037
+ const resolvedContext = resolve2(contextPath);
80038
+ let generatedBuildArgs = [];
80039
+ if (!existsSync5(resolvedDockerfile)) {
80040
+ const generated = await tryGenerateDockerfile(options.project);
80041
+ if (generated) {
80042
+ resolvedDockerfile = generated.dockerfilePath;
80043
+ generatedBuildArgs = generated.buildArgs;
80044
+ success(`Dockerfile generated from ${colors.bold(generated.preset)} preset`);
80045
+ } else {
80046
+ warning(`Dockerfile not found: ${resolvedDockerfile}`);
80047
+ info("Options:");
80048
+ info(" 1. Create a Dockerfile in the current directory");
80049
+ info(" 2. Specify a Dockerfile path: --dockerfile <path>");
80050
+ info(" 3. Skip build and use existing image: --image <image-name>");
80051
+ return;
80052
+ }
80053
+ }
80054
+ const allBuildArgs = [...generatedBuildArgs, ...options.buildArg || []];
80055
+ const dirName = basename(process.cwd());
80056
+ const timestamp = Date.now();
80057
+ imageName = options.tag || `${projectName || dirName}:local-${timestamp}`;
80058
+ newline();
80059
+ box(`Dockerfile: ${colors.bold(resolvedDockerfile)}
80060
+ ` + `Context: ${colors.bold(resolvedContext)}
80061
+ ` + `Image Tag: ${colors.bold(imageName)}` + (allBuildArgs.length ? `
80062
+ Build Args: ${colors.bold(allBuildArgs.join(", "))}` : ""), `${icons.package} Docker Build`);
80063
+ newline();
80064
+ startSpinner("Building Docker image...");
80065
+ try {
80066
+ await dockerBuild({
80067
+ dockerfile: resolvedDockerfile,
80068
+ context: resolvedContext,
80069
+ tag: imageName,
80070
+ buildArgs: allBuildArgs,
80071
+ onOutput: (line) => {
80072
+ const trimmed = line.trim();
80073
+ if (trimmed) {
80074
+ updateSpinner(`Building: ${trimmed.substring(0, 60)}${trimmed.length > 60 ? "..." : ""}`);
80075
+ }
80076
+ }
80077
+ });
80078
+ succeedSpinner(`Image built: ${imageName}`);
80079
+ didBuild = true;
80080
+ } catch (err) {
80081
+ failSpinner("Docker build failed");
80082
+ if (err instanceof Error) {
80083
+ warning(err.message);
80084
+ }
80085
+ return;
80086
+ }
80087
+ } else if (options.image) {
80088
+ imageName = options.image;
80089
+ startSpinner("Verifying local Docker image...");
80090
+ const imageExists = await checkImageExists(imageName);
80091
+ if (!imageExists) {
80092
+ failSpinner(`Image "${imageName}" not found locally`);
80093
+ info("Make sure the image exists by running: docker images");
80094
+ info("Or remove --image to build from Dockerfile");
80095
+ return;
80096
+ }
80097
+ succeedSpinner(`Found local image: ${imageName}`);
80098
+ } else {
80099
+ warning("No image specified and build is disabled");
80100
+ info("Use: temps deploy:local-image --image <image-name>");
80101
+ info("Or remove --no-build to build from Dockerfile");
80102
+ return;
80103
+ }
80104
+ const imageSize = await getImageSize(imageName);
80105
+ info(`Image size: ${formatFileSize(imageSize)}`);
80106
+ newline();
80107
+ box(`Project: ${colors.bold(projectName)}
80108
+ ` + `Environment: ${colors.bold(environmentName)}
80109
+ ` + `Image: ${colors.bold(imageName)}
80110
+ ` + `Size: ${colors.bold(formatFileSize(imageSize))}` + (didBuild ? `
80111
+ ${colors.dim("(freshly built)")}` : ""), `${icons.rocket} Deploy Local Image`);
80112
+ newline();
80113
+ const tempFilename = `temps-image-${Date.now()}.tar`;
80114
+ const tempFilePath = join2(tmpdir2(), tempFilename);
80115
+ startSpinner("Exporting image with docker save...");
80116
+ let exportedSize;
80117
+ try {
80118
+ exportedSize = await dockerSaveToFile(imageName, tempFilePath, (progress) => {
80119
+ updateSpinner(`Exporting image... ${formatFileSize(progress)} saved`);
80120
+ });
80121
+ succeedSpinner(`Image exported: ${formatFileSize(exportedSize)}`);
80122
+ } catch (err) {
80123
+ failSpinner("Failed to export image");
80124
+ if (err instanceof Error) {
80125
+ warning(err.message);
80126
+ }
80127
+ return;
80128
+ }
80129
+ const MAX_SIZE = 1024 * 1024 * 1024;
80130
+ if (exportedSize > MAX_SIZE) {
80131
+ warning(`Image size (${formatFileSize(exportedSize)}) exceeds maximum allowed (1 GB)`);
80132
+ await unlink(tempFilePath).catch(() => {});
80133
+ return;
80134
+ }
80135
+ startSpinner("Uploading image to server...");
80136
+ const apiUrl = normalizeApiUrl(config.get("apiUrl"));
80137
+ const apiKey = await credentials.getApiKey();
80138
+ try {
80139
+ const uploadUrl = `${apiUrl}/projects/${projectData.id}/environments/${environmentId}/deploy/image-upload`;
80140
+ const queryParams = new URLSearchParams;
80141
+ if (options.tag) {
80142
+ queryParams.set("tag", options.tag);
80143
+ }
80144
+ const finalUrl = queryParams.toString() ? `${uploadUrl}?${queryParams.toString()}` : uploadUrl;
80145
+ const file = Bun.file(tempFilePath);
80146
+ const filename = `${imageName.replace(/[/:]/g, "-")}.tar`;
80147
+ const boundary = `----BunFormBoundary${Date.now().toString(16)}`;
80148
+ const fileStream = file.stream();
80149
+ const header2 = [
80150
+ `--${boundary}`,
80151
+ `Content-Disposition: form-data; name="file"; filename="${filename}"`,
80152
+ "Content-Type: application/x-tar",
80153
+ "",
80154
+ ""
80155
+ ].join(`\r
80156
+ `);
80157
+ const footer = `\r
80158
+ --${boundary}--\r
80159
+ `;
80160
+ const headerBytes = new TextEncoder().encode(header2);
80161
+ const footerBytes = new TextEncoder().encode(footer);
80162
+ let uploadedBytes = 0;
80163
+ const combinedStream = new ReadableStream({
80164
+ async start(controller) {
80165
+ controller.enqueue(headerBytes);
80166
+ const reader = fileStream.getReader();
80167
+ try {
80168
+ while (true) {
80169
+ const { done, value } = await reader.read();
80170
+ if (done)
80171
+ break;
80172
+ uploadedBytes += value.byteLength;
80173
+ updateSpinner(`Uploading... ${formatFileSize(uploadedBytes)} / ${formatFileSize(exportedSize)}`);
80174
+ controller.enqueue(value);
80175
+ }
80176
+ } finally {
80177
+ reader.releaseLock();
80178
+ }
80179
+ controller.enqueue(footerBytes);
80180
+ controller.close();
80181
+ }
80182
+ });
80183
+ const uploadResponse = await fetch(finalUrl, {
80184
+ method: "POST",
80185
+ headers: {
80186
+ Authorization: `Bearer ${apiKey}`,
80187
+ "Content-Type": `multipart/form-data; boundary=${boundary}`
80188
+ },
80189
+ body: combinedStream,
80190
+ duplex: "half"
80191
+ });
80192
+ await unlink(tempFilePath).catch(() => {});
80193
+ if (!uploadResponse.ok) {
80194
+ const errorText = await uploadResponse.text();
80195
+ failSpinner(`Upload failed: ${uploadResponse.status}`);
80196
+ info(`URL: ${finalUrl}`);
80197
+ warning(`Response: ${errorText}`);
80198
+ return;
80199
+ }
80200
+ const responseText = await uploadResponse.text();
80201
+ let deployment;
80202
+ try {
80203
+ deployment = JSON.parse(responseText);
80204
+ } catch (parseErr) {
80205
+ failSpinner("Failed to parse deployment response");
80206
+ info(`URL: ${finalUrl}`);
80207
+ warning(`Response: ${responseText}`);
80208
+ return;
80209
+ }
80210
+ succeedSpinner(`Deployment started: ${deployment.slug}`);
80211
+ if (options.wait !== false) {
80212
+ const result = await watchDeployment({
80213
+ projectId: projectData.id,
80214
+ deploymentId: deployment.id,
80215
+ timeoutSecs: parseInt(options.timeout || "600", 10),
80216
+ projectName
80217
+ });
80218
+ if (!result.success) {
80219
+ process.exitCode = 1;
80220
+ }
80221
+ } else {
80222
+ newline();
80223
+ info("Deployment running in background");
80224
+ info(`Check status with: temps deployments list --project ${projectName}`);
80225
+ newline();
80226
+ success("Local image deployment initiated successfully!");
80227
+ newline();
80228
+ }
80229
+ } catch (err) {
80230
+ failSpinner("Deployment failed");
80231
+ throw err;
80232
+ }
80233
+ }
80234
+ async function dockerBuild(options) {
80235
+ return new Promise((resolve3, reject) => {
80236
+ const args = [
80237
+ "build",
80238
+ "-f",
80239
+ options.dockerfile,
80240
+ "-t",
80241
+ options.tag
80242
+ ];
80243
+ for (const arg of options.buildArgs) {
80244
+ args.push("--build-arg", arg);
80245
+ }
80246
+ args.push(options.context);
80247
+ const docker = spawn2("docker", args, {
80248
+ stdio: ["ignore", "pipe", "pipe"]
80249
+ });
80250
+ let stderr = "";
80251
+ docker.stdout.on("data", (chunk) => {
80252
+ const lines = chunk.toString().split(`
80253
+ `);
80254
+ for (const line of lines) {
80255
+ if (line.trim() && options.onOutput) {
80256
+ options.onOutput(line);
80257
+ }
80258
+ }
80259
+ });
80260
+ docker.stderr.on("data", (chunk) => {
80261
+ stderr += chunk.toString();
80262
+ const lines = chunk.toString().split(`
80263
+ `);
80264
+ for (const line of lines) {
80265
+ if (line.trim() && options.onOutput) {
80266
+ options.onOutput(line);
80267
+ }
80268
+ }
80269
+ });
80270
+ docker.on("close", (code) => {
80271
+ if (code === 0) {
80272
+ resolve3();
80273
+ } else {
80274
+ reject(new Error(`docker build failed with code ${code}:
80275
+ ${stderr}`));
80276
+ }
80277
+ });
80278
+ docker.on("error", (err) => {
80279
+ reject(new Error(`Failed to spawn docker: ${err.message}`));
80280
+ });
80281
+ });
80282
+ }
80283
+ async function checkImageExists(imageName) {
80284
+ return new Promise((resolve3) => {
80285
+ const docker = spawn2("docker", ["image", "inspect", imageName], {
80286
+ stdio: ["ignore", "pipe", "pipe"]
80287
+ });
80288
+ docker.on("close", (code) => {
80289
+ resolve3(code === 0);
80290
+ });
80291
+ docker.on("error", () => {
80292
+ resolve3(false);
80293
+ });
80294
+ });
80295
+ }
80296
+ async function getImageSize(imageName) {
80297
+ return new Promise((resolve3) => {
80298
+ const docker = spawn2("docker", ["image", "inspect", "--format", "{{.Size}}", imageName], {
80299
+ stdio: ["ignore", "pipe", "pipe"]
80300
+ });
80301
+ let output = "";
80302
+ docker.stdout.on("data", (chunk) => {
80303
+ output += chunk.toString();
80304
+ });
80305
+ docker.on("close", (code) => {
80306
+ if (code === 0) {
80307
+ const size = parseInt(output.trim(), 10);
80308
+ resolve3(isNaN(size) ? 0 : size);
80309
+ } else {
80310
+ resolve3(0);
80311
+ }
80312
+ });
80313
+ docker.on("error", () => {
80314
+ resolve3(0);
80315
+ });
80316
+ });
80317
+ }
80318
+ async function dockerSaveToFile(imageName, outputPath, onProgress) {
80319
+ return new Promise((resolve3, reject) => {
80320
+ let totalBytes = 0;
80321
+ const docker = spawn2("docker", ["save", imageName], {
80322
+ stdio: ["ignore", "pipe", "pipe"]
80323
+ });
80324
+ const writeStream = createWriteStream(outputPath);
80325
+ docker.stdout.on("data", (chunk) => {
80326
+ writeStream.write(chunk);
80327
+ totalBytes += chunk.length;
80328
+ if (onProgress) {
80329
+ onProgress(totalBytes);
80330
+ }
80331
+ });
80332
+ let stderr = "";
80333
+ docker.stderr.on("data", (chunk) => {
80334
+ stderr += chunk.toString();
80335
+ });
80336
+ docker.on("close", (code) => {
80337
+ writeStream.end();
80338
+ if (code === 0) {
80339
+ resolve3(totalBytes);
80340
+ } else {
80341
+ reject(new Error(`docker save failed with code ${code}: ${stderr}`));
80342
+ }
80343
+ });
80344
+ docker.on("error", (err) => {
80345
+ writeStream.end();
80346
+ reject(new Error(`Failed to spawn docker: ${err.message}`));
80347
+ });
80348
+ writeStream.on("error", (err) => {
80349
+ reject(new Error(`Failed to write to file: ${err.message}`));
80350
+ });
80351
+ });
80352
+ }
80353
+ function formatFileSize(bytes) {
80354
+ if (bytes < 1024)
80355
+ return `${bytes} B`;
80356
+ if (bytes < 1024 * 1024)
80357
+ return `${(bytes / 1024).toFixed(1)} KB`;
80358
+ if (bytes < 1024 * 1024 * 1024)
80359
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
80360
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
80361
+ }
80362
+ async function tryGenerateDockerfile(projectSlug) {
80363
+ let slug = projectSlug;
80364
+ if (!slug) {
80365
+ const resolved = await resolveProjectSlug();
80366
+ slug = resolved?.slug;
80367
+ }
80368
+ if (!slug)
80369
+ return null;
80370
+ let preset;
80371
+ try {
80372
+ const isNumericId = /^\d+$/.test(slug);
80373
+ if (isNumericId) {
80374
+ const { data } = await getProject({
80375
+ client,
80376
+ path: { id: parseInt(slug, 10) }
80377
+ });
80378
+ preset = data?.preset;
80379
+ } else {
80380
+ const { data } = await getProjectBySlug({
80381
+ client,
80382
+ path: { slug }
80383
+ });
80384
+ preset = data?.preset;
80385
+ }
80386
+ } catch {
80387
+ return null;
80388
+ }
80389
+ if (!preset || preset === "dockerfile")
80390
+ return null;
80391
+ info(`No Dockerfile found. Generating from ${colors.bold(preset)} preset...`);
80392
+ const packageManager = detectLocalPackageManager();
80393
+ try {
80394
+ const { data, error: apiError } = await generatePresetDockerfile({
80395
+ client,
80396
+ path: { slug: preset },
80397
+ body: {
80398
+ package_manager: packageManager,
80399
+ project_name: slug,
80400
+ use_buildkit: true
80401
+ }
80402
+ });
80403
+ if (apiError || !data) {
80404
+ const errorMsg = apiError ? typeof apiError === "object" && apiError !== null && "detail" in apiError ? String(apiError.detail) : JSON.stringify(apiError) : "No data returned";
80405
+ warning(`Failed to generate Dockerfile: ${errorMsg}`);
80406
+ return null;
80407
+ }
80408
+ let parsed;
80409
+ if (typeof data === "string") {
80410
+ try {
80411
+ parsed = JSON.parse(data);
80412
+ } catch {
80413
+ warning("Failed to generate Dockerfile: could not parse API response");
80414
+ return null;
80415
+ }
80416
+ } else {
80417
+ parsed = data;
80418
+ }
80419
+ const dockerfileContent = typeof parsed.dockerfile === "string" ? parsed.dockerfile : undefined;
80420
+ const buildArgsObj = parsed.build_args && typeof parsed.build_args === "object" ? parsed.build_args : {};
80421
+ const presetSlug = typeof parsed.preset === "string" ? parsed.preset : preset;
80422
+ if (!dockerfileContent) {
80423
+ warning(`Failed to generate Dockerfile: unexpected response (keys: ${Object.keys(parsed).join(", ")})`);
80424
+ return null;
80425
+ }
80426
+ const tempDir = join2(tmpdir2(), `temps-dockerfile-${Date.now()}`);
80427
+ mkdirSync(tempDir, { recursive: true });
80428
+ const dockerfilePath = join2(tempDir, "Dockerfile");
80429
+ writeFileSync3(dockerfilePath, dockerfileContent);
80430
+ const buildArgs = Object.entries(buildArgsObj).map(([key, value]) => `${key}=${value}`);
80431
+ return { dockerfilePath, buildArgs, preset: presetSlug };
80432
+ } catch (err) {
80433
+ const msg = err instanceof Error ? err.message : String(err);
80434
+ warning(`Failed to generate Dockerfile: ${msg}`);
80435
+ return null;
80436
+ }
80437
+ }
80438
+ function detectLocalPackageManager() {
80439
+ const cwd2 = process.cwd();
80440
+ if (existsSync5(join2(cwd2, "pnpm-lock.yaml")))
80441
+ return "pnpm";
80442
+ if (existsSync5(join2(cwd2, "yarn.lock")))
80443
+ return "yarn";
80444
+ if (existsSync5(join2(cwd2, "bun.lockb")) || existsSync5(join2(cwd2, "bun.lock")))
80445
+ return "bun";
80446
+ if (existsSync5(join2(cwd2, "package-lock.json")))
80447
+ return "npm";
80448
+ return "npm";
80449
+ }
80450
+
80451
+ // src/commands/deploy/deploy-static.ts
80452
+ init_sdk_gen();
80453
+ init_prompts();
80454
+ init_output();
80455
+ import { existsSync as existsSync6, statSync } from "node:fs";
80456
+ import { readFile as readFile3 } from "node:fs/promises";
80457
+ import { basename as basename2, extname, resolve as resolve3 } from "node:path";
80458
+ import { spawn as spawn3 } from "node:child_process";
80459
+ async function deployStatic(options) {
80460
+ await requireAuth();
80461
+ await setupClient();
80462
+ newline();
80463
+ const resolvedPath = resolve3(options.path);
80464
+ if (!existsSync6(resolvedPath)) {
80465
+ warning(`Path does not exist: ${resolvedPath}`);
80466
+ return;
80467
+ }
80468
+ const stat = statSync(resolvedPath);
80469
+ const isDirectory = stat.isDirectory();
80470
+ const isArchive = !isDirectory && isValidArchive(resolvedPath);
80471
+ if (!isDirectory && !isArchive) {
80472
+ warning("Path must be a directory or a .tar.gz/.tgz/.zip archive");
80473
+ return;
80474
+ }
80475
+ const resolved = await resolveProjectSlug(options.project);
80476
+ if (!resolved) {
80477
+ warning("No project specified");
80478
+ info("Use: bunx @temps-sdk/cli deploy:static --project <slug>");
80479
+ info("Or link this directory: bunx @temps-sdk/cli link <slug>");
80480
+ return;
80481
+ }
80482
+ const projectName = resolved.slug;
80483
+ if (resolved.source !== "flag") {
80484
+ info(`Using project ${colors.bold(projectName)} (from ${resolved.source})`);
80485
+ }
79828
80486
  startSpinner("Fetching project details...");
79829
80487
  let projectData;
79830
80488
  let environments = [];
@@ -79926,7 +80584,7 @@ async function deployStatic(options) {
79926
80584
  info("Create an environment first or specify --environment-id directly");
79927
80585
  return;
79928
80586
  }
79929
- const fileSize = isDirectory ? "(will be archived)" : formatFileSize(stat.size);
80587
+ const fileSize = isDirectory ? "(will be archived)" : formatFileSize2(stat.size);
79930
80588
  newline();
79931
80589
  box(`Project: ${colors.bold(projectName)}
79932
80590
  ` + `Environment: ${colors.bold(environmentName)}
@@ -79944,17 +80602,17 @@ async function deployStatic(options) {
79944
80602
  filename = result.filename;
79945
80603
  contentType = "application/gzip";
79946
80604
  } else {
79947
- fileData = await readFile2(resolvedPath);
79948
- filename = basename(resolvedPath);
80605
+ fileData = await readFile3(resolvedPath);
80606
+ filename = basename2(resolvedPath);
79949
80607
  contentType = getContentType(resolvedPath);
79950
80608
  }
79951
- succeedSpinner(`Prepared bundle: ${filename} (${formatFileSize(fileData.length)}) [${contentType}]`);
80609
+ succeedSpinner(`Prepared bundle: ${filename} (${formatFileSize2(fileData.length)}) [${contentType}]`);
79952
80610
  } catch (err) {
79953
80611
  failSpinner("Failed to prepare bundle");
79954
80612
  throw err;
79955
80613
  }
79956
80614
  startSpinner("Uploading static bundle...");
79957
- const apiUrl = config.get("apiUrl");
80615
+ const apiUrl = normalizeApiUrl(config.get("apiUrl"));
79958
80616
  const apiKey = await credentials.getApiKey();
79959
80617
  try {
79960
80618
  const uploadUrl = `${apiUrl}/projects/${projectData.id}/upload/static`;
@@ -80044,14 +80702,14 @@ async function deployStatic(options) {
80044
80702
  }
80045
80703
  function isValidArchive(path6) {
80046
80704
  const ext = extname(path6).toLowerCase();
80047
- const name = basename(path6).toLowerCase();
80705
+ const name = basename2(path6).toLowerCase();
80048
80706
  if (name.endsWith(".tar.gz")) {
80049
80707
  return true;
80050
80708
  }
80051
80709
  return ext === ".tgz" || ext === ".zip";
80052
80710
  }
80053
80711
  function getContentType(path6) {
80054
- const name = basename(path6).toLowerCase();
80712
+ const name = basename2(path6).toLowerCase();
80055
80713
  if (name.endsWith(".tar.gz") || name.endsWith(".tgz")) {
80056
80714
  return "application/gzip";
80057
80715
  }
@@ -80060,7 +80718,7 @@ function getContentType(path6) {
80060
80718
  }
80061
80719
  return "application/octet-stream";
80062
80720
  }
80063
- function formatFileSize(bytes) {
80721
+ function formatFileSize2(bytes) {
80064
80722
  if (bytes < 1024)
80065
80723
  return `${bytes} B`;
80066
80724
  if (bytes < 1024 * 1024)
@@ -80068,11 +80726,11 @@ function formatFileSize(bytes) {
80068
80726
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
80069
80727
  }
80070
80728
  async function createTarGzFromDirectory(dirPath) {
80071
- const dirName = basename(dirPath);
80729
+ const dirName = basename2(dirPath);
80072
80730
  const filename = `${dirName}.tar.gz`;
80073
- return new Promise((resolve2, reject) => {
80731
+ return new Promise((resolve4, reject) => {
80074
80732
  const chunks = [];
80075
- const tar = spawn2("tar", ["-czf", "-", "-C", dirPath, "."], {
80733
+ const tar = spawn3("tar", ["-czf", "-", "-C", dirPath, "."], {
80076
80734
  stdio: ["ignore", "pipe", "pipe"]
80077
80735
  });
80078
80736
  tar.stdout.on("data", (chunk) => {
@@ -80084,7 +80742,7 @@ async function createTarGzFromDirectory(dirPath) {
80084
80742
  });
80085
80743
  tar.on("close", (code) => {
80086
80744
  if (code === 0) {
80087
- resolve2({
80745
+ resolve4({
80088
80746
  data: Buffer.concat(chunks),
80089
80747
  filename
80090
80748
  });
@@ -80098,107 +80756,187 @@ async function createTarGzFromDirectory(dirPath) {
80098
80756
  });
80099
80757
  }
80100
80758
 
80101
- // src/commands/deploy/deploy-image.ts
80102
- init_sdk_gen();
80103
- init_prompts();
80104
- init_output();
80105
- async function deployImage(options) {
80759
+ // src/commands/deploy/deploy.ts
80760
+ async function fetchRemoteCommits(repositoryId, branch, perPage = 20) {
80761
+ try {
80762
+ const response = await client.get({
80763
+ security: [{ scheme: "bearer", type: "http" }],
80764
+ url: "/repository/{repository_id}/commits",
80765
+ path: { repository_id: repositoryId },
80766
+ query: { branch, per_page: perPage }
80767
+ });
80768
+ const data = response.data;
80769
+ return data?.commits ?? [];
80770
+ } catch {
80771
+ return [];
80772
+ }
80773
+ }
80774
+ async function getRepositoryId(repoOwner, repoName, connectionId) {
80775
+ try {
80776
+ const { data } = await getRepositoryByName({
80777
+ client,
80778
+ path: { owner: repoOwner, name: repoName },
80779
+ query: connectionId ? { connection_id: String(connectionId) } : undefined
80780
+ });
80781
+ return data?.id ?? null;
80782
+ } catch {
80783
+ return null;
80784
+ }
80785
+ }
80786
+ function getRelativeTime(date) {
80787
+ const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
80788
+ if (seconds < 60)
80789
+ return "just now";
80790
+ const minutes = Math.floor(seconds / 60);
80791
+ if (minutes < 60)
80792
+ return `${minutes}m ago`;
80793
+ const hours = Math.floor(minutes / 60);
80794
+ if (hours < 24)
80795
+ return `${hours}h ago`;
80796
+ const days = Math.floor(hours / 24);
80797
+ return `${days}d ago`;
80798
+ }
80799
+ async function deploy(options) {
80106
80800
  await requireAuth();
80107
80801
  await setupClient();
80108
80802
  newline();
80109
- let imageRef = options.image;
80110
- if (!imageRef && !options.yes) {
80111
- imageRef = await promptText({
80112
- message: "Docker image reference",
80113
- default: "",
80114
- validate: (value) => {
80115
- if (!value || value.trim() === "") {
80116
- return "Image reference is required";
80117
- }
80118
- return true;
80119
- }
80120
- });
80121
- }
80122
- if (!imageRef) {
80123
- warning("No image specified");
80124
- info("Use: temps deploy image --image <image-ref>");
80125
- return;
80126
- }
80127
- const projectName = options.project ?? config.get("defaultProject");
80128
- if (!projectName) {
80803
+ const resolved = await resolveProjectSlug(options.project);
80804
+ if (!resolved) {
80129
80805
  warning("No project specified");
80130
- info("Use: temps deploy image --project <project> or set a default with temps configure");
80806
+ info("Use: bunx @temps-sdk/cli deploy --project <slug>");
80807
+ info("Or link this directory: bunx @temps-sdk/cli link <slug>");
80131
80808
  return;
80132
80809
  }
80810
+ const projectName = resolved.slug;
80811
+ if (resolved.source !== "flag") {
80812
+ info(`Using project ${colors.bold(projectName)} (from ${resolved.source})`);
80813
+ }
80133
80814
  startSpinner("Fetching project details...");
80134
- let projectData;
80815
+ let project;
80135
80816
  let environments = [];
80136
80817
  try {
80137
- const isNumericId = /^\d+$/.test(projectName);
80138
- if (isNumericId) {
80139
- const result = await getProject({
80140
- client,
80141
- path: { id: parseInt(projectName, 10) }
80142
- });
80143
- if (result.error || !result.data) {
80144
- failSpinner(`Project with ID "${projectName}" not found`);
80145
- info(`Debug: ${JSON.stringify(result)}`);
80146
- return;
80147
- }
80148
- const responseData = result.data;
80149
- if (responseData.id !== undefined) {
80150
- projectData = result.data;
80151
- } else if (responseData.data && typeof responseData.data === "object") {
80152
- projectData = responseData.data;
80153
- } else {
80154
- failSpinner(`Unexpected project response format`);
80155
- info(`Debug: ${JSON.stringify(result.data)}`);
80156
- return;
80157
- }
80158
- } else {
80159
- const { data, error: error3 } = await getProjectBySlug({
80160
- client,
80161
- path: { slug: projectName }
80162
- });
80163
- if (error3 || !data) {
80164
- failSpinner(`Project "${projectName}" not found`);
80165
- return;
80818
+ const { data, error: error3 } = await getProjectBySlug({
80819
+ client,
80820
+ path: { slug: projectName }
80821
+ });
80822
+ if (error3 || !data) {
80823
+ const rawApiUrl = config.get("apiUrl");
80824
+ const baseUrl = client.getConfig().baseUrl ?? rawApiUrl;
80825
+ failSpinner(`Project "${projectName}" not found`);
80826
+ info(`API: ${colors.muted(`${baseUrl}/projects/by-slug/${projectName}`)}`);
80827
+ if (error3) {
80828
+ info(`Error: ${getErrorMessage(error3)}`);
80166
80829
  }
80167
- projectData = data;
80830
+ return;
80168
80831
  }
80169
- succeedSpinner(`Found project: ${projectData.name || projectData.slug}`);
80832
+ project = data;
80833
+ succeedSpinner(`Found project: ${project.name}`);
80170
80834
  const { data: envData } = await getEnvironments({
80171
80835
  client,
80172
- path: { project_id: projectData.id }
80836
+ path: { project_id: project.id }
80173
80837
  });
80174
- if (Array.isArray(envData)) {
80175
- environments = envData;
80176
- } else if (envData && typeof envData === "object") {
80177
- const wrapped = envData;
80178
- if (Array.isArray(wrapped.data)) {
80179
- environments = wrapped.data;
80180
- } else if (Array.isArray(wrapped.environments)) {
80181
- environments = wrapped.environments;
80182
- }
80183
- }
80838
+ environments = envData ?? [];
80184
80839
  } catch (err) {
80185
80840
  failSpinner("Failed to fetch project");
80186
80841
  throw err;
80187
80842
  }
80843
+ const sourceType = project.source_type;
80844
+ const isGitBased = sourceType === "git";
80845
+ const hasGitConnection = isGitBased && !!project.git_provider_connection_id;
80846
+ if (sourceType === "static_files") {
80847
+ info(`Project uses static files deployment`);
80848
+ info(`Delegating to: ${colors.muted("deploy:static")}`);
80849
+ newline();
80850
+ await deployStatic({
80851
+ path: ".",
80852
+ project: projectName,
80853
+ environment: options.environment,
80854
+ environmentId: options.environmentId,
80855
+ wait: options.wait,
80856
+ yes: options.yes
80857
+ });
80858
+ return;
80859
+ }
80860
+ if (sourceType === "docker_image" || sourceType === "manual") {
80861
+ info(`Project uses ${sourceType === "docker_image" ? "Docker image" : "manual"} deployment`);
80862
+ info(`Delegating to: ${colors.muted("deploy:local-image")}`);
80863
+ newline();
80864
+ await deployLocalImage({
80865
+ project: projectName,
80866
+ environment: options.environment,
80867
+ environmentId: options.environmentId,
80868
+ wait: options.wait,
80869
+ yes: options.yes
80870
+ });
80871
+ return;
80872
+ }
80873
+ if (!hasGitConnection) {
80874
+ warning("Project is git-based but no git provider is connected");
80875
+ newline();
80876
+ info("Options:");
80877
+ info(` 1. Connect a git provider: ${colors.muted("bunx @temps-sdk/cli providers add")}`);
80878
+ info(` 2. Deploy a local Docker image: ${colors.muted(`bunx @temps-sdk/cli deploy:local-image -p ${projectName}`)}`);
80879
+ info(` 3. Deploy static files: ${colors.muted(`bunx @temps-sdk/cli deploy:static -p ${projectName} --path ./dist`)}`);
80880
+ newline();
80881
+ if (!options.yes) {
80882
+ const choice = await promptSelect({
80883
+ message: "How would you like to deploy?",
80884
+ choices: [
80885
+ { name: "Build & deploy local Docker image", value: "local-image" },
80886
+ { name: "Deploy static files", value: "static" },
80887
+ { name: "Cancel", value: "cancel" }
80888
+ ]
80889
+ });
80890
+ if (choice === "local-image") {
80891
+ await deployLocalImage({
80892
+ project: projectName,
80893
+ environment: options.environment,
80894
+ environmentId: options.environmentId,
80895
+ wait: options.wait,
80896
+ yes: options.yes
80897
+ });
80898
+ return;
80899
+ }
80900
+ if (choice === "static") {
80901
+ const staticPath = await promptText({
80902
+ message: "Path to static files",
80903
+ default: "./dist"
80904
+ });
80905
+ await deployStatic({
80906
+ path: staticPath,
80907
+ project: projectName,
80908
+ environment: options.environment,
80909
+ environmentId: options.environmentId,
80910
+ wait: options.wait,
80911
+ yes: options.yes
80912
+ });
80913
+ return;
80914
+ }
80915
+ return;
80916
+ }
80917
+ info("Falling back to local Docker image deployment (--yes mode)");
80918
+ await deployLocalImage({
80919
+ project: projectName,
80920
+ environment: options.environment,
80921
+ environmentId: options.environmentId,
80922
+ wait: options.wait,
80923
+ yes: options.yes
80924
+ });
80925
+ return;
80926
+ }
80927
+ if (project.repo_owner && project.repo_name) {
80928
+ info(`Repository: ${colors.muted(`${project.repo_owner}/${project.repo_name}`)}`);
80929
+ }
80188
80930
  let environmentId;
80189
80931
  let environmentName = options.environment || "production";
80190
- if (options.environmentId) {
80191
- environmentId = parseInt(options.environmentId, 10);
80192
- if (environments.length > 0) {
80932
+ if (environments.length > 0) {
80933
+ if (options.environmentId) {
80934
+ environmentId = parseInt(options.environmentId, 10);
80193
80935
  const env4 = environments.find((e) => e.id === environmentId);
80194
80936
  if (env4) {
80195
80937
  environmentName = env4.name;
80196
80938
  }
80197
- } else {
80198
- environmentName = `Environment #${environmentId}`;
80199
- }
80200
- } else if (environments.length > 0) {
80201
- if (options.environment) {
80939
+ } else if (options.environment) {
80202
80940
  const env4 = environments.find((e) => e.name === options.environment);
80203
80941
  if (env4) {
80204
80942
  environmentId = env4.id;
@@ -80226,74 +80964,126 @@ async function deployImage(options) {
80226
80964
  environmentName = environments[0].name;
80227
80965
  }
80228
80966
  }
80229
- } else if (!options.environmentId) {
80230
- warning("No environments found for this project");
80231
- info("Create an environment first or specify --environment-id directly");
80232
- return;
80967
+ }
80968
+ let branch = options.branch;
80969
+ if (!branch) {
80970
+ if (options.yes) {
80971
+ branch = project.main_branch || "main";
80972
+ } else {
80973
+ branch = await promptText({
80974
+ message: "Branch to deploy",
80975
+ default: project.main_branch || "main"
80976
+ });
80977
+ }
80978
+ }
80979
+ let commit = options.commit;
80980
+ if (!commit && !options.yes && project.repo_owner && project.repo_name) {
80981
+ const repositoryId = await getRepositoryId(project.repo_owner, project.repo_name, project.git_provider_connection_id);
80982
+ if (repositoryId) {
80983
+ startSpinner("Fetching recent commits...");
80984
+ const commits = await fetchRemoteCommits(repositoryId, branch);
80985
+ if (commits.length > 0) {
80986
+ succeedSpinner(`Found ${commits.length} recent commits`);
80987
+ const HEAD_VALUE = "__HEAD__";
80988
+ const selected = await promptSelect({
80989
+ message: "Select commit to deploy",
80990
+ choices: [
80991
+ { name: `${colors.bold("HEAD")} ${colors.muted("(latest on branch)")}`, value: HEAD_VALUE },
80992
+ ...commits.map((c) => {
80993
+ const sha = colors.muted(c.sha.substring(0, 7));
80994
+ const msg = c.message.split(`
80995
+ `)[0].substring(0, 60);
80996
+ const ago = getRelativeTime(new Date(c.date));
80997
+ return {
80998
+ name: `${sha} ${msg} ${colors.muted(`(${c.author}, ${ago})`)}`,
80999
+ value: c.sha
81000
+ };
81001
+ })
81002
+ ]
81003
+ });
81004
+ if (selected !== HEAD_VALUE) {
81005
+ commit = selected;
81006
+ }
81007
+ } else {
81008
+ succeedSpinner("No commits found, deploying HEAD");
81009
+ }
81010
+ }
80233
81011
  }
80234
81012
  newline();
80235
- box(`Project: ${colors.bold(projectName)}
80236
- ` + `Environment: ${colors.bold(environmentName)}
80237
- ` + `Image: ${colors.bold(imageRef)}`, `${icons.rocket} Docker Image Deployment`);
81013
+ box([
81014
+ `Project: ${colors.bold(projectName)}`,
81015
+ `Environment: ${colors.bold(environmentName)}`,
81016
+ `Branch: ${colors.bold(branch)}`,
81017
+ commit ? `Commit: ${colors.bold(commit.substring(0, 7))}` : null,
81018
+ project.preset ? `Preset: ${colors.bold(project.preset)}` : null,
81019
+ project.repo_owner && project.repo_name ? `Repository: ${colors.bold(`${project.repo_owner}/${project.repo_name}`)}` : null
81020
+ ].filter(Boolean).join(`
81021
+ `), `${icons.rocket} Deployment Preview`);
80238
81022
  newline();
80239
81023
  startSpinner("Starting deployment...");
80240
- const apiUrl = config.get("apiUrl");
80241
- const apiKey = await credentials.getApiKey();
80242
81024
  try {
80243
- const deployUrl = `${apiUrl}/projects/${projectData.id}/environments/${environmentId}/deploy/image`;
80244
- const deployBody = {
80245
- image_ref: imageRef
80246
- };
80247
- if (options.metadata) {
80248
- try {
80249
- deployBody.metadata = JSON.parse(options.metadata);
80250
- } catch {
80251
- failSpinner("Invalid metadata JSON");
80252
- return;
81025
+ const { data, error: error3 } = await triggerProjectPipeline({
81026
+ client,
81027
+ path: { id: project.id },
81028
+ body: {
81029
+ branch,
81030
+ commit: commit ?? undefined,
81031
+ environment_id: environmentId
80253
81032
  }
80254
- }
80255
- const deployResponse = await fetch(deployUrl, {
80256
- method: "POST",
80257
- headers: {
80258
- Authorization: `Bearer ${apiKey}`,
80259
- "Content-Type": "application/json"
80260
- },
80261
- body: JSON.stringify(deployBody)
80262
81033
  });
80263
- const deployResponseText = await deployResponse.text();
80264
- if (!deployResponse.ok) {
80265
- failSpinner(`Deployment failed: ${deployResponse.status}`);
80266
- info(`URL: ${deployUrl}`);
80267
- warning(`Response: ${deployResponseText}`);
81034
+ if (error3 || !data) {
81035
+ failSpinner("Failed to start deployment");
81036
+ const msg = getErrorMessage(error3);
81037
+ if (msg) {
81038
+ info(`Reason: ${msg}`);
81039
+ }
80268
81040
  return;
80269
81041
  }
80270
- let deployment;
80271
- try {
80272
- deployment = JSON.parse(deployResponseText);
80273
- } catch (parseErr) {
80274
- failSpinner("Failed to parse deployment response");
80275
- info(`URL: ${deployUrl}`);
80276
- warning(`Response: ${deployResponseText}`);
81042
+ succeedSpinner("Deployment started");
81043
+ info(data.message ?? "Pipeline triggered successfully");
81044
+ const webUrl = getWebUrl();
81045
+ info(`Dashboard: ${colors.primary(`${webUrl}/projects/${projectName}/deployments`)}`);
81046
+ if (options.wait === false) {
80277
81047
  return;
80278
81048
  }
80279
- succeedSpinner(`Deployment started: ${deployment.slug}`);
80280
- if (options.wait !== false) {
81049
+ startSpinner("Waiting for deployment to start...");
81050
+ let deploymentId = null;
81051
+ for (let attempt = 0;attempt < 15; attempt++) {
81052
+ const { data: deployList, error: deployError } = await getProjectDeployments({
81053
+ client,
81054
+ path: { id: project.id },
81055
+ query: {
81056
+ per_page: 1,
81057
+ ...environmentId ? { environment_id: environmentId } : {}
81058
+ }
81059
+ });
81060
+ if (deployError) {
81061
+ failSpinner("Failed to fetch deployment status");
81062
+ info(`Error: ${getErrorMessage(deployError)}`);
81063
+ info(`Dashboard: ${colors.primary(`${webUrl}/projects/${projectName}/deployments`)}`);
81064
+ return;
81065
+ }
81066
+ const latest = deployList?.deployments?.[0];
81067
+ if (latest?.id) {
81068
+ deploymentId = latest.id;
81069
+ break;
81070
+ }
81071
+ await new Promise((r) => setTimeout(r, 2000));
81072
+ }
81073
+ if (deploymentId) {
81074
+ succeedSpinner(`Deployment #${deploymentId} found`);
80281
81075
  const result = await watchDeployment({
80282
- projectId: projectData.id,
80283
- deploymentId: deployment.id,
80284
- timeoutSecs: parseInt(options.timeout || "300", 10),
81076
+ projectId: project.id,
81077
+ deploymentId,
81078
+ timeoutSecs: 600,
80285
81079
  projectName
80286
81080
  });
80287
81081
  if (!result.success) {
80288
81082
  process.exitCode = 1;
80289
81083
  }
80290
81084
  } else {
80291
- newline();
80292
- info("Deployment running in background");
80293
- info(`Check status with: temps deployments list --project ${projectName}`);
80294
- newline();
80295
- success("Docker image deployment initiated successfully!");
80296
- newline();
81085
+ failSpinner("Could not locate the deployment to track");
81086
+ info(`Dashboard: ${colors.primary(`${webUrl}/projects/${projectName}/deployments`)}`);
80297
81087
  }
80298
81088
  } catch (err) {
80299
81089
  failSpinner("Deployment failed");
@@ -80301,25 +81091,43 @@ async function deployImage(options) {
80301
81091
  }
80302
81092
  }
80303
81093
 
80304
- // src/commands/deploy/deploy-local-image.ts
81094
+ // src/commands/deploy/deploy-image.ts
80305
81095
  init_sdk_gen();
80306
81096
  init_prompts();
80307
81097
  init_output();
80308
- import { spawn as spawn3 } from "node:child_process";
80309
- import { existsSync as existsSync4, createWriteStream, writeFileSync as writeFileSync3, mkdirSync } from "node:fs";
80310
- import { unlink } from "node:fs/promises";
80311
- import { resolve as resolve2, basename as basename2, join } from "node:path";
80312
- import { tmpdir as tmpdir2 } from "node:os";
80313
- async function deployLocalImage(options) {
81098
+ async function deployImage(options) {
80314
81099
  await requireAuth();
80315
81100
  await setupClient();
80316
81101
  newline();
80317
- const projectName = options.project ?? config.get("defaultProject");
80318
- if (!projectName) {
81102
+ let imageRef = options.image;
81103
+ if (!imageRef && !options.yes) {
81104
+ imageRef = await promptText({
81105
+ message: "Docker image reference",
81106
+ default: "",
81107
+ validate: (value) => {
81108
+ if (!value || value.trim() === "") {
81109
+ return "Image reference is required";
81110
+ }
81111
+ return true;
81112
+ }
81113
+ });
81114
+ }
81115
+ if (!imageRef) {
81116
+ warning("No image specified");
81117
+ info("Use: temps deploy image --image <image-ref>");
81118
+ return;
81119
+ }
81120
+ const resolved = await resolveProjectSlug(options.project);
81121
+ if (!resolved) {
80319
81122
  warning("No project specified");
80320
- info("Use: temps deploy:local-image --project <project> or set a default with temps configure");
81123
+ info("Use: bunx @temps-sdk/cli deploy:image --project <slug>");
81124
+ info("Or link this directory: bunx @temps-sdk/cli link <slug>");
80321
81125
  return;
80322
81126
  }
81127
+ const projectName = resolved.slug;
81128
+ if (resolved.source !== "flag") {
81129
+ info(`Using project ${colors.bold(projectName)} (from ${resolved.source})`);
81130
+ }
80323
81131
  startSpinner("Fetching project details...");
80324
81132
  let projectData;
80325
81133
  let environments = [];
@@ -80341,7 +81149,7 @@ async function deployLocalImage(options) {
80341
81149
  } else if (responseData.data && typeof responseData.data === "object") {
80342
81150
  projectData = responseData.data;
80343
81151
  } else {
80344
- failSpinner("Unexpected project response format");
81152
+ failSpinner(`Unexpected project response format`);
80345
81153
  info(`Debug: ${JSON.stringify(result.data)}`);
80346
81154
  return;
80347
81155
  }
@@ -80421,185 +81229,49 @@ async function deployLocalImage(options) {
80421
81229
  info("Create an environment first or specify --environment-id directly");
80422
81230
  return;
80423
81231
  }
80424
- info(`Environment: ${colors.bold(environmentName)}`);
80425
- let imageName;
80426
- let didBuild = false;
80427
- const shouldBuild = !options.noBuild && !options.image;
80428
- if (shouldBuild) {
80429
- let dockerfilePath = options.dockerfile || "Dockerfile";
80430
- const contextPath = options.context || ".";
80431
- let resolvedDockerfile = resolve2(dockerfilePath);
80432
- const resolvedContext = resolve2(contextPath);
80433
- let generatedBuildArgs = [];
80434
- if (!existsSync4(resolvedDockerfile)) {
80435
- const generated = await tryGenerateDockerfile(options.project);
80436
- if (generated) {
80437
- resolvedDockerfile = generated.dockerfilePath;
80438
- generatedBuildArgs = generated.buildArgs;
80439
- success(`Dockerfile generated from ${colors.bold(generated.preset)} preset`);
80440
- } else {
80441
- warning(`Dockerfile not found: ${resolvedDockerfile}`);
80442
- info("Options:");
80443
- info(" 1. Create a Dockerfile in the current directory");
80444
- info(" 2. Specify a Dockerfile path: --dockerfile <path>");
80445
- info(" 3. Skip build and use existing image: --image <image-name>");
80446
- return;
80447
- }
80448
- }
80449
- const allBuildArgs = [...generatedBuildArgs, ...options.buildArg || []];
80450
- const dirName = basename2(process.cwd());
80451
- const timestamp = Date.now();
80452
- imageName = options.tag || `${projectName || dirName}:local-${timestamp}`;
80453
- newline();
80454
- box(`Dockerfile: ${colors.bold(resolvedDockerfile)}
80455
- ` + `Context: ${colors.bold(resolvedContext)}
80456
- ` + `Image Tag: ${colors.bold(imageName)}` + (allBuildArgs.length ? `
80457
- Build Args: ${colors.bold(allBuildArgs.join(", "))}` : ""), `${icons.package} Docker Build`);
80458
- newline();
80459
- startSpinner("Building Docker image...");
80460
- try {
80461
- await dockerBuild({
80462
- dockerfile: resolvedDockerfile,
80463
- context: resolvedContext,
80464
- tag: imageName,
80465
- buildArgs: allBuildArgs,
80466
- onOutput: (line) => {
80467
- const trimmed = line.trim();
80468
- if (trimmed) {
80469
- updateSpinner(`Building: ${trimmed.substring(0, 60)}${trimmed.length > 60 ? "..." : ""}`);
80470
- }
80471
- }
80472
- });
80473
- succeedSpinner(`Image built: ${imageName}`);
80474
- didBuild = true;
80475
- } catch (err) {
80476
- failSpinner("Docker build failed");
80477
- if (err instanceof Error) {
80478
- warning(err.message);
80479
- }
80480
- return;
80481
- }
80482
- } else if (options.image) {
80483
- imageName = options.image;
80484
- startSpinner("Verifying local Docker image...");
80485
- const imageExists = await checkImageExists(imageName);
80486
- if (!imageExists) {
80487
- failSpinner(`Image "${imageName}" not found locally`);
80488
- info("Make sure the image exists by running: docker images");
80489
- info("Or remove --image to build from Dockerfile");
80490
- return;
80491
- }
80492
- succeedSpinner(`Found local image: ${imageName}`);
80493
- } else {
80494
- warning("No image specified and build is disabled");
80495
- info("Use: temps deploy:local-image --image <image-name>");
80496
- info("Or remove --no-build to build from Dockerfile");
80497
- return;
80498
- }
80499
- const imageSize = await getImageSize(imageName);
80500
- info(`Image size: ${formatFileSize2(imageSize)}`);
80501
81232
  newline();
80502
81233
  box(`Project: ${colors.bold(projectName)}
80503
81234
  ` + `Environment: ${colors.bold(environmentName)}
80504
- ` + `Image: ${colors.bold(imageName)}
80505
- ` + `Size: ${colors.bold(formatFileSize2(imageSize))}` + (didBuild ? `
80506
- ${colors.dim("(freshly built)")}` : ""), `${icons.rocket} Deploy Local Image`);
81235
+ ` + `Image: ${colors.bold(imageRef)}`, `${icons.rocket} Docker Image Deployment`);
80507
81236
  newline();
80508
- const tempFilename = `temps-image-${Date.now()}.tar`;
80509
- const tempFilePath = join(tmpdir2(), tempFilename);
80510
- startSpinner("Exporting image with docker save...");
80511
- let exportedSize;
80512
- try {
80513
- exportedSize = await dockerSaveToFile(imageName, tempFilePath, (progress) => {
80514
- updateSpinner(`Exporting image... ${formatFileSize2(progress)} saved`);
80515
- });
80516
- succeedSpinner(`Image exported: ${formatFileSize2(exportedSize)}`);
80517
- } catch (err) {
80518
- failSpinner("Failed to export image");
80519
- if (err instanceof Error) {
80520
- warning(err.message);
80521
- }
80522
- return;
80523
- }
80524
- const MAX_SIZE = 1024 * 1024 * 1024;
80525
- if (exportedSize > MAX_SIZE) {
80526
- warning(`Image size (${formatFileSize2(exportedSize)}) exceeds maximum allowed (1 GB)`);
80527
- await unlink(tempFilePath).catch(() => {});
80528
- return;
80529
- }
80530
- startSpinner("Uploading image to server...");
80531
- const apiUrl = config.get("apiUrl");
81237
+ startSpinner("Starting deployment...");
81238
+ const apiUrl = normalizeApiUrl(config.get("apiUrl"));
80532
81239
  const apiKey = await credentials.getApiKey();
80533
81240
  try {
80534
- const uploadUrl = `${apiUrl}/projects/${projectData.id}/environments/${environmentId}/deploy/image-upload`;
80535
- const queryParams = new URLSearchParams;
80536
- if (options.tag) {
80537
- queryParams.set("tag", options.tag);
80538
- }
80539
- const finalUrl = queryParams.toString() ? `${uploadUrl}?${queryParams.toString()}` : uploadUrl;
80540
- const file = Bun.file(tempFilePath);
80541
- const filename = `${imageName.replace(/[/:]/g, "-")}.tar`;
80542
- const boundary = `----BunFormBoundary${Date.now().toString(16)}`;
80543
- const fileStream = file.stream();
80544
- const header2 = [
80545
- `--${boundary}`,
80546
- `Content-Disposition: form-data; name="file"; filename="${filename}"`,
80547
- "Content-Type: application/x-tar",
80548
- "",
80549
- ""
80550
- ].join(`\r
80551
- `);
80552
- const footer = `\r
80553
- --${boundary}--\r
80554
- `;
80555
- const headerBytes = new TextEncoder().encode(header2);
80556
- const footerBytes = new TextEncoder().encode(footer);
80557
- let uploadedBytes = 0;
80558
- const combinedStream = new ReadableStream({
80559
- async start(controller) {
80560
- controller.enqueue(headerBytes);
80561
- const reader = fileStream.getReader();
80562
- try {
80563
- while (true) {
80564
- const { done, value } = await reader.read();
80565
- if (done)
80566
- break;
80567
- uploadedBytes += value.byteLength;
80568
- updateSpinner(`Uploading... ${formatFileSize2(uploadedBytes)} / ${formatFileSize2(exportedSize)}`);
80569
- controller.enqueue(value);
80570
- }
80571
- } finally {
80572
- reader.releaseLock();
80573
- }
80574
- controller.enqueue(footerBytes);
80575
- controller.close();
81241
+ const deployUrl = `${apiUrl}/projects/${projectData.id}/environments/${environmentId}/deploy/image`;
81242
+ const deployBody = {
81243
+ image_ref: imageRef
81244
+ };
81245
+ if (options.metadata) {
81246
+ try {
81247
+ deployBody.metadata = JSON.parse(options.metadata);
81248
+ } catch {
81249
+ failSpinner("Invalid metadata JSON");
81250
+ return;
80576
81251
  }
80577
- });
80578
- const uploadResponse = await fetch(finalUrl, {
81252
+ }
81253
+ const deployResponse = await fetch(deployUrl, {
80579
81254
  method: "POST",
80580
81255
  headers: {
80581
81256
  Authorization: `Bearer ${apiKey}`,
80582
- "Content-Type": `multipart/form-data; boundary=${boundary}`
81257
+ "Content-Type": "application/json"
80583
81258
  },
80584
- body: combinedStream,
80585
- duplex: "half"
81259
+ body: JSON.stringify(deployBody)
80586
81260
  });
80587
- await unlink(tempFilePath).catch(() => {});
80588
- if (!uploadResponse.ok) {
80589
- const errorText = await uploadResponse.text();
80590
- failSpinner(`Upload failed: ${uploadResponse.status}`);
80591
- info(`URL: ${finalUrl}`);
80592
- warning(`Response: ${errorText}`);
81261
+ const deployResponseText = await deployResponse.text();
81262
+ if (!deployResponse.ok) {
81263
+ failSpinner(`Deployment failed: ${deployResponse.status}`);
81264
+ info(`URL: ${deployUrl}`);
81265
+ warning(`Response: ${deployResponseText}`);
80593
81266
  return;
80594
81267
  }
80595
- const responseText = await uploadResponse.text();
80596
81268
  let deployment;
80597
81269
  try {
80598
- deployment = JSON.parse(responseText);
81270
+ deployment = JSON.parse(deployResponseText);
80599
81271
  } catch (parseErr) {
80600
81272
  failSpinner("Failed to parse deployment response");
80601
- info(`URL: ${finalUrl}`);
80602
- warning(`Response: ${responseText}`);
81273
+ info(`URL: ${deployUrl}`);
81274
+ warning(`Response: ${deployResponseText}`);
80603
81275
  return;
80604
81276
  }
80605
81277
  succeedSpinner(`Deployment started: ${deployment.slug}`);
@@ -80607,7 +81279,7 @@ ${colors.dim("(freshly built)")}` : ""), `${icons.rocket} Deploy Local Image`);
80607
81279
  const result = await watchDeployment({
80608
81280
  projectId: projectData.id,
80609
81281
  deploymentId: deployment.id,
80610
- timeoutSecs: parseInt(options.timeout || "600", 10),
81282
+ timeoutSecs: parseInt(options.timeout || "300", 10),
80611
81283
  projectName
80612
81284
  });
80613
81285
  if (!result.success) {
@@ -80618,7 +81290,7 @@ ${colors.dim("(freshly built)")}` : ""), `${icons.rocket} Deploy Local Image`);
80618
81290
  info("Deployment running in background");
80619
81291
  info(`Check status with: temps deployments list --project ${projectName}`);
80620
81292
  newline();
80621
- success("Local image deployment initiated successfully!");
81293
+ success("Docker image deployment initiated successfully!");
80622
81294
  newline();
80623
81295
  }
80624
81296
  } catch (err) {
@@ -80626,218 +81298,6 @@ ${colors.dim("(freshly built)")}` : ""), `${icons.rocket} Deploy Local Image`);
80626
81298
  throw err;
80627
81299
  }
80628
81300
  }
80629
- async function dockerBuild(options) {
80630
- return new Promise((resolve3, reject) => {
80631
- const args = [
80632
- "build",
80633
- "-f",
80634
- options.dockerfile,
80635
- "-t",
80636
- options.tag
80637
- ];
80638
- for (const arg of options.buildArgs) {
80639
- args.push("--build-arg", arg);
80640
- }
80641
- args.push(options.context);
80642
- const docker = spawn3("docker", args, {
80643
- stdio: ["ignore", "pipe", "pipe"]
80644
- });
80645
- let stderr = "";
80646
- docker.stdout.on("data", (chunk) => {
80647
- const lines = chunk.toString().split(`
80648
- `);
80649
- for (const line of lines) {
80650
- if (line.trim() && options.onOutput) {
80651
- options.onOutput(line);
80652
- }
80653
- }
80654
- });
80655
- docker.stderr.on("data", (chunk) => {
80656
- stderr += chunk.toString();
80657
- const lines = chunk.toString().split(`
80658
- `);
80659
- for (const line of lines) {
80660
- if (line.trim() && options.onOutput) {
80661
- options.onOutput(line);
80662
- }
80663
- }
80664
- });
80665
- docker.on("close", (code) => {
80666
- if (code === 0) {
80667
- resolve3();
80668
- } else {
80669
- reject(new Error(`docker build failed with code ${code}:
80670
- ${stderr}`));
80671
- }
80672
- });
80673
- docker.on("error", (err) => {
80674
- reject(new Error(`Failed to spawn docker: ${err.message}`));
80675
- });
80676
- });
80677
- }
80678
- async function checkImageExists(imageName) {
80679
- return new Promise((resolve3) => {
80680
- const docker = spawn3("docker", ["image", "inspect", imageName], {
80681
- stdio: ["ignore", "pipe", "pipe"]
80682
- });
80683
- docker.on("close", (code) => {
80684
- resolve3(code === 0);
80685
- });
80686
- docker.on("error", () => {
80687
- resolve3(false);
80688
- });
80689
- });
80690
- }
80691
- async function getImageSize(imageName) {
80692
- return new Promise((resolve3) => {
80693
- const docker = spawn3("docker", ["image", "inspect", "--format", "{{.Size}}", imageName], {
80694
- stdio: ["ignore", "pipe", "pipe"]
80695
- });
80696
- let output = "";
80697
- docker.stdout.on("data", (chunk) => {
80698
- output += chunk.toString();
80699
- });
80700
- docker.on("close", (code) => {
80701
- if (code === 0) {
80702
- const size = parseInt(output.trim(), 10);
80703
- resolve3(isNaN(size) ? 0 : size);
80704
- } else {
80705
- resolve3(0);
80706
- }
80707
- });
80708
- docker.on("error", () => {
80709
- resolve3(0);
80710
- });
80711
- });
80712
- }
80713
- async function dockerSaveToFile(imageName, outputPath, onProgress) {
80714
- return new Promise((resolve3, reject) => {
80715
- let totalBytes = 0;
80716
- const docker = spawn3("docker", ["save", imageName], {
80717
- stdio: ["ignore", "pipe", "pipe"]
80718
- });
80719
- const writeStream = createWriteStream(outputPath);
80720
- docker.stdout.on("data", (chunk) => {
80721
- writeStream.write(chunk);
80722
- totalBytes += chunk.length;
80723
- if (onProgress) {
80724
- onProgress(totalBytes);
80725
- }
80726
- });
80727
- let stderr = "";
80728
- docker.stderr.on("data", (chunk) => {
80729
- stderr += chunk.toString();
80730
- });
80731
- docker.on("close", (code) => {
80732
- writeStream.end();
80733
- if (code === 0) {
80734
- resolve3(totalBytes);
80735
- } else {
80736
- reject(new Error(`docker save failed with code ${code}: ${stderr}`));
80737
- }
80738
- });
80739
- docker.on("error", (err) => {
80740
- writeStream.end();
80741
- reject(new Error(`Failed to spawn docker: ${err.message}`));
80742
- });
80743
- writeStream.on("error", (err) => {
80744
- reject(new Error(`Failed to write to file: ${err.message}`));
80745
- });
80746
- });
80747
- }
80748
- function formatFileSize2(bytes) {
80749
- if (bytes < 1024)
80750
- return `${bytes} B`;
80751
- if (bytes < 1024 * 1024)
80752
- return `${(bytes / 1024).toFixed(1)} KB`;
80753
- if (bytes < 1024 * 1024 * 1024)
80754
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
80755
- return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
80756
- }
80757
- async function tryGenerateDockerfile(projectSlug) {
80758
- const slug = projectSlug ?? config.get("defaultProject");
80759
- if (!slug)
80760
- return null;
80761
- let preset;
80762
- try {
80763
- const isNumericId = /^\d+$/.test(slug);
80764
- if (isNumericId) {
80765
- const { data } = await getProject({
80766
- client,
80767
- path: { id: parseInt(slug, 10) }
80768
- });
80769
- preset = data?.preset;
80770
- } else {
80771
- const { data } = await getProjectBySlug({
80772
- client,
80773
- path: { slug }
80774
- });
80775
- preset = data?.preset;
80776
- }
80777
- } catch {
80778
- return null;
80779
- }
80780
- if (!preset || preset === "dockerfile")
80781
- return null;
80782
- info(`No Dockerfile found. Generating from ${colors.bold(preset)} preset...`);
80783
- const packageManager = detectLocalPackageManager();
80784
- try {
80785
- const { data, error: apiError } = await generatePresetDockerfile({
80786
- client,
80787
- path: { slug: preset },
80788
- body: {
80789
- package_manager: packageManager,
80790
- project_name: slug,
80791
- use_buildkit: true
80792
- }
80793
- });
80794
- if (apiError || !data) {
80795
- const errorMsg = apiError ? typeof apiError === "object" && apiError !== null && "detail" in apiError ? String(apiError.detail) : JSON.stringify(apiError) : "No data returned";
80796
- warning(`Failed to generate Dockerfile: ${errorMsg}`);
80797
- return null;
80798
- }
80799
- let parsed;
80800
- if (typeof data === "string") {
80801
- try {
80802
- parsed = JSON.parse(data);
80803
- } catch {
80804
- warning("Failed to generate Dockerfile: could not parse API response");
80805
- return null;
80806
- }
80807
- } else {
80808
- parsed = data;
80809
- }
80810
- const dockerfileContent = typeof parsed.dockerfile === "string" ? parsed.dockerfile : undefined;
80811
- const buildArgsObj = parsed.build_args && typeof parsed.build_args === "object" ? parsed.build_args : {};
80812
- const presetSlug = typeof parsed.preset === "string" ? parsed.preset : preset;
80813
- if (!dockerfileContent) {
80814
- warning(`Failed to generate Dockerfile: unexpected response (keys: ${Object.keys(parsed).join(", ")})`);
80815
- return null;
80816
- }
80817
- const tempDir = join(tmpdir2(), `temps-dockerfile-${Date.now()}`);
80818
- mkdirSync(tempDir, { recursive: true });
80819
- const dockerfilePath = join(tempDir, "Dockerfile");
80820
- writeFileSync3(dockerfilePath, dockerfileContent);
80821
- const buildArgs = Object.entries(buildArgsObj).map(([key, value]) => `${key}=${value}`);
80822
- return { dockerfilePath, buildArgs, preset: presetSlug };
80823
- } catch (err) {
80824
- const msg = err instanceof Error ? err.message : String(err);
80825
- warning(`Failed to generate Dockerfile: ${msg}`);
80826
- return null;
80827
- }
80828
- }
80829
- function detectLocalPackageManager() {
80830
- const cwd2 = process.cwd();
80831
- if (existsSync4(join(cwd2, "pnpm-lock.yaml")))
80832
- return "pnpm";
80833
- if (existsSync4(join(cwd2, "yarn.lock")))
80834
- return "yarn";
80835
- if (existsSync4(join(cwd2, "bun.lockb")) || existsSync4(join(cwd2, "bun.lock")))
80836
- return "bun";
80837
- if (existsSync4(join(cwd2, "package-lock.json")))
80838
- return "npm";
80839
- return "npm";
80840
- }
80841
81301
 
80842
81302
  // src/commands/deploy/list.ts
80843
81303
  init_sdk_gen();
@@ -80845,10 +81305,12 @@ init_output();
80845
81305
  async function list2(options) {
80846
81306
  await requireAuth();
80847
81307
  await setupClient();
80848
- const projectName = options.project ?? config.get("defaultProject");
80849
- if (!projectName) {
80850
- throw new Error("No project specified. Use: temps deployments list --project <project>");
81308
+ const resolved = await resolveProjectSlug(options.project);
81309
+ if (!resolved) {
81310
+ throw new Error(`No project specified. Use: bunx @temps-sdk/cli deployments list --project <slug>
81311
+ ` + "Or link this directory: bunx @temps-sdk/cli link <slug>");
80851
81312
  }
81313
+ const projectName = resolved.slug;
80852
81314
  const deployments = await withSpinner("Fetching deployments...", async () => {
80853
81315
  const { data: projectData, error: projectError } = await getProjectBySlug({
80854
81316
  client,
@@ -80911,14 +81373,40 @@ async function list2(options) {
80911
81373
  // src/commands/deploy/logs.ts
80912
81374
  init_sdk_gen();
80913
81375
  init_output();
81376
+ function parseLogEntries(data) {
81377
+ if (Array.isArray(data)) {
81378
+ return data;
81379
+ }
81380
+ if (typeof data !== "string") {
81381
+ return [];
81382
+ }
81383
+ const lines = data.split(`
81384
+ `).filter((line) => line.trim() !== "");
81385
+ return lines.map((line, index) => {
81386
+ try {
81387
+ const parsed = JSON.parse(line);
81388
+ return {
81389
+ timestamp: parsed.timestamp,
81390
+ level: parsed.level,
81391
+ message: parsed.message ?? line,
81392
+ line: parsed.line ?? index + 1
81393
+ };
81394
+ } catch {
81395
+ return { message: line, line: index + 1 };
81396
+ }
81397
+ });
81398
+ }
80914
81399
  async function logs(options) {
80915
81400
  await requireAuth();
80916
81401
  await setupClient();
80917
- const projectName = options.project ?? config.get("defaultProject");
80918
- if (!projectName) {
80919
- warning("No project specified. Use: temps logs --project <project>");
81402
+ const resolved = await resolveProjectSlug(options.project);
81403
+ if (!resolved) {
81404
+ warning("No project specified");
81405
+ info("Use: bunx @temps-sdk/cli deployments logs --project <slug>");
81406
+ info("Or link this directory: bunx @temps-sdk/cli link <slug>");
80920
81407
  return;
80921
81408
  }
81409
+ const projectName = resolved.slug;
80922
81410
  const { data: projectData, error: projectError } = await getProjectBySlug({
80923
81411
  client,
80924
81412
  path: { slug: projectName }
@@ -80990,7 +81478,7 @@ async function fetchLogs(projectId, deploymentId, jobs, limit) {
80990
81478
  console.log(colors.muted("No logs available for this job"));
80991
81479
  continue;
80992
81480
  }
80993
- const logs2 = Array.isArray(data) ? data : [data];
81481
+ const logs2 = parseLogEntries(data);
80994
81482
  const limitedLogs = logs2.slice(-limit);
80995
81483
  for (const log of limitedLogs) {
80996
81484
  printLogLine(log);
@@ -81013,7 +81501,7 @@ async function streamLogs(projectId, deploymentId, jobs) {
81013
81501
  }
81014
81502
  });
81015
81503
  if (data) {
81016
- const logs2 = Array.isArray(data) ? data : [data];
81504
+ const logs2 = parseLogEntries(data);
81017
81505
  const lastLine8 = lastLines[job.id] || 0;
81018
81506
  for (const log of logs2) {
81019
81507
  if (log.line && log.line > lastLine8) {
@@ -81021,17 +81509,10 @@ async function streamLogs(projectId, deploymentId, jobs) {
81021
81509
  lastLines[job.id] = log.line;
81022
81510
  }
81023
81511
  }
81024
- if (logs2.length > 0 && logs2[0]?.line) {
81025
- const newLogs = logs2.slice(lastLine8);
81026
- for (const log of newLogs) {
81027
- console.log(colors.muted(`[${job.name}]`), formatLogMessage(log));
81028
- }
81029
- lastLines[job.id] = logs2.length;
81030
- }
81031
81512
  }
81032
81513
  } catch {}
81033
81514
  }
81034
- await new Promise((resolve3) => setTimeout(resolve3, 1000));
81515
+ await new Promise((resolve4) => setTimeout(resolve4, 1000));
81035
81516
  }
81036
81517
  }
81037
81518
  function printLogLine(log) {
@@ -81056,18 +81537,19 @@ init_output();
81056
81537
  async function rollback(options) {
81057
81538
  await requireAuth();
81058
81539
  await setupClient();
81059
- if (!options.project) {
81060
- throw new Error("Project is required. Use: temps deployments rollback --project <project>");
81540
+ const resolved = await requireProjectSlug(options.project);
81541
+ if (resolved.source !== "flag") {
81542
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
81061
81543
  }
81062
81544
  newline();
81063
- warning(`Rolling back ${colors.bold(options.project)} in ${colors.bold(options.environment)}`);
81545
+ warning(`Rolling back ${colors.bold(resolved.slug)} in ${colors.bold(options.environment)}`);
81064
81546
  newline();
81065
81547
  const { data: projectData, error: projectError } = await getProjectBySlug({
81066
81548
  client,
81067
- path: { slug: options.project }
81549
+ path: { slug: resolved.slug }
81068
81550
  });
81069
81551
  if (projectError || !projectData) {
81070
- throw new Error(`Project "${options.project}" not found`);
81552
+ throw new Error(`Project "${resolved.slug}" not found`);
81071
81553
  }
81072
81554
  let targetDeploymentId = options.to ? parseInt(options.to, 10) : undefined;
81073
81555
  if (!targetDeploymentId) {
@@ -81079,20 +81561,26 @@ async function rollback(options) {
81079
81561
  if (error3 || !data) {
81080
81562
  throw new Error(getErrorMessage(error3));
81081
81563
  }
81082
- return data.deployments.filter((d) => d.environment?.name === options.environment && (d.status === "success" || d.status === "completed" || d.status === "deployed")).slice(0, 5);
81564
+ return data.deployments.filter((d) => d.environment?.name === options.environment && (d.status === "success" || d.status === "completed" || d.status === "deployed")).slice(0, 10);
81083
81565
  });
81084
- if (deployments.length < 2) {
81085
- warning("No previous deployments to rollback to");
81566
+ if (deployments.length === 0) {
81567
+ warning("No completed deployments found for this environment");
81086
81568
  return;
81087
81569
  }
81088
- const previousDeployments = deployments.slice(1);
81089
81570
  const selectedId = await promptSelect({
81090
81571
  message: "Select deployment to rollback to",
81091
- choices: previousDeployments.map((d) => ({
81092
- name: `#${d.id} - ${d.branch ?? "unknown"} (${d.commit_hash?.substring(0, 7) ?? "unknown"})`,
81093
- value: String(d.id),
81094
- description: new Date(d.created_at * 1000).toLocaleString()
81095
- }))
81572
+ choices: deployments.map((d) => {
81573
+ const isRollback = d.metadata?.isRollback;
81574
+ const branch = d.branch ?? (isRollback ? "rollback" : "unknown");
81575
+ const commit = d.commit_hash?.substring(0, 7) ?? (isRollback ? `from #${d.metadata?.rolledBackFromId ?? "?"}` : "-");
81576
+ const currentTag = d.is_current ? " (current)" : "";
81577
+ const date = new Date(d.created_at * 1000).toLocaleString();
81578
+ return {
81579
+ name: `#${d.id} - ${branch} (${commit})${currentTag}`,
81580
+ value: String(d.id),
81581
+ description: date
81582
+ };
81583
+ })
81096
81584
  });
81097
81585
  targetDeploymentId = parseInt(selectedId, 10);
81098
81586
  }
@@ -81122,7 +81610,7 @@ async function rollback(options) {
81122
81610
  keyValue("New Deployment ID", newDeployment.id);
81123
81611
  keyValue("Status", newDeployment.status);
81124
81612
  newline();
81125
- info(`Track progress with: temps deployments status --project ${options.project} --deployment-id ${newDeployment.id}`);
81613
+ info(`Track progress with: temps deployments status --project ${resolved.slug} --deployment-id ${newDeployment.id}`);
81126
81614
  }
81127
81615
 
81128
81616
  // src/commands/deploy/status.ts
@@ -81131,18 +81619,19 @@ init_output();
81131
81619
  async function status(options) {
81132
81620
  await requireAuth();
81133
81621
  await setupClient();
81134
- if (!options.project) {
81135
- throw new Error("Project is required. Use: temps deployments status --project <project> --deployment-id <id>");
81622
+ const resolved = await requireProjectSlug(options.project);
81623
+ if (resolved.source !== "flag") {
81624
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
81136
81625
  }
81137
81626
  if (!options.deploymentId) {
81138
- throw new Error("Deployment ID is required. Use: temps deployments status --project <project> --deployment-id <id>");
81627
+ throw new Error("Deployment ID is required. Use: temps deployments status --deployment-id <id>");
81139
81628
  }
81140
81629
  const { data: projectData, error: projectError } = await getProjectBySlug({
81141
81630
  client,
81142
- path: { slug: options.project }
81631
+ path: { slug: resolved.slug }
81143
81632
  });
81144
81633
  if (projectError || !projectData) {
81145
- throw new Error(`Project "${options.project}" not found`);
81634
+ throw new Error(`Project "${resolved.slug}" not found`);
81146
81635
  }
81147
81636
  const projectId = projectData.id;
81148
81637
  const depId = parseInt(options.deploymentId, 10);
@@ -81320,7 +81809,7 @@ async function teardownDeploymentAction(options) {
81320
81809
 
81321
81810
  // src/commands/deploy/index.ts
81322
81811
  function registerDeployCommands(program2) {
81323
- program2.command("deploy [project]").description("Deploy a project from git").option("-p, --project <project>", "Project slug or ID").option("-e, --environment <env>", "Target environment name").option("--environment-id <id>", "Target environment ID").option("-b, --branch <branch>", "Git branch to deploy").option("--no-wait", "Do not wait for deployment to complete").option("-y, --yes", "Skip confirmation prompts (for automation)").action((projectArg, options) => {
81812
+ program2.command("deploy [project]").description("Deploy a project from git").option("-p, --project <project>", "Project slug or ID").option("-e, --environment <env>", "Target environment name").option("--environment-id <id>", "Target environment ID").option("-b, --branch <branch>", "Git branch to deploy").option("-c, --commit <sha>", "Specific commit SHA to deploy").option("--no-wait", "Do not wait for deployment to complete").option("-y, --yes", "Skip confirmation prompts (for automation)").action((projectArg, options) => {
81324
81813
  if (projectArg && !options.project) {
81325
81814
  options.project = projectArg;
81326
81815
  }
@@ -81337,7 +81826,7 @@ function registerDeployCommands(program2) {
81337
81826
  deployments.command("pause").description("Pause a deployment").requiredOption("-p, --project-id <id>", "Project ID").requiredOption("-d, --deployment-id <id>", "Deployment ID").action(pauseDeploymentAction);
81338
81827
  deployments.command("resume").description("Resume a paused deployment").requiredOption("-p, --project-id <id>", "Project ID").requiredOption("-d, --deployment-id <id>", "Deployment ID").action(resumeDeploymentAction);
81339
81828
  deployments.command("teardown").description("Teardown a deployment and remove all resources").requiredOption("-p, --project-id <id>", "Project ID").requiredOption("-d, --deployment-id <id>", "Deployment ID").option("-f, --force", "Skip confirmation").action(teardownDeploymentAction);
81340
- program2.command("logs").description("Stream deployment logs").option("-p, --project <project>", "Project slug or ID").option("-e, --environment <env>", "Environment", "production").option("-f, --follow", "Follow log output").option("-n, --lines <number>", "Number of lines to show", "100").option("-d, --deployment <id>", "Specific deployment ID").action(logs);
81829
+ deployments.command("logs").description("Show deployment build logs").option("-p, --project <project>", "Project slug or ID").option("-e, --environment <env>", "Environment", "production").option("-f, --follow", "Follow log output").option("-n, --lines <number>", "Number of lines to show", "100").option("-d, --deployment <id>", "Specific deployment ID").action(logs);
81341
81830
  }
81342
81831
 
81343
81832
  // src/commands/domains/index.ts
@@ -81354,7 +81843,7 @@ async function findDomainIdByName(domainName) {
81354
81843
  function registerDomainsCommands(program2) {
81355
81844
  const domains = program2.command("domains").alias("domain").description("Manage custom domains");
81356
81845
  domains.command("list").alias("ls").description("List domains").option("--json", "Output in JSON format").action(listDomains3);
81357
- domains.command("add").description("Add a custom domain").requiredOption("-d, --domain <domain>", "Domain name").option("-c, --challenge <type>", "Challenge type (http-01 or dns-01)", "http-01").action(addDomain);
81846
+ domains.command("add").description("Add a custom domain").requiredOption("-d, --domain <domain>", "Domain name").option("-c, --challenge <type>", "Challenge type (http-01 or dns-01)", "http-01").option("-y, --yes", "Skip confirmation prompts").action(addDomain);
81358
81847
  domains.command("verify").description("Verify domain and provision SSL certificate").requiredOption("-d, --domain <domain>", "Domain name").action(verifyDomain2);
81359
81848
  domains.command("remove").alias("rm").description("Remove a domain").requiredOption("-d, --domain <domain>", "Domain name").option("-f, --force", "Skip confirmation").option("-y, --yes", "Skip confirmation prompts (alias for --force)").action(removeDomain);
81360
81849
  domains.command("ssl").description("Manage SSL certificate").requiredOption("-d, --domain <domain>", "Domain name").option("--renew", "Force certificate renewal").action(manageSsl);
@@ -81418,9 +81907,10 @@ async function addDomain(options) {
81418
81907
  newline();
81419
81908
  success(`Domain ${domain} added`);
81420
81909
  if (result?.dns_challenge_token && result?.dns_challenge_value) {
81910
+ const baseDomain = domain.startsWith("*.") ? domain.slice(2) : domain;
81421
81911
  newline();
81422
81912
  box(`Type: TXT
81423
- ` + `Name: ${result.dns_challenge_token}
81913
+ ` + `Name: _acme-challenge.${baseDomain}
81424
81914
  ` + `Value: ${result.dns_challenge_value}`, "Add this DNS record to verify ownership");
81425
81915
  newline();
81426
81916
  info(`Run "temps domains verify --domain ${domain}" after adding the record`);
@@ -81916,48 +82406,48 @@ init_prompts();
81916
82406
  init_output();
81917
82407
  function registerEnvironmentsCommands(program2) {
81918
82408
  const environments = program2.command("environments").alias("envs").alias("env").description("Manage environments and environment variables");
81919
- environments.command("list <project>").alias("ls").description("List environments for a project").option("--json", "Output in JSON format").action(listEnvironments);
81920
- environments.command("create <project>").description("Create a new environment").option("-n, --name <name>", "Environment name").option("-b, --branch <branch>", "Git branch").option("--preview", "Set as preview environment").action(createEnvironmentCmd);
81921
- environments.command("delete <project> <environment>").alias("rm").description("Delete an environment").option("-f, --force", "Skip confirmation").action(deleteEnvironmentCmd);
81922
- const vars = environments.command("vars <project>").description("Manage environment variables");
81923
- vars.command("list").alias("ls").description("List environment variables").option("-e, --environment <name>", "Filter by environment name").option("--show-values", "Show actual values (hidden by default)").option("--json", "Output in JSON format").action((options, cmd) => {
81924
- const project = cmd.parent.args[0];
81925
- return listEnvVars(project, options);
82409
+ environments.command("list").alias("ls").description("List environments for a project").option("-p, --project <project>", "Project slug or ID").option("--json", "Output in JSON format").action(listEnvironments);
82410
+ environments.command("create").description("Create a new environment").option("-p, --project <project>", "Project slug or ID").option("-n, --name <name>", "Environment name").option("-b, --branch <branch>", "Git branch").option("--preview", "Set as preview environment").action(createEnvironmentCmd);
82411
+ environments.command("delete <environment>").alias("rm").description("Delete an environment").option("-p, --project <project>", "Project slug or ID").option("-f, --force", "Skip confirmation").action(deleteEnvironmentCmd);
82412
+ const vars = environments.command("vars").description("Manage environment variables").option("-p, --project <project>", "Project slug or ID");
82413
+ vars.command("list").alias("ls").description("List environment variables").option("-e, --environment <name>", "Filter by environment name").option("--show-values", "Show actual values (hidden by default)").option("--json", "Output in JSON format").action(async (options, cmd) => {
82414
+ const projectSlug = cmd.parent.opts().project;
82415
+ return listEnvVars(projectSlug, options);
81926
82416
  });
81927
- vars.command("get <key>").description("Get a specific environment variable").option("-e, --environment <name>", "Specify environment (if variable exists in multiple)").action((key, options, cmd) => {
81928
- const project = cmd.parent.parent.args[0];
81929
- return getEnvVar(project, key, options);
82417
+ vars.command("get <key>").description("Get a specific environment variable").option("-e, --environment <name>", "Specify environment (if variable exists in multiple)").action(async (key, options, cmd) => {
82418
+ const projectSlug = cmd.parent.parent.opts().project;
82419
+ return getEnvVar(projectSlug, key, options);
81930
82420
  });
81931
- vars.command("set <key> [value]").description("Set an environment variable").option("-e, --environments <names>", "Comma-separated environment names (interactive if not provided)").option("--no-preview", "Exclude from preview environments").option("--update", "Update existing variable instead of creating new").action((key, value, options, cmd) => {
81932
- const project = cmd.parent.parent.args[0];
81933
- return setEnvVar(project, key, value, options);
82421
+ vars.command("set <key> [value]").description("Set an environment variable").option("-e, --environments <names>", "Comma-separated environment names (interactive if not provided)").option("--no-preview", "Exclude from preview environments").option("--update", "Update existing variable instead of creating new").action(async (key, value, options, cmd) => {
82422
+ const projectSlug = cmd.parent.parent.opts().project;
82423
+ return setEnvVar(projectSlug, key, value, options);
81934
82424
  });
81935
- vars.command("delete <key>").alias("rm").alias("unset").description("Delete an environment variable").option("-e, --environment <name>", "Delete only from specific environment").option("-f, --force", "Skip confirmation").action((key, options, cmd) => {
81936
- const project = cmd.parent.parent.args[0];
81937
- return deleteEnvVar(project, key, options);
82425
+ vars.command("delete <key>").alias("rm").alias("unset").description("Delete an environment variable").option("-e, --environment <name>", "Delete only from specific environment").option("-f, --force", "Skip confirmation").action(async (key, options, cmd) => {
82426
+ const projectSlug = cmd.parent.parent.opts().project;
82427
+ return deleteEnvVar(projectSlug, key, options);
81938
82428
  });
81939
- vars.command("import [file]").description("Import environment variables from a .env file").option("-e, --environments <names>", "Comma-separated environment names").option("--overwrite", "Overwrite existing variables").action((file, options, cmd) => {
81940
- const project = cmd.parent.parent.args[0];
81941
- return importEnvVars(project, file, options);
82429
+ vars.command("import [file]").description("Import environment variables from a .env file").option("-e, --environments <names>", "Comma-separated environment names").option("--overwrite", "Overwrite existing variables").action(async (file, options, cmd) => {
82430
+ const projectSlug = cmd.parent.parent.opts().project;
82431
+ return importEnvVars(projectSlug, file, options);
81942
82432
  });
81943
- vars.command("export").description("Export environment variables to .env format").option("-e, --environment <name>", "Export from specific environment").option("-o, --output <file>", "Write to file instead of stdout").action((options, cmd) => {
81944
- const project = cmd.parent.parent.args[0];
81945
- return exportEnvVars(project, options);
82433
+ vars.command("export").description("Export environment variables to .env format").option("-e, --environment <name>", "Export from specific environment").option("-o, --output <file>", "Write to file instead of stdout").action(async (options, cmd) => {
82434
+ const projectSlug = cmd.parent.parent.opts().project;
82435
+ return exportEnvVars(projectSlug, options);
81946
82436
  });
81947
- environments.command("resources <project> <environment>").description("View or set CPU/memory resources for an environment").option("--cpu <millicores>", "CPU limit in millicores (e.g., 500 = 0.5 CPU)").option("--memory <mb>", "Memory limit in MB (e.g., 512)").option("--cpu-request <millicores>", "CPU request in millicores (guaranteed minimum)").option("--memory-request <mb>", "Memory request in MB (guaranteed minimum)").option("--json", "Output in JSON format").action(resourcesCmd);
81948
- environments.command("scale <project> <environment> [replicas]").description("View or set the number of replicas for an environment").option("--json", "Output in JSON format").action(scaleCmd);
81949
- const crons = environments.command("crons <project> <environment>").description("Manage cron jobs");
81950
- crons.command("list").alias("ls").description("List cron jobs for an environment").option("--json", "Output in JSON format").action((options, cmd) => {
81951
- const [project, environment] = cmd.parent.args;
81952
- return listCrons(project, environment, options);
82437
+ environments.command("resources <environment>").description("View or set CPU/memory resources for an environment").option("-p, --project <project>", "Project slug or ID").option("--cpu <millicores>", "CPU limit in millicores (e.g., 500 = 0.5 CPU)").option("--memory <mb>", "Memory limit in MB (e.g., 512)").option("--cpu-request <millicores>", "CPU request in millicores (guaranteed minimum)").option("--memory-request <mb>", "Memory request in MB (guaranteed minimum)").option("--json", "Output in JSON format").action(resourcesCmd);
82438
+ environments.command("scale").description("View or set the number of replicas for an environment").option("-p, --project <project>", "Project slug or ID").option("-e, --environment <env>", "Environment name or slug", "production").option("-r, --replicas <count>", "Number of replicas to set").option("--json", "Output in JSON format").action(scaleCmd);
82439
+ const crons = environments.command("crons").description("Manage cron jobs").option("-p, --project <project>", "Project slug or ID").requiredOption("-e, --environment <env>", "Environment name or slug");
82440
+ crons.command("list").alias("ls").description("List cron jobs for an environment").option("--json", "Output in JSON format").action(async (options, cmd) => {
82441
+ const parentOpts = cmd.parent.opts();
82442
+ return listCrons(parentOpts.project, parentOpts.environment, options);
81953
82443
  });
81954
- crons.command("show").description("Show cron job details").requiredOption("--id <id>", "Cron job ID").option("--json", "Output in JSON format").action((options, cmd) => {
81955
- const [project, environment] = cmd.parent.args;
81956
- return showCron(project, environment, options);
82444
+ crons.command("show").description("Show cron job details").requiredOption("--id <id>", "Cron job ID").option("--json", "Output in JSON format").action(async (options, cmd) => {
82445
+ const parentOpts = cmd.parent.opts();
82446
+ return showCron(parentOpts.project, parentOpts.environment, options);
81957
82447
  });
81958
- crons.command("executions").alias("execs").description("Show cron job execution history").requiredOption("--id <id>", "Cron job ID").option("--page <page>", "Page number", "1").option("--per-page <count>", "Items per page", "20").option("--json", "Output in JSON format").action((options, cmd) => {
81959
- const [project, environment] = cmd.parent.args;
81960
- return listCronExecutions(project, environment, options);
82448
+ crons.command("executions").alias("execs").description("Show cron job execution history").requiredOption("--id <id>", "Cron job ID").option("--page <page>", "Page number", "1").option("--per-page <count>", "Items per page", "20").option("--json", "Output in JSON format").action(async (options, cmd) => {
82449
+ const parentOpts = cmd.parent.opts();
82450
+ return listCronExecutions(parentOpts.project, parentOpts.environment, options);
81961
82451
  });
81962
82452
  }
81963
82453
  async function getProjectId(projectSlug) {
@@ -81970,9 +82460,14 @@ async function getProjectId(projectSlug) {
81970
82460
  }
81971
82461
  return data.id;
81972
82462
  }
81973
- async function listEnvironments(project, options) {
82463
+ async function listEnvironments(options) {
81974
82464
  await requireAuth();
81975
82465
  await setupClient();
82466
+ const resolved = await requireProjectSlug(options.project);
82467
+ const project = resolved.slug;
82468
+ if (resolved.source !== "flag") {
82469
+ info(`Using project ${colors.bold(project)} (from ${resolved.source})`);
82470
+ }
81976
82471
  const environments = await withSpinner("Fetching environments...", async () => {
81977
82472
  const projectId = await getProjectId(project);
81978
82473
  const { data, error: error3 } = await getEnvironments({
@@ -81999,8 +82494,13 @@ async function listEnvironments(project, options) {
81999
82494
  printTable(environments, columns, { style: "minimal" });
82000
82495
  newline();
82001
82496
  }
82002
- async function createEnvironmentCmd(project, options) {
82497
+ async function createEnvironmentCmd(options) {
82003
82498
  await requireAuth();
82499
+ await setupClient();
82500
+ const resolved = await requireProjectSlug(options.project);
82501
+ if (resolved.source !== "flag") {
82502
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
82503
+ }
82004
82504
  const name = options.name ?? await promptText({
82005
82505
  message: "Environment name",
82006
82506
  required: true,
@@ -82010,9 +82510,8 @@ async function createEnvironmentCmd(project, options) {
82010
82510
  message: "Git branch",
82011
82511
  default: name === "production" ? "main" : name
82012
82512
  });
82013
- await setupClient();
82014
82513
  const environment = await withSpinner("Creating environment...", async () => {
82015
- const projectId = await getProjectId(project);
82514
+ const projectId = await getProjectId(resolved.slug);
82016
82515
  const { data, error: error3 } = await createEnvironment({
82017
82516
  client,
82018
82517
  path: { project_id: projectId },
@@ -82032,15 +82531,20 @@ async function createEnvironmentCmd(project, options) {
82032
82531
  info(`URL: ${colors.primary(environment.main_url)}`);
82033
82532
  }
82034
82533
  }
82035
- async function deleteEnvironmentCmd(project, environment, options) {
82534
+ async function deleteEnvironmentCmd(environment, options) {
82036
82535
  await requireAuth();
82536
+ await setupClient();
82537
+ const resolved = await requireProjectSlug(options.project);
82538
+ if (resolved.source !== "flag") {
82539
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
82540
+ }
82037
82541
  if (environment === "production") {
82038
82542
  warning("Cannot delete production environment");
82039
82543
  return;
82040
82544
  }
82041
82545
  if (!options.force) {
82042
82546
  const confirmed = await promptConfirm({
82043
- message: `Delete environment "${environment}" from ${project}?`,
82547
+ message: `Delete environment "${environment}" from ${resolved.slug}?`,
82044
82548
  default: false
82045
82549
  });
82046
82550
  if (!confirmed) {
@@ -82048,9 +82552,8 @@ async function deleteEnvironmentCmd(project, environment, options) {
82048
82552
  return;
82049
82553
  }
82050
82554
  }
82051
- await setupClient();
82052
82555
  await withSpinner("Deleting environment...", async () => {
82053
- const projectId = await getProjectId(project);
82556
+ const projectId = await getProjectId(resolved.slug);
82054
82557
  const { error: error3 } = await deleteEnvironment({
82055
82558
  client,
82056
82559
  path: { project_id: projectId, env_id: environment }
@@ -82060,9 +82563,14 @@ async function deleteEnvironmentCmd(project, environment, options) {
82060
82563
  });
82061
82564
  success(`Environment "${environment}" deleted`);
82062
82565
  }
82063
- async function listEnvVars(project, options) {
82566
+ async function listEnvVars(projectFlag, options) {
82064
82567
  await requireAuth();
82065
82568
  await setupClient();
82569
+ const resolved = await requireProjectSlug(projectFlag);
82570
+ const project = resolved.slug;
82571
+ if (resolved.source !== "flag") {
82572
+ info(`Using project ${colors.bold(project)} (from ${resolved.source})`);
82573
+ }
82066
82574
  const [vars, environments] = await withSpinner("Fetching environment variables...", async () => {
82067
82575
  const projectId = await getProjectId(project);
82068
82576
  const [varsResult, envsResult] = await Promise.all([
@@ -82129,9 +82637,14 @@ async function listEnvVars(project, options) {
82129
82637
  }
82130
82638
  newline();
82131
82639
  }
82132
- async function getEnvVar(project, key, options) {
82640
+ async function getEnvVar(projectFlag, key, options) {
82133
82641
  await requireAuth();
82134
82642
  await setupClient();
82643
+ const resolved = await requireProjectSlug(projectFlag);
82644
+ const project = resolved.slug;
82645
+ if (resolved.source !== "flag") {
82646
+ info(`Using project ${colors.bold(project)} (from ${resolved.source})`);
82647
+ }
82135
82648
  const [vars, environments] = await withSpinner(`Fetching ${key}...`, async () => {
82136
82649
  const projectId = await getProjectId(project);
82137
82650
  const [varsResult, envsResult] = await Promise.all([
@@ -82184,9 +82697,14 @@ async function getEnvVar(project, key, options) {
82184
82697
  newline();
82185
82698
  }
82186
82699
  }
82187
- async function setEnvVar(project, key, value, options) {
82700
+ async function setEnvVar(projectFlag, key, value, options) {
82188
82701
  await requireAuth();
82189
82702
  await setupClient();
82703
+ const resolved = await requireProjectSlug(projectFlag);
82704
+ const project = resolved.slug;
82705
+ if (resolved.source !== "flag") {
82706
+ info(`Using project ${colors.bold(project)} (from ${resolved.source})`);
82707
+ }
82190
82708
  const [existingVars, envs] = await withSpinner("Fetching environments...", async () => {
82191
82709
  const projectId2 = await getProjectId(project);
82192
82710
  const [varsResult, envsResult] = await Promise.all([
@@ -82647,10 +83165,15 @@ function displayResources(env4) {
82647
83165
  newline();
82648
83166
  info(`Example: ${colors.muted("temps env resources my-project production --cpu 1000 --memory 512")}`);
82649
83167
  }
82650
- async function scaleCmd(project, environment, replicas, options) {
83168
+ async function scaleCmd(options) {
82651
83169
  await requireAuth();
82652
83170
  await setupClient();
82653
- const projectId = await getProjectId(project);
83171
+ const resolved = await requireProjectSlug(options.project);
83172
+ if (resolved.source !== "flag") {
83173
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
83174
+ }
83175
+ const environment = options.environment;
83176
+ const projectId = await getProjectId(resolved.slug);
82654
83177
  const envs = await withSpinner("Fetching environments...", async () => {
82655
83178
  const { data, error: error3 } = await getEnvironments({
82656
83179
  client,
@@ -82666,8 +83189,8 @@ async function scaleCmd(project, environment, replicas, options) {
82666
83189
  info(`Available environments: ${envs.map((e) => e.slug).join(", ")}`);
82667
83190
  return;
82668
83191
  }
82669
- if (replicas !== undefined) {
82670
- const replicaCount = parseInt(replicas, 10);
83192
+ if (options.replicas !== undefined) {
83193
+ const replicaCount = parseInt(options.replicas, 10);
82671
83194
  if (isNaN(replicaCount) || replicaCount < 0) {
82672
83195
  error("Replicas must be a non-negative number");
82673
83196
  return;
@@ -82693,7 +83216,7 @@ async function scaleCmd(project, environment, replicas, options) {
82693
83216
  return;
82694
83217
  }
82695
83218
  newline();
82696
- success(`Scaled ${project}/${environment} to ${replicaCount} replica${replicaCount !== 1 ? "s" : ""}`);
83219
+ success(`Scaled ${resolved.slug}/${environment} to ${replicaCount} replica${replicaCount !== 1 ? "s" : ""}`);
82697
83220
  newline();
82698
83221
  info(`Note: Scaling takes effect on the next deployment or restart`);
82699
83222
  } else {
@@ -82706,12 +83229,12 @@ async function scaleCmd(project, environment, replicas, options) {
82706
83229
  return;
82707
83230
  }
82708
83231
  newline();
82709
- header(`${icons.folder} Scale for ${project}/${environment}`);
83232
+ header(`${icons.folder} Scale for ${resolved.slug}/${environment}`);
82710
83233
  newline();
82711
83234
  keyValue("Current Replicas", String(currentReplicas));
82712
83235
  newline();
82713
- info(`To scale: ${colors.muted(`temps env scale ${project} ${environment} <replicas>`)}`);
82714
- info(`Example: ${colors.muted(`temps env scale ${project} ${environment} 3`)}`);
83236
+ info(`To scale: ${colors.muted(`bunx @temps-sdk/cli env scale -p ${resolved.slug} -e ${environment} --replicas <count>`)}`);
83237
+ info(`Example: ${colors.muted(`bunx @temps-sdk/cli env scale -p ${resolved.slug} -e ${environment} --replicas 3`)}`);
82715
83238
  }
82716
83239
  }
82717
83240
  async function resolveEnvironmentId(projectId, environment) {
@@ -82867,28 +83390,6 @@ async function listCronExecutions(project, environment, options) {
82867
83390
  printTable(executions, columns, { style: "minimal" });
82868
83391
  newline();
82869
83392
  }
82870
- function parseEnvFile(content) {
82871
- const variables = {};
82872
- for (const line of content.split(`
82873
- `)) {
82874
- const trimmed = line.trim();
82875
- if (!trimmed || trimmed.startsWith("#"))
82876
- continue;
82877
- const match = trimmed.match(/^([^=]+)=(.*)$/);
82878
- if (!match)
82879
- continue;
82880
- const [, key, rawValue] = match;
82881
- if (!key || rawValue === undefined)
82882
- continue;
82883
- let value = rawValue.trim();
82884
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
82885
- value = value.slice(1, -1).replace(/\\n/g, `
82886
- `).replace(/\\"/g, '"').replace(/\\'/g, "'");
82887
- }
82888
- variables[key.trim()] = value;
82889
- }
82890
- return variables;
82891
- }
82892
83393
 
82893
83394
  // src/commands/providers/index.ts
82894
83395
  init_sdk_gen();
@@ -84184,16 +84685,22 @@ function maskSecret(value) {
84184
84685
  init_sdk_gen();
84185
84686
  init_output();
84186
84687
  function registerRuntimeLogsCommand(program2) {
84187
- program2.command("runtime-logs").alias("rlogs").description("Stream runtime container logs (not build logs)").option("-p, --project <project>", "Project slug or ID").option("-e, --environment <env>", "Environment name", "production").option("-c, --container <id>", "Container ID (partial match supported)").option("-n, --tail <lines>", "Number of lines to tail", "1000").option("-t, --timestamps", "Show timestamps").action(runtimeLogs);
84688
+ program2.command("runtime-logs").alias("rlogs").description("View runtime container logs (use -f to follow in real-time)").option("-p, --project <project>", "Project slug or ID").option("-e, --environment <env>", "Environment name", "production").option("-c, --container <id>", "Container ID (partial match supported)").option("-n, --tail <lines>", "Number of lines to tail", "1000").option("-t, --timestamps", "Show timestamps").option("-f, --follow", "Follow log output (stream in real-time)").action(runtimeLogs);
84188
84689
  }
84189
84690
  async function runtimeLogs(options) {
84190
84691
  const apiKey = await requireAuth();
84191
84692
  await setupClient();
84192
- const projectName = options.project ?? config.get("defaultProject");
84193
- if (!projectName) {
84693
+ const resolved = await resolveProjectSlug(options.project);
84694
+ if (!resolved) {
84194
84695
  warning("No project specified");
84696
+ info("Use: bunx @temps-sdk/cli runtime-logs --project <slug>");
84697
+ info("Or link this directory: bunx @temps-sdk/cli link <slug>");
84195
84698
  return;
84196
84699
  }
84700
+ const projectName = resolved.slug;
84701
+ if (resolved.source !== "flag") {
84702
+ info(`Using project ${colors.bold(projectName)} (from ${resolved.source})`);
84703
+ }
84197
84704
  startSpinner("Finding project...");
84198
84705
  const { data: projectData, error: projectError } = await getProjectBySlug({
84199
84706
  client,
@@ -84255,71 +84762,93 @@ async function runtimeLogs(options) {
84255
84762
  info(`Streaming logs for container: ${colors.bold(selectedContainer.container_name || selectedContainer.container_id.substring(0, 12))}`);
84256
84763
  info(`Container ID: ${colors.muted(selectedContainer.container_id)}`);
84257
84764
  newline();
84258
- const apiUrl = config.get("apiUrl");
84765
+ const apiUrl = normalizeApiUrl(config.get("apiUrl"));
84259
84766
  const wsProtocol = apiUrl.startsWith("https") ? "wss" : "ws";
84260
84767
  const urlWithoutProtocol = apiUrl.replace(/^https?:\/\//, "").replace(/\/$/, "");
84768
+ const follow = options.follow ?? false;
84261
84769
  const params = new URLSearchParams;
84262
84770
  params.append("tail", options.tail);
84263
84771
  params.append("timestamps", String(options.timestamps ?? false));
84772
+ params.append("follow", String(follow));
84264
84773
  const wsUrl = `${wsProtocol}://${urlWithoutProtocol}/projects/${projectData.id}/environments/${environment.id}/containers/${selectedContainer.container_id}/logs?${params.toString()}`;
84265
- info(`Connecting to WebSocket...`);
84266
- info(`URL: ${colors.muted(wsUrl)}`);
84774
+ if (follow) {
84775
+ info(`Streaming logs (follow mode)...`);
84776
+ } else {
84777
+ info(`Fetching logs...`);
84778
+ }
84267
84779
  newline();
84268
- await connectWebSocket(wsUrl, apiKey);
84780
+ await connectWebSocket(wsUrl, apiKey, follow);
84269
84781
  }
84270
- async function connectWebSocket(url, apiKey) {
84271
- return new Promise((resolve4, reject) => {
84782
+ function formatLogMessage2(raw) {
84783
+ const data = raw.replace(/\r?\n$/, "");
84784
+ try {
84785
+ const parsed = JSON.parse(data);
84786
+ if (parsed.error) {
84787
+ console.log(colors.error(`ERROR: ${parsed.error}`));
84788
+ if (parsed.detail) {
84789
+ console.log(colors.muted(` ${parsed.detail}`));
84790
+ }
84791
+ } else if (parsed.message) {
84792
+ console.log(parsed.message.replace(/\r?\n$/, ""));
84793
+ } else {
84794
+ console.log(data);
84795
+ }
84796
+ } catch {
84797
+ console.log(data);
84798
+ }
84799
+ }
84800
+ async function connectWebSocket(url, apiKey, follow) {
84801
+ return new Promise((resolve5) => {
84272
84802
  const ws = new WebSocket(url, {
84273
84803
  headers: {
84274
84804
  Authorization: `Bearer ${apiKey}`
84275
84805
  }
84276
84806
  });
84807
+ let sigintHandler = null;
84277
84808
  ws.onopen = () => {
84278
- console.log(colors.success("✓ Connected to log stream"));
84279
- console.log(colors.muted("─".repeat(60)));
84280
- console.log(colors.muted("Press Ctrl+C to stop"));
84281
- console.log(colors.muted("─".repeat(60)));
84282
- console.log();
84809
+ if (follow) {
84810
+ console.log(colors.success("✓ Connected to log stream"));
84811
+ console.log(colors.muted("─".repeat(60)));
84812
+ console.log(colors.muted("Press Ctrl+C to stop"));
84813
+ console.log(colors.muted("─".repeat(60)));
84814
+ console.log();
84815
+ }
84283
84816
  };
84284
84817
  ws.onmessage = (event) => {
84285
- const data = event.data.toString();
84286
- try {
84287
- const parsed = JSON.parse(data);
84288
- if (parsed.error) {
84289
- console.log(colors.error(`ERROR: ${parsed.error}`));
84290
- if (parsed.detail) {
84291
- console.log(colors.muted(` ${parsed.detail}`));
84292
- }
84293
- } else if (parsed.message) {
84294
- console.log(parsed.message);
84295
- } else {
84296
- console.log(data);
84297
- }
84298
- } catch {
84299
- console.log(data);
84300
- }
84818
+ formatLogMessage2(event.data.toString());
84301
84819
  };
84302
84820
  ws.onerror = (error3) => {
84303
84821
  console.error(colors.error("WebSocket error:"), error3);
84304
84822
  };
84305
84823
  ws.onclose = (event) => {
84306
- console.log();
84307
- console.log(colors.muted("─".repeat(60)));
84308
- if (event.code === 1000) {
84309
- console.log(colors.info("Connection closed normally"));
84310
- } else {
84311
- console.log(colors.warning(`Connection closed (code: ${event.code})`));
84312
- if (event.reason) {
84313
- console.log(colors.muted(`Reason: ${event.reason}`));
84824
+ if (sigintHandler) {
84825
+ process.removeListener("SIGINT", sigintHandler);
84826
+ }
84827
+ if (follow) {
84828
+ console.log();
84829
+ console.log(colors.muted("─".repeat(60)));
84830
+ if (event.code === 1000) {
84831
+ console.log(colors.info("Connection closed normally"));
84832
+ } else {
84833
+ console.log(colors.warning(`Connection closed (code: ${event.code})`));
84834
+ if (event.reason) {
84835
+ console.log(colors.muted(`Reason: ${event.reason}`));
84836
+ }
84314
84837
  }
84315
84838
  }
84316
- resolve4();
84839
+ resolve5();
84317
84840
  };
84318
- process.on("SIGINT", () => {
84841
+ sigintHandler = () => {
84319
84842
  console.log();
84320
84843
  console.log(colors.muted("Closing connection..."));
84321
- ws.close(1000, "User requested close");
84322
- });
84844
+ try {
84845
+ ws.close(1000, "User requested close");
84846
+ } catch {}
84847
+ setTimeout(() => {
84848
+ process.exit(0);
84849
+ }, 500);
84850
+ };
84851
+ process.on("SIGINT", sigintHandler);
84323
84852
  });
84324
84853
  }
84325
84854
 
@@ -85334,19 +85863,70 @@ var SERVICE_TYPE_LABELS = {
85334
85863
  redis: "Redis",
85335
85864
  s3: "MinIO (S3)"
85336
85865
  };
85866
+ var SERVICE_TYPE_DEFAULTS = {
85867
+ postgres: { database: "myapp", username: "postgres" },
85868
+ mongodb: { database: "myapp", username: "mongoadmin" },
85869
+ redis: {},
85870
+ s3: {}
85871
+ };
85872
+ function schemaToPromptParams(schema) {
85873
+ if (!schema?.properties)
85874
+ return [];
85875
+ const required = new Set(schema.required ?? []);
85876
+ const readonly = new Set(schema.readonly ?? []);
85877
+ return Object.entries(schema.properties).map(([name, prop]) => ({
85878
+ name,
85879
+ label: name.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
85880
+ description: prop.description,
85881
+ default_value: prop.default ?? prop.example,
85882
+ required: required.has(name),
85883
+ readonly: readonly.has(name),
85884
+ enum_values: prop.enum,
85885
+ param_type: prop.type ?? "string"
85886
+ }));
85887
+ }
85888
+ function parseSetPairs(pairs) {
85889
+ const result = {};
85890
+ for (const pair of pairs) {
85891
+ const eqIdx = pair.indexOf("=");
85892
+ if (eqIdx === -1) {
85893
+ throw new Error(`Invalid parameter "${pair}". Expected format: key=value`);
85894
+ }
85895
+ const key = pair.slice(0, eqIdx).trim();
85896
+ const raw = pair.slice(eqIdx + 1);
85897
+ if (!key) {
85898
+ throw new Error(`Invalid parameter "${pair}". Key cannot be empty`);
85899
+ }
85900
+ if (raw === "true")
85901
+ result[key] = true;
85902
+ else if (raw === "false")
85903
+ result[key] = false;
85904
+ else if (raw === "0")
85905
+ result[key] = 0;
85906
+ else if (raw !== "" && !isNaN(Number(raw)) && !raw.startsWith("0"))
85907
+ result[key] = Number(raw);
85908
+ else
85909
+ result[key] = raw;
85910
+ }
85911
+ return result;
85912
+ }
85913
+ function collectSet(value, previous) {
85914
+ return previous.concat([value]);
85915
+ }
85337
85916
  function registerServicesCommands(program2) {
85338
85917
  const services = program2.command("services").alias("svc").description("Manage external services (databases, caches, storage)");
85339
85918
  services.command("list").alias("ls").description("List all external services").option("--json", "Output in JSON format").action(listServicesAction);
85340
- services.command("create").alias("add").description("Create a new external service").option("-t, --type <type>", "Service type (postgres, mongodb, redis, s3)").option("-n, --name <name>", "Service name").option("--parameters <json>", "Service parameters as JSON string").option("-y, --yes", "Skip confirmation prompts (for automation)").action(createServiceAction);
85919
+ services.command("create").alias("add").description("Create a new external service").option("-t, --type <type>", "Service type (postgres, mongodb, redis, s3)").option("-n, --name <name>", "Service name").option("-s, --set <key=value>", "Set a parameter (repeatable)", collectSet, []).option("-y, --yes", "Skip confirmation prompts (for automation)").action(createServiceAction);
85341
85920
  services.command("show").description("Show service details").requiredOption("--id <id>", "Service ID").option("--json", "Output in JSON format").action(showService);
85342
85921
  services.command("remove").alias("rm").description("Remove a service").requiredOption("--id <id>", "Service ID").option("-f, --force", "Skip confirmation").option("-y, --yes", "Skip confirmation prompts (alias for --force)").action(removeService);
85343
85922
  services.command("start").description("Start a stopped service").requiredOption("--id <id>", "Service ID").action(startServiceAction);
85344
85923
  services.command("stop").description("Stop a running service").requiredOption("--id <id>", "Service ID").action(stopServiceAction);
85345
- services.command("types").description("List available service types").option("--json", "Output in JSON format").action(listServiceTypes);
85924
+ const typesCmd = services.command("types").description("List available service types").option("--json", "Output in JSON format").action(listServiceTypes);
85925
+ typesCmd.command("info <type>").description("Show parameters schema for a service type (useful for automation)").option("--json", "Output as raw JSON schema (default)").action(showServiceTypeInfo);
85346
85926
  services.command("projects").description("List projects linked to a service").requiredOption("--id <id>", "Service ID").option("--json", "Output in JSON format").action(listLinkedProjects);
85347
- services.command("update").description("Update a service").requiredOption("--id <id>", "Service ID").option("-n, --name <name>", "Docker image name (e.g., postgres:18-alpine)").option("--parameters <json>", "Service parameters as JSON string").action(updateServiceAction);
85927
+ services.command("update").description("Update a service").requiredOption("--id <id>", "Service ID").option("-n, --name <name>", "Docker image name (e.g., postgres:18-alpine)").option("-s, --set <key=value>", "Set a parameter (repeatable)", collectSet, []).action(updateServiceAction);
85348
85928
  services.command("upgrade").description("Upgrade a service to a newer version").requiredOption("--id <id>", "Service ID").option("-v, --version <version>", "Docker image to upgrade to (e.g., postgres:18-alpine)").action(upgradeServiceAction);
85349
- services.command("import").description("Import an existing external service").option("-t, --type <type>", "Service type (postgres, mongodb, redis, s3)").option("-n, --name <name>", "Service name").option("--container-id <id>", "Container ID or name to import").option("--parameters <json>", "Service parameters as JSON string").option("--version <version>", "Optional version override").option("-y, --yes", "Skip confirmation prompts (for automation)").action(importServiceAction);
85929
+ services.command("import").description("Import an existing external service").option("-t, --type <type>", "Service type (postgres, mongodb, redis, s3)").option("-n, --name <name>", "Service name").option("--container-id <id>", "Container ID or name to import").option("-s, --set <key=value>", "Set a parameter (repeatable)", collectSet, []).option("--version <version>", "Optional version override").option("-y, --yes", "Skip confirmation prompts (for automation)").action(importServiceAction);
85350
85930
  services.command("link").description("Link a service to a project").requiredOption("--id <id>", "Service ID").requiredOption("--project-id <id>", "Project ID").action(linkServiceAction);
85351
85931
  services.command("unlink").description("Unlink a service from a project").requiredOption("--id <id>", "Service ID").requiredOption("--project-id <id>", "Project ID").option("-f, --force", "Skip confirmation").option("-y, --yes", "Skip confirmation prompts (alias for --force)").action(unlinkServiceAction);
85352
85932
  services.command("env").description("Show environment variables for a linked service").requiredOption("--id <id>", "Service ID").requiredOption("--project-id <id>", "Project ID").option("--json", "Output in JSON format").action(envAction);
@@ -85401,7 +85981,8 @@ async function createServiceAction(options) {
85401
85981
  let serviceType;
85402
85982
  let name;
85403
85983
  let parameters = {};
85404
- const isAutomation = options.yes && options.type && options.name;
85984
+ const hasSetParams = options.set && options.set.length > 0;
85985
+ const isAutomation = options.yes && options.type && options.name || options.type && options.name && hasSetParams;
85405
85986
  if (isAutomation) {
85406
85987
  if (!types.includes(options.type)) {
85407
85988
  warning(`Invalid service type: ${options.type}. Available: ${types.join(", ")}`);
@@ -85409,40 +85990,57 @@ async function createServiceAction(options) {
85409
85990
  }
85410
85991
  serviceType = options.type;
85411
85992
  name = options.name;
85412
- if (options.parameters) {
85993
+ if (hasSetParams) {
85413
85994
  try {
85414
- parameters = JSON.parse(options.parameters);
85415
- } catch {
85416
- warning("Invalid JSON in --parameters");
85995
+ parameters = parseSetPairs(options.set);
85996
+ } catch (e) {
85997
+ warning(e.message);
85417
85998
  return;
85418
85999
  }
86000
+ } else {
86001
+ parameters = { ...SERVICE_TYPE_DEFAULTS[serviceType] ?? {} };
85419
86002
  }
85420
86003
  } else {
85421
- serviceType = await promptSelect({
85422
- message: "Service type",
85423
- choices: types.map((t) => ({
85424
- name: SERVICE_TYPE_LABELS[t] || t,
85425
- value: t
85426
- }))
85427
- });
85428
- name = await promptText({
85429
- message: "Service name",
85430
- default: `my-${serviceType}`,
85431
- required: true
85432
- });
86004
+ if (options.type) {
86005
+ if (!types.includes(options.type)) {
86006
+ warning(`Invalid service type: ${options.type}. Available: ${types.join(", ")}`);
86007
+ return;
86008
+ }
86009
+ serviceType = options.type;
86010
+ info(`Service type: ${colors.bold(SERVICE_TYPE_LABELS[serviceType] || serviceType)}`);
86011
+ } else {
86012
+ serviceType = await promptSelect({
86013
+ message: "Service type",
86014
+ choices: types.map((t) => ({
86015
+ name: SERVICE_TYPE_LABELS[t] || t,
86016
+ value: t
86017
+ }))
86018
+ });
86019
+ }
86020
+ if (options.name) {
86021
+ name = options.name;
86022
+ } else {
86023
+ name = await promptText({
86024
+ message: "Service name",
86025
+ default: `my-${serviceType}`,
86026
+ required: true
86027
+ });
86028
+ }
85433
86029
  const { data: typeInfo } = await getServiceTypeParameters({
85434
86030
  client,
85435
86031
  path: { service_type: serviceType }
85436
86032
  });
85437
- const paramResponse = typeInfo;
85438
- if (paramResponse?.parameters && paramResponse.parameters.length > 0) {
86033
+ const schema = typeInfo;
86034
+ const promptParams = schemaToPromptParams(schema ?? {});
86035
+ const configurableParams = promptParams.filter((p) => !p.readonly || p.required);
86036
+ if (configurableParams.length > 0) {
85439
86037
  info(`
85440
86038
  Configure ${SERVICE_TYPE_LABELS[serviceType] || serviceType} parameters:`);
85441
86039
  newline();
85442
- for (const param of paramResponse.parameters) {
86040
+ for (const param of configurableParams) {
85443
86041
  if (param.default_value !== undefined && !param.required) {
85444
86042
  const useDefault = await promptConfirm({
85445
- message: `${param.label || param.name}: Use default "${param.default_value}"?`,
86043
+ message: `${param.label}${param.description ? ` (${param.description})` : ""}: Use default "${param.default_value}"?`,
85446
86044
  default: true
85447
86045
  });
85448
86046
  if (useDefault) {
@@ -85453,14 +86051,14 @@ Configure ${SERVICE_TYPE_LABELS[serviceType] || serviceType} parameters:`);
85453
86051
  let value;
85454
86052
  if (param.enum_values && param.enum_values.length > 0) {
85455
86053
  value = await promptSelect({
85456
- message: param.label || param.name,
86054
+ message: param.label,
85457
86055
  choices: param.enum_values.map((v) => ({ name: v, value: v }))
85458
86056
  });
85459
86057
  } else {
85460
86058
  value = await promptText({
85461
- message: param.label || param.name,
85462
- default: param.default_value?.toString() || "",
85463
- required: param.required || false
86059
+ message: `${param.label}${param.description ? ` (${param.description})` : ""}`,
86060
+ default: param.default_value?.toString() ?? "",
86061
+ required: param.required
85464
86062
  });
85465
86063
  }
85466
86064
  if (value) {
@@ -85634,6 +86232,57 @@ async function listServiceTypes(options) {
85634
86232
  console.log(` ${colors.bold(SERVICE_TYPE_LABELS[t] || t)} ${colors.muted(`(${t})`)}`);
85635
86233
  }
85636
86234
  newline();
86235
+ info(`Run ${colors.bold("services types info <type>")} to see parameters for a specific type`);
86236
+ }
86237
+ function buildExampleCommand(type, schema) {
86238
+ const setParts = [];
86239
+ if (schema?.properties) {
86240
+ for (const [key, prop] of Object.entries(schema.properties)) {
86241
+ if (prop.default === null || prop.default === undefined)
86242
+ continue;
86243
+ setParts.push(`--set ${key}=${prop.default}`);
86244
+ }
86245
+ }
86246
+ const setsStr = setParts.length > 0 ? ` ${setParts.join(" ")}` : "";
86247
+ return `bunx @temps-sdk/cli services create -t ${type} -n my-${type}${setsStr}`;
86248
+ }
86249
+ async function showServiceTypeInfo(type) {
86250
+ await requireAuth();
86251
+ await setupClient();
86252
+ const { data, error: error3 } = await getServiceTypeParameters({
86253
+ client,
86254
+ path: { service_type: type }
86255
+ });
86256
+ if (error3) {
86257
+ warning(`Failed to get parameters for "${type}": ${getErrorMessage(error3)}`);
86258
+ return;
86259
+ }
86260
+ const schema = data;
86261
+ if (!schema?.properties) {
86262
+ json({ type, parameters: {}, defaults: SERVICE_TYPE_DEFAULTS[type] ?? {} });
86263
+ return;
86264
+ }
86265
+ const params = {};
86266
+ const requiredKeys = new Set(schema.required ?? []);
86267
+ const readonlyKeys = new Set(schema.readonly ?? []);
86268
+ for (const [name, prop] of Object.entries(schema.properties)) {
86269
+ params[name] = {
86270
+ type: prop.type ?? "string",
86271
+ ...prop.description ? { description: prop.description } : {},
86272
+ required: requiredKeys.has(name),
86273
+ readonly: readonlyKeys.has(name),
86274
+ ...prop.default !== undefined ? { default: prop.default } : {},
86275
+ ...prop.example !== undefined ? { example: prop.example } : {}
86276
+ };
86277
+ }
86278
+ const output = {
86279
+ service_type: type,
86280
+ label: SERVICE_TYPE_LABELS[type] || type,
86281
+ parameters: params,
86282
+ defaults: SERVICE_TYPE_DEFAULTS[type] ?? {},
86283
+ example_create: buildExampleCommand(type, schema)
86284
+ };
86285
+ json(output);
85637
86286
  }
85638
86287
  async function listLinkedProjects(options) {
85639
86288
  await requireAuth();
@@ -85678,11 +86327,11 @@ async function updateServiceAction(options) {
85678
86327
  return;
85679
86328
  }
85680
86329
  let parameters = {};
85681
- if (options.parameters) {
86330
+ if (options.set && options.set.length > 0) {
85682
86331
  try {
85683
- parameters = JSON.parse(options.parameters);
85684
- } catch {
85685
- warning("Invalid JSON in --parameters");
86332
+ parameters = parseSetPairs(options.set);
86333
+ } catch (e) {
86334
+ warning(e.message);
85686
86335
  return;
85687
86336
  }
85688
86337
  }
@@ -85757,11 +86406,11 @@ async function importServiceAction(options) {
85757
86406
  serviceType = options.type;
85758
86407
  name = options.name;
85759
86408
  containerId = options.containerId;
85760
- if (options.parameters) {
86409
+ if (options.set && options.set.length > 0) {
85761
86410
  try {
85762
- parameters = JSON.parse(options.parameters);
85763
- } catch {
85764
- warning("Invalid JSON in --parameters");
86411
+ parameters = parseSetPairs(options.set);
86412
+ } catch (e) {
86413
+ warning(e.message);
85765
86414
  return;
85766
86415
  }
85767
86416
  }
@@ -85793,11 +86442,11 @@ async function importServiceAction(options) {
85793
86442
  message: "Container ID or name to import",
85794
86443
  required: true
85795
86444
  });
85796
- if (options.parameters) {
86445
+ if (options.set && options.set.length > 0) {
85797
86446
  try {
85798
- parameters = JSON.parse(options.parameters);
85799
- } catch {
85800
- warning("Invalid JSON in --parameters");
86447
+ parameters = parseSetPairs(options.set);
86448
+ } catch (e) {
86449
+ warning(e.message);
85801
86450
  return;
85802
86451
  }
85803
86452
  }
@@ -87931,7 +88580,7 @@ async function watchMetrics(projectId, environmentId, containerIds, intervalMs)
87931
88580
  process.stdout.write("\x1B[H\x1B[2J");
87932
88581
  if (allMetrics.length === 0) {
87933
88582
  console.log(colors.warning("No metrics available"));
87934
- await new Promise((resolve4) => setTimeout(resolve4, intervalMs));
88583
+ await new Promise((resolve5) => setTimeout(resolve5, intervalMs));
87935
88584
  continue;
87936
88585
  }
87937
88586
  const now = Date.now();
@@ -88015,7 +88664,7 @@ async function watchMetrics(projectId, environmentId, containerIds, intervalMs)
88015
88664
  } catch (err) {
88016
88665
  console.log(colors.error(`Error fetching metrics: ${err}`));
88017
88666
  }
88018
- await new Promise((resolve4) => setTimeout(resolve4, intervalMs));
88667
+ await new Promise((resolve5) => setTimeout(resolve5, intervalMs));
88019
88668
  }
88020
88669
  console.log("\x1B[?25h");
88021
88670
  }
@@ -88037,7 +88686,7 @@ var PERMISSIONS = [
88037
88686
  { value: "errors:read", name: "Errors Read", description: "Read error tracking data" }
88038
88687
  ];
88039
88688
  async function makeRequest(method, path7, body) {
88040
- const apiUrl = config.get("apiUrl");
88689
+ const apiUrl = normalizeApiUrl(config.get("apiUrl"));
88041
88690
  const apiKey = await credentials.getApiKey();
88042
88691
  const response = await fetch(`${apiUrl}${path7}`, {
88043
88692
  method,
@@ -88056,44 +88705,38 @@ async function makeRequest(method, path7, body) {
88056
88705
  }
88057
88706
  return response.json();
88058
88707
  }
88059
- async function resolveProjectId(projectIdentifier) {
88060
- const numId = parseInt(projectIdentifier, 10);
88708
+ async function resolveProjectId(projectSlug) {
88709
+ const numId = parseInt(projectSlug, 10);
88061
88710
  if (!isNaN(numId)) {
88062
88711
  return numId;
88063
88712
  }
88064
- const apiUrl = config.get("apiUrl");
88065
- const apiKey = await credentials.getApiKey();
88066
- const response = await fetch(`${apiUrl}/api/projects?page_size=100`, {
88067
- headers: {
88068
- Authorization: `Bearer ${apiKey}`
88069
- }
88070
- });
88071
- if (!response.ok) {
88072
- throw new Error("Failed to fetch projects");
88073
- }
88074
- const data = await response.json();
88075
- const project = data.projects?.find((p) => p.slug === projectIdentifier || p.slug.toLowerCase() === projectIdentifier.toLowerCase());
88713
+ const projects = await makeRequest("GET", `/projects?page_size=100`);
88714
+ const project = projects.projects?.find((p) => p.slug === projectSlug || p.slug.toLowerCase() === projectSlug.toLowerCase());
88076
88715
  if (!project) {
88077
- throw new Error(`Project "${projectIdentifier}" not found`);
88716
+ throw new Error(`Project "${projectSlug}" not found`);
88078
88717
  }
88079
88718
  return project.id;
88080
88719
  }
88081
88720
  function registerTokensCommands(program2) {
88082
88721
  const tokens = program2.command("tokens").alias("token").description("Manage deployment tokens for project API access (KV, Blob, etc.)");
88083
- tokens.command("list").alias("ls").description("List deployment tokens for a project").requiredOption("-p, --project <project>", "Project slug or ID").option("--json", "Output in JSON format").action(listTokensAction);
88084
- tokens.command("create").alias("add").description("Create a new deployment token").requiredOption("-p, --project <project>", "Project slug or ID").option("-n, --name <name>", "Token name").option("--permissions <permissions>", 'Comma-separated permissions (e.g., "visitors:enrich,emails:send" or "*" for full access)').option("-e, --expires-in <days>", 'Expires in N days (7, 30, 90, 365, or "never")').option("-y, --yes", "Skip confirmation prompts (for automation)").action(createTokenAction);
88085
- tokens.command("show").alias("get").description("Show deployment token details").requiredOption("-p, --project <project>", "Project slug or ID").requiredOption("--id <id>", "Token ID").option("--json", "Output in JSON format").action(showTokenAction);
88086
- tokens.command("delete").alias("rm").description("Delete a deployment token").requiredOption("-p, --project <project>", "Project slug or ID").requiredOption("--id <id>", "Token ID").option("-f, --force", "Skip confirmation").option("-y, --yes", "Skip confirmation (alias for --force)").action(deleteTokenAction);
88722
+ tokens.command("list").alias("ls").description("List deployment tokens for a project").option("-p, --project <project>", "Project slug or ID").option("--json", "Output in JSON format").action(listTokensAction);
88723
+ tokens.command("create").alias("add").description("Create a new deployment token").option("-p, --project <project>", "Project slug or ID").option("-n, --name <name>", "Token name").option("--permissions <permissions>", 'Comma-separated permissions (e.g., "visitors:enrich,emails:send" or "*" for full access)').option("-e, --expires-in <days>", 'Expires in N days (7, 30, 90, 365, or "never")').option("-y, --yes", "Skip confirmation prompts (for automation)").action(createTokenAction);
88724
+ tokens.command("show").alias("get").description("Show deployment token details").option("-p, --project <project>", "Project slug or ID").requiredOption("--id <id>", "Token ID").option("--json", "Output in JSON format").action(showTokenAction);
88725
+ tokens.command("delete").alias("rm").description("Delete a deployment token").option("-p, --project <project>", "Project slug or ID").requiredOption("--id <id>", "Token ID").option("-f, --force", "Skip confirmation").option("-y, --yes", "Skip confirmation (alias for --force)").action(deleteTokenAction);
88087
88726
  tokens.command("permissions").description("List available deployment token permissions").option("--json", "Output in JSON format").action(listPermissionsAction);
88088
88727
  }
88089
88728
  async function listTokensAction(options) {
88090
88729
  await requireAuth();
88091
88730
  await setupClient();
88731
+ const resolved = await requireProjectSlug(options.project);
88732
+ if (resolved.source !== "flag") {
88733
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
88734
+ }
88092
88735
  const projectId = await withSpinner("Resolving project...", async () => {
88093
- return resolveProjectId(options.project);
88736
+ return resolveProjectId(resolved.slug);
88094
88737
  });
88095
88738
  const response = await withSpinner("Fetching deployment tokens...", async () => {
88096
- return makeRequest("GET", `/api/projects/${projectId}/deployment-tokens`);
88739
+ return makeRequest("GET", `/projects/${projectId}/deployment-tokens`);
88097
88740
  });
88098
88741
  const tokensList = response?.tokens ?? [];
88099
88742
  if (options.json) {
@@ -88104,7 +88747,7 @@ async function listTokensAction(options) {
88104
88747
  header(`${icons.info} Deployment Tokens (${tokensList.length})`);
88105
88748
  if (tokensList.length === 0) {
88106
88749
  info("No deployment tokens found");
88107
- info(`Run: temps tokens create -p ${options.project} --name my-token -y`);
88750
+ info(`Run: temps tokens create -p ${resolved.slug} --name my-token -y`);
88108
88751
  newline();
88109
88752
  return;
88110
88753
  }
@@ -88123,8 +88766,12 @@ async function listTokensAction(options) {
88123
88766
  async function createTokenAction(options) {
88124
88767
  await requireAuth();
88125
88768
  await setupClient();
88769
+ const resolved = await requireProjectSlug(options.project);
88770
+ if (resolved.source !== "flag") {
88771
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
88772
+ }
88126
88773
  const projectId = await withSpinner("Resolving project...", async () => {
88127
- return resolveProjectId(options.project);
88774
+ return resolveProjectId(resolved.slug);
88128
88775
  });
88129
88776
  let name;
88130
88777
  let permissions = null;
@@ -88188,7 +88835,7 @@ Available permissions:`);
88188
88835
  }
88189
88836
  }
88190
88837
  const result = await withSpinner("Creating deployment token...", async () => {
88191
- return makeRequest("POST", `/api/projects/${projectId}/deployment-tokens`, {
88838
+ return makeRequest("POST", `/projects/${projectId}/deployment-tokens`, {
88192
88839
  name,
88193
88840
  permissions,
88194
88841
  expires_at: expiresAt
@@ -88220,8 +88867,12 @@ Available permissions:`);
88220
88867
  async function showTokenAction(options) {
88221
88868
  await requireAuth();
88222
88869
  await setupClient();
88870
+ const resolved = await requireProjectSlug(options.project);
88871
+ if (resolved.source !== "flag") {
88872
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
88873
+ }
88223
88874
  const projectId = await withSpinner("Resolving project...", async () => {
88224
- return resolveProjectId(options.project);
88875
+ return resolveProjectId(resolved.slug);
88225
88876
  });
88226
88877
  const tokenId = parseInt(options.id, 10);
88227
88878
  if (isNaN(tokenId)) {
@@ -88229,7 +88880,7 @@ async function showTokenAction(options) {
88229
88880
  return;
88230
88881
  }
88231
88882
  const token = await withSpinner("Fetching token...", async () => {
88232
- return makeRequest("GET", `/api/projects/${projectId}/deployment-tokens/${tokenId}`);
88883
+ return makeRequest("GET", `/projects/${projectId}/deployment-tokens/${tokenId}`);
88233
88884
  });
88234
88885
  if (options.json) {
88235
88886
  json(token);
@@ -88249,8 +88900,12 @@ async function showTokenAction(options) {
88249
88900
  async function deleteTokenAction(options) {
88250
88901
  await requireAuth();
88251
88902
  await setupClient();
88903
+ const resolved = await requireProjectSlug(options.project);
88904
+ if (resolved.source !== "flag") {
88905
+ info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
88906
+ }
88252
88907
  const projectId = await withSpinner("Resolving project...", async () => {
88253
- return resolveProjectId(options.project);
88908
+ return resolveProjectId(resolved.slug);
88254
88909
  });
88255
88910
  const tokenId = parseInt(options.id, 10);
88256
88911
  if (isNaN(tokenId)) {
@@ -88258,7 +88913,7 @@ async function deleteTokenAction(options) {
88258
88913
  return;
88259
88914
  }
88260
88915
  const token = await withSpinner("Fetching token...", async () => {
88261
- return makeRequest("GET", `/api/projects/${projectId}/deployment-tokens/${tokenId}`);
88916
+ return makeRequest("GET", `/projects/${projectId}/deployment-tokens/${tokenId}`);
88262
88917
  });
88263
88918
  const skipConfirmation = options.force || options.yes;
88264
88919
  if (!skipConfirmation) {
@@ -88273,7 +88928,7 @@ async function deleteTokenAction(options) {
88273
88928
  }
88274
88929
  }
88275
88930
  await withSpinner("Deleting token...", async () => {
88276
- return makeRequest("DELETE", `/api/projects/${projectId}/deployment-tokens/${tokenId}`);
88931
+ return makeRequest("DELETE", `/projects/${projectId}/deployment-tokens/${tokenId}`);
88277
88932
  });
88278
88933
  success("Deployment token deleted");
88279
88934
  }
@@ -94471,7 +95126,7 @@ async function syncAndFindRepo(connectionId, owner, repo) {
94471
95126
  client,
94472
95127
  path: { connection_id: connectionId }
94473
95128
  });
94474
- await new Promise((resolve4) => setTimeout(resolve4, 1000));
95129
+ await new Promise((resolve5) => setTimeout(resolve5, 1000));
94475
95130
  return findRepoOnConnection(connectionId, owner, repo);
94476
95131
  } catch {
94477
95132
  return false;
@@ -94717,12 +95372,12 @@ async function executeSetEnvVars(plan, ctx) {
94717
95372
  errors8.push(`${ev.key}: ${err instanceof Error ? err.message : String(err)}`);
94718
95373
  }
94719
95374
  }
94720
- const success5 = failCount === 0;
94721
- const message = success5 ? `Set ${successCount} environment variable(s)` : `Set ${successCount}/${activeEnvVars.length} env vars (${failCount} failed: ${errors8.slice(0, 3).join("; ")}${errors8.length > 3 ? "..." : ""})`;
95375
+ const success4 = failCount === 0;
95376
+ const message = success4 ? `Set ${successCount} environment variable(s)` : `Set ${successCount}/${activeEnvVars.length} env vars (${failCount} failed: ${errors8.slice(0, 3).join("; ")}${errors8.length > 3 ? "..." : ""})`;
94722
95377
  return {
94723
95378
  stepId: "set-env-vars",
94724
95379
  title: `Set ${activeEnvVars.length} environment variable(s)`,
94725
- success: success5,
95380
+ success: success4,
94726
95381
  skipped: false,
94727
95382
  message
94728
95383
  };
@@ -94874,7 +95529,7 @@ async function syncAndFindRepo2(connectionId, owner, repo) {
94874
95529
  client,
94875
95530
  path: { connection_id: connectionId }
94876
95531
  });
94877
- await new Promise((resolve4) => setTimeout(resolve4, 1000));
95532
+ await new Promise((resolve5) => setTimeout(resolve5, 1000));
94878
95533
  return findRepoOnConnection2(connectionId, owner, repo);
94879
95534
  } catch {
94880
95535
  return false;
@@ -96040,58 +96695,6 @@ async function resetPreferencesAction(options) {
96040
96695
 
96041
96696
  // src/commands/init/index.ts
96042
96697
  init_sdk_gen();
96043
-
96044
- // src/config/project-config.ts
96045
- import { readFile as readFile3, writeFile as writeFile2, mkdir as mkdir2 } from "node:fs/promises";
96046
- import { existsSync as existsSync6 } from "node:fs";
96047
- import { join as join2, dirname as dirname2 } from "node:path";
96048
- var CONFIG_DIR = ".temps";
96049
- var CONFIG_FILE = "config.json";
96050
- var GITIGNORE_FILE = ".gitignore";
96051
- function findProjectConfigDir(startDir) {
96052
- let dir = startDir ?? process.cwd();
96053
- while (true) {
96054
- const configPath = join2(dir, CONFIG_DIR, CONFIG_FILE);
96055
- if (existsSync6(configPath)) {
96056
- return join2(dir, CONFIG_DIR);
96057
- }
96058
- const parent = dirname2(dir);
96059
- if (parent === dir)
96060
- break;
96061
- dir = parent;
96062
- }
96063
- return null;
96064
- }
96065
- async function readProjectConfig() {
96066
- const configDir = findProjectConfigDir();
96067
- if (!configDir)
96068
- return null;
96069
- try {
96070
- const configPath = join2(configDir, CONFIG_FILE);
96071
- const content = await readFile3(configPath, "utf-8");
96072
- return JSON.parse(content);
96073
- } catch {
96074
- return null;
96075
- }
96076
- }
96077
- async function writeProjectConfig(config2) {
96078
- const configDir = join2(process.cwd(), CONFIG_DIR);
96079
- await mkdir2(configDir, { recursive: true });
96080
- const configPath = join2(configDir, CONFIG_FILE);
96081
- await writeFile2(configPath, JSON.stringify(config2, null, 2) + `
96082
- `, "utf-8");
96083
- const gitignorePath = join2(configDir, GITIGNORE_FILE);
96084
- if (!existsSync6(gitignorePath)) {
96085
- await writeFile2(gitignorePath, `*
96086
- `, "utf-8");
96087
- }
96088
- return configPath;
96089
- }
96090
- function hasProjectConfig() {
96091
- return findProjectConfigDir() !== null;
96092
- }
96093
-
96094
- // src/commands/init/index.ts
96095
96698
  init_prompts();
96096
96699
  init_output();
96097
96700
  async function init(projectSlug, options) {
@@ -96307,38 +96910,8 @@ function registerLinkCommand(program2) {
96307
96910
  program2.command("link [project-slug]").description("Link current directory to a Temps project").option("-e, --environment <name>", "Set default environment").action(link2);
96308
96911
  }
96309
96912
 
96310
- // src/config/resolve-project.ts
96311
- async function resolveProjectSlug(flagValue) {
96312
- if (flagValue) {
96313
- return { slug: flagValue, source: "flag" };
96314
- }
96315
- const localConfig = await readProjectConfig();
96316
- if (localConfig?.projectSlug) {
96317
- return { slug: localConfig.projectSlug, source: "local-config" };
96318
- }
96319
- const envProject = process.env.TEMPS_PROJECT;
96320
- if (envProject) {
96321
- return { slug: envProject, source: "env-var" };
96322
- }
96323
- const defaultProject = config.get("defaultProject");
96324
- if (defaultProject) {
96325
- return { slug: defaultProject, source: "global-config" };
96326
- }
96327
- return null;
96328
- }
96329
- async function requireProjectSlug(flagValue) {
96330
- const resolved = await resolveProjectSlug(flagValue);
96331
- if (resolved)
96332
- return resolved;
96333
- throw new Error(`No project specified. You can:
96334
- ` + ` • Pass --project <slug> flag
96335
- ` + ` • Run "temps link" to link this directory to a project
96336
- ` + ` • Set TEMPS_PROJECT environment variable
96337
- ` + ' • Run "temps configure" to set a default project');
96338
- }
96339
-
96340
96913
  // src/lib/detect-project.ts
96341
- import { existsSync as existsSync7 } from "node:fs";
96914
+ import { existsSync as existsSync8 } from "node:fs";
96342
96915
  import { readFile as readFile4 } from "node:fs/promises";
96343
96916
  import { execSync } from "node:child_process";
96344
96917
  import { join as join3, basename as basename3 } from "node:path";
@@ -96417,7 +96990,7 @@ var PRESET_RULES = [
96417
96990
  function detectPreset(dir) {
96418
96991
  const projectDir = dir ?? process.cwd();
96419
96992
  for (const rule of PRESET_RULES) {
96420
- const matched = rule.files.some((file) => existsSync7(join3(projectDir, file)));
96993
+ const matched = rule.files.some((file) => existsSync8(join3(projectDir, file)));
96421
96994
  if (matched) {
96422
96995
  return {
96423
96996
  slug: rule.slug,
@@ -96426,14 +96999,14 @@ function detectPreset(dir) {
96426
96999
  };
96427
97000
  }
96428
97001
  }
96429
- if (existsSync7(join3(projectDir, "package.json"))) {
97002
+ if (existsSync8(join3(projectDir, "package.json"))) {
96430
97003
  return {
96431
97004
  slug: "nodejs",
96432
97005
  label: "Node.js",
96433
97006
  confidence: "low"
96434
97007
  };
96435
97008
  }
96436
- if (existsSync7(join3(projectDir, "index.html"))) {
97009
+ if (existsSync8(join3(projectDir, "index.html"))) {
96437
97010
  return {
96438
97011
  slug: "static",
96439
97012
  label: "Static Site",
@@ -96445,7 +97018,7 @@ function detectPreset(dir) {
96445
97018
  async function refinePythonPreset(dir) {
96446
97019
  const projectDir = dir ?? process.cwd();
96447
97020
  const reqPath = join3(projectDir, "requirements.txt");
96448
- if (existsSync7(reqPath)) {
97021
+ if (existsSync8(reqPath)) {
96449
97022
  try {
96450
97023
  const content = await readFile4(reqPath, "utf-8");
96451
97024
  const lower = content.toLowerCase();
@@ -96458,7 +97031,7 @@ async function refinePythonPreset(dir) {
96458
97031
  } catch {}
96459
97032
  }
96460
97033
  const pyprojectPath = join3(projectDir, "pyproject.toml");
96461
- if (existsSync7(pyprojectPath)) {
97034
+ if (existsSync8(pyprojectPath)) {
96462
97035
  try {
96463
97036
  const content = await readFile4(pyprojectPath, "utf-8");
96464
97037
  const lower = content.toLowerCase();
@@ -96536,7 +97109,7 @@ async function detectServiceHints(dir) {
96536
97109
  const envFiles = [".env", ".env.example", ".env.local", ".env.development"];
96537
97110
  for (const envFile of envFiles) {
96538
97111
  const envPath = join3(projectDir, envFile);
96539
- if (existsSync7(envPath)) {
97112
+ if (existsSync8(envPath)) {
96540
97113
  try {
96541
97114
  const content = await readFile4(envPath, "utf-8");
96542
97115
  const upper = content.toUpperCase();
@@ -96556,7 +97129,7 @@ async function detectServiceHints(dir) {
96556
97129
  }
96557
97130
  }
96558
97131
  const prismaPath = join3(projectDir, "prisma", "schema.prisma");
96559
- if (existsSync7(prismaPath)) {
97132
+ if (existsSync8(prismaPath)) {
96560
97133
  try {
96561
97134
  const content = await readFile4(prismaPath, "utf-8");
96562
97135
  if (content.includes("postgresql") || content.includes("postgres")) {
@@ -96569,7 +97142,7 @@ async function detectServiceHints(dir) {
96569
97142
  }
96570
97143
  const drizzleFiles = ["drizzle.config.ts", "drizzle.config.js"];
96571
97144
  for (const drizzleFile of drizzleFiles) {
96572
- if (existsSync7(join3(projectDir, drizzleFile))) {
97145
+ if (existsSync8(join3(projectDir, drizzleFile))) {
96573
97146
  hints.add("postgres");
96574
97147
  break;
96575
97148
  }
@@ -96579,7 +97152,7 @@ async function detectServiceHints(dir) {
96579
97152
  async function suggestProjectName(dir) {
96580
97153
  const projectDir = dir ?? process.cwd();
96581
97154
  const pkgPath = join3(projectDir, "package.json");
96582
- if (existsSync7(pkgPath)) {
97155
+ if (existsSync8(pkgPath)) {
96583
97156
  try {
96584
97157
  const content = await readFile4(pkgPath, "utf-8");
96585
97158
  const pkg = JSON.parse(content);
@@ -96605,8 +97178,8 @@ function sanitizeProjectName(name) {
96605
97178
  init_prompts();
96606
97179
  init_output();
96607
97180
  init_sdk_gen();
96608
- import { existsSync as existsSync8, writeFileSync as writeFileSync5, mkdirSync as mkdirSync2 } from "node:fs";
96609
- import { resolve as resolve4, join as join4 } from "node:path";
97181
+ import { existsSync as existsSync9, writeFileSync as writeFileSync5, mkdirSync as mkdirSync2 } from "node:fs";
97182
+ import { resolve as resolve5, join as join4 } from "node:path";
96610
97183
  import { tmpdir as tmpdir3 } from "node:os";
96611
97184
  async function runSetupWizard(options) {
96612
97185
  newline();
@@ -96834,7 +97407,7 @@ async function runSetupWizard(options) {
96834
97407
  deploymentId = deployment.id;
96835
97408
  break;
96836
97409
  }
96837
- await new Promise((resolve5) => setTimeout(resolve5, 2000));
97410
+ await new Promise((resolve6) => setTimeout(resolve6, 2000));
96838
97411
  }
96839
97412
  if (deploymentId) {
96840
97413
  const result = await watchDeployment({
@@ -96859,7 +97432,7 @@ async function runSetupWizard(options) {
96859
97432
  info("Building and deploying...");
96860
97433
  newline();
96861
97434
  try {
96862
- const hasDockerfile = existsSync8(resolve4("Dockerfile"));
97435
+ const hasDockerfile = existsSync9(resolve5("Dockerfile"));
96863
97436
  let dockerfilePath;
96864
97437
  let buildArgsList;
96865
97438
  if (!hasDockerfile && presetSlug && presetSlug !== "dockerfile") {
@@ -96993,14 +97566,14 @@ async function selectPresetFromAll() {
96993
97566
  });
96994
97567
  }
96995
97568
  function detectPackageManager(dir) {
96996
- const projectDir = dir ? resolve4(dir) : process.cwd();
96997
- if (existsSync8(join4(projectDir, "pnpm-lock.yaml")))
97569
+ const projectDir = dir ? resolve5(dir) : process.cwd();
97570
+ if (existsSync9(join4(projectDir, "pnpm-lock.yaml")))
96998
97571
  return "pnpm";
96999
- if (existsSync8(join4(projectDir, "yarn.lock")))
97572
+ if (existsSync9(join4(projectDir, "yarn.lock")))
97000
97573
  return "yarn";
97001
- if (existsSync8(join4(projectDir, "bun.lockb")) || existsSync8(join4(projectDir, "bun.lock")))
97574
+ if (existsSync9(join4(projectDir, "bun.lockb")) || existsSync9(join4(projectDir, "bun.lock")))
97002
97575
  return "bun";
97003
- if (existsSync8(join4(projectDir, "package-lock.json")))
97576
+ if (existsSync9(join4(projectDir, "package-lock.json")))
97004
97577
  return "npm";
97005
97578
  return "npm";
97006
97579
  }
@@ -97030,12 +97603,91 @@ async function up(projectArg, options) {
97030
97603
  if (resolved.source !== "flag") {
97031
97604
  info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
97032
97605
  }
97033
- const { data: project } = await getProjectBySlug({
97034
- client,
97035
- path: { slug: resolved.slug }
97036
- });
97037
- const sourceType = project?.source_type;
97606
+ newline();
97607
+ startSpinner("Fetching project details...");
97608
+ let project;
97609
+ let environments = [];
97610
+ try {
97611
+ const { data, error: error4 } = await getProjectBySlug({
97612
+ client,
97613
+ path: { slug: resolved.slug }
97614
+ });
97615
+ if (error4 || !data) {
97616
+ const rawApiUrl = config.get("apiUrl");
97617
+ const baseUrl = client.getConfig().baseUrl ?? rawApiUrl;
97618
+ failSpinner(`Project "${resolved.slug}" not found`);
97619
+ info(`API: ${colors.muted(`${baseUrl}/projects/by-slug/${resolved.slug}`)}`);
97620
+ if (error4) {
97621
+ info(`Error: ${getErrorMessage(error4)}`);
97622
+ }
97623
+ return;
97624
+ }
97625
+ project = data;
97626
+ succeedSpinner(`Found project: ${project.name}`);
97627
+ const { data: envData } = await getEnvironments({
97628
+ client,
97629
+ path: { project_id: project.id }
97630
+ });
97631
+ environments = envData ?? [];
97632
+ } catch (err) {
97633
+ failSpinner("Failed to fetch project");
97634
+ throw err;
97635
+ }
97636
+ const sourceType = project.source_type;
97637
+ const isGitBased = sourceType !== "manual" && sourceType !== "docker_image";
97638
+ if (isGitBased && project.repo_owner && project.repo_name) {
97639
+ info(`Repository: ${colors.muted(`${project.repo_owner}/${project.repo_name}`)}`);
97640
+ } else if (isGitBased && !project.git_provider_connection_id) {
97641
+ warning("No git provider connected to this project");
97642
+ info(`Connect one with: ${colors.muted("bunx @temps-sdk/cli providers add")}`);
97643
+ info(`Or deploy manually: ${colors.muted(`bunx @temps-sdk/cli deploy:local-image -p ${resolved.slug}`)}`);
97644
+ newline();
97645
+ }
97646
+ if (project.preset) {
97647
+ info(`Preset: ${colors.muted(project.preset)}`);
97648
+ }
97649
+ let environmentId;
97650
+ let environmentName = options.environment || "production";
97651
+ if (environments.length > 0) {
97652
+ if (options.environment) {
97653
+ const env4 = environments.find((e) => e.name === options.environment);
97654
+ if (env4) {
97655
+ environmentId = env4.id;
97656
+ environmentName = env4.name;
97657
+ }
97658
+ } else if (!options.yes) {
97659
+ const selectedEnv = await promptSelect({
97660
+ message: "Select environment",
97661
+ choices: environments.map((env4) => ({
97662
+ name: env4.name,
97663
+ value: String(env4.id),
97664
+ description: env4.is_preview ? "Preview environment" : undefined
97665
+ })),
97666
+ default: String(environments.find((e) => e.name === "production")?.id ?? environments[0]?.id ?? "")
97667
+ });
97668
+ environmentId = parseInt(selectedEnv, 10);
97669
+ environmentName = environments.find((e) => e.id === environmentId)?.name ?? "production";
97670
+ } else {
97671
+ const prodEnv = environments.find((e) => e.name === "production");
97672
+ if (prodEnv) {
97673
+ environmentId = prodEnv.id;
97674
+ environmentName = prodEnv.name;
97675
+ } else if (environments[0]) {
97676
+ environmentId = environments[0].id;
97677
+ environmentName = environments[0].name;
97678
+ }
97679
+ }
97680
+ }
97038
97681
  if (sourceType === "manual" || sourceType === "docker_image") {
97682
+ newline();
97683
+ box([
97684
+ `Project: ${colors.bold(project.name)}`,
97685
+ `Environment: ${colors.bold(environmentName)}`,
97686
+ project.preset ? `Preset: ${colors.bold(project.preset)}` : null,
97687
+ `Deploy: ${colors.bold("Manual (local image upload)")}`
97688
+ ].filter(Boolean).join(`
97689
+ `), `${icons.rocket} Deployment Preview`);
97690
+ newline();
97039
97691
  await deployLocalImage({
97040
97692
  project: resolved.slug,
97041
97693
  environment: options.environment,
@@ -97050,13 +97702,94 @@ async function up(projectArg, options) {
97050
97702
  branch = detectedBranch;
97051
97703
  }
97052
97704
  }
97053
- await deploy({
97054
- project: resolved.slug,
97055
- environment: options.environment,
97056
- branch,
97057
- wait: options.wait,
97058
- yes: options.yes
97059
- });
97705
+ if (!branch) {
97706
+ if (options.yes) {
97707
+ branch = project.main_branch || "main";
97708
+ } else {
97709
+ branch = await promptText({
97710
+ message: "Branch to deploy",
97711
+ default: project.main_branch || "main"
97712
+ });
97713
+ }
97714
+ }
97715
+ newline();
97716
+ box([
97717
+ `Project: ${colors.bold(project.name)}`,
97718
+ `Environment: ${colors.bold(environmentName)}`,
97719
+ `Branch: ${colors.bold(branch)}`,
97720
+ project.preset ? `Preset: ${colors.bold(project.preset)}` : null,
97721
+ project.repo_owner && project.repo_name ? `Repository: ${colors.bold(`${project.repo_owner}/${project.repo_name}`)}` : null
97722
+ ].filter(Boolean).join(`
97723
+ `), `${icons.rocket} Deployment Preview`);
97724
+ newline();
97725
+ startSpinner("Starting deployment...");
97726
+ try {
97727
+ const { data: pipelineData, error: pipelineError } = await triggerProjectPipeline({
97728
+ client,
97729
+ path: { id: project.id },
97730
+ body: {
97731
+ branch,
97732
+ environment_id: environmentId
97733
+ }
97734
+ });
97735
+ if (pipelineError || !pipelineData) {
97736
+ failSpinner("Failed to start deployment");
97737
+ const msg = getErrorMessage(pipelineError);
97738
+ if (msg) {
97739
+ info(`Reason: ${msg}`);
97740
+ }
97741
+ return;
97742
+ }
97743
+ succeedSpinner("Deployment started");
97744
+ info(pipelineData.message ?? "Pipeline triggered successfully");
97745
+ if (options.wait === false) {
97746
+ newline();
97747
+ info("Deployment running in background");
97748
+ info(`Check status: ${colors.muted("bunx @temps-sdk/cli status")}`);
97749
+ return;
97750
+ }
97751
+ startSpinner("Waiting for deployment to start...");
97752
+ let deploymentId = null;
97753
+ for (let attempt = 0;attempt < 15; attempt++) {
97754
+ const { data: deployList, error: deployError } = await getProjectDeployments({
97755
+ client,
97756
+ path: { id: project.id },
97757
+ query: {
97758
+ per_page: 1,
97759
+ ...environmentId ? { environment_id: environmentId } : {}
97760
+ }
97761
+ });
97762
+ if (deployError) {
97763
+ failSpinner("Failed to fetch deployment status");
97764
+ info(`Error: ${getErrorMessage(deployError)}`);
97765
+ return;
97766
+ }
97767
+ const latest = deployList?.deployments?.[0];
97768
+ if (latest?.id) {
97769
+ deploymentId = latest.id;
97770
+ break;
97771
+ }
97772
+ await new Promise((r) => setTimeout(r, 2000));
97773
+ }
97774
+ if (deploymentId) {
97775
+ succeedSpinner(`Deployment #${deploymentId} found`);
97776
+ const result = await watchDeployment({
97777
+ projectId: project.id,
97778
+ deploymentId,
97779
+ timeoutSecs: 600,
97780
+ projectName: resolved.slug
97781
+ });
97782
+ if (!result.success) {
97783
+ process.exitCode = 1;
97784
+ }
97785
+ } else {
97786
+ failSpinner("Could not locate the deployment to track");
97787
+ info(`Check status: ${colors.muted("bunx @temps-sdk/cli status")}`);
97788
+ }
97789
+ } catch (err) {
97790
+ failSpinner("Deployment failed");
97791
+ throw err;
97792
+ }
97060
97793
  }
97061
97794
  if (!hasProjectConfig() && !options.yes) {
97062
97795
  newline();
@@ -97184,7 +97917,7 @@ function registerStatusCommand(program2) {
97184
97917
 
97185
97918
  // src/config/instances.ts
97186
97919
  import { readFile as readFile5, writeFile as writeFile3, mkdir as mkdir3 } from "node:fs/promises";
97187
- import { existsSync as existsSync9 } from "node:fs";
97920
+ import { existsSync as existsSync10 } from "node:fs";
97188
97921
  import { dirname as dirname3 } from "node:path";
97189
97922
  function getInstancesPath() {
97190
97923
  const home = process.env.HOME || process.env.USERPROFILE || "~";
@@ -97193,7 +97926,7 @@ function getInstancesPath() {
97193
97926
  async function loadInstances() {
97194
97927
  const path7 = getInstancesPath();
97195
97928
  try {
97196
- if (existsSync9(path7)) {
97929
+ if (existsSync10(path7)) {
97197
97930
  const content = await readFile5(path7, "utf-8");
97198
97931
  return JSON.parse(content);
97199
97932
  }
@@ -97642,8 +98375,8 @@ async function open(projectArg, options) {
97642
98375
  info(`Using project ${colors.bold(resolved.slug)} (from ${resolved.source})`);
97643
98376
  }
97644
98377
  if (options.dashboard) {
97645
- const apiUrl = config.get("apiUrl");
97646
- const dashboardUrl = `${apiUrl}/dashboard/projects/${resolved.slug}`;
98378
+ const webUrl = getWebUrl();
98379
+ const dashboardUrl = `${webUrl}/projects/${resolved.slug}`;
97647
98380
  success(`Opening dashboard for ${resolved.slug}`);
97648
98381
  openUrl(dashboardUrl);
97649
98382
  return;
@@ -98240,7 +98973,7 @@ function openBrowser2(url) {
98240
98973
  } catch {}
98241
98974
  }
98242
98975
  function sleep(ms) {
98243
- return new Promise((resolve6) => setTimeout(resolve6, ms));
98976
+ return new Promise((resolve7) => setTimeout(resolve7, ms));
98244
98977
  }
98245
98978
  async function cloudLogin() {
98246
98979
  const cloudUrl = getCloudUrl();
@@ -98381,7 +99114,7 @@ ${source_default.cyan("╚══════════════════
98381
99114
  `;
98382
99115
  function createProgram() {
98383
99116
  const program2 = new Command;
98384
- program2.name("temps").description("CLI for Temps deployment platform").version(VERSION, "-v, --version", "Display version number").option("--no-color", "Disable colored output").option("--debug", "Enable debug output").hook("preAction", (thisCommand) => {
99117
+ program2.name("temps").description("CLI for Temps deployment platform").version(VERSION, "-V, --version", "Display version number").option("--no-color", "Disable colored output").option("--debug", "Enable debug output").hook("preAction", (thisCommand) => {
98385
99118
  const opts = thisCommand.opts();
98386
99119
  if (opts.debug) {
98387
99120
  process.env.DEBUG = "1";
@@ -98705,7 +99438,7 @@ ${source_default.cyan("╚══════════════════
98705
99438
  `;
98706
99439
  function createProgram2() {
98707
99440
  const program2 = new Command;
98708
- program2.name("temps").description("CLI for Temps deployment platform").version(VERSION2, "-v, --version", "Display version number").option("--no-color", "Disable colored output").option("--debug", "Enable debug output").hook("preAction", (thisCommand) => {
99441
+ program2.name("temps").description("CLI for Temps deployment platform").version(VERSION2, "-V, --version", "Display version number").option("--no-color", "Disable colored output").option("--debug", "Enable debug output").hook("preAction", (thisCommand) => {
98709
99442
  const opts = thisCommand.opts();
98710
99443
  if (opts.debug) {
98711
99444
  process.env.DEBUG = "1";