storyblok 4.21.1 → 4.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import 'dotenv/config';
3
+ import { Command, Option, CommanderError } from 'commander';
3
4
  import { fileURLToPath, pathToFileURL } from 'node:url';
4
5
  import { resolve, dirname, join, parse, extname, relative, isAbsolute, basename } from 'pathe';
5
6
  import { existsSync, mkdirSync, appendFileSync, writeFileSync, readdirSync, unlinkSync, readFileSync } from 'node:fs';
6
7
  import { homedir } from 'node:os';
7
8
  import { loadConfig as loadConfig$1, SUPPORTED_EXTENSIONS } from 'c12';
8
9
  import chalk from 'chalk';
9
- import { readPackageUp } from 'read-package-up';
10
- import { Command, Option } from 'commander';
11
10
  import { MultiBar, Presets } from 'cli-progress';
12
11
  import { Spinner } from '@topcli/spinner';
12
+ import { readPackageUp } from 'read-package-up';
13
13
  import fs, { mkdir, writeFile, readdir, readFile as readFile$1, appendFile, access, constants, unlink } from 'node:fs/promises';
14
14
  import filenamify from 'filenamify';
15
15
  import { createManagementApiClient, normalizeAssetUrl } from '@storyblok/management-api-client';
@@ -904,6 +904,184 @@ function setLoggerTransports(transports) {
904
904
  }
905
905
  }
906
906
 
907
+ const toCamelCase = (str) => {
908
+ return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/_/g, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/[^a-z0-9]([a-z])/gi, (_, letter) => letter.toUpperCase()).replace(/[^a-z0-9]/gi, "");
909
+ };
910
+ const toPascalCase = (str) => {
911
+ const camelCase = toCamelCase(str);
912
+ return camelCase ? camelCase[0].toUpperCase() + camelCase.slice(1) : camelCase;
913
+ };
914
+ const capitalize = (str) => {
915
+ return str.charAt(0).toUpperCase() + str.slice(1);
916
+ };
917
+ const toHumanReadable = (str) => {
918
+ return str.replace(/[-_]/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ").replace(/\s+/g, " ").trim();
919
+ };
920
+ function maskToken(token) {
921
+ if (token.length <= 4) {
922
+ return token;
923
+ }
924
+ const visiblePart = token.slice(0, 4);
925
+ const maskedPart = "*".repeat(token.length - 4);
926
+ return `${visiblePart}${maskedPart}`;
927
+ }
928
+ const slugify = (text) => text.toString().toLowerCase().replace(/\s+/g, "-").replace(/[^\w-]+/g, "").replace(/-{2,}/g, "-").replace(/^-+/, "").replace(/-+$/, "");
929
+ function createRegexFromGlob(pattern) {
930
+ return new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*")}$`);
931
+ }
932
+
933
+ const noopProgressBar = {
934
+ increment: () => {
935
+ },
936
+ setTotal: () => {
937
+ },
938
+ stop: () => {
939
+ }
940
+ };
941
+ const noopSpinner = {
942
+ failed: (_title) => {
943
+ },
944
+ succeed: (_title) => {
945
+ },
946
+ elapsedTime: 0
947
+ };
948
+ class UI {
949
+ console;
950
+ enabled;
951
+ multiBar;
952
+ constructor({ enabled }) {
953
+ this.enabled = enabled;
954
+ this.console = null;
955
+ this.multiBar = null;
956
+ this.applyEnabled(enabled);
957
+ }
958
+ /** Update the enabled state (called by getUI when preAction resolves config). */
959
+ setEnabled(enabled) {
960
+ if (this.enabled === enabled) {
961
+ return;
962
+ }
963
+ this.applyEnabled(enabled);
964
+ }
965
+ applyEnabled(enabled) {
966
+ this.enabled = enabled;
967
+ this.console = enabled ? {
968
+ log: (...args) => console.error(...args),
969
+ info: (...args) => console.error(...args),
970
+ warn: (...args) => console.warn(...args),
971
+ error: (...args) => console.error(...args)
972
+ } : null;
973
+ this.multiBar = enabled ? new MultiBar({
974
+ clearOnComplete: false,
975
+ format: `${chalk.bold(" {title} ")} ${chalk.hex(colorPalette.PRIMARY)("[{bar}]")} {percentage}% | {eta_formatted} | {value}/{total} processed`,
976
+ etaBuffer: 60
977
+ }, Presets.rect) : null;
978
+ }
979
+ title(message, color, subtitle) {
980
+ if (subtitle) {
981
+ this.console?.log(`${chalk.bgHex(color).bold(` ${capitalize(message)} `)} ${subtitle}`);
982
+ } else {
983
+ this.console?.log(chalk.bgHex(color).bold(` ${capitalize(message)} `));
984
+ }
985
+ this.br();
986
+ this.br();
987
+ }
988
+ br() {
989
+ this.console?.log("");
990
+ }
991
+ ok(message, header = false) {
992
+ if (header) {
993
+ this.br();
994
+ const successHeader = chalk.bgGreen.bold.white(` Success `);
995
+ this.console?.log(successHeader);
996
+ this.br();
997
+ }
998
+ this.console?.log(message ? `${chalk.green("\u2714")} ${message}` : "");
999
+ }
1000
+ info(message, options = {}) {
1001
+ const { header = false, margin = true } = options;
1002
+ if (header) {
1003
+ this.br();
1004
+ const infoHeader = chalk.bgBlue.bold.white(` Info `);
1005
+ this.console?.info(infoHeader);
1006
+ }
1007
+ this.console?.info(message ? `${chalk.blue("\u2139")} ${message}` : "");
1008
+ if (margin) {
1009
+ this.br();
1010
+ }
1011
+ }
1012
+ warn(message, header = false) {
1013
+ if (header) {
1014
+ this.br();
1015
+ const warnHeader = chalk.bgYellow.bold.black(` Warning `);
1016
+ this.console?.warn(warnHeader);
1017
+ }
1018
+ this.console?.warn(message ? `${chalk.yellow("\u26A0\uFE0F ")} ${message}` : "");
1019
+ }
1020
+ error(message, info, options = {}) {
1021
+ const { header = false, margin = false } = options;
1022
+ const out = this.console ?? { error: (...args) => console.error(...args), log: (...args) => console.error(...args) };
1023
+ if (header) {
1024
+ const errorHeader = chalk.bgRed.bold.white(` Error `);
1025
+ out.error(errorHeader);
1026
+ out.log("");
1027
+ }
1028
+ if (info) {
1029
+ out.error(`${chalk.red.bold("\u25B2 error")} ${message}`, info);
1030
+ } else {
1031
+ out.error(`${chalk.red.bold("\u25B2 error")} ${message}`);
1032
+ }
1033
+ if (margin) {
1034
+ out.log("");
1035
+ }
1036
+ }
1037
+ /** Plain console.log passthrough — use for preformatted or multi-line text. */
1038
+ log(message) {
1039
+ this.console?.log(message);
1040
+ }
1041
+ list(items) {
1042
+ for (const item of items) {
1043
+ this.console?.log(` ${item}`);
1044
+ }
1045
+ }
1046
+ createProgressBar(options) {
1047
+ const bar = this.multiBar?.create(0, 0, options);
1048
+ if (!bar) {
1049
+ return noopProgressBar;
1050
+ }
1051
+ return {
1052
+ increment: (count = 1) => bar.increment(count, options),
1053
+ // cli-progress renders `{eta_formatted}` as "LLs" when total is 0.
1054
+ // Floor at 1 so an empty phase stays a clean 0/1 instead.
1055
+ setTotal: (total) => {
1056
+ bar.setTotal(Math.max(total, 1));
1057
+ bar.update(options);
1058
+ },
1059
+ stop: () => bar.stop()
1060
+ };
1061
+ }
1062
+ stopAllProgressBars() {
1063
+ this.multiBar?.stop();
1064
+ }
1065
+ createSpinner(title) {
1066
+ if (!this.enabled) {
1067
+ return noopSpinner;
1068
+ }
1069
+ const spinner = new Spinner({ verbose: !isVitest });
1070
+ spinner.stream = process.stderr;
1071
+ return spinner.start(title);
1072
+ }
1073
+ }
1074
+ const stderrPromptContext = { output: process.stderr };
1075
+ let uiInstance = null;
1076
+ function getUI(options) {
1077
+ if (!uiInstance) {
1078
+ uiInstance = new UI(options ?? { enabled: DEFAULT_GLOBAL_CONFIG.ui.enabled });
1079
+ } else if (options !== void 0) {
1080
+ uiInstance.setEnabled(options.enabled);
1081
+ }
1082
+ return uiInstance;
1083
+ }
1084
+
907
1085
  const FS_ERRORS = {
908
1086
  file_not_found: "The file requested was not found",
909
1087
  permission_denied: "Permission denied while accessing the file",
@@ -1015,45 +1193,54 @@ function getResponseStatus(maybeError) {
1015
1193
  return typeof response.status === "number" ? response.status : void 0;
1016
1194
  }
1017
1195
  function handleVerboseError(error) {
1196
+ const ui = getUI();
1018
1197
  if (error instanceof CommandError || error instanceof APIError || error instanceof FileSystemError) {
1019
1198
  const errorDetails = "getInfo" in error ? error.getInfo() : {};
1020
1199
  if (error instanceof CommandError) {
1021
- konsola.error(`Command Error: ${error.getInfo().message}`, errorDetails);
1200
+ ui.error(`Command Error: ${error.getInfo().message}`, errorDetails);
1022
1201
  } else if (error instanceof APIError) {
1023
- konsola.error(`API Error: ${error.getInfo().cause}`, errorDetails);
1202
+ ui.error(`API Error: ${error.getInfo().cause}`, errorDetails);
1024
1203
  } else if (error instanceof FileSystemError) {
1025
- konsola.error(`File System Error: ${error.getInfo().cause}`, errorDetails);
1204
+ ui.error(`File System Error: ${error.getInfo().cause}`, errorDetails);
1026
1205
  } else {
1027
- konsola.error(`Unexpected Error: ${error}`, errorDetails);
1206
+ ui.error(`Unexpected Error: ${error}`, errorDetails);
1028
1207
  }
1029
1208
  } else {
1030
- konsola.error(`Unexpected Error`, error);
1209
+ ui.error("Unexpected Error", error);
1031
1210
  }
1032
1211
  }
1212
+ function isPromptCancellation(error) {
1213
+ return error.name === "ExitPromptError" || error.name === "AbortPromptError" || error.name === "CancelPromptError";
1214
+ }
1033
1215
  function handleError(error, verbose = false, context) {
1216
+ if (isPromptCancellation(error)) {
1217
+ process.exitCode = 0;
1218
+ return;
1219
+ }
1220
+ const ui = getUI();
1034
1221
  if (error instanceof APIError || error instanceof FileSystemError) {
1035
1222
  const messageStack = error.messageStack;
1036
1223
  messageStack.forEach((message, index) => {
1037
- konsola.error(message, null, {
1038
- header: index === 0,
1039
- margin: false
1040
- });
1224
+ if (index === 0) {
1225
+ ui.error(message, void 0, { header: true });
1226
+ } else {
1227
+ ui.error(message);
1228
+ }
1041
1229
  });
1042
1230
  } else {
1043
- konsola.error(error.message, null, {
1044
- header: true
1045
- });
1231
+ ui.error(error.message, void 0, { header: true });
1046
1232
  }
1047
1233
  if (verbose) {
1048
1234
  handleVerboseError(error);
1049
1235
  } else {
1050
- konsola.br();
1051
- konsola.info("For more information about the error, run the command with the `--verbose` flag");
1052
- }
1053
- if (!process.env.VITEST) {
1054
- console.log("");
1236
+ ui.br();
1237
+ ui.info("For more information about the error, run the command with the `--verbose` flag");
1055
1238
  }
1239
+ ui.br();
1056
1240
  getLogger().error(error.message, { error, errorCode: "code" in error ? String(error.code) : "UNKNOWN_ERROR", context });
1241
+ if (!process.exitCode) {
1242
+ process.exitCode = error instanceof CommandError ? 2 : 1;
1243
+ }
1057
1244
  }
1058
1245
  function logOnlyError(error, context) {
1059
1246
  getLogger().error(error.message, { error, errorCode: "code" in error ? String(error.code) : "UNKNOWN_ERROR", context });
@@ -1070,92 +1257,6 @@ function requireAuthentication(state, verbose = false) {
1070
1257
  return true;
1071
1258
  }
1072
1259
 
1073
- const toCamelCase = (str) => {
1074
- return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/_/g, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/[^a-z0-9]([a-z])/gi, (_, letter) => letter.toUpperCase()).replace(/[^a-z0-9]/gi, "");
1075
- };
1076
- const toPascalCase = (str) => {
1077
- const camelCase = toCamelCase(str);
1078
- return camelCase ? camelCase[0].toUpperCase() + camelCase.slice(1) : camelCase;
1079
- };
1080
- const capitalize = (str) => {
1081
- return str.charAt(0).toUpperCase() + str.slice(1);
1082
- };
1083
- const toHumanReadable = (str) => {
1084
- return str.replace(/[-_]/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ").replace(/\s+/g, " ").trim();
1085
- };
1086
- function maskToken(token) {
1087
- if (token.length <= 4) {
1088
- return token;
1089
- }
1090
- const visiblePart = token.slice(0, 4);
1091
- const maskedPart = "*".repeat(token.length - 4);
1092
- return `${visiblePart}${maskedPart}`;
1093
- }
1094
- const slugify = (text) => text.toString().toLowerCase().replace(/\s+/g, "-").replace(/[^\w-]+/g, "").replace(/-{2,}/g, "-").replace(/^-+/, "").replace(/-+$/, "");
1095
- function createRegexFromGlob(pattern) {
1096
- return new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*")}$`);
1097
- }
1098
-
1099
- function formatHeader(title) {
1100
- return `${title}`;
1101
- }
1102
- const konsola = {
1103
- title: (message, color, subtitle) => {
1104
- if (subtitle) {
1105
- console.log(`${formatHeader(chalk.bgHex(color).bold(` ${capitalize(message)} `))} ${subtitle}`);
1106
- } else {
1107
- console.log(formatHeader(chalk.bgHex(color).bold(` ${capitalize(message)} `)));
1108
- }
1109
- console.log("");
1110
- console.log("");
1111
- },
1112
- br: () => {
1113
- console.log("");
1114
- },
1115
- ok: (message, header = false) => {
1116
- if (header) {
1117
- console.log("");
1118
- const successHeader = chalk.bgGreen.bold.white(` Success `);
1119
- console.log(formatHeader(successHeader));
1120
- console.log("");
1121
- }
1122
- console.log(message ? `${chalk.green("\u2714")} ${message}` : "");
1123
- },
1124
- info: (message, options = {
1125
- header: false,
1126
- margin: true
1127
- }) => {
1128
- if (options.header) {
1129
- console.log("");
1130
- const infoHeader = chalk.bgBlue.bold.white(` Info `);
1131
- console.log(formatHeader(infoHeader));
1132
- }
1133
- console.log(message ? `${chalk.blue("\u2139")} ${message}` : "");
1134
- if (options.margin) {
1135
- console.error("");
1136
- }
1137
- },
1138
- warn: (message, header = false) => {
1139
- if (header) {
1140
- console.log("");
1141
- const warnHeader = chalk.bgYellow.bold.black(` Warning `);
1142
- console.warn(formatHeader(warnHeader));
1143
- }
1144
- console.warn(message ? `${chalk.yellow("\u26A0\uFE0F ")} ${message}` : "");
1145
- },
1146
- error: (message, info, options) => {
1147
- if (options?.header) {
1148
- const errorHeader = chalk.bgRed.bold.white(` Error `);
1149
- console.error(formatHeader(errorHeader));
1150
- console.log("");
1151
- }
1152
- console.error(`${chalk.red.bold("\u25B2 error")} ${message}`, info || "");
1153
- if (options?.margin) {
1154
- console.error("");
1155
- }
1156
- }
1157
- };
1158
-
1159
1260
  const __filename$2 = fileURLToPath(import.meta.url);
1160
1261
  const __dirname$2 = dirname(__filename$2);
1161
1262
  const result = await readPackageUp({
@@ -1167,7 +1268,7 @@ const packageJson$1 = result ? result.packageJson : {
1167
1268
  version: "0.0.0"
1168
1269
  };
1169
1270
  if (!result) {
1170
- console.debug("Metadata not found");
1271
+ console.error("Metadata not found");
1171
1272
  }
1172
1273
  function getPackageJson() {
1173
1274
  return packageJson$1;
@@ -1199,126 +1300,6 @@ function isRegion(value) {
1199
1300
  }
1200
1301
  const isVitest = process.env.VITEST === "true";
1201
1302
 
1202
- const noopProgressBar = {
1203
- increment: () => {
1204
- },
1205
- setTotal: () => {
1206
- },
1207
- stop: () => {
1208
- }
1209
- };
1210
- const noopSpinner = {
1211
- failed: (_title) => {
1212
- },
1213
- succeed: (_title) => {
1214
- },
1215
- elapsedTime: 0
1216
- };
1217
- class UI {
1218
- console;
1219
- enabled;
1220
- multiBar;
1221
- constructor({ enabled }) {
1222
- this.console = enabled ? console : null;
1223
- this.enabled = enabled;
1224
- this.multiBar = enabled ? new MultiBar({
1225
- clearOnComplete: false,
1226
- format: `${chalk.bold(" {title} ")} ${chalk.hex(colorPalette.PRIMARY)("[{bar}]")} {percentage}% | {eta_formatted} | {value}/{total} processed`,
1227
- etaBuffer: 60
1228
- }, Presets.rect) : null;
1229
- }
1230
- title(message, color, subtitle) {
1231
- if (subtitle) {
1232
- this.console?.log(`${chalk.bgHex(color).bold(` ${capitalize(message)} `)} ${subtitle}`);
1233
- } else {
1234
- this.console?.log(chalk.bgHex(color).bold(` ${capitalize(message)} `));
1235
- }
1236
- this.br();
1237
- this.br();
1238
- }
1239
- br() {
1240
- this.console?.log("");
1241
- }
1242
- ok(message, header = false) {
1243
- if (header) {
1244
- this.br();
1245
- const successHeader = chalk.bgGreen.bold.white(` Success `);
1246
- this.console?.log(successHeader);
1247
- this.br();
1248
- }
1249
- this.console?.log(message ? `${chalk.green("\u2714")} ${message}` : "");
1250
- }
1251
- info(message, options = {}) {
1252
- const { header = false, margin = true } = options;
1253
- if (header) {
1254
- this.br();
1255
- const infoHeader = chalk.bgBlue.bold.white(` Info `);
1256
- this.console?.info(infoHeader);
1257
- }
1258
- this.console?.info(message ? `${chalk.blue("\u2139")} ${message}` : "");
1259
- if (margin) {
1260
- this.br();
1261
- }
1262
- }
1263
- warn(message, header = false) {
1264
- if (header) {
1265
- this.br();
1266
- const warnHeader = chalk.bgYellow.bold.black(` Warning `);
1267
- this.console?.warn(warnHeader);
1268
- }
1269
- this.console?.warn(message ? `${chalk.yellow("\u26A0\uFE0F ")} ${message}` : "");
1270
- }
1271
- error(message, info, options = {}) {
1272
- const { header = false, margin = false } = options;
1273
- if (header) {
1274
- const errorHeader = chalk.bgRed.bold.white(` Error `);
1275
- this.console?.error(errorHeader);
1276
- this.br();
1277
- }
1278
- this.console?.error(`${chalk.red.bold("\u25B2 error")} ${message}`, info || "");
1279
- if (margin) {
1280
- this.br();
1281
- }
1282
- }
1283
- /** Plain console.log passthrough — use for preformatted or multi-line text. */
1284
- log(message) {
1285
- this.console?.log(message);
1286
- }
1287
- list(items) {
1288
- for (const item of items) {
1289
- this.console?.log(` ${item}`);
1290
- }
1291
- }
1292
- createProgressBar(options) {
1293
- const bar = this.multiBar?.create(0, 0, options);
1294
- if (!bar) {
1295
- return noopProgressBar;
1296
- }
1297
- return {
1298
- increment: (count = 1) => bar.increment(count),
1299
- // cli-progress renders `{eta_formatted}` as "LLs" when total is 0.
1300
- // Floor at 1 so an empty phase stays a clean 0/1 instead.
1301
- setTotal: (total) => bar.setTotal(Math.max(total, 1)),
1302
- stop: () => bar.stop()
1303
- };
1304
- }
1305
- stopAllProgressBars() {
1306
- this.multiBar?.stop();
1307
- }
1308
- createSpinner(title) {
1309
- return this.enabled ? new Spinner({
1310
- verbose: !isVitest
1311
- }).start(title) : noopSpinner;
1312
- }
1313
- }
1314
- let uiInstance = null;
1315
- function getUI(options = { enabled: false }) {
1316
- if (!uiInstance) {
1317
- uiInstance = new UI(options);
1318
- }
1319
- return uiInstance;
1320
- }
1321
-
1322
1303
  const DEFAULT_STORAGE_DIR = ".storyblok";
1323
1304
  const getStoryblokGlobalPath = () => {
1324
1305
  const homeDirectory = process.env[process.platform.startsWith("win") ? "USERPROFILE" : "HOME"] || process.cwd();
@@ -1698,20 +1679,7 @@ class ConsoleTransport {
1698
1679
  return;
1699
1680
  }
1700
1681
  const line = this.format(record);
1701
- switch (record.level) {
1702
- case "error":
1703
- (console.error ?? console.log).call(console, line);
1704
- break;
1705
- case "warn":
1706
- (console.warn ?? console.log).call(console, line);
1707
- break;
1708
- case "info":
1709
- (console.info ?? console.log).call(console, line);
1710
- break;
1711
- case "debug":
1712
- (console.debug ?? console.log).call(console, line);
1713
- break;
1714
- }
1682
+ console.error(line);
1715
1683
  }
1716
1684
  levelRank(level) {
1717
1685
  switch (level) {
@@ -2028,8 +1996,9 @@ function getProgram() {
2028
1996
  }
2029
1997
  }
2030
1998
  });
1999
+ programInstance.exitOverride();
2031
2000
  programInstance.configureOutput({
2032
- writeErr: (str) => handleError(new Error(str))
2001
+ writeErr: (str) => handleError(new CommandError(str.replace(/^error:\s*/i, "").trim()))
2033
2002
  });
2034
2003
  }
2035
2004
  return programInstance;
@@ -2094,9 +2063,8 @@ const loginWithOtp = async (email, password, otp, region) => {
2094
2063
 
2095
2064
  async function performInteractiveLogin(options) {
2096
2065
  const { verbose = false, preSelectedRegion, showWelcomeMessage = true } = options || {};
2097
- const spinner = new Spinner({
2098
- verbose: !isVitest
2099
- });
2066
+ const ui = getUI();
2067
+ let activeSpinner = null;
2100
2068
  try {
2101
2069
  const strategy = await select({
2102
2070
  message: "How would you like to login?",
@@ -2112,11 +2080,11 @@ async function performInteractiveLogin(options) {
2112
2080
  short: "Token"
2113
2081
  }
2114
2082
  ]
2115
- });
2083
+ }, stderrPromptContext);
2116
2084
  let userToken;
2117
2085
  let userRegion;
2118
2086
  if (strategy === "login-with-token") {
2119
- konsola.info([
2087
+ ui.info([
2120
2088
  "\u{1F511} You can use a Personal Access Token to log in.",
2121
2089
  "This works for all accounts, including SSO accounts.",
2122
2090
  `Generate one in your Storyblok account settings: ${chalk.underline.blue("https://app.storyblok.com/#/me/account?tab=token")}`
@@ -2126,7 +2094,7 @@ async function performInteractiveLogin(options) {
2126
2094
  validate: (value) => {
2127
2095
  return value.length > 0;
2128
2096
  }
2129
- });
2097
+ }, stderrPromptContext);
2130
2098
  userRegion = preSelectedRegion || await select({
2131
2099
  message: "Please select the region you would like to work in:",
2132
2100
  choices: Object.values(regions).map((region) => ({
@@ -2134,16 +2102,16 @@ async function performInteractiveLogin(options) {
2134
2102
  value: region
2135
2103
  })),
2136
2104
  default: regions.EU
2137
- });
2138
- spinner.start(`Logging in with token`);
2105
+ }, stderrPromptContext);
2106
+ activeSpinner = ui.createSpinner(`Logging in with token`);
2139
2107
  const user = await loginWithToken(userToken, userRegion);
2140
- spinner.succeed();
2108
+ activeSpinner.succeed();
2141
2109
  if (user) {
2142
2110
  const { updateSession, persistCredentials } = session();
2143
2111
  updateSession(user.email, userToken, userRegion);
2144
2112
  await persistCredentials(userRegion);
2145
2113
  if (showWelcomeMessage) {
2146
- konsola.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(user.friendly_name)}.`, true);
2114
+ ui.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(user.friendly_name)}.`, true);
2147
2115
  }
2148
2116
  return { token: userToken, region: userRegion };
2149
2117
  }
@@ -2155,10 +2123,10 @@ async function performInteractiveLogin(options) {
2155
2123
  const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
2156
2124
  return emailRegex.test(value);
2157
2125
  }
2158
- });
2126
+ }, stderrPromptContext);
2159
2127
  const userPassword = await password({
2160
2128
  message: "Please enter your password:"
2161
- });
2129
+ }, stderrPromptContext);
2162
2130
  userRegion = preSelectedRegion || await select({
2163
2131
  message: "Please select the region you would like to work in:",
2164
2132
  choices: Object.values(regions).map((region) => ({
@@ -2166,15 +2134,15 @@ async function performInteractiveLogin(options) {
2166
2134
  value: region
2167
2135
  })),
2168
2136
  default: regions.EU
2169
- });
2170
- spinner.start(`Logging in with email`);
2171
- spinner.succeed();
2137
+ }, stderrPromptContext);
2138
+ activeSpinner = ui.createSpinner(`Logging in with email`);
2172
2139
  const response = await loginWithEmailAndPassword(userEmail, userPassword, userRegion);
2140
+ activeSpinner.succeed();
2173
2141
  if (response?.otp_required) {
2174
2142
  const otp = await input({
2175
2143
  message: "Add the code from your Authenticator app, or the one we sent to your e-mail / phone:",
2176
2144
  required: true
2177
- });
2145
+ }, stderrPromptContext);
2178
2146
  const otpResponse = await loginWithOtp(userEmail, userPassword, otp, userRegion);
2179
2147
  if (otpResponse?.access_token) {
2180
2148
  userToken = otpResponse.access_token;
@@ -2187,15 +2155,15 @@ async function performInteractiveLogin(options) {
2187
2155
  updateSession(userEmail, userToken, userRegion);
2188
2156
  await persistCredentials(userRegion);
2189
2157
  if (showWelcomeMessage) {
2190
- konsola.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(userEmail)}.`, true);
2158
+ ui.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(userEmail)}.`, true);
2191
2159
  }
2192
2160
  return { token: userToken, region: userRegion };
2193
2161
  }
2194
2162
  }
2195
2163
  return null;
2196
2164
  } catch (error) {
2197
- spinner.failed();
2198
- konsola.br();
2165
+ activeSpinner?.failed();
2166
+ ui.br();
2199
2167
  handleError(error, verbose);
2200
2168
  return null;
2201
2169
  }
@@ -2207,12 +2175,13 @@ program$f.command(commands.LOGIN).description("Login to the Storyblok CLI").opti
2207
2175
  "-r, --region <region>",
2208
2176
  `The region you would like to work in. Please keep in mind that the region must match the region of your space. This region flag will be used for the other cli's commands. You can use the values: ${allRegionsText}.`
2209
2177
  ).action(async (options) => {
2210
- konsola.title(`${commands.LOGIN}`, colorPalette.LOGIN);
2178
+ const ui = getUI();
2179
+ ui.title(`${commands.LOGIN}`, colorPalette.LOGIN);
2211
2180
  const verbose = program$f.opts().verbose;
2212
2181
  const { token, region } = options;
2213
2182
  const { state, updateSession, persistCredentials } = session();
2214
2183
  if (state.isLoggedIn && !state.envLogin) {
2215
- konsola.ok(`You are already logged in. If you want to login with a different account, please logout first.`);
2184
+ ui.ok(`You are already logged in. If you want to login with a different account, please logout first.`);
2216
2185
  return;
2217
2186
  }
2218
2187
  if (region && !isRegion(region)) {
@@ -2220,9 +2189,7 @@ program$f.command(commands.LOGIN).description("Login to the Storyblok CLI").opti
2220
2189
  return;
2221
2190
  }
2222
2191
  if (token) {
2223
- const spinner = new Spinner({
2224
- verbose: !isVitest
2225
- });
2192
+ let spinner = null;
2226
2193
  try {
2227
2194
  let userRegion = region;
2228
2195
  if (!userRegion) {
@@ -2233,19 +2200,19 @@ program$f.command(commands.LOGIN).description("Login to the Storyblok CLI").opti
2233
2200
  value: region2
2234
2201
  })),
2235
2202
  default: regions.EU
2236
- });
2203
+ }, stderrPromptContext);
2237
2204
  }
2238
- spinner.start(`Logging in with token`);
2205
+ spinner = ui.createSpinner(`Logging in with token`);
2239
2206
  const user = await loginWithToken(token, userRegion);
2240
2207
  if (user) {
2241
2208
  updateSession(user.email, token, userRegion);
2242
2209
  await persistCredentials(userRegion);
2243
2210
  spinner.succeed();
2244
- konsola.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(user.friendly_name)}.`, true);
2211
+ ui.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(user.friendly_name)}.`, true);
2245
2212
  }
2246
2213
  } catch (error) {
2247
- spinner.failed();
2248
- konsola.br();
2214
+ spinner?.failed();
2215
+ ui.br();
2249
2216
  handleError(error, verbose);
2250
2217
  }
2251
2218
  } else {
@@ -2256,34 +2223,35 @@ program$f.command(commands.LOGIN).description("Login to the Storyblok CLI").opti
2256
2223
  showWelcomeMessage: true
2257
2224
  });
2258
2225
  if (!result) {
2259
- konsola.warn("Login cancelled or failed.");
2226
+ ui.warn("Login cancelled or failed.");
2260
2227
  }
2261
2228
  } catch (error) {
2262
- konsola.br();
2229
+ ui.br();
2263
2230
  handleError(error, verbose);
2264
2231
  }
2265
2232
  }
2266
- konsola.br();
2233
+ ui.br();
2267
2234
  });
2268
2235
 
2269
2236
  const program$e = getProgram();
2270
2237
  program$e.command(commands.LOGOUT).description("Logout from the Storyblok CLI").action(async () => {
2271
- konsola.title(`${commands.LOGOUT}`, colorPalette.LOGOUT);
2238
+ const ui = getUI();
2239
+ ui.title(`${commands.LOGOUT}`, colorPalette.LOGOUT);
2272
2240
  const verbose = program$e.opts().verbose;
2273
2241
  try {
2274
2242
  const { state } = session();
2275
2243
  if (!state.isLoggedIn || !state.password || !state.region) {
2276
- konsola.warn(`You are already logged out. If you want to login, please use the login command.`);
2277
- konsola.br();
2244
+ ui.warn(`You are already logged out. If you want to login, please use the login command.`);
2245
+ ui.br();
2278
2246
  return;
2279
2247
  }
2280
2248
  await removeAllCredentials();
2281
- konsola.ok(`Successfully logged out.`, true);
2282
- konsola.br();
2249
+ ui.ok(`Successfully logged out.`, true);
2250
+ ui.br();
2283
2251
  } catch (error) {
2284
2252
  handleError(error, verbose);
2285
2253
  }
2286
- konsola.br();
2254
+ ui.br();
2287
2255
  });
2288
2256
 
2289
2257
  const execAsync = promisify(exec);
@@ -2318,39 +2286,39 @@ async function openSignupInBrowser(url) {
2318
2286
 
2319
2287
  const program$d = getProgram();
2320
2288
  program$d.command(commands.SIGNUP).description("Sign up for Storyblok").action(async () => {
2321
- konsola.title(`${commands.SIGNUP}`, colorPalette.SIGNUP);
2289
+ const ui = getUI();
2290
+ ui.title(`${commands.SIGNUP}`, colorPalette.SIGNUP);
2322
2291
  const verbose = program$d.opts().verbose;
2323
2292
  const { state } = session();
2324
2293
  if (state.isLoggedIn && !state.envLogin) {
2325
- konsola.ok(`You are already logged in. If you want to signup with a different account, please logout first.`);
2294
+ ui.ok(`You are already logged in. If you want to signup with a different account, please logout first.`);
2326
2295
  return;
2327
2296
  }
2328
2297
  try {
2329
2298
  const signupUrl = buildSignupUrl();
2330
- konsola.info(`Opening Storyblok signup page...`);
2331
- konsola.info(`URL: ${chalk.dim(signupUrl)}`);
2299
+ ui.info(`Opening Storyblok signup page...`);
2300
+ ui.info(`URL: ${chalk.dim(signupUrl)}`);
2332
2301
  await openSignupInBrowser(signupUrl);
2333
- konsola.ok(`Browser opened! Please complete the signup process.`);
2334
- konsola.br();
2335
- konsola.info(`Once you've completed signup, run ${chalk.hex(colorPalette.PRIMARY)("storyblok login")} to authenticate with the CLI.`);
2302
+ ui.ok(`Browser opened! Please complete the signup process.`);
2303
+ ui.br();
2304
+ ui.info(`Once you've completed signup, run ${chalk.hex(colorPalette.PRIMARY)("storyblok login")} to authenticate with the CLI.`);
2336
2305
  } catch (error) {
2337
- konsola.br();
2306
+ ui.br();
2338
2307
  handleError(error, verbose);
2339
2308
  }
2340
- konsola.br();
2309
+ ui.br();
2341
2310
  });
2342
2311
 
2343
2312
  const program$c = getProgram();
2344
2313
  program$c.command(commands.USER).description("Get the current user").action(async () => {
2345
- konsola.title(`${commands.USER}`, colorPalette.USER);
2314
+ const ui = getUI();
2315
+ ui.title(`${commands.USER}`, colorPalette.USER);
2346
2316
  const verbose = program$c.opts().verbose;
2347
2317
  const { state } = session();
2348
2318
  if (!requireAuthentication(state)) {
2349
2319
  return;
2350
2320
  }
2351
- const spinner = new Spinner({
2352
- verbose: !isVitest
2353
- }).start(`Fetching user info`);
2321
+ const spinner = ui.createSpinner(`Fetching user info`);
2354
2322
  try {
2355
2323
  const { password, region } = state;
2356
2324
  if (!password || !region) {
@@ -2359,16 +2327,16 @@ program$c.command(commands.USER).description("Get the current user").action(asyn
2359
2327
  const user = await getUser(password, region);
2360
2328
  if (user) {
2361
2329
  if (verbose) {
2362
- konsola.info(JSON.stringify(user, null, 2));
2330
+ ui.info(JSON.stringify(user, null, 2));
2363
2331
  }
2364
2332
  spinner.succeed();
2365
- konsola.ok(`Hi ${chalk.bold(user.friendly_name)}, you are currently logged in with ${chalk.hex(colorPalette.PRIMARY)(user.email)} on ${chalk.bold(region)} region`, true);
2333
+ ui.ok(`Hi ${chalk.bold(user.friendly_name)}, you are currently logged in with ${chalk.hex(colorPalette.PRIMARY)(user.email)} on ${chalk.bold(region)} region`, true);
2366
2334
  }
2367
2335
  } catch (error) {
2368
2336
  spinner.failed();
2369
2337
  handleError(error, true);
2370
2338
  }
2371
- konsola.br();
2339
+ ui.br();
2372
2340
  });
2373
2341
 
2374
2342
  const program$b = getProgram();
@@ -2855,7 +2823,7 @@ function buildDependencyGraph(context) {
2855
2823
  const nodeId = `preset:${preset.id}`;
2856
2824
  const sourceComponent = componentMap.get(preset.component_id);
2857
2825
  if (!sourceComponent) {
2858
- console.warn(`Warning: Preset "${preset.name}" (ID: ${preset.id}) references component ID ${preset.component_id} which is not available in local data. Skipping preset.`);
2826
+ getLogger().warn(`Preset "${preset.name}" (ID: ${preset.id}) references component ID ${preset.component_id} which is not available in local data. Skipping preset.`);
2859
2827
  return;
2860
2828
  }
2861
2829
  const compositeKey = `${sourceComponent.name}:${preset.name}`;
@@ -3128,17 +3096,18 @@ function determineProcessingOrder(graph) {
3128
3096
  return levels;
3129
3097
  }
3130
3098
  function validateGraph(graph) {
3131
- console.log(`\u{1F4CA} Built dependency graph with ${graph.nodes.size} nodes`);
3099
+ const logger = getLogger();
3100
+ logger.info(`Built dependency graph with ${graph.nodes.size} nodes`);
3132
3101
  const problematicCycles = detectProblematicCycles(graph);
3133
3102
  if (problematicCycles.length > 0) {
3134
- throw new Error(`\u274C Problematic cycles detected:
3103
+ throw new Error(`Problematic cycles detected:
3135
3104
  ${problematicCycles.join("\n")}`);
3136
3105
  }
3137
3106
  const circularWhitelists = detectCircularWhitelists(graph);
3138
3107
  if (circularWhitelists.length > 0) {
3139
- console.log(`\u2139\uFE0F Circular component whitelists detected (allowed): ${circularWhitelists.join(", ")}`);
3108
+ logger.info(`Circular component whitelists detected (allowed): ${circularWhitelists.join(", ")}`);
3140
3109
  }
3141
- console.log(`\u2705 Graph validation passed`);
3110
+ logger.info(`Graph validation passed`);
3142
3111
  }
3143
3112
  class GraphNode {
3144
3113
  id;
@@ -3578,31 +3547,49 @@ pullCmd$4.action(async (componentName, options, command) => {
3578
3547
  return;
3579
3548
  }
3580
3549
  logger.info("Pulling components started", { space, componentName });
3581
- const spinnerGroups = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.COMPONENTS)("components groups")}`);
3582
- const spinnerPresets = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.COMPONENTS)("components presets")}`);
3583
- const spinnerInternalTags = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.COMPONENTS)("components internal tags")}`);
3584
- const spinnerComponents = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.COMPONENTS)("components")}`);
3550
+ const pad = "Components".length;
3551
+ const barGroups = ui.createProgressBar({ title: "Groups".padEnd(pad) });
3552
+ const barPresets = ui.createProgressBar({ title: "Presets".padEnd(pad) });
3553
+ const barTags = ui.createProgressBar({ title: "Tags".padEnd(pad) });
3554
+ const barComponents = ui.createProgressBar({ title: "Components" });
3555
+ barGroups.setTotal(1);
3556
+ barPresets.setTotal(1);
3557
+ barTags.setTotal(1);
3558
+ barComponents.setTotal(1);
3585
3559
  try {
3586
- let groups = await fetchComponentGroups(space);
3587
- spinnerGroups.succeed(`${chalk.hex(colorPalette.COMPONENTS)("Groups")} - Completed in ${spinnerGroups.elapsedTime.toFixed(2)}ms`);
3588
- let presets = await fetchComponentPresets(space);
3589
- spinnerPresets.succeed(`${chalk.hex(colorPalette.COMPONENTS)("Presets")} - Completed in ${spinnerPresets.elapsedTime.toFixed(2)}ms`);
3590
- let internalTags = await fetchComponentInternalTags(space);
3591
- spinnerInternalTags.succeed(`${chalk.hex(colorPalette.COMPONENTS)("Tags")} - Completed in ${spinnerInternalTags.elapsedTime.toFixed(2)}ms`);
3560
+ const componentsFetch = componentName ? fetchComponent(space, componentName).then((c) => c ? [c] : void 0) : fetchComponents(space);
3561
+ const [groupsResult, presetsResult, tagsResult, componentsResult] = await Promise.all([
3562
+ fetchComponentGroups(space),
3563
+ fetchComponentPresets(space),
3564
+ fetchComponentInternalTags(space),
3565
+ componentsFetch
3566
+ ]);
3567
+ let groups = groupsResult;
3568
+ logger.info("Fetched groups", { count: groups?.length ?? 0 });
3569
+ barGroups.increment();
3570
+ let presets = presetsResult;
3571
+ logger.info("Fetched presets", { count: presets?.length ?? 0 });
3572
+ barPresets.increment();
3573
+ let internalTags = tagsResult;
3574
+ logger.info("Fetched tags", { count: internalTags?.length ?? 0 });
3575
+ barTags.increment();
3592
3576
  let components;
3593
3577
  if (componentName) {
3594
- const component = await fetchComponent(space, componentName);
3595
- if (!component) {
3596
- spinnerComponents.failed(`No component found with name "${componentName}"`);
3578
+ if (!componentsResult || componentsResult.length === 0) {
3579
+ barComponents.stop();
3580
+ ui.stopAllProgressBars();
3581
+ handleError(new CommandError(`No component found with name "${componentName}"`), verbose);
3597
3582
  return;
3598
3583
  }
3599
- components = [component];
3584
+ components = componentsResult;
3600
3585
  } else {
3601
- components = await fetchComponents(space);
3602
- if (!components || components.length === 0) {
3603
- spinnerComponents.failed(`No components found in the space ${space}`);
3586
+ if (!componentsResult || componentsResult.length === 0) {
3587
+ barComponents.stop();
3588
+ ui.stopAllProgressBars();
3589
+ handleError(new CommandError(`No components found in the space ${space}`), verbose);
3604
3590
  return;
3605
3591
  }
3592
+ components = componentsResult;
3606
3593
  const hasSelectors = Boolean(filter) || group && group.length > 0 || tag && tag.length > 0;
3607
3594
  if (hasSelectors) {
3608
3595
  const groupUuids = group && group.length > 0 ? new Set(group.flatMap((g) => [...resolveGroupSelector(groups || [], g)])) : void 0;
@@ -3612,7 +3599,8 @@ pullCmd$4.action(async (componentName, options, command) => {
3612
3599
  { filter, groupUuids, tagIds }
3613
3600
  );
3614
3601
  if (filtered.components.length === 0) {
3615
- spinnerComponents.failed("No components found matching the given selectors.");
3602
+ barComponents.stop();
3603
+ ui.stopAllProgressBars();
3616
3604
  ui.warn("No components found matching the given selectors.");
3617
3605
  return;
3618
3606
  }
@@ -3622,7 +3610,13 @@ pullCmd$4.action(async (componentName, options, command) => {
3622
3610
  internalTags = filtered.internalTags;
3623
3611
  }
3624
3612
  }
3625
- spinnerComponents.succeed(`${chalk.hex(colorPalette.COMPONENTS)("Components")} - Completed in ${spinnerComponents.elapsedTime.toFixed(2)}ms`);
3613
+ logger.info("Fetched components", { count: components.length });
3614
+ barComponents.increment();
3615
+ barGroups.stop();
3616
+ barPresets.stop();
3617
+ barTags.stop();
3618
+ barComponents.stop();
3619
+ ui.stopAllProgressBars();
3626
3620
  await saveComponentsToFiles(
3627
3621
  space,
3628
3622
  { components, groups: groups || [], presets: presets || [], internalTags: internalTags || [], datasources: [] },
@@ -3649,10 +3643,11 @@ pullCmd$4.action(async (componentName, options, command) => {
3649
3643
  }
3650
3644
  ui.br();
3651
3645
  } catch (error) {
3652
- spinnerGroups.failed(`Pulling ${chalk.hex(colorPalette.COMPONENTS)("Groups")} - Failed`);
3653
- spinnerPresets.failed(`Pulling ${chalk.hex(colorPalette.COMPONENTS)("Presets")} - Failed`);
3654
- spinnerInternalTags.failed(`Pulling ${chalk.hex(colorPalette.COMPONENTS)("Tags")} - Failed`);
3655
- spinnerComponents.failed(`Pulling ${chalk.hex(colorPalette.COMPONENTS)("Components")} - Failed`);
3646
+ barGroups.stop();
3647
+ barPresets.stop();
3648
+ barTags.stop();
3649
+ barComponents.stop();
3650
+ ui.stopAllProgressBars();
3656
3651
  ui.br();
3657
3652
  handleError(error, verbose);
3658
3653
  } finally {
@@ -3660,143 +3655,60 @@ pullCmd$4.action(async (componentName, options, command) => {
3660
3655
  }
3661
3656
  });
3662
3657
 
3663
- class ProgressDisplay {
3664
- total = 0;
3665
- processed = 0;
3666
- updated = 0;
3667
- unchanged = 0;
3668
- failed = 0;
3669
- currentProgressLine = "";
3670
- // Track start time for calculating elapsed time on completion
3671
- startTime = null;
3672
- start(total) {
3673
- this.total = total;
3674
- this.processed = 0;
3675
- this.updated = 0;
3676
- this.unchanged = 0;
3677
- this.failed = 0;
3678
- this.startTime = Date.now();
3679
- konsola.br();
3680
- console.log(`Processing ${total} resources...`);
3681
- this.updateProgress();
3682
- }
3683
- handleEvent(event) {
3684
- switch (event.type) {
3685
- case "start":
3686
- this.start(event.total);
3687
- break;
3688
- case "success": {
3689
- this.processed++;
3690
- this.updated++;
3691
- this.clearProgress();
3692
- const successTimeString = event.elapsedMs ? chalk.dim(` (${this.formatElapsedTime(event.elapsedMs)})`) : "";
3693
- console.log(`${chalk.green("\u2713")} ${this.capitalize(event.resourceType)}\u2192 ${chalk.hex(event.color)(event.name)} - Updated${successTimeString}`);
3694
- this.updateProgress();
3695
- break;
3696
- }
3697
- case "skip": {
3698
- this.processed++;
3699
- this.unchanged++;
3700
- const skipTimeString = event.elapsedMs && event.elapsedMs > 10 ? chalk.dim(` (${this.formatElapsedTime(event.elapsedMs)})`) : "";
3701
- if (skipTimeString) {
3702
- this.clearProgress();
3703
- console.log(`${chalk.dim("\u2014")} ${this.capitalize(event.resourceType)}\u2192 ${chalk.dim(event.name)} - Skipped${skipTimeString}`);
3704
- }
3705
- this.updateProgress();
3706
- break;
3707
- }
3708
- case "error": {
3709
- this.processed++;
3710
- this.failed++;
3711
- this.clearProgress();
3712
- const errorTimeString = event.elapsedMs ? chalk.dim(` (${this.formatElapsedTime(event.elapsedMs)})`) : "";
3713
- console.log(`${chalk.red("\u2717")} ${this.capitalize(event.resourceType)}\u2192 ${chalk.red(event.name)} - Failed${errorTimeString}`);
3714
- this.updateProgress();
3715
- break;
3716
- }
3717
- case "complete": {
3718
- this.clearProgress();
3719
- const { updated, unchanged, failed } = event.summary;
3720
- const elapsedTime = this.startTime ? Date.now() - this.startTime : null;
3721
- const timeString = elapsedTime ? this.formatElapsedTime(elapsedTime) : "";
3722
- konsola.ok(`Completed: ${updated} updated, ${unchanged} unchanged, ${failed} failed${timeString ? ` in ${timeString}` : ""}`, true);
3723
- konsola.br();
3724
- if (unchanged > 5) {
3725
- console.log(chalk.dim(` (${unchanged} resources were already up-to-date)`));
3726
- }
3727
- break;
3658
+ async function processAllResources(graph, space, backpressure = getActiveConfig().api.rateLimit) {
3659
+ const ui = getUI();
3660
+ const logger = getLogger();
3661
+ const levels = determineProcessingOrder(graph);
3662
+ const results = { successful: [], failed: [] };
3663
+ const countByType = /* @__PURE__ */ new Map();
3664
+ for (const level of levels) {
3665
+ for (const nodeId of level.nodes) {
3666
+ const node = graph.nodes.get(nodeId);
3667
+ if (node) {
3668
+ countByType.set(node.type, (countByType.get(node.type) ?? 0) + 1);
3728
3669
  }
3729
3670
  }
3730
3671
  }
3731
- updateProgress() {
3732
- this.currentProgressLine = `[${this.processed}/${this.total}] ${this.updated} updated, ${this.unchanged} unchanged, ${this.failed} failed`;
3733
- process.stdout.write(`\r${this.currentProgressLine}`);
3734
- }
3735
- clearProgress() {
3736
- if (this.currentProgressLine) {
3737
- process.stdout.write(`\r${" ".repeat(this.currentProgressLine.length)}\r`);
3672
+ logger.info("Processing order determined", {
3673
+ levels: levels.length,
3674
+ totalResources: Array.from(countByType.values()).reduce((a, b) => a + b, 0),
3675
+ cyclic: levels.filter((l) => l.isCyclic).length
3676
+ });
3677
+ const typeOrder = ["tag", "group", "component", "preset"];
3678
+ const typeLabels = { tag: "Tags", group: "Groups", component: "Components", preset: "Presets" };
3679
+ const pad = Math.max(...Object.values(typeLabels).map((l) => l.length));
3680
+ const bars = /* @__PURE__ */ new Map();
3681
+ for (const type of typeOrder) {
3682
+ const count = countByType.get(type);
3683
+ if (count && count > 0) {
3684
+ const bar = ui.createProgressBar({ title: typeLabels[type].padEnd(pad) });
3685
+ bar.setTotal(count);
3686
+ bars.set(type, bar);
3738
3687
  }
3739
3688
  }
3740
- capitalize(str) {
3741
- return str.charAt(0).toUpperCase() + str.slice(1);
3742
- }
3743
- /**
3744
- * Formats elapsed time in milliseconds to a human-readable string
3745
- * @param ms - Time in milliseconds
3746
- * @returns Formatted time string (e.g., "1.2s", "2m 30s", "1h 5m")
3747
- */
3748
- formatElapsedTime(ms) {
3749
- if (ms < 1e3) {
3750
- return `${ms}ms`;
3751
- }
3752
- const seconds = Math.floor(ms / 1e3);
3753
- const minutes = Math.floor(seconds / 60);
3754
- const hours = Math.floor(minutes / 60);
3755
- if (hours > 0) {
3756
- const remainingMinutes = minutes % 60;
3757
- return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
3758
- }
3759
- if (minutes > 0) {
3760
- const remainingSeconds = seconds % 60;
3761
- return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
3689
+ try {
3690
+ for (const level of levels) {
3691
+ if (level.isCyclic) {
3692
+ const cyclicResults = await processCyclicLevel(level, graph, space, backpressure, bars);
3693
+ mergeResults(results, cyclicResults);
3694
+ } else {
3695
+ const levelResults = await processLevel(level.nodes, graph, space, backpressure, bars);
3696
+ mergeResults(results, levelResults);
3697
+ }
3762
3698
  }
3763
- const preciseSeconds = (ms / 1e3).toFixed(1);
3764
- return `${preciseSeconds}s`;
3765
- }
3766
- }
3767
- const progressDisplay = new ProgressDisplay();
3768
-
3769
- async function processAllResources(graph, space, backpressure = getActiveConfig().api.rateLimit) {
3770
- const levels = determineProcessingOrder(graph);
3771
- const results = { successful: [], failed: [] };
3772
- const totalResources = levels.reduce((sum, level) => sum + level.nodes.length, 0);
3773
- progressDisplay.start(totalResources);
3774
- for (const level of levels) {
3775
- if (level.isCyclic) {
3776
- const cyclicResults = await processCyclicLevel(level, graph, space, backpressure);
3777
- mergeResults(results, cyclicResults);
3778
- } else {
3779
- const levelResults = await processLevel(level.nodes, graph, space, backpressure);
3780
- mergeResults(results, levelResults);
3699
+ } finally {
3700
+ for (const bar of bars.values()) {
3701
+ bar.stop();
3781
3702
  }
3703
+ ui.stopAllProgressBars();
3782
3704
  }
3783
- progressDisplay.handleEvent({
3784
- type: "complete",
3785
- summary: {
3786
- updated: results.successful.length,
3787
- unchanged: 0,
3788
- // No longer skip resources - all are processed
3789
- failed: results.failed.length
3790
- }
3791
- });
3792
3705
  return results;
3793
3706
  }
3794
- async function processCyclicLevel(level, graph, space, backpressure) {
3795
- progressDisplay.clearProgress();
3796
- console.log(`
3797
- \u{1F504} Detected circular dependencies: ${level.nodes.map((id) => id.replace("component:", "")).join(", ")}`);
3707
+ async function processCyclicLevel(level, graph, space, backpressure, bars) {
3708
+ const logger = getLogger();
3709
+ logger.warn(`Detected circular dependencies: ${level.nodes.map((id) => id.replace("component:", "")).join(", ")}`);
3798
3710
  await createStubComponents(level.nodes, graph, space);
3799
- return await processLevel(level.nodes, graph, space, backpressure);
3711
+ return await processLevel(level.nodes, graph, space, backpressure, bars);
3800
3712
  }
3801
3713
  async function createStubComponents(nodeIds, graph, space) {
3802
3714
  const missingComponents = [];
@@ -3809,7 +3721,8 @@ async function createStubComponents(nodeIds, graph, space) {
3809
3721
  if (missingComponents.length === 0) {
3810
3722
  return;
3811
3723
  }
3812
- console.log(`\u{1F4DD} Creating stub components for circular dependencies: ${missingComponents.join(", ")}`);
3724
+ const logger = getLogger();
3725
+ logger.info(`Creating stub components for circular dependencies: ${missingComponents.join(", ")}`);
3813
3726
  for (const nodeId of nodeIds) {
3814
3727
  const node = graph.nodes.get(nodeId);
3815
3728
  if (node && node.type === "component" && !node.targetData) {
@@ -3818,15 +3731,14 @@ async function createStubComponents(nodeIds, graph, space) {
3818
3731
  const result = await pushComponent(space, stubComponent);
3819
3732
  if (result) {
3820
3733
  node.updateTargetData(result);
3821
- console.log(`${chalk.green("\u2713")} Created stub component: ${node.name}`);
3734
+ logger.info(`Created stub component: ${node.name}`);
3822
3735
  }
3823
3736
  } catch (error) {
3824
- console.error(`\u2717 Failed to create stub component ${node.name}:`, error);
3737
+ logger.error(`Failed to create stub component ${node.name}`, { error });
3825
3738
  throw error;
3826
3739
  }
3827
3740
  }
3828
3741
  }
3829
- console.log("");
3830
3742
  }
3831
3743
  function createMinimalStubComponent(name) {
3832
3744
  return {
@@ -3836,10 +3748,12 @@ function createMinimalStubComponent(name) {
3836
3748
  // Minimal empty schema
3837
3749
  };
3838
3750
  }
3839
- async function processLevel(level, graph, space, backpressure) {
3751
+ async function processLevel(level, graph, space, backpressure, bars) {
3752
+ const logger = getLogger();
3840
3753
  for (const nodeId of level) {
3841
3754
  const node = graph.nodes.get(nodeId);
3842
3755
  node.resolveReferences(graph);
3756
+ logger.info(`Resolved references: ${node.getName()}`, { type: node.type });
3843
3757
  }
3844
3758
  const semaphore = Array.from({ length: backpressure }, () => null);
3845
3759
  const promises = [];
@@ -3849,37 +3763,29 @@ async function processLevel(level, graph, space, backpressure) {
3849
3763
  if (i >= backpressure && semaphore[slotIndex]) {
3850
3764
  await semaphore[slotIndex];
3851
3765
  }
3852
- const promise = processNode(nodeId, graph, space);
3766
+ const promise = processNode(nodeId, graph, space, bars);
3853
3767
  promises.push(promise);
3854
3768
  semaphore[slotIndex] = promise;
3855
3769
  }
3856
3770
  const results = await Promise.all(promises);
3857
3771
  return aggregateResults(results);
3858
3772
  }
3859
- async function processNode(nodeId, graph, space) {
3773
+ async function processNode(nodeId, graph, space, bars) {
3860
3774
  const node = graph.nodes.get(nodeId);
3775
+ const logger = getLogger();
3861
3776
  const startTime = Date.now();
3862
3777
  try {
3778
+ logger.info(`Upserting ${node.type}: ${node.getName()}`);
3863
3779
  const result = await node.upsert(space);
3864
3780
  node.updateTargetData(result);
3865
3781
  const elapsedMs = Date.now() - startTime;
3866
- progressDisplay.handleEvent({
3867
- type: "success",
3868
- name: node.getName(),
3869
- resourceType: getResourceTypeName(node.type),
3870
- color: getResourceTypeColor(node.type),
3871
- elapsedMs
3872
- });
3782
+ logger.info(`Upserted ${node.type}: ${node.getName()}`, { elapsedMs });
3783
+ bars.get(node.type)?.increment();
3873
3784
  return { name: node.getName() };
3874
3785
  } catch (error) {
3875
3786
  const elapsedMs = Date.now() - startTime;
3876
- progressDisplay.handleEvent({
3877
- type: "error",
3878
- name: node.getName(),
3879
- resourceType: getResourceTypeName(node.type),
3880
- error,
3881
- elapsedMs
3882
- });
3787
+ logger.error(`Failed to upsert ${node.type}: ${node.getName()}`, { elapsedMs, error });
3788
+ bars.get(node.type)?.increment();
3883
3789
  return { name: node.getName(), error };
3884
3790
  }
3885
3791
  }
@@ -3898,40 +3804,26 @@ function mergeResults(target, source) {
3898
3804
  target.successful.push(...source.successful);
3899
3805
  target.failed.push(...source.failed);
3900
3806
  }
3901
- function getResourceTypeName(type) {
3902
- switch (type) {
3903
- case "component":
3904
- return "component";
3905
- case "group":
3906
- return "group";
3907
- case "tag":
3908
- return "tag";
3909
- case "preset":
3910
- return "preset";
3911
- default:
3912
- return type;
3913
- }
3914
- }
3915
- function getResourceTypeColor(type) {
3916
- switch (type) {
3917
- case "component":
3918
- return colorPalette.COMPONENTS;
3919
- case "group":
3920
- return colorPalette.GROUPS;
3921
- case "tag":
3922
- return colorPalette.TAGS;
3923
- case "preset":
3924
- return colorPalette.PRESETS;
3925
- default:
3926
- return colorPalette.COMPONENTS;
3927
- }
3928
- }
3929
3807
 
3930
3808
  async function pushWithDependencyGraph(space, spaceState, backpressure = getActiveConfig().api.rateLimit) {
3809
+ const ui = getUI();
3810
+ const logger = getLogger();
3811
+ const graphSpinner = ui.createSpinner("Building dependency graph...");
3812
+ logger.info("Building dependency graph");
3931
3813
  const context = { spaceState };
3932
3814
  const graph = buildDependencyGraph(context);
3933
- validateGraph(graph);
3815
+ graphSpinner.succeed(`Dependency graph built (${graph.nodes.size} resources)`);
3816
+ const validateSpinner = ui.createSpinner("Validating graph...");
3817
+ try {
3818
+ validateGraph(graph);
3819
+ validateSpinner.succeed("Graph validation passed");
3820
+ } catch (error) {
3821
+ validateSpinner.failed("Graph validation failed");
3822
+ throw error;
3823
+ }
3934
3824
  const results = await processAllResources(graph, space, backpressure);
3825
+ const status = results.failed.length > 0 ? `${results.successful.length} updated, ${results.failed.length} failed` : `${results.successful.length} updated`;
3826
+ ui.ok(status, true);
3935
3827
  return results;
3936
3828
  }
3937
3829
 
@@ -4044,7 +3936,6 @@ pushCmd$3.action(async (componentName, options, command) => {
4044
3936
  localPresetKeys.add(`${componentName2}:${preset.name}`);
4045
3937
  }
4046
3938
  }
4047
- ui.info("Using graph-based dependency resolution");
4048
3939
  const graphResults = await pushWithDependencyGraph(space, spaceState);
4049
3940
  results.successful.push(...graphResults.successful);
4050
3941
  results.failed.push(...graphResults.failed);
@@ -4071,7 +3962,7 @@ pushCmd$3.action(async (componentName, options, command) => {
4071
3962
  });
4072
3963
  }
4073
3964
  }
4074
- console.log(`${requestCount} requests made`);
3965
+ ui.log(`${requestCount} requests made`);
4075
3966
  const referencedDatasources = /* @__PURE__ */ new Set();
4076
3967
  spaceState.local.components.forEach((component) => {
4077
3968
  if (component.schema) {
@@ -4160,7 +4051,8 @@ const program$a = getProgram();
4160
4051
  const languagesCommand = program$a.command(commands.LANGUAGES).alias("lang").description(`Manage your space's languages`);
4161
4052
  const pullCmd$3 = languagesCommand.command("pull").description(`Download your space's languages schema as json`).option("-f, --filename <filename>", "filename to save the file as <filename>.<suffix>.json").option("--su, --suffix <suffix>", "suffix to add to the file name (e.g. languages.<suffix>.json). By default, the space ID is used.").option("-s, --space <space>", "space ID");
4162
4053
  pullCmd$3.action(async (options, command) => {
4163
- konsola.title(`${commands.LANGUAGES}`, colorPalette.LANGUAGES);
4054
+ const ui = getUI();
4055
+ ui.title(`${commands.LANGUAGES}`, colorPalette.LANGUAGES);
4164
4056
  const { space, path, verbose } = command.optsWithGlobals();
4165
4057
  const { filename = "languages", suffix = options.space } = options;
4166
4058
  const { state } = session();
@@ -4171,16 +4063,13 @@ pullCmd$3.action(async (options, command) => {
4171
4063
  handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
4172
4064
  return;
4173
4065
  }
4174
- const spinner = new Spinner({
4175
- verbose: !isVitest
4176
- });
4066
+ const spinner = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.LANGUAGES)("languages")}`);
4177
4067
  try {
4178
- spinner.start(`Fetching ${chalk.hex(colorPalette.LANGUAGES)("languages")}`);
4179
4068
  const internationalization = await fetchLanguages(space);
4180
4069
  if (!internationalization || internationalization.languages?.length === 0) {
4181
4070
  spinner.failed();
4182
- konsola.warn(`No languages found in the space ${space}`, true);
4183
- konsola.br();
4071
+ ui.warn(`No languages found in the space ${space}`, true);
4072
+ ui.br();
4184
4073
  return;
4185
4074
  }
4186
4075
  await saveLanguagesToFile(space, internationalization, {
@@ -4194,13 +4083,13 @@ pullCmd$3.action(async (options, command) => {
4194
4083
  const filePath = join(languagesOutputDir, fileName);
4195
4084
  const displayPath = path && isAbsolute(path) ? filePath : relative(process.cwd(), filePath);
4196
4085
  spinner.succeed();
4197
- konsola.ok(`Languages schema downloaded successfully at ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`, true);
4086
+ ui.ok(`Languages schema downloaded successfully at ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`, true);
4198
4087
  } catch (error) {
4199
4088
  spinner.failed();
4200
- konsola.br();
4089
+ ui.br();
4201
4090
  handleError(error, verbose);
4202
4091
  }
4203
- konsola.br();
4092
+ ui.br();
4204
4093
  });
4205
4094
 
4206
4095
  const program$9 = getProgram();
@@ -4593,8 +4482,7 @@ const createStoriesStream = async ({
4593
4482
  const listStoriesStream = Readable.from(iterator);
4594
4483
  return pipeline(listStoriesStream, new StoriesStream(spaceId, onProgress), (err) => {
4595
4484
  if (err) {
4596
- console.error(err);
4597
- getLogger().error(err.message, { errorCode: ERROR_CODES.MIGRATION_CREATE_STORIES_PIPELINE_ERROR });
4485
+ getLogger().error(err.message, { error: err, errorCode: ERROR_CODES.MIGRATION_CREATE_STORIES_PIPELINE_ERROR });
4598
4486
  }
4599
4487
  });
4600
4488
  };
@@ -6071,7 +5959,8 @@ const generateTypes = async (spaceData, options = {
6071
5959
  const resolvedComponentsSchema = await Promise.all(componentsSchema);
6072
5960
  const datasourcesSchema = spaceData.datasources.map(async (datasource) => {
6073
5961
  const allComponentTypes = resolvedComponentsSchema.map((schema) => schema.title);
6074
- const enumValues = datasource.entries?.filter((d) => d.value).map((d) => d.value);
5962
+ const filtered = datasource.entries?.filter((d) => d.value).map((d) => d.value);
5963
+ const enumValues = filtered?.length ? filtered : void 0;
6075
5964
  if (!datasource.slug) {
6076
5965
  return null;
6077
5966
  }
@@ -6083,7 +5972,7 @@ const generateTypes = async (spaceData, options = {
6083
5972
  $id: `#/${datasource.slug}`,
6084
5973
  title: type,
6085
5974
  type: "string",
6086
- enum: enumValues
5975
+ ...enumValues && { enum: enumValues }
6087
5976
  };
6088
5977
  return datasourceSchema;
6089
5978
  });
@@ -6102,15 +5991,21 @@ const generateTypes = async (spaceData, options = {
6102
5991
  ...resolvedDatasourcesSchema,
6103
5992
  contentTypeSchema
6104
5993
  ];
5994
+ const logger = getLogger();
6105
5995
  const result = await Promise.all(schemas.map(async (schema) => {
6106
5996
  const title = schema.title || schema.$id.replace("#/", "");
5997
+ const kind = componentTitles.has(title) ? "component" : datasourceTitles.has(title) ? "datasource" : "type";
5998
+ logger.info(`Compiling ${kind}: ${title}`);
5999
+ const startTime = Date.now();
6000
+ const content = await compile(schema, title, {
6001
+ additionalProperties: !options.strict,
6002
+ bannerComment: "",
6003
+ ...compilerOptions
6004
+ });
6005
+ logger.info(`Compiled ${kind}: ${title}`, { elapsedMs: Date.now() - startTime });
6107
6006
  return {
6108
6007
  title,
6109
- content: await compile(schema, title, {
6110
- additionalProperties: !options.strict,
6111
- bannerComment: "",
6112
- ...compilerOptions
6113
- }),
6008
+ content,
6114
6009
  isComponent: componentTitles.has(title),
6115
6010
  isDatasource: datasourceTitles.has(title)
6116
6011
  };
@@ -6393,13 +6288,17 @@ const generateCmd = typesCommand.command("generate").description("Generate types
6393
6288
  "Base file name for all component types when generating a single declarations file (e.g. components.d.ts). Ignored when using --separate-files."
6394
6289
  ).option("--sf, --separate-files", "Generate one .d.ts file per component instead of a single combined file").option("--strict", "strict mode, no loose typing").option("--type-prefix <prefix>", "prefix to be prepended to all generated component type names").option("--type-suffix <suffix>", "suffix to be appended to all generated component type names").option("--suffix <suffix>", "Components suffix").option("--custom-fields-parser <path>", "Path to the parser file for Custom Field Types").option("--compiler-options <options>", "path to the compiler options from json-schema-to-typescript").option("-s, --space <space>", "space ID");
6395
6290
  generateCmd.action(async (options, command) => {
6396
- konsola.title(`${commands.TYPES}`, colorPalette.TYPES, "Generating types...");
6291
+ const ui = getUI();
6292
+ ui.title(`${commands.TYPES}`, colorPalette.TYPES, "Generating types...");
6397
6293
  const { space, path, verbose, suffix, filename, separateFiles } = command.optsWithGlobals();
6398
- const spinner = new Spinner({
6399
- verbose
6400
- });
6294
+ if (!space) {
6295
+ handleError(new CommandError("Please provide the space as argument --space SPACE_ID."), verbose);
6296
+ return;
6297
+ }
6298
+ const logger = getLogger();
6299
+ const spinner = ui.createSpinner("Processing schemas...");
6401
6300
  try {
6402
- spinner.start(`Generating types...`);
6301
+ logger.info("Generating types started", { space });
6403
6302
  const componentsData = await readComponentsFiles({
6404
6303
  from: space,
6405
6304
  path,
@@ -6428,25 +6327,32 @@ generateCmd.action(async (options, command) => {
6428
6327
  ...componentsData,
6429
6328
  ...dataSourceData
6430
6329
  };
6330
+ logger.info("Processing schemas", {
6331
+ components: componentsData.components.length,
6332
+ datasources: dataSourceData.datasources.length
6333
+ });
6431
6334
  const typedefData = await generateTypes(spaceDataWithComponentsAndDatasources, {
6432
6335
  ...options
6433
6336
  });
6434
- if (typedefData) {
6435
- await saveTypesToComponentsFile(space, typedefData, {
6436
- filename,
6437
- path,
6438
- separateFiles
6439
- });
6337
+ if (!typedefData) {
6338
+ spinner.failed("No types generated");
6339
+ return;
6440
6340
  }
6441
- spinner.succeed();
6341
+ await saveTypesToComponentsFile(space, typedefData, {
6342
+ filename,
6343
+ path,
6344
+ separateFiles
6345
+ });
6346
+ spinner.succeed(`Types generated for ${componentsData.components.length} components`);
6442
6347
  if (separateFiles && filename) {
6443
- konsola.warn(`The --filename option is ignored when using --separate-files`);
6348
+ ui.warn(`The --filename option is ignored when using --separate-files`);
6444
6349
  }
6445
- konsola.ok(`Successfully generated types for space ${space}`, true);
6446
- konsola.br();
6350
+ logger.info("Types generated successfully", { space });
6351
+ ui.ok(`Successfully generated types for space ${space}`, true);
6352
+ ui.br();
6447
6353
  } catch (error) {
6448
- spinner.failed(`Failed to generate types for space ${space}`);
6449
- konsola.br();
6354
+ spinner.failed("Type generation failed");
6355
+ logger.error("Type generation failed", { error });
6450
6356
  handleError(error, verbose);
6451
6357
  }
6452
6358
  });
@@ -6582,7 +6488,8 @@ const saveDatasourcesToFiles = async (space, datasources, options) => {
6582
6488
 
6583
6489
  const pullCmd$2 = datasourcesCommand.command("pull [datasourceName]").option("-f, --filename <filename>", "custom name to be used in file(s) name instead of space id").option("--sf, --separate-files", "Argument to create a single file for each datasource").option("--su, --suffix <suffix>", "suffix to add to the file name (e.g. datasources.<suffix>.json)").option("-s, --space <space>", "space ID").description("Pull datasources from your space");
6584
6490
  pullCmd$2.action(async (datasourceName, options, command) => {
6585
- konsola.title(`${commands.DATASOURCES}`, colorPalette.DATASOURCES, datasourceName ? `Pulling datasource ${datasourceName}...` : "Pulling datasources...");
6491
+ const ui = getUI();
6492
+ ui.title(`${commands.DATASOURCES}`, colorPalette.DATASOURCES, datasourceName ? `Pulling datasource ${datasourceName}...` : "Pulling datasources...");
6586
6493
  const { space, path, verbose } = command.optsWithGlobals();
6587
6494
  const {
6588
6495
  separateFiles = false,
@@ -6599,7 +6506,6 @@ pullCmd$2.action(async (datasourceName, options, command) => {
6599
6506
  handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
6600
6507
  return;
6601
6508
  }
6602
- const ui = getUI();
6603
6509
  const logger = getLogger();
6604
6510
  logger.info("Pulling datasources started", { space, datasourceName });
6605
6511
  const spinnerDatasources = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.DATASOURCES)("datasources")}`);
@@ -6625,29 +6531,29 @@ pullCmd$2.action(async (datasourceName, options, command) => {
6625
6531
  datasources,
6626
6532
  { ...options, path, separateFiles: separateFiles || !!datasourceName }
6627
6533
  );
6628
- konsola.br();
6534
+ ui.br();
6629
6535
  if (separateFiles) {
6630
6536
  if (filename && filename !== DEFAULT_DATASOURCES_FILENAME) {
6631
- konsola.warn(`The --filename option is ignored when using --separate-files`);
6537
+ ui.warn(`The --filename option is ignored when using --separate-files`);
6632
6538
  }
6633
6539
  const filePath = `${datasourcesOutputDir}/`;
6634
6540
  const displayPath = path && isAbsolute(path) ? filePath : `${relative(process.cwd(), datasourcesOutputDir)}/`;
6635
- konsola.ok(`Datasources downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);
6541
+ ui.ok(`Datasources downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);
6636
6542
  } else if (datasourceName) {
6637
6543
  const fileName = suffix ? `${actualFilename}.${suffix}.json` : `${datasourceName}.json`;
6638
6544
  const filePath = join(datasourcesOutputDir, fileName);
6639
6545
  const displayPath = path && isAbsolute(path) ? filePath : relative(process.cwd(), filePath);
6640
- konsola.ok(`Datasource ${chalk.hex(colorPalette.PRIMARY)(datasourceName)} downloaded successfully in ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);
6546
+ ui.ok(`Datasource ${chalk.hex(colorPalette.PRIMARY)(datasourceName)} downloaded successfully in ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);
6641
6547
  } else {
6642
6548
  const fileName = suffix ? `${actualFilename}.${suffix}.json` : `${actualFilename}.json`;
6643
6549
  const filePath = join(datasourcesOutputDir, fileName);
6644
6550
  const displayPath = path && isAbsolute(path) ? filePath : relative(process.cwd(), filePath);
6645
- konsola.ok(`Datasources downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);
6551
+ ui.ok(`Datasources downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);
6646
6552
  }
6647
- konsola.br();
6553
+ ui.br();
6648
6554
  } catch (error) {
6649
6555
  spinnerDatasources.failed(`Fetching ${chalk.hex(colorPalette.DATASOURCES)("Datasources")} - Failed`);
6650
- konsola.br();
6556
+ ui.br();
6651
6557
  handleError(error, verbose);
6652
6558
  } finally {
6653
6559
  logger.info("Pulling datasources finished", { space, datasourceName });
@@ -6664,7 +6570,8 @@ function dimensionValuesEqual(a, b) {
6664
6570
  }
6665
6571
  const pushCmd$2 = datasourcesCommand.command("push [datasourceName]").description(`Push your space's datasources schema as json`).option("-f, --from <from>", "source space id").option("--fi, --filter <filter>", "glob filter to apply to the datasources before pushing").option("--sf, --separate-files", "Read from separate files instead of consolidated files").option("--su, --suffix <suffix>", "Load only files matching *.<suffix>.json (e.g. datasources.dev.json)").option("-s, --space <space>", "space ID");
6666
6572
  pushCmd$2.action(async (datasourceName, options, command) => {
6667
- konsola.title(`${commands.DATASOURCES}`, colorPalette.DATASOURCES, datasourceName ? `Pushing datasource ${datasourceName}...` : "Pushing datasources...");
6573
+ const ui = getUI();
6574
+ ui.title(`${commands.DATASOURCES}`, colorPalette.DATASOURCES, datasourceName ? `Pushing datasource ${datasourceName}...` : "Pushing datasources...");
6668
6575
  const { space, path, verbose } = command.optsWithGlobals();
6669
6576
  const { filter } = options;
6670
6577
  const fromSpace = options.from || space;
@@ -6678,8 +6585,8 @@ pushCmd$2.action(async (datasourceName, options, command) => {
6678
6585
  }
6679
6586
  const logger = getLogger();
6680
6587
  logger.info("Pushing datasources started", { space, fromSpace, datasourceName, filter });
6681
- konsola.info(`Attempting to push datasources ${chalk.bold("from")} space ${chalk.hex(colorPalette.DATASOURCES)(fromSpace)} ${chalk.bold("to")} ${chalk.hex(colorPalette.DATASOURCES)(space)}`);
6682
- konsola.br();
6588
+ ui.info(`Attempting to push datasources ${chalk.bold("from")} space ${chalk.hex(colorPalette.DATASOURCES)(fromSpace)} ${chalk.bold("to")} ${chalk.hex(colorPalette.DATASOURCES)(space)}`);
6589
+ ui.br();
6683
6590
  try {
6684
6591
  const spaceState = {
6685
6592
  local: await readDatasourcesFiles({
@@ -6712,17 +6619,16 @@ pushCmd$2.action(async (datasourceName, options, command) => {
6712
6619
  handleError(new CommandError(`No datasources found matching pattern "${filter}".`), verbose);
6713
6620
  return;
6714
6621
  }
6715
- konsola.info(`Filter applied: ${filter}`);
6622
+ ui.info(`Filter applied: ${filter}`);
6716
6623
  }
6717
6624
  if (!spaceState.local.datasources.length) {
6718
- konsola.warn("No datasources found. Please make sure you have pulled the datasources first.");
6625
+ ui.warn("No datasources found. Please make sure you have pulled the datasources first.");
6719
6626
  return;
6720
6627
  }
6721
6628
  const results = {
6722
6629
  successful: [],
6723
6630
  failed: []
6724
6631
  };
6725
- const ui = getUI();
6726
6632
  for (const datasource of spaceState.local.datasources) {
6727
6633
  const spinner = ui.createSpinner(`Pushing ${chalk.hex(colorPalette.DATASOURCES)(datasource.name)}`);
6728
6634
  const existingDatasource = spaceState.target.datasources.get(datasource.name);
@@ -6783,7 +6689,7 @@ pushCmd$2.action(async (datasourceName, options, command) => {
6783
6689
  }
6784
6690
  }
6785
6691
  spinner.succeed(`${chalk.hex(colorPalette.DATASOURCES)(datasource.name)} - Completed in ${spinner.elapsedTime.toFixed(2)}ms`);
6786
- dimensionWarnings.forEach((warning) => konsola.warn(warning));
6692
+ dimensionWarnings.forEach((warning) => ui.warn(warning));
6787
6693
  } else {
6788
6694
  results.failed.push({ name: datasource.name, error: result });
6789
6695
  spinner.failed(`${chalk.hex(colorPalette.DATASOURCES)(datasource.name)} - Failed in ${spinner.elapsedTime.toFixed(2)}ms`);
@@ -6791,8 +6697,8 @@ pushCmd$2.action(async (datasourceName, options, command) => {
6791
6697
  }
6792
6698
  if (results.failed.length > 0) {
6793
6699
  if (!verbose) {
6794
- konsola.br();
6795
- konsola.info("For more information about the error, run the command with the `--verbose` flag");
6700
+ ui.br();
6701
+ ui.info("For more information about the error, run the command with the `--verbose` flag");
6796
6702
  } else {
6797
6703
  results.failed.forEach((failed) => {
6798
6704
  handleError(failed.error, verbose);
@@ -6822,13 +6728,14 @@ async function deleteDatasource(spaceId, id) {
6822
6728
 
6823
6729
  const deleteCmd = datasourcesCommand.command("delete [name]").description("Delete a datasource from your space by name or id").option("--id <id>", "Delete by datasource id instead of name").option("--force", "Skip confirmation prompt for deletion (useful for CI)").option("-s, --space <space>", "space ID");
6824
6730
  deleteCmd.action(async (name, options, command) => {
6825
- konsola.title(
6731
+ const ui = getUI();
6732
+ ui.title(
6826
6733
  `${commands.DATASOURCES}`,
6827
6734
  colorPalette.DATASOURCES,
6828
6735
  options.id ? `Deleting datasource with id ${options.id}...` : `Deleting datasource with name ${name}...`
6829
6736
  );
6830
6737
  if (name && options.id) {
6831
- konsola.warn(
6738
+ ui.warn(
6832
6739
  "Both a datasource name and an id were provided. Only one is required. The id will be used as the source of truth."
6833
6740
  );
6834
6741
  }
@@ -6841,7 +6748,6 @@ deleteCmd.action(async (name, options, command) => {
6841
6748
  handleError(new CommandError("Please provide the space as argument --space YOUR_SPACE_ID."), verbose);
6842
6749
  return;
6843
6750
  }
6844
- const ui = getUI();
6845
6751
  const logger = getLogger();
6846
6752
  logger.info("Deleting datasource started", { space, name, id: options.id });
6847
6753
  try {
@@ -6849,34 +6755,36 @@ deleteCmd.action(async (name, options, command) => {
6849
6755
  const spinner = ui.createSpinner(`Deleting datasource...`);
6850
6756
  await deleteDatasource(space, options.id);
6851
6757
  spinner.succeed(`Datasource deleted`);
6852
- konsola.ok(`Datasource ${chalk.hex(colorPalette.DATASOURCES)(options.id)} deleted successfully from space ${space}.`);
6758
+ ui.ok(`Datasource ${chalk.hex(colorPalette.DATASOURCES)(options.id)} deleted successfully from space ${space}.`);
6853
6759
  } else {
6854
6760
  const datasource = await fetchDatasource(space, name);
6855
6761
  if (!datasource) {
6856
6762
  throw new CommandError(`Datasource with name '${name}' not found in space ${space}.`);
6857
6763
  }
6858
6764
  if (!options.force) {
6859
- konsola.info(`Datasource details:`);
6860
- console.log(` Name: ${chalk.hex(colorPalette.DATASOURCES)(datasource.name)}`);
6861
- console.log(` ID: ${chalk.hex(colorPalette.DATASOURCES)(datasource.id)}`);
6862
- console.log(` Space: ${chalk.hex(colorPalette.DATASOURCES)(space)}`);
6863
- console.log(` Slug: ${chalk.hex(colorPalette.DATASOURCES)(datasource.slug)}`);
6864
- console.log(` Created at: ${chalk.hex(colorPalette.DATASOURCES)(datasource.created_at)}`);
6865
- console.log(` Updated at: ${chalk.hex(colorPalette.DATASOURCES)(datasource.updated_at)}`);
6866
- konsola.br();
6765
+ ui.info(`Datasource details:`);
6766
+ ui.list([
6767
+ `Name: ${chalk.hex(colorPalette.DATASOURCES)(datasource.name)}`,
6768
+ `ID: ${chalk.hex(colorPalette.DATASOURCES)(datasource.id)}`,
6769
+ `Space: ${chalk.hex(colorPalette.DATASOURCES)(space)}`,
6770
+ `Slug: ${chalk.hex(colorPalette.DATASOURCES)(datasource.slug)}`,
6771
+ `Created at: ${chalk.hex(colorPalette.DATASOURCES)(datasource.created_at)}`,
6772
+ `Updated at: ${chalk.hex(colorPalette.DATASOURCES)(datasource.updated_at)}`
6773
+ ]);
6774
+ ui.br();
6867
6775
  const confirmed = await confirm({
6868
6776
  message: `\u26A0\uFE0F ${chalk.yellow(` Are you sure you want to delete the ${datasource.name} datasource from space ${space}? This action cannot be undone.`)} `,
6869
6777
  default: false
6870
- });
6778
+ }, stderrPromptContext);
6871
6779
  if (!confirmed) {
6872
- konsola.warn("Deletion aborted by user.");
6780
+ ui.warn("Deletion aborted by user.");
6873
6781
  return;
6874
6782
  }
6875
6783
  }
6876
6784
  const spinner = ui.createSpinner(`Deleting datasource...`);
6877
6785
  await deleteDatasource(space, datasource.id.toString());
6878
6786
  spinner.succeed(`Datasource deleted`);
6879
- konsola.ok(`Datasource ${chalk.hex(colorPalette.DATASOURCES)(name)} deleted successfully from space ${space}.`);
6787
+ ui.ok(`Datasource ${chalk.hex(colorPalette.DATASOURCES)(name)} deleted successfully from space ${space}.`);
6880
6788
  }
6881
6789
  } catch (error) {
6882
6790
  handleError(error, verbose);
@@ -6950,7 +6858,6 @@ const templates = {
6950
6858
  }
6951
6859
  };
6952
6860
 
6953
- const ui$1 = getUI({ enabled: true });
6954
6861
  const generateProject = async (blueprint, projectName, targetPath = process.cwd()) => {
6955
6862
  try {
6956
6863
  const projectPath = join(targetPath, projectName);
@@ -7027,29 +6934,30 @@ const updateAngularEnvironmentFiles = async (projectPath, token, region) => {
7027
6934
  return { updatedFiles };
7028
6935
  };
7029
6936
  async function handleEnvFileCreation(resolvedPath, token, region, template) {
6937
+ const ui = getUI();
7030
6938
  if (template === "angular") {
7031
6939
  if (!token && !region) {
7032
- ui$1.info("No environment variables to write");
6940
+ ui.info("No environment variables to write");
7033
6941
  return true;
7034
6942
  }
7035
6943
  try {
7036
6944
  const { updatedFiles } = await updateAngularEnvironmentFiles(resolvedPath, token, region);
7037
6945
  if (updatedFiles.length === 0) {
7038
- ui$1.info("No Angular environment files found to update");
6946
+ ui.info("No Angular environment files found to update");
7039
6947
  return true;
7040
6948
  }
7041
6949
  const writtenVars = [token && "accessToken", region && "region"].filter(Boolean).join(", ");
7042
- ui$1.ok(`Updated Angular environment files with: ${writtenVars}`, true);
6950
+ ui.ok(`Updated Angular environment files with: ${writtenVars}`, true);
7043
6951
  return true;
7044
6952
  } catch (error) {
7045
- ui$1.warn(`Failed to update Angular environment files: ${error.message}`);
6953
+ ui.warn(`Failed to update Angular environment files: ${error.message}`);
7046
6954
  if (token) {
7047
- ui$1.info(
6955
+ ui.info(
7048
6956
  `You can manually add accessToken to src/environments/environment.ts and src/environments/environment.development.ts`
7049
6957
  );
7050
6958
  }
7051
6959
  if (region) {
7052
- ui$1.info(
6960
+ ui.info(
7053
6961
  `You can manually add region to src/environments/environment.ts and src/environments/environment.development.ts`
7054
6962
  );
7055
6963
  }
@@ -7064,23 +6972,23 @@ async function handleEnvFileCreation(resolvedPath, token, region, template) {
7064
6972
  envVars.STORYBLOK_REGION = region;
7065
6973
  }
7066
6974
  if (Object.keys(envVars).length === 0) {
7067
- ui$1.info("No environment variables to write");
6975
+ ui.info("No environment variables to write");
7068
6976
  return true;
7069
6977
  }
7070
6978
  try {
7071
6979
  await createEnvFile(resolvedPath, envVars);
7072
6980
  const writtenKeys = Object.keys(envVars).join(", ");
7073
- ui$1.ok(`Created .env file with: ${writtenKeys}`, true);
6981
+ ui.ok(`Created .env file with: ${writtenKeys}`, true);
7074
6982
  return true;
7075
6983
  } catch (error) {
7076
- ui$1.warn(`Failed to create .env file: ${error.message}`);
6984
+ ui.warn(`Failed to create .env file: ${error.message}`);
7077
6985
  if (token) {
7078
- ui$1.info(
6986
+ ui.info(
7079
6987
  `You can manually add STORYBLOK_DELIVERY_API_TOKEN to your .env file.`
7080
6988
  );
7081
6989
  }
7082
6990
  if (region) {
7083
- ui$1.info(
6991
+ ui.info(
7084
6992
  `You can manually add STORYBLOK_REGION to your .env file.`
7085
6993
  );
7086
6994
  }
@@ -7131,6 +7039,7 @@ const repositoryToTemplate = (repo) => {
7131
7039
  };
7132
7040
  };
7133
7041
  const fetchBlueprintRepositories = async () => {
7042
+ const ui = getUI();
7134
7043
  try {
7135
7044
  const octokit = createOctokit();
7136
7045
  const { data } = await octokit.rest.search.repos({
@@ -7142,13 +7051,13 @@ const fetchBlueprintRepositories = async () => {
7142
7051
  const blueprints = data.items.filter((repo) => repo.name.startsWith("blueprint-core-")).map(repositoryToTemplate).sort((a, b) => (b.stars || 0) - (a.stars || 0));
7143
7052
  return blueprints;
7144
7053
  } catch {
7145
- ui$1.warn("Failed to fetch blueprints from GitHub. Using offline template list.");
7054
+ ui.warn("Failed to fetch blueprints from GitHub. Using offline template list.");
7146
7055
  return Object.values(templates);
7147
7056
  }
7148
7057
  };
7149
7058
 
7150
- const ui = getUI({ enabled: true });
7151
7059
  function showNextSteps(technologyTemplate, finalProjectPath) {
7060
+ const ui = getUI();
7152
7061
  ui.br();
7153
7062
  ui.ok(`Your ${chalk.hex(colorPalette.PRIMARY)(technologyTemplate)} project is ready \u{1F389} !`);
7154
7063
  ui.br();
@@ -7160,12 +7069,13 @@ function showNextSteps(technologyTemplate, finalProjectPath) {
7160
7069
  ui.info(`Or check the dedicated guide at: ${chalk.hex(colorPalette.PRIMARY)(`https://www.storyblok.com/docs/guides/${technologyTemplate}`)}`);
7161
7070
  }
7162
7071
  async function promptForLogin(verbose) {
7072
+ const ui = getUI();
7163
7073
  try {
7164
7074
  ui.br();
7165
7075
  const shouldLogin = await confirm({
7166
7076
  message: "Would you like to login now?",
7167
7077
  default: true
7168
- });
7078
+ }, stderrPromptContext);
7169
7079
  if (!shouldLogin) {
7170
7080
  ui.warn('Login cancelled. You can login later using the "storyblok login" command.');
7171
7081
  return null;
@@ -7182,6 +7092,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
7182
7092
  "-r, --region <region>",
7183
7093
  `The region to apply to the generated project template (does not affect space creation).`
7184
7094
  ).action(async (projectPath, options) => {
7095
+ const ui = getUI();
7185
7096
  ui.title(`${commands.CREATE}`, colorPalette.CREATE);
7186
7097
  const verbose = program$6.opts().verbose;
7187
7098
  const { template, blueprint, token } = options;
@@ -7223,22 +7134,17 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
7223
7134
  region = state.region;
7224
7135
  }
7225
7136
  }
7226
- const spinnerBlueprints = new Spinner({
7227
- verbose: !isVitest
7228
- });
7229
- const spinnerSpace = new Spinner({
7230
- verbose: !isVitest
7231
- });
7137
+ let activeSpinner = null;
7232
7138
  try {
7233
- spinnerBlueprints.start("Fetching starter templates...");
7139
+ activeSpinner = ui.createSpinner("Fetching starter templates...");
7234
7140
  const templates = await fetchBlueprintRepositories();
7235
- spinnerBlueprints.succeed("Starter templates fetched successfully");
7236
7141
  if (templates.length === 0) {
7237
- spinnerBlueprints.failed();
7238
- ui.warn("No starter templates found. Please contact support@storyblok.com");
7142
+ activeSpinner.failed();
7143
+ ui.error("No starter templates found. Please contact support@storyblok.com");
7239
7144
  ui.br();
7240
7145
  return;
7241
7146
  }
7147
+ activeSpinner.succeed("Starter templates fetched successfully");
7242
7148
  let technologyTemplate = selectedTemplate;
7243
7149
  if (selectedTemplate) {
7244
7150
  const validTemplates = templates;
@@ -7257,7 +7163,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
7257
7163
  name: template2.name,
7258
7164
  value: template2.value
7259
7165
  }))
7260
- });
7166
+ }, stderrPromptContext);
7261
7167
  }
7262
7168
  let finalProjectPath = projectPath;
7263
7169
  if (!projectPath) {
@@ -7274,7 +7180,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
7274
7180
  }
7275
7181
  return true;
7276
7182
  }
7277
- });
7183
+ }, stderrPromptContext);
7278
7184
  }
7279
7185
  const resolvedPath = resolve(finalProjectPath);
7280
7186
  const targetDirectory = dirname(resolvedPath);
@@ -7339,7 +7245,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
7339
7245
  whereToCreateSpace = await select({
7340
7246
  message: `Where would you like to create this space?`,
7341
7247
  choices
7342
- });
7248
+ }, stderrPromptContext);
7343
7249
  }
7344
7250
  if (region !== regions.EU && userData.has_org) {
7345
7251
  whereToCreateSpace = "org";
@@ -7349,7 +7255,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
7349
7255
  ui.br();
7350
7256
  return;
7351
7257
  }
7352
- spinnerSpace.start(`Creating space "${toHumanReadable(projectName)}"`);
7258
+ activeSpinner = ui.createSpinner(`Creating space "${toHumanReadable(projectName)}"`);
7353
7259
  const selectedBlueprint = templates.find((bp) => bp.value === technologyTemplate);
7354
7260
  const blueprintDomain = selectedBlueprint?.location || "https://localhost:3000/";
7355
7261
  const spaceToCreate = {
@@ -7363,7 +7269,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
7363
7269
  createSpaceQuery.assign_partner = true;
7364
7270
  }
7365
7271
  createdSpace = await createSpace(spaceToCreate, createSpaceQuery);
7366
- spinnerSpace.succeed(`Space "${chalk.hex(colorPalette.PRIMARY)(toHumanReadable(projectName))}" created successfully`);
7272
+ activeSpinner.succeed(`Space "${chalk.hex(colorPalette.PRIMARY)(toHumanReadable(projectName))}" created successfully`);
7367
7273
  if (createdSpace?.first_token) {
7368
7274
  await handleEnvFileCreation(resolvedPath, createdSpace.first_token, region, technologyTemplate);
7369
7275
  }
@@ -7388,14 +7294,13 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
7388
7294
  }
7389
7295
  }
7390
7296
  } catch (error) {
7391
- spinnerSpace.failed();
7297
+ activeSpinner?.failed();
7392
7298
  ui.br();
7393
7299
  handleError(error, verbose);
7394
7300
  return;
7395
7301
  }
7396
7302
  } catch (error) {
7397
- spinnerSpace.failed();
7398
- spinnerBlueprints.failed();
7303
+ activeSpinner?.failed();
7399
7304
  ui.br();
7400
7305
  handleError(error, verbose);
7401
7306
  }
@@ -8786,12 +8691,10 @@ pullCmd$1.action(async (options, command) => {
8786
8691
  const assetToken = options.assetToken;
8787
8692
  const { state } = session();
8788
8693
  if (!requireAuthentication(state, verbose)) {
8789
- process.exitCode = 2;
8790
8694
  return;
8791
8695
  }
8792
8696
  if (!space) {
8793
8697
  handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
8794
- process.exitCode = 2;
8795
8698
  return;
8796
8699
  }
8797
8700
  const { region } = state;
@@ -9040,7 +8943,9 @@ pullCmd$1.action(async (options, command) => {
9040
8943
  reporter.addSummary("saveResults", summary.save);
9041
8944
  reporter.finalize();
9042
8945
  const failedTotal = summary.folderResults.failed + summary.fetchAssetPages.failed + summary.fetchAssets.failed + summary.save.failed;
9043
- process.exitCode = fatalError ? 2 : failedTotal > 0 ? 1 : 0;
8946
+ if (!fatalError) {
8947
+ process.exitCode = failedTotal > 0 ? 1 : 0;
8948
+ }
9044
8949
  }
9045
8950
  });
9046
8951
 
@@ -9999,12 +9904,10 @@ pushCmd$1.action(async (assetInput, options, command) => {
9999
9904
  const fromSpace = options.from || targetSpace;
10000
9905
  const { state } = session();
10001
9906
  if (!requireAuthentication(state, verbose)) {
10002
- process.exitCode = 2;
10003
9907
  return;
10004
9908
  }
10005
9909
  if (!targetSpace) {
10006
9910
  handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
10007
- process.exitCode = 2;
10008
9911
  return;
10009
9912
  }
10010
9913
  const libraryId = options.library ? Number(options.library) : void 0;
@@ -10013,17 +9916,14 @@ pushCmd$1.action(async (assetInput, options, command) => {
10013
9916
  if (assetBinaryPath) {
10014
9917
  if (target === "auto") {
10015
9918
  handleError(new CommandError("Pushing a single asset requires --target=space or --target=shared, not --target=auto."), verbose);
10016
- process.exitCode = 2;
10017
9919
  return;
10018
9920
  }
10019
9921
  if (target === "shared" && !libraryId) {
10020
9922
  handleError(new CommandError("Pushing a single asset to a library requires --library YOUR_LIBRARY_ID."), verbose);
10021
- process.exitCode = 2;
10022
9923
  return;
10023
9924
  }
10024
9925
  if (target === "space" && libraryId) {
10025
9926
  handleError(new CommandError("--library cannot be combined with --target=space."), verbose);
10026
- process.exitCode = 2;
10027
9927
  return;
10028
9928
  }
10029
9929
  }
@@ -10047,7 +9947,6 @@ pushCmd$1.action(async (assetInput, options, command) => {
10047
9947
  }
10048
9948
  } catch (maybeError) {
10049
9949
  handleError(toError(maybeError), verbose);
10050
- process.exitCode = 2;
10051
9950
  return;
10052
9951
  }
10053
9952
  const summaries = [];
@@ -10205,7 +10104,9 @@ pushCmd$1.action(async (assetInput, options, command) => {
10205
10104
  }
10206
10105
  return total + entry.failed;
10207
10106
  }, 0);
10208
- process.exitCode = fatalError ? 2 : failedTotal > 0 ? 1 : 0;
10107
+ if (!fatalError) {
10108
+ process.exitCode = failedTotal > 0 ? 1 : 0;
10109
+ }
10209
10110
  }
10210
10111
  });
10211
10112
 
@@ -10224,29 +10125,24 @@ transferCmd.action(async (assetIds, options, command) => {
10224
10125
  const { space, verbose } = command.optsWithGlobals();
10225
10126
  const { state } = session();
10226
10127
  if (!requireAuthentication(state, verbose)) {
10227
- process.exitCode = 2;
10228
10128
  return;
10229
10129
  }
10230
10130
  if (!space) {
10231
10131
  handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
10232
- process.exitCode = 2;
10233
10132
  return;
10234
10133
  }
10235
10134
  const folderId = Number(options.folderId);
10236
10135
  if (!options.folderId || !Number.isFinite(folderId) || folderId <= 0) {
10237
10136
  handleError(new CommandError(`Please provide a destination folder with --folder-id YOUR_FOLDER_ID.`), verbose);
10238
- process.exitCode = 2;
10239
10137
  return;
10240
10138
  }
10241
10139
  if (options.all && options.query) {
10242
10140
  handleError(new CommandError(`Cannot combine --all with --query. Use --all to transfer every asset, or --query to transfer a filtered subset.`), verbose);
10243
- process.exitCode = 2;
10244
10141
  return;
10245
10142
  }
10246
10143
  const bulk = Boolean(options.all || options.query);
10247
10144
  if (bulk && assetIds.length > 0) {
10248
10145
  handleError(new CommandError(`Cannot combine explicit asset IDs with --all or --query.`), verbose);
10249
- process.exitCode = 2;
10250
10146
  return;
10251
10147
  }
10252
10148
  let ids;
@@ -10257,7 +10153,6 @@ transferCmd.action(async (assetIds, options, command) => {
10257
10153
  ids = await fetchAllSpaceAssetIds(space, params);
10258
10154
  } catch (maybeError) {
10259
10155
  handleError(toError(maybeError), verbose);
10260
- process.exitCode = 2;
10261
10156
  return;
10262
10157
  }
10263
10158
  logger.info("Enumerated space assets", { count: ids.length });
@@ -10271,7 +10166,6 @@ transferCmd.action(async (assetIds, options, command) => {
10271
10166
  ids = assetIds.map((id) => Number(id)).filter((id) => !Number.isNaN(id));
10272
10167
  if (ids.length === 0) {
10273
10168
  handleError(new CommandError(`Please provide at least one valid asset ID, or use --all.`), verbose);
10274
- process.exitCode = 2;
10275
10169
  return;
10276
10170
  }
10277
10171
  }
@@ -12175,7 +12069,7 @@ schemaCommand.command("push <entry-file>").description("Push local TypeScript sc
12175
12069
  const shouldGenerate = explicitMigrations || await confirm({
12176
12070
  message: "Generate migration files for breaking changes?",
12177
12071
  default: true
12178
- });
12072
+ }, stderrPromptContext);
12179
12073
  if (shouldGenerate) {
12180
12074
  const migrationTimestamp = (/* @__PURE__ */ new Date()).toISOString();
12181
12075
  const resolvedBase = resolvePath(basePath, "");
@@ -12199,7 +12093,7 @@ schemaCommand.command("push <entry-file>").description("Push local TypeScript sc
12199
12093
  const renameConfirmed = await confirm({
12200
12094
  message: "Are these renames correct?",
12201
12095
  default: true
12202
- });
12096
+ }, stderrPromptContext);
12203
12097
  if (!renameConfirmed) {
12204
12098
  comp.changes = comp.changes.map((c) => {
12205
12099
  if (c.kind === "rename") {
@@ -12414,9 +12308,15 @@ function resolveGroupWhitelistRefs(whitelist, folderVarByUuid) {
12414
12308
  function toDslField(field, folderVarByUuid) {
12415
12309
  const { component_whitelist, component_group_whitelist, datasource_slug, restrict_components, restrict_type, ...rest } = field;
12416
12310
  const out = { ...rest };
12417
- const groupRefs = resolveGroupWhitelistRefs(component_group_whitelist, folderVarByUuid);
12418
- const hasBlockNames = Array.isArray(component_whitelist) && component_whitelist.length > 0;
12419
- if (hasBlockNames) {
12311
+ const restrictionDisabled = restrict_components === false;
12312
+ const groupRefs = restrictionDisabled ? void 0 : resolveGroupWhitelistRefs(component_group_whitelist, folderVarByUuid);
12313
+ const hasBlockNames = !restrictionDisabled && Array.isArray(component_whitelist) && component_whitelist.length > 0;
12314
+ if (restrictionDisabled) {
12315
+ out.restrict_components = false;
12316
+ if (restrict_type !== void 0) {
12317
+ out.restrict_type = restrict_type;
12318
+ }
12319
+ } else if (hasBlockNames) {
12420
12320
  out.allow = component_whitelist;
12421
12321
  } else if (groupRefs) {
12422
12322
  out.allow = groupRefs;
@@ -12454,6 +12354,9 @@ function collectWhitelistFolderVars(schema, folderVarByUuid) {
12454
12354
  if (!isRecord(field)) {
12455
12355
  continue;
12456
12356
  }
12357
+ if (field.restrict_components === false) {
12358
+ continue;
12359
+ }
12457
12360
  const refs = resolveGroupWhitelistRefs(field.component_group_whitelist, folderVarByUuid);
12458
12361
  if (refs) {
12459
12362
  refs.forEach((ref) => vars.add(ref.code));
@@ -12579,7 +12482,7 @@ function generateSchemaFile(components, datasources, folders = []) {
12579
12482
  const lines = [];
12580
12483
  lines.push("import { defineSchema } from '@storyblok/schema';");
12581
12484
  lines.push("import type { Schema as InferSchema, Story as InferStory } from '@storyblok/schema';");
12582
- lines.push("import type { MapiStory as InferStoryMapi } from '@storyblok/schema';");
12485
+ lines.push(components.length > 0 ? "import type { BlockContent, MapiStory as InferStoryMapi } from '@storyblok/schema';" : "import type { MapiStory as InferStoryMapi } from '@storyblok/schema';");
12583
12486
  lines.push("");
12584
12487
  for (const { varName, fileName, segments } of components) {
12585
12488
  const subPath = segments.length > 0 ? `${segments.join("/")}/` : "";
@@ -12618,8 +12521,21 @@ function generateSchemaFile(components, datasources, folders = []) {
12618
12521
  lines.push("");
12619
12522
  lines.push("export type Schema = InferSchema<typeof schema>;");
12620
12523
  lines.push("export type Blocks = Schema['blocks'];");
12621
- lines.push("export type Story = InferStory<Blocks>;");
12622
- lines.push("export type StoryMapi = InferStoryMapi<Blocks>;");
12524
+ lines.push("export type FieldPlugins = Schema['fieldPlugins'];");
12525
+ lines.push("export type Story = InferStory<Blocks, FieldPlugins>;");
12526
+ lines.push("export type StoryMapi = InferStoryMapi<Blocks, FieldPlugins>;");
12527
+ if (components.length > 0) {
12528
+ lines.push("");
12529
+ lines.push('// Type a component\'s props by block name: `Block<"hero">`.');
12530
+ lines.push("export type Block<TName extends Blocks['name']> = BlockContent<");
12531
+ lines.push(" Extract<Blocks, { name: TName }>,");
12532
+ lines.push(" Blocks,");
12533
+ lines.push(" FieldPlugins");
12534
+ lines.push(">;");
12535
+ lines.push("");
12536
+ lines.push("// Loose union of every block's content, for a dynamic component dispatcher.");
12537
+ lines.push("export type AnyBlock = BlockContent<Blocks, Blocks, FieldPlugins>;");
12538
+ }
12623
12539
  lines.push("");
12624
12540
  return lines.join("\n");
12625
12541
  }
@@ -13078,7 +12994,7 @@ schemaCommand.command("rollback [changeset-file]").description("Roll back a Stor
13078
12994
  resolvedFile = await select({
13079
12995
  message: "Select a changeset to roll back:",
13080
12996
  choices: available.map((f) => ({ name: basename(f), value: f }))
13081
- });
12997
+ }, stderrPromptContext);
13082
12998
  }
13083
12999
  let changeset;
13084
13000
  try {
@@ -13104,7 +13020,7 @@ schemaCommand.command("rollback [changeset-file]").description("Roll back a Stor
13104
13020
  const confirmed = await confirm({
13105
13021
  message: `Apply rollback of ${ops.length} change(s) from ${basename(resolvedFile)}?`,
13106
13022
  default: false
13107
- });
13023
+ }, stderrPromptContext);
13108
13024
  if (!confirmed) {
13109
13025
  ui.info("Rollback cancelled.");
13110
13026
  return;
@@ -13156,18 +13072,27 @@ schemaCommand.command("rollback [changeset-file]").description("Roll back a Stor
13156
13072
  });
13157
13073
 
13158
13074
  const program = getProgram();
13159
- konsola.br();
13160
- konsola.br();
13161
- konsola.title(` Storyblok CLI `, colorPalette.PRIMARY);
13075
+ const ui = getUI();
13076
+ ui.br();
13077
+ ui.title("Storyblok CLI", colorPalette.PRIMARY);
13078
+ ui.br();
13162
13079
  program.on("command:*", () => {
13163
13080
  console.error(`Invalid command: ${program.args.join(" ")}`);
13164
- konsola.br();
13165
- program.outputHelp();
13166
- process.exit(1);
13081
+ console.error("");
13082
+ console.error(program.helpInformation());
13083
+ process.exitCode = 2;
13167
13084
  });
13168
13085
  try {
13169
- program.parse(process.argv);
13086
+ await program.parseAsync(process.argv);
13170
13087
  } catch (error) {
13171
- handleError(error);
13088
+ if (error instanceof CommanderError) {
13089
+ if (error.exitCode !== 0) {
13090
+ if (!process.exitCode) {
13091
+ process.exitCode = error.exitCode;
13092
+ }
13093
+ }
13094
+ } else {
13095
+ handleError(error);
13096
+ }
13172
13097
  }
13173
13098
  //# sourceMappingURL=index.mjs.map