storyblok 4.21.1 → 4.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1159 -707
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -4
package/dist/index.mjs
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
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';
|
|
13
|
-
import
|
|
12
|
+
import { readPackageUp } from 'read-package-up';
|
|
13
|
+
import fs, { mkdir, writeFile, readdir, readFile as readFile$1, appendFile, access, constants, unlink, stat } from 'node:fs/promises';
|
|
14
14
|
import filenamify from 'filenamify';
|
|
15
15
|
import { createManagementApiClient, normalizeAssetUrl } from '@storyblok/management-api-client';
|
|
16
16
|
import { select, password, input, confirm } from '@inquirer/prompts';
|
|
@@ -136,11 +136,12 @@ const SUPPORTED_ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
|
136
136
|
".wma",
|
|
137
137
|
".m4a",
|
|
138
138
|
".opus",
|
|
139
|
-
// Documents: application/msword, text/plain, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document
|
|
139
|
+
// Documents: application/msword, text/plain, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document, text/vtt
|
|
140
140
|
".pdf",
|
|
141
141
|
".doc",
|
|
142
142
|
".docx",
|
|
143
|
-
".txt"
|
|
143
|
+
".txt",
|
|
144
|
+
".vtt"
|
|
144
145
|
]);
|
|
145
146
|
const directories = {
|
|
146
147
|
assets: "assets",
|
|
@@ -166,6 +167,9 @@ const chunk = (items, size) => {
|
|
|
166
167
|
function isPlainObject(value) {
|
|
167
168
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
168
169
|
}
|
|
170
|
+
function isRecord(value) {
|
|
171
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
172
|
+
}
|
|
169
173
|
function mergeDeep(target, source) {
|
|
170
174
|
if (!isPlainObject(source)) {
|
|
171
175
|
return target;
|
|
@@ -904,6 +908,208 @@ function setLoggerTransports(transports) {
|
|
|
904
908
|
}
|
|
905
909
|
}
|
|
906
910
|
|
|
911
|
+
const toCamelCase = (str) => {
|
|
912
|
+
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, "");
|
|
913
|
+
};
|
|
914
|
+
const toPascalCase = (str) => {
|
|
915
|
+
const camelCase = toCamelCase(str);
|
|
916
|
+
return camelCase ? camelCase[0].toUpperCase() + camelCase.slice(1) : camelCase;
|
|
917
|
+
};
|
|
918
|
+
const capitalize = (str) => {
|
|
919
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
920
|
+
};
|
|
921
|
+
const toHumanReadable = (str) => {
|
|
922
|
+
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();
|
|
923
|
+
};
|
|
924
|
+
function maskToken(token) {
|
|
925
|
+
if (token.length <= 4) {
|
|
926
|
+
return token;
|
|
927
|
+
}
|
|
928
|
+
const visiblePart = token.slice(0, 4);
|
|
929
|
+
const maskedPart = "*".repeat(token.length - 4);
|
|
930
|
+
return `${visiblePart}${maskedPart}`;
|
|
931
|
+
}
|
|
932
|
+
const slugify = (text) => text.toString().toLowerCase().replace(/\s+/g, "-").replace(/[^\w-]+/g, "").replace(/-{2,}/g, "-").replace(/^-+/, "").replace(/-+$/, "");
|
|
933
|
+
function createRegexFromGlob(pattern) {
|
|
934
|
+
return new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*")}$`);
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
let stdoutEpipeGuarded = false;
|
|
938
|
+
function guardStdoutEpipe(ui) {
|
|
939
|
+
if (stdoutEpipeGuarded) {
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
stdoutEpipeGuarded = true;
|
|
943
|
+
process.stdout.on("error", (error) => {
|
|
944
|
+
if (error.code === "EPIPE") {
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
ui.error(`Failed to write to stdout: ${error.message}`);
|
|
948
|
+
process.exitCode = 1;
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
const noopProgressBar = {
|
|
952
|
+
increment: () => {
|
|
953
|
+
},
|
|
954
|
+
setTotal: () => {
|
|
955
|
+
},
|
|
956
|
+
stop: () => {
|
|
957
|
+
}
|
|
958
|
+
};
|
|
959
|
+
const noopSpinner = {
|
|
960
|
+
failed: (_title) => {
|
|
961
|
+
},
|
|
962
|
+
succeed: (_title) => {
|
|
963
|
+
},
|
|
964
|
+
elapsedTime: 0
|
|
965
|
+
};
|
|
966
|
+
class UI {
|
|
967
|
+
console;
|
|
968
|
+
enabled;
|
|
969
|
+
multiBar;
|
|
970
|
+
constructor({ enabled }) {
|
|
971
|
+
this.enabled = enabled;
|
|
972
|
+
this.console = null;
|
|
973
|
+
this.multiBar = null;
|
|
974
|
+
this.applyEnabled(enabled);
|
|
975
|
+
}
|
|
976
|
+
/** Update the enabled state (called by getUI when preAction resolves config). */
|
|
977
|
+
setEnabled(enabled) {
|
|
978
|
+
if (this.enabled === enabled) {
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
this.applyEnabled(enabled);
|
|
982
|
+
}
|
|
983
|
+
applyEnabled(enabled) {
|
|
984
|
+
this.enabled = enabled;
|
|
985
|
+
this.console = enabled ? {
|
|
986
|
+
log: (...args) => console.error(...args),
|
|
987
|
+
info: (...args) => console.error(...args),
|
|
988
|
+
warn: (...args) => console.warn(...args),
|
|
989
|
+
error: (...args) => console.error(...args)
|
|
990
|
+
} : null;
|
|
991
|
+
this.multiBar = enabled ? new MultiBar({
|
|
992
|
+
clearOnComplete: false,
|
|
993
|
+
format: `${chalk.bold(" {title} ")} ${chalk.hex(colorPalette.PRIMARY)("[{bar}]")} {percentage}% | {eta_formatted} | {value}/{total} processed`,
|
|
994
|
+
etaBuffer: 60
|
|
995
|
+
}, Presets.rect) : null;
|
|
996
|
+
}
|
|
997
|
+
title(message, color, subtitle) {
|
|
998
|
+
if (subtitle) {
|
|
999
|
+
this.console?.log(`${chalk.bgHex(color).bold(` ${capitalize(message)} `)} ${subtitle}`);
|
|
1000
|
+
} else {
|
|
1001
|
+
this.console?.log(chalk.bgHex(color).bold(` ${capitalize(message)} `));
|
|
1002
|
+
}
|
|
1003
|
+
this.br();
|
|
1004
|
+
this.br();
|
|
1005
|
+
}
|
|
1006
|
+
br() {
|
|
1007
|
+
this.console?.log("");
|
|
1008
|
+
}
|
|
1009
|
+
ok(message, header = false) {
|
|
1010
|
+
if (header) {
|
|
1011
|
+
this.br();
|
|
1012
|
+
const successHeader = chalk.bgGreen.bold.white(` Success `);
|
|
1013
|
+
this.console?.log(successHeader);
|
|
1014
|
+
this.br();
|
|
1015
|
+
}
|
|
1016
|
+
this.console?.log(message ? `${chalk.green("\u2714")} ${message}` : "");
|
|
1017
|
+
}
|
|
1018
|
+
info(message, options = {}) {
|
|
1019
|
+
const { header = false, margin = true } = options;
|
|
1020
|
+
if (header) {
|
|
1021
|
+
this.br();
|
|
1022
|
+
const infoHeader = chalk.bgBlue.bold.white(` Info `);
|
|
1023
|
+
this.console?.info(infoHeader);
|
|
1024
|
+
}
|
|
1025
|
+
this.console?.info(message ? `${chalk.blue("\u2139")} ${message}` : "");
|
|
1026
|
+
if (margin) {
|
|
1027
|
+
this.br();
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
warn(message, header = false) {
|
|
1031
|
+
if (header) {
|
|
1032
|
+
this.br();
|
|
1033
|
+
const warnHeader = chalk.bgYellow.bold.black(` Warning `);
|
|
1034
|
+
this.console?.warn(warnHeader);
|
|
1035
|
+
}
|
|
1036
|
+
this.console?.warn(message ? `${chalk.yellow("\u26A0\uFE0F ")} ${message}` : "");
|
|
1037
|
+
}
|
|
1038
|
+
error(message, info, options = {}) {
|
|
1039
|
+
const { header = false, margin = false } = options;
|
|
1040
|
+
const out = this.console ?? { error: (...args) => console.error(...args), log: (...args) => console.error(...args) };
|
|
1041
|
+
if (header) {
|
|
1042
|
+
const errorHeader = chalk.bgRed.bold.white(` Error `);
|
|
1043
|
+
out.error(errorHeader);
|
|
1044
|
+
out.log("");
|
|
1045
|
+
}
|
|
1046
|
+
if (info) {
|
|
1047
|
+
out.error(`${chalk.red.bold("\u25B2 error")} ${message}`, info);
|
|
1048
|
+
} else {
|
|
1049
|
+
out.error(`${chalk.red.bold("\u25B2 error")} ${message}`);
|
|
1050
|
+
}
|
|
1051
|
+
if (margin) {
|
|
1052
|
+
out.log("");
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
/** Plain console.log passthrough — use for preformatted or multi-line text. */
|
|
1056
|
+
log(message) {
|
|
1057
|
+
this.console?.log(message);
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Writes machine-readable output straight to stdout, bypassing the UI enable
|
|
1061
|
+
* gate. Decorative output is suppressed alongside it (see `--format json`), so
|
|
1062
|
+
* stdout stays a single pipeable document even with `--no-ui-enabled`.
|
|
1063
|
+
*/
|
|
1064
|
+
writeMachineOutput(payload) {
|
|
1065
|
+
guardStdoutEpipe(this);
|
|
1066
|
+
process.stdout.write(`${payload}
|
|
1067
|
+
`);
|
|
1068
|
+
}
|
|
1069
|
+
list(items) {
|
|
1070
|
+
for (const item of items) {
|
|
1071
|
+
this.console?.log(` ${item}`);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
createProgressBar(options) {
|
|
1075
|
+
const bar = this.multiBar?.create(0, 0, options);
|
|
1076
|
+
if (!bar) {
|
|
1077
|
+
return noopProgressBar;
|
|
1078
|
+
}
|
|
1079
|
+
return {
|
|
1080
|
+
increment: (count = 1) => bar.increment(count, options),
|
|
1081
|
+
// cli-progress renders `{eta_formatted}` as "LLs" when total is 0.
|
|
1082
|
+
// Floor at 1 so an empty phase stays a clean 0/1 instead.
|
|
1083
|
+
setTotal: (total) => {
|
|
1084
|
+
bar.setTotal(Math.max(total, 1));
|
|
1085
|
+
bar.update(options);
|
|
1086
|
+
},
|
|
1087
|
+
stop: () => bar.stop()
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
stopAllProgressBars() {
|
|
1091
|
+
this.multiBar?.stop();
|
|
1092
|
+
}
|
|
1093
|
+
createSpinner(title) {
|
|
1094
|
+
if (!this.enabled) {
|
|
1095
|
+
return noopSpinner;
|
|
1096
|
+
}
|
|
1097
|
+
const spinner = new Spinner({ verbose: !isVitest });
|
|
1098
|
+
spinner.stream = process.stderr;
|
|
1099
|
+
return spinner.start(title);
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
const stderrPromptContext = { output: process.stderr };
|
|
1103
|
+
let uiInstance = null;
|
|
1104
|
+
function getUI(options) {
|
|
1105
|
+
if (!uiInstance) {
|
|
1106
|
+
uiInstance = new UI(options ?? { enabled: DEFAULT_GLOBAL_CONFIG.ui.enabled });
|
|
1107
|
+
} else if (options !== void 0) {
|
|
1108
|
+
uiInstance.setEnabled(options.enabled);
|
|
1109
|
+
}
|
|
1110
|
+
return uiInstance;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
907
1113
|
const FS_ERRORS = {
|
|
908
1114
|
file_not_found: "The file requested was not found",
|
|
909
1115
|
permission_denied: "Permission denied while accessing the file",
|
|
@@ -1015,45 +1221,54 @@ function getResponseStatus(maybeError) {
|
|
|
1015
1221
|
return typeof response.status === "number" ? response.status : void 0;
|
|
1016
1222
|
}
|
|
1017
1223
|
function handleVerboseError(error) {
|
|
1224
|
+
const ui = getUI();
|
|
1018
1225
|
if (error instanceof CommandError || error instanceof APIError || error instanceof FileSystemError) {
|
|
1019
1226
|
const errorDetails = "getInfo" in error ? error.getInfo() : {};
|
|
1020
1227
|
if (error instanceof CommandError) {
|
|
1021
|
-
|
|
1228
|
+
ui.error(`Command Error: ${error.getInfo().message}`, errorDetails);
|
|
1022
1229
|
} else if (error instanceof APIError) {
|
|
1023
|
-
|
|
1230
|
+
ui.error(`API Error: ${error.getInfo().cause}`, errorDetails);
|
|
1024
1231
|
} else if (error instanceof FileSystemError) {
|
|
1025
|
-
|
|
1232
|
+
ui.error(`File System Error: ${error.getInfo().cause}`, errorDetails);
|
|
1026
1233
|
} else {
|
|
1027
|
-
|
|
1234
|
+
ui.error(`Unexpected Error: ${error}`, errorDetails);
|
|
1028
1235
|
}
|
|
1029
1236
|
} else {
|
|
1030
|
-
|
|
1237
|
+
ui.error("Unexpected Error", error);
|
|
1031
1238
|
}
|
|
1032
1239
|
}
|
|
1240
|
+
function isPromptCancellation(error) {
|
|
1241
|
+
return error.name === "ExitPromptError" || error.name === "AbortPromptError" || error.name === "CancelPromptError";
|
|
1242
|
+
}
|
|
1033
1243
|
function handleError(error, verbose = false, context) {
|
|
1244
|
+
if (isPromptCancellation(error)) {
|
|
1245
|
+
process.exitCode = 0;
|
|
1246
|
+
return;
|
|
1247
|
+
}
|
|
1248
|
+
const ui = getUI();
|
|
1034
1249
|
if (error instanceof APIError || error instanceof FileSystemError) {
|
|
1035
1250
|
const messageStack = error.messageStack;
|
|
1036
1251
|
messageStack.forEach((message, index) => {
|
|
1037
|
-
|
|
1038
|
-
header:
|
|
1039
|
-
|
|
1040
|
-
|
|
1252
|
+
if (index === 0) {
|
|
1253
|
+
ui.error(message, void 0, { header: true });
|
|
1254
|
+
} else {
|
|
1255
|
+
ui.error(message);
|
|
1256
|
+
}
|
|
1041
1257
|
});
|
|
1042
1258
|
} else {
|
|
1043
|
-
|
|
1044
|
-
header: true
|
|
1045
|
-
});
|
|
1259
|
+
ui.error(error.message, void 0, { header: true });
|
|
1046
1260
|
}
|
|
1047
1261
|
if (verbose) {
|
|
1048
1262
|
handleVerboseError(error);
|
|
1049
1263
|
} else {
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
}
|
|
1053
|
-
if (!process.env.VITEST) {
|
|
1054
|
-
console.log("");
|
|
1264
|
+
ui.br();
|
|
1265
|
+
ui.info("For more information about the error, run the command with the `--verbose` flag");
|
|
1055
1266
|
}
|
|
1267
|
+
ui.br();
|
|
1056
1268
|
getLogger().error(error.message, { error, errorCode: "code" in error ? String(error.code) : "UNKNOWN_ERROR", context });
|
|
1269
|
+
if (!process.exitCode) {
|
|
1270
|
+
process.exitCode = error instanceof CommandError ? 2 : 1;
|
|
1271
|
+
}
|
|
1057
1272
|
}
|
|
1058
1273
|
function logOnlyError(error, context) {
|
|
1059
1274
|
getLogger().error(error.message, { error, errorCode: "code" in error ? String(error.code) : "UNKNOWN_ERROR", context });
|
|
@@ -1070,92 +1285,6 @@ function requireAuthentication(state, verbose = false) {
|
|
|
1070
1285
|
return true;
|
|
1071
1286
|
}
|
|
1072
1287
|
|
|
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
1288
|
const __filename$2 = fileURLToPath(import.meta.url);
|
|
1160
1289
|
const __dirname$2 = dirname(__filename$2);
|
|
1161
1290
|
const result = await readPackageUp({
|
|
@@ -1167,7 +1296,7 @@ const packageJson$1 = result ? result.packageJson : {
|
|
|
1167
1296
|
version: "0.0.0"
|
|
1168
1297
|
};
|
|
1169
1298
|
if (!result) {
|
|
1170
|
-
console.
|
|
1299
|
+
console.error("Metadata not found");
|
|
1171
1300
|
}
|
|
1172
1301
|
function getPackageJson() {
|
|
1173
1302
|
return packageJson$1;
|
|
@@ -1199,126 +1328,6 @@ function isRegion(value) {
|
|
|
1199
1328
|
}
|
|
1200
1329
|
const isVitest = process.env.VITEST === "true";
|
|
1201
1330
|
|
|
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
1331
|
const DEFAULT_STORAGE_DIR = ".storyblok";
|
|
1323
1332
|
const getStoryblokGlobalPath = () => {
|
|
1324
1333
|
const homeDirectory = process.env[process.platform.startsWith("win") ? "USERPROFILE" : "HOME"] || process.cwd();
|
|
@@ -1698,20 +1707,7 @@ class ConsoleTransport {
|
|
|
1698
1707
|
return;
|
|
1699
1708
|
}
|
|
1700
1709
|
const line = this.format(record);
|
|
1701
|
-
|
|
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
|
-
}
|
|
1710
|
+
console.error(line);
|
|
1715
1711
|
}
|
|
1716
1712
|
levelRank(level) {
|
|
1717
1713
|
switch (level) {
|
|
@@ -2028,8 +2024,9 @@ function getProgram() {
|
|
|
2028
2024
|
}
|
|
2029
2025
|
}
|
|
2030
2026
|
});
|
|
2027
|
+
programInstance.exitOverride();
|
|
2031
2028
|
programInstance.configureOutput({
|
|
2032
|
-
writeErr: (str) => handleError(new
|
|
2029
|
+
writeErr: (str) => handleError(new CommandError(str.replace(/^error:\s*/i, "").trim()))
|
|
2033
2030
|
});
|
|
2034
2031
|
}
|
|
2035
2032
|
return programInstance;
|
|
@@ -2094,9 +2091,8 @@ const loginWithOtp = async (email, password, otp, region) => {
|
|
|
2094
2091
|
|
|
2095
2092
|
async function performInteractiveLogin(options) {
|
|
2096
2093
|
const { verbose = false, preSelectedRegion, showWelcomeMessage = true } = options || {};
|
|
2097
|
-
const
|
|
2098
|
-
|
|
2099
|
-
});
|
|
2094
|
+
const ui = getUI();
|
|
2095
|
+
let activeSpinner = null;
|
|
2100
2096
|
try {
|
|
2101
2097
|
const strategy = await select({
|
|
2102
2098
|
message: "How would you like to login?",
|
|
@@ -2112,11 +2108,11 @@ async function performInteractiveLogin(options) {
|
|
|
2112
2108
|
short: "Token"
|
|
2113
2109
|
}
|
|
2114
2110
|
]
|
|
2115
|
-
});
|
|
2111
|
+
}, stderrPromptContext);
|
|
2116
2112
|
let userToken;
|
|
2117
2113
|
let userRegion;
|
|
2118
2114
|
if (strategy === "login-with-token") {
|
|
2119
|
-
|
|
2115
|
+
ui.info([
|
|
2120
2116
|
"\u{1F511} You can use a Personal Access Token to log in.",
|
|
2121
2117
|
"This works for all accounts, including SSO accounts.",
|
|
2122
2118
|
`Generate one in your Storyblok account settings: ${chalk.underline.blue("https://app.storyblok.com/#/me/account?tab=token")}`
|
|
@@ -2126,7 +2122,7 @@ async function performInteractiveLogin(options) {
|
|
|
2126
2122
|
validate: (value) => {
|
|
2127
2123
|
return value.length > 0;
|
|
2128
2124
|
}
|
|
2129
|
-
});
|
|
2125
|
+
}, stderrPromptContext);
|
|
2130
2126
|
userRegion = preSelectedRegion || await select({
|
|
2131
2127
|
message: "Please select the region you would like to work in:",
|
|
2132
2128
|
choices: Object.values(regions).map((region) => ({
|
|
@@ -2134,16 +2130,16 @@ async function performInteractiveLogin(options) {
|
|
|
2134
2130
|
value: region
|
|
2135
2131
|
})),
|
|
2136
2132
|
default: regions.EU
|
|
2137
|
-
});
|
|
2138
|
-
|
|
2133
|
+
}, stderrPromptContext);
|
|
2134
|
+
activeSpinner = ui.createSpinner(`Logging in with token`);
|
|
2139
2135
|
const user = await loginWithToken(userToken, userRegion);
|
|
2140
|
-
|
|
2136
|
+
activeSpinner.succeed();
|
|
2141
2137
|
if (user) {
|
|
2142
2138
|
const { updateSession, persistCredentials } = session();
|
|
2143
2139
|
updateSession(user.email, userToken, userRegion);
|
|
2144
2140
|
await persistCredentials(userRegion);
|
|
2145
2141
|
if (showWelcomeMessage) {
|
|
2146
|
-
|
|
2142
|
+
ui.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(user.friendly_name)}.`, true);
|
|
2147
2143
|
}
|
|
2148
2144
|
return { token: userToken, region: userRegion };
|
|
2149
2145
|
}
|
|
@@ -2155,10 +2151,10 @@ async function performInteractiveLogin(options) {
|
|
|
2155
2151
|
const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
|
|
2156
2152
|
return emailRegex.test(value);
|
|
2157
2153
|
}
|
|
2158
|
-
});
|
|
2154
|
+
}, stderrPromptContext);
|
|
2159
2155
|
const userPassword = await password({
|
|
2160
2156
|
message: "Please enter your password:"
|
|
2161
|
-
});
|
|
2157
|
+
}, stderrPromptContext);
|
|
2162
2158
|
userRegion = preSelectedRegion || await select({
|
|
2163
2159
|
message: "Please select the region you would like to work in:",
|
|
2164
2160
|
choices: Object.values(regions).map((region) => ({
|
|
@@ -2166,15 +2162,15 @@ async function performInteractiveLogin(options) {
|
|
|
2166
2162
|
value: region
|
|
2167
2163
|
})),
|
|
2168
2164
|
default: regions.EU
|
|
2169
|
-
});
|
|
2170
|
-
|
|
2171
|
-
spinner.succeed();
|
|
2165
|
+
}, stderrPromptContext);
|
|
2166
|
+
activeSpinner = ui.createSpinner(`Logging in with email`);
|
|
2172
2167
|
const response = await loginWithEmailAndPassword(userEmail, userPassword, userRegion);
|
|
2168
|
+
activeSpinner.succeed();
|
|
2173
2169
|
if (response?.otp_required) {
|
|
2174
2170
|
const otp = await input({
|
|
2175
2171
|
message: "Add the code from your Authenticator app, or the one we sent to your e-mail / phone:",
|
|
2176
2172
|
required: true
|
|
2177
|
-
});
|
|
2173
|
+
}, stderrPromptContext);
|
|
2178
2174
|
const otpResponse = await loginWithOtp(userEmail, userPassword, otp, userRegion);
|
|
2179
2175
|
if (otpResponse?.access_token) {
|
|
2180
2176
|
userToken = otpResponse.access_token;
|
|
@@ -2187,15 +2183,15 @@ async function performInteractiveLogin(options) {
|
|
|
2187
2183
|
updateSession(userEmail, userToken, userRegion);
|
|
2188
2184
|
await persistCredentials(userRegion);
|
|
2189
2185
|
if (showWelcomeMessage) {
|
|
2190
|
-
|
|
2186
|
+
ui.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(userEmail)}.`, true);
|
|
2191
2187
|
}
|
|
2192
2188
|
return { token: userToken, region: userRegion };
|
|
2193
2189
|
}
|
|
2194
2190
|
}
|
|
2195
2191
|
return null;
|
|
2196
2192
|
} catch (error) {
|
|
2197
|
-
|
|
2198
|
-
|
|
2193
|
+
activeSpinner?.failed();
|
|
2194
|
+
ui.br();
|
|
2199
2195
|
handleError(error, verbose);
|
|
2200
2196
|
return null;
|
|
2201
2197
|
}
|
|
@@ -2207,12 +2203,13 @@ program$f.command(commands.LOGIN).description("Login to the Storyblok CLI").opti
|
|
|
2207
2203
|
"-r, --region <region>",
|
|
2208
2204
|
`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
2205
|
).action(async (options) => {
|
|
2210
|
-
|
|
2206
|
+
const ui = getUI();
|
|
2207
|
+
ui.title(`${commands.LOGIN}`, colorPalette.LOGIN);
|
|
2211
2208
|
const verbose = program$f.opts().verbose;
|
|
2212
2209
|
const { token, region } = options;
|
|
2213
2210
|
const { state, updateSession, persistCredentials } = session();
|
|
2214
2211
|
if (state.isLoggedIn && !state.envLogin) {
|
|
2215
|
-
|
|
2212
|
+
ui.ok(`You are already logged in. If you want to login with a different account, please logout first.`);
|
|
2216
2213
|
return;
|
|
2217
2214
|
}
|
|
2218
2215
|
if (region && !isRegion(region)) {
|
|
@@ -2220,9 +2217,7 @@ program$f.command(commands.LOGIN).description("Login to the Storyblok CLI").opti
|
|
|
2220
2217
|
return;
|
|
2221
2218
|
}
|
|
2222
2219
|
if (token) {
|
|
2223
|
-
|
|
2224
|
-
verbose: !isVitest
|
|
2225
|
-
});
|
|
2220
|
+
let spinner = null;
|
|
2226
2221
|
try {
|
|
2227
2222
|
let userRegion = region;
|
|
2228
2223
|
if (!userRegion) {
|
|
@@ -2233,19 +2228,19 @@ program$f.command(commands.LOGIN).description("Login to the Storyblok CLI").opti
|
|
|
2233
2228
|
value: region2
|
|
2234
2229
|
})),
|
|
2235
2230
|
default: regions.EU
|
|
2236
|
-
});
|
|
2231
|
+
}, stderrPromptContext);
|
|
2237
2232
|
}
|
|
2238
|
-
spinner.
|
|
2233
|
+
spinner = ui.createSpinner(`Logging in with token`);
|
|
2239
2234
|
const user = await loginWithToken(token, userRegion);
|
|
2240
2235
|
if (user) {
|
|
2241
2236
|
updateSession(user.email, token, userRegion);
|
|
2242
2237
|
await persistCredentials(userRegion);
|
|
2243
2238
|
spinner.succeed();
|
|
2244
|
-
|
|
2239
|
+
ui.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(user.friendly_name)}.`, true);
|
|
2245
2240
|
}
|
|
2246
2241
|
} catch (error) {
|
|
2247
|
-
spinner
|
|
2248
|
-
|
|
2242
|
+
spinner?.failed();
|
|
2243
|
+
ui.br();
|
|
2249
2244
|
handleError(error, verbose);
|
|
2250
2245
|
}
|
|
2251
2246
|
} else {
|
|
@@ -2256,34 +2251,35 @@ program$f.command(commands.LOGIN).description("Login to the Storyblok CLI").opti
|
|
|
2256
2251
|
showWelcomeMessage: true
|
|
2257
2252
|
});
|
|
2258
2253
|
if (!result) {
|
|
2259
|
-
|
|
2254
|
+
ui.warn("Login cancelled or failed.");
|
|
2260
2255
|
}
|
|
2261
2256
|
} catch (error) {
|
|
2262
|
-
|
|
2257
|
+
ui.br();
|
|
2263
2258
|
handleError(error, verbose);
|
|
2264
2259
|
}
|
|
2265
2260
|
}
|
|
2266
|
-
|
|
2261
|
+
ui.br();
|
|
2267
2262
|
});
|
|
2268
2263
|
|
|
2269
2264
|
const program$e = getProgram();
|
|
2270
2265
|
program$e.command(commands.LOGOUT).description("Logout from the Storyblok CLI").action(async () => {
|
|
2271
|
-
|
|
2266
|
+
const ui = getUI();
|
|
2267
|
+
ui.title(`${commands.LOGOUT}`, colorPalette.LOGOUT);
|
|
2272
2268
|
const verbose = program$e.opts().verbose;
|
|
2273
2269
|
try {
|
|
2274
2270
|
const { state } = session();
|
|
2275
2271
|
if (!state.isLoggedIn || !state.password || !state.region) {
|
|
2276
|
-
|
|
2277
|
-
|
|
2272
|
+
ui.warn(`You are already logged out. If you want to login, please use the login command.`);
|
|
2273
|
+
ui.br();
|
|
2278
2274
|
return;
|
|
2279
2275
|
}
|
|
2280
2276
|
await removeAllCredentials();
|
|
2281
|
-
|
|
2282
|
-
|
|
2277
|
+
ui.ok(`Successfully logged out.`, true);
|
|
2278
|
+
ui.br();
|
|
2283
2279
|
} catch (error) {
|
|
2284
2280
|
handleError(error, verbose);
|
|
2285
2281
|
}
|
|
2286
|
-
|
|
2282
|
+
ui.br();
|
|
2287
2283
|
});
|
|
2288
2284
|
|
|
2289
2285
|
const execAsync = promisify(exec);
|
|
@@ -2318,39 +2314,39 @@ async function openSignupInBrowser(url) {
|
|
|
2318
2314
|
|
|
2319
2315
|
const program$d = getProgram();
|
|
2320
2316
|
program$d.command(commands.SIGNUP).description("Sign up for Storyblok").action(async () => {
|
|
2321
|
-
|
|
2317
|
+
const ui = getUI();
|
|
2318
|
+
ui.title(`${commands.SIGNUP}`, colorPalette.SIGNUP);
|
|
2322
2319
|
const verbose = program$d.opts().verbose;
|
|
2323
2320
|
const { state } = session();
|
|
2324
2321
|
if (state.isLoggedIn && !state.envLogin) {
|
|
2325
|
-
|
|
2322
|
+
ui.ok(`You are already logged in. If you want to signup with a different account, please logout first.`);
|
|
2326
2323
|
return;
|
|
2327
2324
|
}
|
|
2328
2325
|
try {
|
|
2329
2326
|
const signupUrl = buildSignupUrl();
|
|
2330
|
-
|
|
2331
|
-
|
|
2327
|
+
ui.info(`Opening Storyblok signup page...`);
|
|
2328
|
+
ui.info(`URL: ${chalk.dim(signupUrl)}`);
|
|
2332
2329
|
await openSignupInBrowser(signupUrl);
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2330
|
+
ui.ok(`Browser opened! Please complete the signup process.`);
|
|
2331
|
+
ui.br();
|
|
2332
|
+
ui.info(`Once you've completed signup, run ${chalk.hex(colorPalette.PRIMARY)("storyblok login")} to authenticate with the CLI.`);
|
|
2336
2333
|
} catch (error) {
|
|
2337
|
-
|
|
2334
|
+
ui.br();
|
|
2338
2335
|
handleError(error, verbose);
|
|
2339
2336
|
}
|
|
2340
|
-
|
|
2337
|
+
ui.br();
|
|
2341
2338
|
});
|
|
2342
2339
|
|
|
2343
2340
|
const program$c = getProgram();
|
|
2344
2341
|
program$c.command(commands.USER).description("Get the current user").action(async () => {
|
|
2345
|
-
|
|
2342
|
+
const ui = getUI();
|
|
2343
|
+
ui.title(`${commands.USER}`, colorPalette.USER);
|
|
2346
2344
|
const verbose = program$c.opts().verbose;
|
|
2347
2345
|
const { state } = session();
|
|
2348
2346
|
if (!requireAuthentication(state)) {
|
|
2349
2347
|
return;
|
|
2350
2348
|
}
|
|
2351
|
-
const spinner =
|
|
2352
|
-
verbose: !isVitest
|
|
2353
|
-
}).start(`Fetching user info`);
|
|
2349
|
+
const spinner = ui.createSpinner(`Fetching user info`);
|
|
2354
2350
|
try {
|
|
2355
2351
|
const { password, region } = state;
|
|
2356
2352
|
if (!password || !region) {
|
|
@@ -2359,16 +2355,16 @@ program$c.command(commands.USER).description("Get the current user").action(asyn
|
|
|
2359
2355
|
const user = await getUser(password, region);
|
|
2360
2356
|
if (user) {
|
|
2361
2357
|
if (verbose) {
|
|
2362
|
-
|
|
2358
|
+
ui.info(JSON.stringify(user, null, 2));
|
|
2363
2359
|
}
|
|
2364
2360
|
spinner.succeed();
|
|
2365
|
-
|
|
2361
|
+
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
2362
|
}
|
|
2367
2363
|
} catch (error) {
|
|
2368
2364
|
spinner.failed();
|
|
2369
2365
|
handleError(error, true);
|
|
2370
2366
|
}
|
|
2371
|
-
|
|
2367
|
+
ui.br();
|
|
2372
2368
|
});
|
|
2373
2369
|
|
|
2374
2370
|
const program$b = getProgram();
|
|
@@ -2855,7 +2851,7 @@ function buildDependencyGraph(context) {
|
|
|
2855
2851
|
const nodeId = `preset:${preset.id}`;
|
|
2856
2852
|
const sourceComponent = componentMap.get(preset.component_id);
|
|
2857
2853
|
if (!sourceComponent) {
|
|
2858
|
-
|
|
2854
|
+
getLogger().warn(`Preset "${preset.name}" (ID: ${preset.id}) references component ID ${preset.component_id} which is not available in local data. Skipping preset.`);
|
|
2859
2855
|
return;
|
|
2860
2856
|
}
|
|
2861
2857
|
const compositeKey = `${sourceComponent.name}:${preset.name}`;
|
|
@@ -3128,17 +3124,18 @@ function determineProcessingOrder(graph) {
|
|
|
3128
3124
|
return levels;
|
|
3129
3125
|
}
|
|
3130
3126
|
function validateGraph(graph) {
|
|
3131
|
-
|
|
3127
|
+
const logger = getLogger();
|
|
3128
|
+
logger.info(`Built dependency graph with ${graph.nodes.size} nodes`);
|
|
3132
3129
|
const problematicCycles = detectProblematicCycles(graph);
|
|
3133
3130
|
if (problematicCycles.length > 0) {
|
|
3134
|
-
throw new Error(
|
|
3131
|
+
throw new Error(`Problematic cycles detected:
|
|
3135
3132
|
${problematicCycles.join("\n")}`);
|
|
3136
3133
|
}
|
|
3137
3134
|
const circularWhitelists = detectCircularWhitelists(graph);
|
|
3138
3135
|
if (circularWhitelists.length > 0) {
|
|
3139
|
-
|
|
3136
|
+
logger.info(`Circular component whitelists detected (allowed): ${circularWhitelists.join(", ")}`);
|
|
3140
3137
|
}
|
|
3141
|
-
|
|
3138
|
+
logger.info(`Graph validation passed`);
|
|
3142
3139
|
}
|
|
3143
3140
|
class GraphNode {
|
|
3144
3141
|
id;
|
|
@@ -3578,31 +3575,49 @@ pullCmd$4.action(async (componentName, options, command) => {
|
|
|
3578
3575
|
return;
|
|
3579
3576
|
}
|
|
3580
3577
|
logger.info("Pulling components started", { space, componentName });
|
|
3581
|
-
const
|
|
3582
|
-
const
|
|
3583
|
-
const
|
|
3584
|
-
const
|
|
3578
|
+
const pad = "Components".length;
|
|
3579
|
+
const barGroups = ui.createProgressBar({ title: "Groups".padEnd(pad) });
|
|
3580
|
+
const barPresets = ui.createProgressBar({ title: "Presets".padEnd(pad) });
|
|
3581
|
+
const barTags = ui.createProgressBar({ title: "Tags".padEnd(pad) });
|
|
3582
|
+
const barComponents = ui.createProgressBar({ title: "Components" });
|
|
3583
|
+
barGroups.setTotal(1);
|
|
3584
|
+
barPresets.setTotal(1);
|
|
3585
|
+
barTags.setTotal(1);
|
|
3586
|
+
barComponents.setTotal(1);
|
|
3585
3587
|
try {
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3588
|
+
const componentsFetch = componentName ? fetchComponent(space, componentName).then((c) => c ? [c] : void 0) : fetchComponents(space);
|
|
3589
|
+
const [groupsResult, presetsResult, tagsResult, componentsResult] = await Promise.all([
|
|
3590
|
+
fetchComponentGroups(space),
|
|
3591
|
+
fetchComponentPresets(space),
|
|
3592
|
+
fetchComponentInternalTags(space),
|
|
3593
|
+
componentsFetch
|
|
3594
|
+
]);
|
|
3595
|
+
let groups = groupsResult;
|
|
3596
|
+
logger.info("Fetched groups", { count: groups?.length ?? 0 });
|
|
3597
|
+
barGroups.increment();
|
|
3598
|
+
let presets = presetsResult;
|
|
3599
|
+
logger.info("Fetched presets", { count: presets?.length ?? 0 });
|
|
3600
|
+
barPresets.increment();
|
|
3601
|
+
let internalTags = tagsResult;
|
|
3602
|
+
logger.info("Fetched tags", { count: internalTags?.length ?? 0 });
|
|
3603
|
+
barTags.increment();
|
|
3592
3604
|
let components;
|
|
3593
3605
|
if (componentName) {
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
3606
|
+
if (!componentsResult || componentsResult.length === 0) {
|
|
3607
|
+
barComponents.stop();
|
|
3608
|
+
ui.stopAllProgressBars();
|
|
3609
|
+
handleError(new CommandError(`No component found with name "${componentName}"`), verbose);
|
|
3597
3610
|
return;
|
|
3598
3611
|
}
|
|
3599
|
-
components =
|
|
3612
|
+
components = componentsResult;
|
|
3600
3613
|
} else {
|
|
3601
|
-
|
|
3602
|
-
|
|
3603
|
-
|
|
3614
|
+
if (!componentsResult || componentsResult.length === 0) {
|
|
3615
|
+
barComponents.stop();
|
|
3616
|
+
ui.stopAllProgressBars();
|
|
3617
|
+
handleError(new CommandError(`No components found in the space ${space}`), verbose);
|
|
3604
3618
|
return;
|
|
3605
3619
|
}
|
|
3620
|
+
components = componentsResult;
|
|
3606
3621
|
const hasSelectors = Boolean(filter) || group && group.length > 0 || tag && tag.length > 0;
|
|
3607
3622
|
if (hasSelectors) {
|
|
3608
3623
|
const groupUuids = group && group.length > 0 ? new Set(group.flatMap((g) => [...resolveGroupSelector(groups || [], g)])) : void 0;
|
|
@@ -3612,7 +3627,8 @@ pullCmd$4.action(async (componentName, options, command) => {
|
|
|
3612
3627
|
{ filter, groupUuids, tagIds }
|
|
3613
3628
|
);
|
|
3614
3629
|
if (filtered.components.length === 0) {
|
|
3615
|
-
|
|
3630
|
+
barComponents.stop();
|
|
3631
|
+
ui.stopAllProgressBars();
|
|
3616
3632
|
ui.warn("No components found matching the given selectors.");
|
|
3617
3633
|
return;
|
|
3618
3634
|
}
|
|
@@ -3622,7 +3638,13 @@ pullCmd$4.action(async (componentName, options, command) => {
|
|
|
3622
3638
|
internalTags = filtered.internalTags;
|
|
3623
3639
|
}
|
|
3624
3640
|
}
|
|
3625
|
-
|
|
3641
|
+
logger.info("Fetched components", { count: components.length });
|
|
3642
|
+
barComponents.increment();
|
|
3643
|
+
barGroups.stop();
|
|
3644
|
+
barPresets.stop();
|
|
3645
|
+
barTags.stop();
|
|
3646
|
+
barComponents.stop();
|
|
3647
|
+
ui.stopAllProgressBars();
|
|
3626
3648
|
await saveComponentsToFiles(
|
|
3627
3649
|
space,
|
|
3628
3650
|
{ components, groups: groups || [], presets: presets || [], internalTags: internalTags || [], datasources: [] },
|
|
@@ -3649,10 +3671,11 @@ pullCmd$4.action(async (componentName, options, command) => {
|
|
|
3649
3671
|
}
|
|
3650
3672
|
ui.br();
|
|
3651
3673
|
} catch (error) {
|
|
3652
|
-
|
|
3653
|
-
|
|
3654
|
-
|
|
3655
|
-
|
|
3674
|
+
barGroups.stop();
|
|
3675
|
+
barPresets.stop();
|
|
3676
|
+
barTags.stop();
|
|
3677
|
+
barComponents.stop();
|
|
3678
|
+
ui.stopAllProgressBars();
|
|
3656
3679
|
ui.br();
|
|
3657
3680
|
handleError(error, verbose);
|
|
3658
3681
|
} finally {
|
|
@@ -3660,143 +3683,60 @@ pullCmd$4.action(async (componentName, options, command) => {
|
|
|
3660
3683
|
}
|
|
3661
3684
|
});
|
|
3662
3685
|
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
3666
|
-
|
|
3667
|
-
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
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;
|
|
3686
|
+
async function processAllResources(graph, space, backpressure = getActiveConfig().api.rateLimit) {
|
|
3687
|
+
const ui = getUI();
|
|
3688
|
+
const logger = getLogger();
|
|
3689
|
+
const levels = determineProcessingOrder(graph);
|
|
3690
|
+
const results = { successful: [], failed: [] };
|
|
3691
|
+
const countByType = /* @__PURE__ */ new Map();
|
|
3692
|
+
for (const level of levels) {
|
|
3693
|
+
for (const nodeId of level.nodes) {
|
|
3694
|
+
const node = graph.nodes.get(nodeId);
|
|
3695
|
+
if (node) {
|
|
3696
|
+
countByType.set(node.type, (countByType.get(node.type) ?? 0) + 1);
|
|
3728
3697
|
}
|
|
3729
3698
|
}
|
|
3730
3699
|
}
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3700
|
+
logger.info("Processing order determined", {
|
|
3701
|
+
levels: levels.length,
|
|
3702
|
+
totalResources: Array.from(countByType.values()).reduce((a, b) => a + b, 0),
|
|
3703
|
+
cyclic: levels.filter((l) => l.isCyclic).length
|
|
3704
|
+
});
|
|
3705
|
+
const typeOrder = ["tag", "group", "component", "preset"];
|
|
3706
|
+
const typeLabels = { tag: "Tags", group: "Groups", component: "Components", preset: "Presets" };
|
|
3707
|
+
const pad = Math.max(...Object.values(typeLabels).map((l) => l.length));
|
|
3708
|
+
const bars = /* @__PURE__ */ new Map();
|
|
3709
|
+
for (const type of typeOrder) {
|
|
3710
|
+
const count = countByType.get(type);
|
|
3711
|
+
if (count && count > 0) {
|
|
3712
|
+
const bar = ui.createProgressBar({ title: typeLabels[type].padEnd(pad) });
|
|
3713
|
+
bar.setTotal(count);
|
|
3714
|
+
bars.set(type, bar);
|
|
3738
3715
|
}
|
|
3739
3716
|
}
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
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`;
|
|
3717
|
+
try {
|
|
3718
|
+
for (const level of levels) {
|
|
3719
|
+
if (level.isCyclic) {
|
|
3720
|
+
const cyclicResults = await processCyclicLevel(level, graph, space, backpressure, bars);
|
|
3721
|
+
mergeResults(results, cyclicResults);
|
|
3722
|
+
} else {
|
|
3723
|
+
const levelResults = await processLevel(level.nodes, graph, space, backpressure, bars);
|
|
3724
|
+
mergeResults(results, levelResults);
|
|
3725
|
+
}
|
|
3762
3726
|
}
|
|
3763
|
-
|
|
3764
|
-
|
|
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);
|
|
3727
|
+
} finally {
|
|
3728
|
+
for (const bar of bars.values()) {
|
|
3729
|
+
bar.stop();
|
|
3781
3730
|
}
|
|
3731
|
+
ui.stopAllProgressBars();
|
|
3782
3732
|
}
|
|
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
3733
|
return results;
|
|
3793
3734
|
}
|
|
3794
|
-
async function processCyclicLevel(level, graph, space, backpressure) {
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
\u{1F504} Detected circular dependencies: ${level.nodes.map((id) => id.replace("component:", "")).join(", ")}`);
|
|
3735
|
+
async function processCyclicLevel(level, graph, space, backpressure, bars) {
|
|
3736
|
+
const logger = getLogger();
|
|
3737
|
+
logger.warn(`Detected circular dependencies: ${level.nodes.map((id) => id.replace("component:", "")).join(", ")}`);
|
|
3798
3738
|
await createStubComponents(level.nodes, graph, space);
|
|
3799
|
-
return await processLevel(level.nodes, graph, space, backpressure);
|
|
3739
|
+
return await processLevel(level.nodes, graph, space, backpressure, bars);
|
|
3800
3740
|
}
|
|
3801
3741
|
async function createStubComponents(nodeIds, graph, space) {
|
|
3802
3742
|
const missingComponents = [];
|
|
@@ -3809,7 +3749,8 @@ async function createStubComponents(nodeIds, graph, space) {
|
|
|
3809
3749
|
if (missingComponents.length === 0) {
|
|
3810
3750
|
return;
|
|
3811
3751
|
}
|
|
3812
|
-
|
|
3752
|
+
const logger = getLogger();
|
|
3753
|
+
logger.info(`Creating stub components for circular dependencies: ${missingComponents.join(", ")}`);
|
|
3813
3754
|
for (const nodeId of nodeIds) {
|
|
3814
3755
|
const node = graph.nodes.get(nodeId);
|
|
3815
3756
|
if (node && node.type === "component" && !node.targetData) {
|
|
@@ -3818,15 +3759,14 @@ async function createStubComponents(nodeIds, graph, space) {
|
|
|
3818
3759
|
const result = await pushComponent(space, stubComponent);
|
|
3819
3760
|
if (result) {
|
|
3820
3761
|
node.updateTargetData(result);
|
|
3821
|
-
|
|
3762
|
+
logger.info(`Created stub component: ${node.name}`);
|
|
3822
3763
|
}
|
|
3823
3764
|
} catch (error) {
|
|
3824
|
-
|
|
3765
|
+
logger.error(`Failed to create stub component ${node.name}`, { error });
|
|
3825
3766
|
throw error;
|
|
3826
3767
|
}
|
|
3827
3768
|
}
|
|
3828
3769
|
}
|
|
3829
|
-
console.log("");
|
|
3830
3770
|
}
|
|
3831
3771
|
function createMinimalStubComponent(name) {
|
|
3832
3772
|
return {
|
|
@@ -3836,10 +3776,12 @@ function createMinimalStubComponent(name) {
|
|
|
3836
3776
|
// Minimal empty schema
|
|
3837
3777
|
};
|
|
3838
3778
|
}
|
|
3839
|
-
async function processLevel(level, graph, space, backpressure) {
|
|
3779
|
+
async function processLevel(level, graph, space, backpressure, bars) {
|
|
3780
|
+
const logger = getLogger();
|
|
3840
3781
|
for (const nodeId of level) {
|
|
3841
3782
|
const node = graph.nodes.get(nodeId);
|
|
3842
3783
|
node.resolveReferences(graph);
|
|
3784
|
+
logger.info(`Resolved references: ${node.getName()}`, { type: node.type });
|
|
3843
3785
|
}
|
|
3844
3786
|
const semaphore = Array.from({ length: backpressure }, () => null);
|
|
3845
3787
|
const promises = [];
|
|
@@ -3849,37 +3791,29 @@ async function processLevel(level, graph, space, backpressure) {
|
|
|
3849
3791
|
if (i >= backpressure && semaphore[slotIndex]) {
|
|
3850
3792
|
await semaphore[slotIndex];
|
|
3851
3793
|
}
|
|
3852
|
-
const promise = processNode(nodeId, graph, space);
|
|
3794
|
+
const promise = processNode(nodeId, graph, space, bars);
|
|
3853
3795
|
promises.push(promise);
|
|
3854
3796
|
semaphore[slotIndex] = promise;
|
|
3855
3797
|
}
|
|
3856
3798
|
const results = await Promise.all(promises);
|
|
3857
3799
|
return aggregateResults(results);
|
|
3858
3800
|
}
|
|
3859
|
-
async function processNode(nodeId, graph, space) {
|
|
3801
|
+
async function processNode(nodeId, graph, space, bars) {
|
|
3860
3802
|
const node = graph.nodes.get(nodeId);
|
|
3803
|
+
const logger = getLogger();
|
|
3861
3804
|
const startTime = Date.now();
|
|
3862
3805
|
try {
|
|
3806
|
+
logger.info(`Upserting ${node.type}: ${node.getName()}`);
|
|
3863
3807
|
const result = await node.upsert(space);
|
|
3864
3808
|
node.updateTargetData(result);
|
|
3865
3809
|
const elapsedMs = Date.now() - startTime;
|
|
3866
|
-
|
|
3867
|
-
|
|
3868
|
-
name: node.getName(),
|
|
3869
|
-
resourceType: getResourceTypeName(node.type),
|
|
3870
|
-
color: getResourceTypeColor(node.type),
|
|
3871
|
-
elapsedMs
|
|
3872
|
-
});
|
|
3810
|
+
logger.info(`Upserted ${node.type}: ${node.getName()}`, { elapsedMs });
|
|
3811
|
+
bars.get(node.type)?.increment();
|
|
3873
3812
|
return { name: node.getName() };
|
|
3874
3813
|
} catch (error) {
|
|
3875
3814
|
const elapsedMs = Date.now() - startTime;
|
|
3876
|
-
|
|
3877
|
-
|
|
3878
|
-
name: node.getName(),
|
|
3879
|
-
resourceType: getResourceTypeName(node.type),
|
|
3880
|
-
error,
|
|
3881
|
-
elapsedMs
|
|
3882
|
-
});
|
|
3815
|
+
logger.error(`Failed to upsert ${node.type}: ${node.getName()}`, { elapsedMs, error });
|
|
3816
|
+
bars.get(node.type)?.increment();
|
|
3883
3817
|
return { name: node.getName(), error };
|
|
3884
3818
|
}
|
|
3885
3819
|
}
|
|
@@ -3898,40 +3832,26 @@ function mergeResults(target, source) {
|
|
|
3898
3832
|
target.successful.push(...source.successful);
|
|
3899
3833
|
target.failed.push(...source.failed);
|
|
3900
3834
|
}
|
|
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
3835
|
|
|
3930
3836
|
async function pushWithDependencyGraph(space, spaceState, backpressure = getActiveConfig().api.rateLimit) {
|
|
3837
|
+
const ui = getUI();
|
|
3838
|
+
const logger = getLogger();
|
|
3839
|
+
const graphSpinner = ui.createSpinner("Building dependency graph...");
|
|
3840
|
+
logger.info("Building dependency graph");
|
|
3931
3841
|
const context = { spaceState };
|
|
3932
3842
|
const graph = buildDependencyGraph(context);
|
|
3933
|
-
|
|
3843
|
+
graphSpinner.succeed(`Dependency graph built (${graph.nodes.size} resources)`);
|
|
3844
|
+
const validateSpinner = ui.createSpinner("Validating graph...");
|
|
3845
|
+
try {
|
|
3846
|
+
validateGraph(graph);
|
|
3847
|
+
validateSpinner.succeed("Graph validation passed");
|
|
3848
|
+
} catch (error) {
|
|
3849
|
+
validateSpinner.failed("Graph validation failed");
|
|
3850
|
+
throw error;
|
|
3851
|
+
}
|
|
3934
3852
|
const results = await processAllResources(graph, space, backpressure);
|
|
3853
|
+
const status = results.failed.length > 0 ? `${results.successful.length} updated, ${results.failed.length} failed` : `${results.successful.length} updated`;
|
|
3854
|
+
ui.ok(status, true);
|
|
3935
3855
|
return results;
|
|
3936
3856
|
}
|
|
3937
3857
|
|
|
@@ -4044,7 +3964,6 @@ pushCmd$3.action(async (componentName, options, command) => {
|
|
|
4044
3964
|
localPresetKeys.add(`${componentName2}:${preset.name}`);
|
|
4045
3965
|
}
|
|
4046
3966
|
}
|
|
4047
|
-
ui.info("Using graph-based dependency resolution");
|
|
4048
3967
|
const graphResults = await pushWithDependencyGraph(space, spaceState);
|
|
4049
3968
|
results.successful.push(...graphResults.successful);
|
|
4050
3969
|
results.failed.push(...graphResults.failed);
|
|
@@ -4071,7 +3990,7 @@ pushCmd$3.action(async (componentName, options, command) => {
|
|
|
4071
3990
|
});
|
|
4072
3991
|
}
|
|
4073
3992
|
}
|
|
4074
|
-
|
|
3993
|
+
ui.log(`${requestCount} requests made`);
|
|
4075
3994
|
const referencedDatasources = /* @__PURE__ */ new Set();
|
|
4076
3995
|
spaceState.local.components.forEach((component) => {
|
|
4077
3996
|
if (component.schema) {
|
|
@@ -4160,7 +4079,8 @@ const program$a = getProgram();
|
|
|
4160
4079
|
const languagesCommand = program$a.command(commands.LANGUAGES).alias("lang").description(`Manage your space's languages`);
|
|
4161
4080
|
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
4081
|
pullCmd$3.action(async (options, command) => {
|
|
4163
|
-
|
|
4082
|
+
const ui = getUI();
|
|
4083
|
+
ui.title(`${commands.LANGUAGES}`, colorPalette.LANGUAGES);
|
|
4164
4084
|
const { space, path, verbose } = command.optsWithGlobals();
|
|
4165
4085
|
const { filename = "languages", suffix = options.space } = options;
|
|
4166
4086
|
const { state } = session();
|
|
@@ -4171,16 +4091,13 @@ pullCmd$3.action(async (options, command) => {
|
|
|
4171
4091
|
handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
|
|
4172
4092
|
return;
|
|
4173
4093
|
}
|
|
4174
|
-
const spinner =
|
|
4175
|
-
verbose: !isVitest
|
|
4176
|
-
});
|
|
4094
|
+
const spinner = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.LANGUAGES)("languages")}`);
|
|
4177
4095
|
try {
|
|
4178
|
-
spinner.start(`Fetching ${chalk.hex(colorPalette.LANGUAGES)("languages")}`);
|
|
4179
4096
|
const internationalization = await fetchLanguages(space);
|
|
4180
4097
|
if (!internationalization || internationalization.languages?.length === 0) {
|
|
4181
4098
|
spinner.failed();
|
|
4182
|
-
|
|
4183
|
-
|
|
4099
|
+
ui.warn(`No languages found in the space ${space}`, true);
|
|
4100
|
+
ui.br();
|
|
4184
4101
|
return;
|
|
4185
4102
|
}
|
|
4186
4103
|
await saveLanguagesToFile(space, internationalization, {
|
|
@@ -4194,13 +4111,13 @@ pullCmd$3.action(async (options, command) => {
|
|
|
4194
4111
|
const filePath = join(languagesOutputDir, fileName);
|
|
4195
4112
|
const displayPath = path && isAbsolute(path) ? filePath : relative(process.cwd(), filePath);
|
|
4196
4113
|
spinner.succeed();
|
|
4197
|
-
|
|
4114
|
+
ui.ok(`Languages schema downloaded successfully at ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`, true);
|
|
4198
4115
|
} catch (error) {
|
|
4199
4116
|
spinner.failed();
|
|
4200
|
-
|
|
4117
|
+
ui.br();
|
|
4201
4118
|
handleError(error, verbose);
|
|
4202
4119
|
}
|
|
4203
|
-
|
|
4120
|
+
ui.br();
|
|
4204
4121
|
});
|
|
4205
4122
|
|
|
4206
4123
|
const program$9 = getProgram();
|
|
@@ -4282,6 +4199,7 @@ generateCmd$1.action(async (componentName, options, command) => {
|
|
|
4282
4199
|
});
|
|
4283
4200
|
|
|
4284
4201
|
const normalizeFullSlug = (slug) => slug.replace(/\/$/, "");
|
|
4202
|
+
const normalizeStartsWith = (prefix) => prefix.replace(/^\/+/, "");
|
|
4285
4203
|
|
|
4286
4204
|
const fetchStories = async (spaceId, params) => {
|
|
4287
4205
|
try {
|
|
@@ -4593,8 +4511,7 @@ const createStoriesStream = async ({
|
|
|
4593
4511
|
const listStoriesStream = Readable.from(iterator);
|
|
4594
4512
|
return pipeline(listStoriesStream, new StoriesStream(spaceId, onProgress), (err) => {
|
|
4595
4513
|
if (err) {
|
|
4596
|
-
|
|
4597
|
-
getLogger().error(err.message, { errorCode: ERROR_CODES.MIGRATION_CREATE_STORIES_PIPELINE_ERROR });
|
|
4514
|
+
getLogger().error(err.message, { error: err, errorCode: ERROR_CODES.MIGRATION_CREATE_STORIES_PIPELINE_ERROR });
|
|
4598
4515
|
}
|
|
4599
4516
|
});
|
|
4600
4517
|
};
|
|
@@ -6071,7 +5988,8 @@ const generateTypes = async (spaceData, options = {
|
|
|
6071
5988
|
const resolvedComponentsSchema = await Promise.all(componentsSchema);
|
|
6072
5989
|
const datasourcesSchema = spaceData.datasources.map(async (datasource) => {
|
|
6073
5990
|
const allComponentTypes = resolvedComponentsSchema.map((schema) => schema.title);
|
|
6074
|
-
const
|
|
5991
|
+
const filtered = datasource.entries?.filter((d) => d.value).map((d) => d.value);
|
|
5992
|
+
const enumValues = filtered?.length ? filtered : void 0;
|
|
6075
5993
|
if (!datasource.slug) {
|
|
6076
5994
|
return null;
|
|
6077
5995
|
}
|
|
@@ -6083,7 +6001,7 @@ const generateTypes = async (spaceData, options = {
|
|
|
6083
6001
|
$id: `#/${datasource.slug}`,
|
|
6084
6002
|
title: type,
|
|
6085
6003
|
type: "string",
|
|
6086
|
-
enum: enumValues
|
|
6004
|
+
...enumValues && { enum: enumValues }
|
|
6087
6005
|
};
|
|
6088
6006
|
return datasourceSchema;
|
|
6089
6007
|
});
|
|
@@ -6102,15 +6020,21 @@ const generateTypes = async (spaceData, options = {
|
|
|
6102
6020
|
...resolvedDatasourcesSchema,
|
|
6103
6021
|
contentTypeSchema
|
|
6104
6022
|
];
|
|
6023
|
+
const logger = getLogger();
|
|
6105
6024
|
const result = await Promise.all(schemas.map(async (schema) => {
|
|
6106
6025
|
const title = schema.title || schema.$id.replace("#/", "");
|
|
6026
|
+
const kind = componentTitles.has(title) ? "component" : datasourceTitles.has(title) ? "datasource" : "type";
|
|
6027
|
+
logger.info(`Compiling ${kind}: ${title}`);
|
|
6028
|
+
const startTime = Date.now();
|
|
6029
|
+
const content = await compile(schema, title, {
|
|
6030
|
+
additionalProperties: !options.strict,
|
|
6031
|
+
bannerComment: "",
|
|
6032
|
+
...compilerOptions
|
|
6033
|
+
});
|
|
6034
|
+
logger.info(`Compiled ${kind}: ${title}`, { elapsedMs: Date.now() - startTime });
|
|
6107
6035
|
return {
|
|
6108
6036
|
title,
|
|
6109
|
-
content
|
|
6110
|
-
additionalProperties: !options.strict,
|
|
6111
|
-
bannerComment: "",
|
|
6112
|
-
...compilerOptions
|
|
6113
|
-
}),
|
|
6037
|
+
content,
|
|
6114
6038
|
isComponent: componentTitles.has(title),
|
|
6115
6039
|
isDatasource: datasourceTitles.has(title)
|
|
6116
6040
|
};
|
|
@@ -6393,13 +6317,17 @@ const generateCmd = typesCommand.command("generate").description("Generate types
|
|
|
6393
6317
|
"Base file name for all component types when generating a single declarations file (e.g. components.d.ts). Ignored when using --separate-files."
|
|
6394
6318
|
).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
6319
|
generateCmd.action(async (options, command) => {
|
|
6396
|
-
|
|
6320
|
+
const ui = getUI();
|
|
6321
|
+
ui.title(`${commands.TYPES}`, colorPalette.TYPES, "Generating types...");
|
|
6397
6322
|
const { space, path, verbose, suffix, filename, separateFiles } = command.optsWithGlobals();
|
|
6398
|
-
|
|
6399
|
-
verbose
|
|
6400
|
-
|
|
6323
|
+
if (!space) {
|
|
6324
|
+
handleError(new CommandError("Please provide the space as argument --space SPACE_ID."), verbose);
|
|
6325
|
+
return;
|
|
6326
|
+
}
|
|
6327
|
+
const logger = getLogger();
|
|
6328
|
+
const spinner = ui.createSpinner("Processing schemas...");
|
|
6401
6329
|
try {
|
|
6402
|
-
|
|
6330
|
+
logger.info("Generating types started", { space });
|
|
6403
6331
|
const componentsData = await readComponentsFiles({
|
|
6404
6332
|
from: space,
|
|
6405
6333
|
path,
|
|
@@ -6428,25 +6356,32 @@ generateCmd.action(async (options, command) => {
|
|
|
6428
6356
|
...componentsData,
|
|
6429
6357
|
...dataSourceData
|
|
6430
6358
|
};
|
|
6359
|
+
logger.info("Processing schemas", {
|
|
6360
|
+
components: componentsData.components.length,
|
|
6361
|
+
datasources: dataSourceData.datasources.length
|
|
6362
|
+
});
|
|
6431
6363
|
const typedefData = await generateTypes(spaceDataWithComponentsAndDatasources, {
|
|
6432
6364
|
...options
|
|
6433
6365
|
});
|
|
6434
|
-
if (typedefData) {
|
|
6435
|
-
|
|
6436
|
-
|
|
6437
|
-
path,
|
|
6438
|
-
separateFiles
|
|
6439
|
-
});
|
|
6366
|
+
if (!typedefData) {
|
|
6367
|
+
spinner.failed("No types generated");
|
|
6368
|
+
return;
|
|
6440
6369
|
}
|
|
6441
|
-
|
|
6370
|
+
await saveTypesToComponentsFile(space, typedefData, {
|
|
6371
|
+
filename,
|
|
6372
|
+
path,
|
|
6373
|
+
separateFiles
|
|
6374
|
+
});
|
|
6375
|
+
spinner.succeed(`Types generated for ${componentsData.components.length} components`);
|
|
6442
6376
|
if (separateFiles && filename) {
|
|
6443
|
-
|
|
6377
|
+
ui.warn(`The --filename option is ignored when using --separate-files`);
|
|
6444
6378
|
}
|
|
6445
|
-
|
|
6446
|
-
|
|
6379
|
+
logger.info("Types generated successfully", { space });
|
|
6380
|
+
ui.ok(`Successfully generated types for space ${space}`, true);
|
|
6381
|
+
ui.br();
|
|
6447
6382
|
} catch (error) {
|
|
6448
|
-
spinner.failed(
|
|
6449
|
-
|
|
6383
|
+
spinner.failed("Type generation failed");
|
|
6384
|
+
logger.error("Type generation failed", { error });
|
|
6450
6385
|
handleError(error, verbose);
|
|
6451
6386
|
}
|
|
6452
6387
|
});
|
|
@@ -6582,7 +6517,8 @@ const saveDatasourcesToFiles = async (space, datasources, options) => {
|
|
|
6582
6517
|
|
|
6583
6518
|
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
6519
|
pullCmd$2.action(async (datasourceName, options, command) => {
|
|
6585
|
-
|
|
6520
|
+
const ui = getUI();
|
|
6521
|
+
ui.title(`${commands.DATASOURCES}`, colorPalette.DATASOURCES, datasourceName ? `Pulling datasource ${datasourceName}...` : "Pulling datasources...");
|
|
6586
6522
|
const { space, path, verbose } = command.optsWithGlobals();
|
|
6587
6523
|
const {
|
|
6588
6524
|
separateFiles = false,
|
|
@@ -6599,7 +6535,6 @@ pullCmd$2.action(async (datasourceName, options, command) => {
|
|
|
6599
6535
|
handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
|
|
6600
6536
|
return;
|
|
6601
6537
|
}
|
|
6602
|
-
const ui = getUI();
|
|
6603
6538
|
const logger = getLogger();
|
|
6604
6539
|
logger.info("Pulling datasources started", { space, datasourceName });
|
|
6605
6540
|
const spinnerDatasources = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.DATASOURCES)("datasources")}`);
|
|
@@ -6625,29 +6560,29 @@ pullCmd$2.action(async (datasourceName, options, command) => {
|
|
|
6625
6560
|
datasources,
|
|
6626
6561
|
{ ...options, path, separateFiles: separateFiles || !!datasourceName }
|
|
6627
6562
|
);
|
|
6628
|
-
|
|
6563
|
+
ui.br();
|
|
6629
6564
|
if (separateFiles) {
|
|
6630
6565
|
if (filename && filename !== DEFAULT_DATASOURCES_FILENAME) {
|
|
6631
|
-
|
|
6566
|
+
ui.warn(`The --filename option is ignored when using --separate-files`);
|
|
6632
6567
|
}
|
|
6633
6568
|
const filePath = `${datasourcesOutputDir}/`;
|
|
6634
6569
|
const displayPath = path && isAbsolute(path) ? filePath : `${relative(process.cwd(), datasourcesOutputDir)}/`;
|
|
6635
|
-
|
|
6570
|
+
ui.ok(`Datasources downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);
|
|
6636
6571
|
} else if (datasourceName) {
|
|
6637
6572
|
const fileName = suffix ? `${actualFilename}.${suffix}.json` : `${datasourceName}.json`;
|
|
6638
6573
|
const filePath = join(datasourcesOutputDir, fileName);
|
|
6639
6574
|
const displayPath = path && isAbsolute(path) ? filePath : relative(process.cwd(), filePath);
|
|
6640
|
-
|
|
6575
|
+
ui.ok(`Datasource ${chalk.hex(colorPalette.PRIMARY)(datasourceName)} downloaded successfully in ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);
|
|
6641
6576
|
} else {
|
|
6642
6577
|
const fileName = suffix ? `${actualFilename}.${suffix}.json` : `${actualFilename}.json`;
|
|
6643
6578
|
const filePath = join(datasourcesOutputDir, fileName);
|
|
6644
6579
|
const displayPath = path && isAbsolute(path) ? filePath : relative(process.cwd(), filePath);
|
|
6645
|
-
|
|
6580
|
+
ui.ok(`Datasources downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);
|
|
6646
6581
|
}
|
|
6647
|
-
|
|
6582
|
+
ui.br();
|
|
6648
6583
|
} catch (error) {
|
|
6649
6584
|
spinnerDatasources.failed(`Fetching ${chalk.hex(colorPalette.DATASOURCES)("Datasources")} - Failed`);
|
|
6650
|
-
|
|
6585
|
+
ui.br();
|
|
6651
6586
|
handleError(error, verbose);
|
|
6652
6587
|
} finally {
|
|
6653
6588
|
logger.info("Pulling datasources finished", { space, datasourceName });
|
|
@@ -6664,7 +6599,8 @@ function dimensionValuesEqual(a, b) {
|
|
|
6664
6599
|
}
|
|
6665
6600
|
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
6601
|
pushCmd$2.action(async (datasourceName, options, command) => {
|
|
6667
|
-
|
|
6602
|
+
const ui = getUI();
|
|
6603
|
+
ui.title(`${commands.DATASOURCES}`, colorPalette.DATASOURCES, datasourceName ? `Pushing datasource ${datasourceName}...` : "Pushing datasources...");
|
|
6668
6604
|
const { space, path, verbose } = command.optsWithGlobals();
|
|
6669
6605
|
const { filter } = options;
|
|
6670
6606
|
const fromSpace = options.from || space;
|
|
@@ -6678,8 +6614,8 @@ pushCmd$2.action(async (datasourceName, options, command) => {
|
|
|
6678
6614
|
}
|
|
6679
6615
|
const logger = getLogger();
|
|
6680
6616
|
logger.info("Pushing datasources started", { space, fromSpace, datasourceName, filter });
|
|
6681
|
-
|
|
6682
|
-
|
|
6617
|
+
ui.info(`Attempting to push datasources ${chalk.bold("from")} space ${chalk.hex(colorPalette.DATASOURCES)(fromSpace)} ${chalk.bold("to")} ${chalk.hex(colorPalette.DATASOURCES)(space)}`);
|
|
6618
|
+
ui.br();
|
|
6683
6619
|
try {
|
|
6684
6620
|
const spaceState = {
|
|
6685
6621
|
local: await readDatasourcesFiles({
|
|
@@ -6712,17 +6648,16 @@ pushCmd$2.action(async (datasourceName, options, command) => {
|
|
|
6712
6648
|
handleError(new CommandError(`No datasources found matching pattern "${filter}".`), verbose);
|
|
6713
6649
|
return;
|
|
6714
6650
|
}
|
|
6715
|
-
|
|
6651
|
+
ui.info(`Filter applied: ${filter}`);
|
|
6716
6652
|
}
|
|
6717
6653
|
if (!spaceState.local.datasources.length) {
|
|
6718
|
-
|
|
6654
|
+
ui.warn("No datasources found. Please make sure you have pulled the datasources first.");
|
|
6719
6655
|
return;
|
|
6720
6656
|
}
|
|
6721
6657
|
const results = {
|
|
6722
6658
|
successful: [],
|
|
6723
6659
|
failed: []
|
|
6724
6660
|
};
|
|
6725
|
-
const ui = getUI();
|
|
6726
6661
|
for (const datasource of spaceState.local.datasources) {
|
|
6727
6662
|
const spinner = ui.createSpinner(`Pushing ${chalk.hex(colorPalette.DATASOURCES)(datasource.name)}`);
|
|
6728
6663
|
const existingDatasource = spaceState.target.datasources.get(datasource.name);
|
|
@@ -6783,7 +6718,7 @@ pushCmd$2.action(async (datasourceName, options, command) => {
|
|
|
6783
6718
|
}
|
|
6784
6719
|
}
|
|
6785
6720
|
spinner.succeed(`${chalk.hex(colorPalette.DATASOURCES)(datasource.name)} - Completed in ${spinner.elapsedTime.toFixed(2)}ms`);
|
|
6786
|
-
dimensionWarnings.forEach((warning) =>
|
|
6721
|
+
dimensionWarnings.forEach((warning) => ui.warn(warning));
|
|
6787
6722
|
} else {
|
|
6788
6723
|
results.failed.push({ name: datasource.name, error: result });
|
|
6789
6724
|
spinner.failed(`${chalk.hex(colorPalette.DATASOURCES)(datasource.name)} - Failed in ${spinner.elapsedTime.toFixed(2)}ms`);
|
|
@@ -6791,8 +6726,8 @@ pushCmd$2.action(async (datasourceName, options, command) => {
|
|
|
6791
6726
|
}
|
|
6792
6727
|
if (results.failed.length > 0) {
|
|
6793
6728
|
if (!verbose) {
|
|
6794
|
-
|
|
6795
|
-
|
|
6729
|
+
ui.br();
|
|
6730
|
+
ui.info("For more information about the error, run the command with the `--verbose` flag");
|
|
6796
6731
|
} else {
|
|
6797
6732
|
results.failed.forEach((failed) => {
|
|
6798
6733
|
handleError(failed.error, verbose);
|
|
@@ -6822,13 +6757,14 @@ async function deleteDatasource(spaceId, id) {
|
|
|
6822
6757
|
|
|
6823
6758
|
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
6759
|
deleteCmd.action(async (name, options, command) => {
|
|
6825
|
-
|
|
6760
|
+
const ui = getUI();
|
|
6761
|
+
ui.title(
|
|
6826
6762
|
`${commands.DATASOURCES}`,
|
|
6827
6763
|
colorPalette.DATASOURCES,
|
|
6828
6764
|
options.id ? `Deleting datasource with id ${options.id}...` : `Deleting datasource with name ${name}...`
|
|
6829
6765
|
);
|
|
6830
6766
|
if (name && options.id) {
|
|
6831
|
-
|
|
6767
|
+
ui.warn(
|
|
6832
6768
|
"Both a datasource name and an id were provided. Only one is required. The id will be used as the source of truth."
|
|
6833
6769
|
);
|
|
6834
6770
|
}
|
|
@@ -6841,7 +6777,6 @@ deleteCmd.action(async (name, options, command) => {
|
|
|
6841
6777
|
handleError(new CommandError("Please provide the space as argument --space YOUR_SPACE_ID."), verbose);
|
|
6842
6778
|
return;
|
|
6843
6779
|
}
|
|
6844
|
-
const ui = getUI();
|
|
6845
6780
|
const logger = getLogger();
|
|
6846
6781
|
logger.info("Deleting datasource started", { space, name, id: options.id });
|
|
6847
6782
|
try {
|
|
@@ -6849,34 +6784,36 @@ deleteCmd.action(async (name, options, command) => {
|
|
|
6849
6784
|
const spinner = ui.createSpinner(`Deleting datasource...`);
|
|
6850
6785
|
await deleteDatasource(space, options.id);
|
|
6851
6786
|
spinner.succeed(`Datasource deleted`);
|
|
6852
|
-
|
|
6787
|
+
ui.ok(`Datasource ${chalk.hex(colorPalette.DATASOURCES)(options.id)} deleted successfully from space ${space}.`);
|
|
6853
6788
|
} else {
|
|
6854
6789
|
const datasource = await fetchDatasource(space, name);
|
|
6855
6790
|
if (!datasource) {
|
|
6856
6791
|
throw new CommandError(`Datasource with name '${name}' not found in space ${space}.`);
|
|
6857
6792
|
}
|
|
6858
6793
|
if (!options.force) {
|
|
6859
|
-
|
|
6860
|
-
|
|
6861
|
-
|
|
6862
|
-
|
|
6863
|
-
|
|
6864
|
-
|
|
6865
|
-
|
|
6866
|
-
|
|
6794
|
+
ui.info(`Datasource details:`);
|
|
6795
|
+
ui.list([
|
|
6796
|
+
`Name: ${chalk.hex(colorPalette.DATASOURCES)(datasource.name)}`,
|
|
6797
|
+
`ID: ${chalk.hex(colorPalette.DATASOURCES)(datasource.id)}`,
|
|
6798
|
+
`Space: ${chalk.hex(colorPalette.DATASOURCES)(space)}`,
|
|
6799
|
+
`Slug: ${chalk.hex(colorPalette.DATASOURCES)(datasource.slug)}`,
|
|
6800
|
+
`Created at: ${chalk.hex(colorPalette.DATASOURCES)(datasource.created_at)}`,
|
|
6801
|
+
`Updated at: ${chalk.hex(colorPalette.DATASOURCES)(datasource.updated_at)}`
|
|
6802
|
+
]);
|
|
6803
|
+
ui.br();
|
|
6867
6804
|
const confirmed = await confirm({
|
|
6868
6805
|
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
6806
|
default: false
|
|
6870
|
-
});
|
|
6807
|
+
}, stderrPromptContext);
|
|
6871
6808
|
if (!confirmed) {
|
|
6872
|
-
|
|
6809
|
+
ui.warn("Deletion aborted by user.");
|
|
6873
6810
|
return;
|
|
6874
6811
|
}
|
|
6875
6812
|
}
|
|
6876
6813
|
const spinner = ui.createSpinner(`Deleting datasource...`);
|
|
6877
6814
|
await deleteDatasource(space, datasource.id.toString());
|
|
6878
6815
|
spinner.succeed(`Datasource deleted`);
|
|
6879
|
-
|
|
6816
|
+
ui.ok(`Datasource ${chalk.hex(colorPalette.DATASOURCES)(name)} deleted successfully from space ${space}.`);
|
|
6880
6817
|
}
|
|
6881
6818
|
} catch (error) {
|
|
6882
6819
|
handleError(error, verbose);
|
|
@@ -6950,7 +6887,6 @@ const templates = {
|
|
|
6950
6887
|
}
|
|
6951
6888
|
};
|
|
6952
6889
|
|
|
6953
|
-
const ui$1 = getUI({ enabled: true });
|
|
6954
6890
|
const generateProject = async (blueprint, projectName, targetPath = process.cwd()) => {
|
|
6955
6891
|
try {
|
|
6956
6892
|
const projectPath = join(targetPath, projectName);
|
|
@@ -7027,29 +6963,30 @@ const updateAngularEnvironmentFiles = async (projectPath, token, region) => {
|
|
|
7027
6963
|
return { updatedFiles };
|
|
7028
6964
|
};
|
|
7029
6965
|
async function handleEnvFileCreation(resolvedPath, token, region, template) {
|
|
6966
|
+
const ui = getUI();
|
|
7030
6967
|
if (template === "angular") {
|
|
7031
6968
|
if (!token && !region) {
|
|
7032
|
-
ui
|
|
6969
|
+
ui.info("No environment variables to write");
|
|
7033
6970
|
return true;
|
|
7034
6971
|
}
|
|
7035
6972
|
try {
|
|
7036
6973
|
const { updatedFiles } = await updateAngularEnvironmentFiles(resolvedPath, token, region);
|
|
7037
6974
|
if (updatedFiles.length === 0) {
|
|
7038
|
-
ui
|
|
6975
|
+
ui.info("No Angular environment files found to update");
|
|
7039
6976
|
return true;
|
|
7040
6977
|
}
|
|
7041
6978
|
const writtenVars = [token && "accessToken", region && "region"].filter(Boolean).join(", ");
|
|
7042
|
-
ui
|
|
6979
|
+
ui.ok(`Updated Angular environment files with: ${writtenVars}`, true);
|
|
7043
6980
|
return true;
|
|
7044
6981
|
} catch (error) {
|
|
7045
|
-
ui
|
|
6982
|
+
ui.warn(`Failed to update Angular environment files: ${error.message}`);
|
|
7046
6983
|
if (token) {
|
|
7047
|
-
ui
|
|
6984
|
+
ui.info(
|
|
7048
6985
|
`You can manually add accessToken to src/environments/environment.ts and src/environments/environment.development.ts`
|
|
7049
6986
|
);
|
|
7050
6987
|
}
|
|
7051
6988
|
if (region) {
|
|
7052
|
-
ui
|
|
6989
|
+
ui.info(
|
|
7053
6990
|
`You can manually add region to src/environments/environment.ts and src/environments/environment.development.ts`
|
|
7054
6991
|
);
|
|
7055
6992
|
}
|
|
@@ -7064,23 +7001,23 @@ async function handleEnvFileCreation(resolvedPath, token, region, template) {
|
|
|
7064
7001
|
envVars.STORYBLOK_REGION = region;
|
|
7065
7002
|
}
|
|
7066
7003
|
if (Object.keys(envVars).length === 0) {
|
|
7067
|
-
ui
|
|
7004
|
+
ui.info("No environment variables to write");
|
|
7068
7005
|
return true;
|
|
7069
7006
|
}
|
|
7070
7007
|
try {
|
|
7071
7008
|
await createEnvFile(resolvedPath, envVars);
|
|
7072
7009
|
const writtenKeys = Object.keys(envVars).join(", ");
|
|
7073
|
-
ui
|
|
7010
|
+
ui.ok(`Created .env file with: ${writtenKeys}`, true);
|
|
7074
7011
|
return true;
|
|
7075
7012
|
} catch (error) {
|
|
7076
|
-
ui
|
|
7013
|
+
ui.warn(`Failed to create .env file: ${error.message}`);
|
|
7077
7014
|
if (token) {
|
|
7078
|
-
ui
|
|
7015
|
+
ui.info(
|
|
7079
7016
|
`You can manually add STORYBLOK_DELIVERY_API_TOKEN to your .env file.`
|
|
7080
7017
|
);
|
|
7081
7018
|
}
|
|
7082
7019
|
if (region) {
|
|
7083
|
-
ui
|
|
7020
|
+
ui.info(
|
|
7084
7021
|
`You can manually add STORYBLOK_REGION to your .env file.`
|
|
7085
7022
|
);
|
|
7086
7023
|
}
|
|
@@ -7131,6 +7068,7 @@ const repositoryToTemplate = (repo) => {
|
|
|
7131
7068
|
};
|
|
7132
7069
|
};
|
|
7133
7070
|
const fetchBlueprintRepositories = async () => {
|
|
7071
|
+
const ui = getUI();
|
|
7134
7072
|
try {
|
|
7135
7073
|
const octokit = createOctokit();
|
|
7136
7074
|
const { data } = await octokit.rest.search.repos({
|
|
@@ -7142,13 +7080,13 @@ const fetchBlueprintRepositories = async () => {
|
|
|
7142
7080
|
const blueprints = data.items.filter((repo) => repo.name.startsWith("blueprint-core-")).map(repositoryToTemplate).sort((a, b) => (b.stars || 0) - (a.stars || 0));
|
|
7143
7081
|
return blueprints;
|
|
7144
7082
|
} catch {
|
|
7145
|
-
ui
|
|
7083
|
+
ui.warn("Failed to fetch blueprints from GitHub. Using offline template list.");
|
|
7146
7084
|
return Object.values(templates);
|
|
7147
7085
|
}
|
|
7148
7086
|
};
|
|
7149
7087
|
|
|
7150
|
-
const ui = getUI({ enabled: true });
|
|
7151
7088
|
function showNextSteps(technologyTemplate, finalProjectPath) {
|
|
7089
|
+
const ui = getUI();
|
|
7152
7090
|
ui.br();
|
|
7153
7091
|
ui.ok(`Your ${chalk.hex(colorPalette.PRIMARY)(technologyTemplate)} project is ready \u{1F389} !`);
|
|
7154
7092
|
ui.br();
|
|
@@ -7160,12 +7098,13 @@ function showNextSteps(technologyTemplate, finalProjectPath) {
|
|
|
7160
7098
|
ui.info(`Or check the dedicated guide at: ${chalk.hex(colorPalette.PRIMARY)(`https://www.storyblok.com/docs/guides/${technologyTemplate}`)}`);
|
|
7161
7099
|
}
|
|
7162
7100
|
async function promptForLogin(verbose) {
|
|
7101
|
+
const ui = getUI();
|
|
7163
7102
|
try {
|
|
7164
7103
|
ui.br();
|
|
7165
7104
|
const shouldLogin = await confirm({
|
|
7166
7105
|
message: "Would you like to login now?",
|
|
7167
7106
|
default: true
|
|
7168
|
-
});
|
|
7107
|
+
}, stderrPromptContext);
|
|
7169
7108
|
if (!shouldLogin) {
|
|
7170
7109
|
ui.warn('Login cancelled. You can login later using the "storyblok login" command.');
|
|
7171
7110
|
return null;
|
|
@@ -7182,6 +7121,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
|
|
|
7182
7121
|
"-r, --region <region>",
|
|
7183
7122
|
`The region to apply to the generated project template (does not affect space creation).`
|
|
7184
7123
|
).action(async (projectPath, options) => {
|
|
7124
|
+
const ui = getUI();
|
|
7185
7125
|
ui.title(`${commands.CREATE}`, colorPalette.CREATE);
|
|
7186
7126
|
const verbose = program$6.opts().verbose;
|
|
7187
7127
|
const { template, blueprint, token } = options;
|
|
@@ -7223,22 +7163,17 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
|
|
|
7223
7163
|
region = state.region;
|
|
7224
7164
|
}
|
|
7225
7165
|
}
|
|
7226
|
-
|
|
7227
|
-
verbose: !isVitest
|
|
7228
|
-
});
|
|
7229
|
-
const spinnerSpace = new Spinner({
|
|
7230
|
-
verbose: !isVitest
|
|
7231
|
-
});
|
|
7166
|
+
let activeSpinner = null;
|
|
7232
7167
|
try {
|
|
7233
|
-
|
|
7168
|
+
activeSpinner = ui.createSpinner("Fetching starter templates...");
|
|
7234
7169
|
const templates = await fetchBlueprintRepositories();
|
|
7235
|
-
spinnerBlueprints.succeed("Starter templates fetched successfully");
|
|
7236
7170
|
if (templates.length === 0) {
|
|
7237
|
-
|
|
7238
|
-
ui.
|
|
7171
|
+
activeSpinner.failed();
|
|
7172
|
+
ui.error("No starter templates found. Please contact support@storyblok.com");
|
|
7239
7173
|
ui.br();
|
|
7240
7174
|
return;
|
|
7241
7175
|
}
|
|
7176
|
+
activeSpinner.succeed("Starter templates fetched successfully");
|
|
7242
7177
|
let technologyTemplate = selectedTemplate;
|
|
7243
7178
|
if (selectedTemplate) {
|
|
7244
7179
|
const validTemplates = templates;
|
|
@@ -7257,7 +7192,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
|
|
|
7257
7192
|
name: template2.name,
|
|
7258
7193
|
value: template2.value
|
|
7259
7194
|
}))
|
|
7260
|
-
});
|
|
7195
|
+
}, stderrPromptContext);
|
|
7261
7196
|
}
|
|
7262
7197
|
let finalProjectPath = projectPath;
|
|
7263
7198
|
if (!projectPath) {
|
|
@@ -7274,7 +7209,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
|
|
|
7274
7209
|
}
|
|
7275
7210
|
return true;
|
|
7276
7211
|
}
|
|
7277
|
-
});
|
|
7212
|
+
}, stderrPromptContext);
|
|
7278
7213
|
}
|
|
7279
7214
|
const resolvedPath = resolve(finalProjectPath);
|
|
7280
7215
|
const targetDirectory = dirname(resolvedPath);
|
|
@@ -7339,7 +7274,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
|
|
|
7339
7274
|
whereToCreateSpace = await select({
|
|
7340
7275
|
message: `Where would you like to create this space?`,
|
|
7341
7276
|
choices
|
|
7342
|
-
});
|
|
7277
|
+
}, stderrPromptContext);
|
|
7343
7278
|
}
|
|
7344
7279
|
if (region !== regions.EU && userData.has_org) {
|
|
7345
7280
|
whereToCreateSpace = "org";
|
|
@@ -7349,7 +7284,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
|
|
|
7349
7284
|
ui.br();
|
|
7350
7285
|
return;
|
|
7351
7286
|
}
|
|
7352
|
-
|
|
7287
|
+
activeSpinner = ui.createSpinner(`Creating space "${toHumanReadable(projectName)}"`);
|
|
7353
7288
|
const selectedBlueprint = templates.find((bp) => bp.value === technologyTemplate);
|
|
7354
7289
|
const blueprintDomain = selectedBlueprint?.location || "https://localhost:3000/";
|
|
7355
7290
|
const spaceToCreate = {
|
|
@@ -7363,7 +7298,7 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
|
|
|
7363
7298
|
createSpaceQuery.assign_partner = true;
|
|
7364
7299
|
}
|
|
7365
7300
|
createdSpace = await createSpace(spaceToCreate, createSpaceQuery);
|
|
7366
|
-
|
|
7301
|
+
activeSpinner.succeed(`Space "${chalk.hex(colorPalette.PRIMARY)(toHumanReadable(projectName))}" created successfully`);
|
|
7367
7302
|
if (createdSpace?.first_token) {
|
|
7368
7303
|
await handleEnvFileCreation(resolvedPath, createdSpace.first_token, region, technologyTemplate);
|
|
7369
7304
|
}
|
|
@@ -7388,14 +7323,13 @@ program$6.command(`${commands.CREATE} [project-path]`).alias("c").description(`S
|
|
|
7388
7323
|
}
|
|
7389
7324
|
}
|
|
7390
7325
|
} catch (error) {
|
|
7391
|
-
|
|
7326
|
+
activeSpinner?.failed();
|
|
7392
7327
|
ui.br();
|
|
7393
7328
|
handleError(error, verbose);
|
|
7394
7329
|
return;
|
|
7395
7330
|
}
|
|
7396
7331
|
} catch (error) {
|
|
7397
|
-
|
|
7398
|
-
spinnerBlueprints.failed();
|
|
7332
|
+
activeSpinner?.failed();
|
|
7399
7333
|
ui.br();
|
|
7400
7334
|
handleError(error, verbose);
|
|
7401
7335
|
}
|
|
@@ -8786,12 +8720,10 @@ pullCmd$1.action(async (options, command) => {
|
|
|
8786
8720
|
const assetToken = options.assetToken;
|
|
8787
8721
|
const { state } = session();
|
|
8788
8722
|
if (!requireAuthentication(state, verbose)) {
|
|
8789
|
-
process.exitCode = 2;
|
|
8790
8723
|
return;
|
|
8791
8724
|
}
|
|
8792
8725
|
if (!space) {
|
|
8793
8726
|
handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
|
|
8794
|
-
process.exitCode = 2;
|
|
8795
8727
|
return;
|
|
8796
8728
|
}
|
|
8797
8729
|
const { region } = state;
|
|
@@ -9040,7 +8972,9 @@ pullCmd$1.action(async (options, command) => {
|
|
|
9040
8972
|
reporter.addSummary("saveResults", summary.save);
|
|
9041
8973
|
reporter.finalize();
|
|
9042
8974
|
const failedTotal = summary.folderResults.failed + summary.fetchAssetPages.failed + summary.fetchAssets.failed + summary.save.failed;
|
|
9043
|
-
|
|
8975
|
+
if (!fatalError) {
|
|
8976
|
+
process.exitCode = failedTotal > 0 ? 1 : 0;
|
|
8977
|
+
}
|
|
9044
8978
|
}
|
|
9045
8979
|
});
|
|
9046
8980
|
|
|
@@ -9999,12 +9933,10 @@ pushCmd$1.action(async (assetInput, options, command) => {
|
|
|
9999
9933
|
const fromSpace = options.from || targetSpace;
|
|
10000
9934
|
const { state } = session();
|
|
10001
9935
|
if (!requireAuthentication(state, verbose)) {
|
|
10002
|
-
process.exitCode = 2;
|
|
10003
9936
|
return;
|
|
10004
9937
|
}
|
|
10005
9938
|
if (!targetSpace) {
|
|
10006
9939
|
handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
|
|
10007
|
-
process.exitCode = 2;
|
|
10008
9940
|
return;
|
|
10009
9941
|
}
|
|
10010
9942
|
const libraryId = options.library ? Number(options.library) : void 0;
|
|
@@ -10013,17 +9945,14 @@ pushCmd$1.action(async (assetInput, options, command) => {
|
|
|
10013
9945
|
if (assetBinaryPath) {
|
|
10014
9946
|
if (target === "auto") {
|
|
10015
9947
|
handleError(new CommandError("Pushing a single asset requires --target=space or --target=shared, not --target=auto."), verbose);
|
|
10016
|
-
process.exitCode = 2;
|
|
10017
9948
|
return;
|
|
10018
9949
|
}
|
|
10019
9950
|
if (target === "shared" && !libraryId) {
|
|
10020
9951
|
handleError(new CommandError("Pushing a single asset to a library requires --library YOUR_LIBRARY_ID."), verbose);
|
|
10021
|
-
process.exitCode = 2;
|
|
10022
9952
|
return;
|
|
10023
9953
|
}
|
|
10024
9954
|
if (target === "space" && libraryId) {
|
|
10025
9955
|
handleError(new CommandError("--library cannot be combined with --target=space."), verbose);
|
|
10026
|
-
process.exitCode = 2;
|
|
10027
9956
|
return;
|
|
10028
9957
|
}
|
|
10029
9958
|
}
|
|
@@ -10047,7 +9976,6 @@ pushCmd$1.action(async (assetInput, options, command) => {
|
|
|
10047
9976
|
}
|
|
10048
9977
|
} catch (maybeError) {
|
|
10049
9978
|
handleError(toError(maybeError), verbose);
|
|
10050
|
-
process.exitCode = 2;
|
|
10051
9979
|
return;
|
|
10052
9980
|
}
|
|
10053
9981
|
const summaries = [];
|
|
@@ -10205,7 +10133,9 @@ pushCmd$1.action(async (assetInput, options, command) => {
|
|
|
10205
10133
|
}
|
|
10206
10134
|
return total + entry.failed;
|
|
10207
10135
|
}, 0);
|
|
10208
|
-
|
|
10136
|
+
if (!fatalError) {
|
|
10137
|
+
process.exitCode = failedTotal > 0 ? 1 : 0;
|
|
10138
|
+
}
|
|
10209
10139
|
}
|
|
10210
10140
|
});
|
|
10211
10141
|
|
|
@@ -10224,29 +10154,24 @@ transferCmd.action(async (assetIds, options, command) => {
|
|
|
10224
10154
|
const { space, verbose } = command.optsWithGlobals();
|
|
10225
10155
|
const { state } = session();
|
|
10226
10156
|
if (!requireAuthentication(state, verbose)) {
|
|
10227
|
-
process.exitCode = 2;
|
|
10228
10157
|
return;
|
|
10229
10158
|
}
|
|
10230
10159
|
if (!space) {
|
|
10231
10160
|
handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);
|
|
10232
|
-
process.exitCode = 2;
|
|
10233
10161
|
return;
|
|
10234
10162
|
}
|
|
10235
10163
|
const folderId = Number(options.folderId);
|
|
10236
10164
|
if (!options.folderId || !Number.isFinite(folderId) || folderId <= 0) {
|
|
10237
10165
|
handleError(new CommandError(`Please provide a destination folder with --folder-id YOUR_FOLDER_ID.`), verbose);
|
|
10238
|
-
process.exitCode = 2;
|
|
10239
10166
|
return;
|
|
10240
10167
|
}
|
|
10241
10168
|
if (options.all && options.query) {
|
|
10242
10169
|
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
10170
|
return;
|
|
10245
10171
|
}
|
|
10246
10172
|
const bulk = Boolean(options.all || options.query);
|
|
10247
10173
|
if (bulk && assetIds.length > 0) {
|
|
10248
10174
|
handleError(new CommandError(`Cannot combine explicit asset IDs with --all or --query.`), verbose);
|
|
10249
|
-
process.exitCode = 2;
|
|
10250
10175
|
return;
|
|
10251
10176
|
}
|
|
10252
10177
|
let ids;
|
|
@@ -10257,7 +10182,6 @@ transferCmd.action(async (assetIds, options, command) => {
|
|
|
10257
10182
|
ids = await fetchAllSpaceAssetIds(space, params);
|
|
10258
10183
|
} catch (maybeError) {
|
|
10259
10184
|
handleError(toError(maybeError), verbose);
|
|
10260
|
-
process.exitCode = 2;
|
|
10261
10185
|
return;
|
|
10262
10186
|
}
|
|
10263
10187
|
logger.info("Enumerated space assets", { count: ids.length });
|
|
@@ -10271,7 +10195,6 @@ transferCmd.action(async (assetIds, options, command) => {
|
|
|
10271
10195
|
ids = assetIds.map((id) => Number(id)).filter((id) => !Number.isNaN(id));
|
|
10272
10196
|
if (ids.length === 0) {
|
|
10273
10197
|
handleError(new CommandError(`Please provide at least one valid asset ID, or use --all.`), verbose);
|
|
10274
|
-
process.exitCode = 2;
|
|
10275
10198
|
return;
|
|
10276
10199
|
}
|
|
10277
10200
|
}
|
|
@@ -10321,7 +10244,7 @@ transferCmd.action(async (assetIds, options, command) => {
|
|
|
10321
10244
|
const program$2 = getProgram();
|
|
10322
10245
|
const storiesCommand = program$2.command(commands.STORIES).description(`Manage your space's stories`);
|
|
10323
10246
|
|
|
10324
|
-
const pullCmd = storiesCommand.command("pull").option("-s, --space <space>", "space ID").option("-d, --dry-run", "Preview changes without applying them to Storyblok").option("-q, --query <query>", 'Filter stories by content attributes using Storyblok filter query syntax. Example: --query="[highlighted][in]=true"').option("--starts-with <path>", 'Filter stories by path. Example: --starts-with="
|
|
10247
|
+
const pullCmd = storiesCommand.command("pull").option("-s, --space <space>", "space ID").option("-d, --dry-run", "Preview changes without applying them to Storyblok").option("-q, --query <query>", 'Filter stories by content attributes using Storyblok filter query syntax. Example: --query="[highlighted][in]=true"').option("--starts-with <path>", 'Filter stories by path. Example: --starts-with="en/blog/"').description(`Download your space's stories as separate json files.`);
|
|
10325
10248
|
pullCmd.action(async (options, command) => {
|
|
10326
10249
|
const ui = getUI();
|
|
10327
10250
|
const logger = getLogger();
|
|
@@ -10356,7 +10279,9 @@ pullCmd.action(async (options, command) => {
|
|
|
10356
10279
|
spaceId: space,
|
|
10357
10280
|
params: {
|
|
10358
10281
|
filter_query: options.query ? parseFilterQuery(options.query) : void 0,
|
|
10359
|
-
|
|
10282
|
+
// A `full_slug` never starts with a slash and MAPI matches the prefix
|
|
10283
|
+
// literally, so `/en/blog/` would pull nothing at all.
|
|
10284
|
+
starts_with: options.startsWith === void 0 ? void 0 : normalizeStartsWith(options.startsWith) || void 0
|
|
10360
10285
|
},
|
|
10361
10286
|
setTotalPages: (totalPages) => {
|
|
10362
10287
|
summary.fetchStoryPages.total = totalPages;
|
|
@@ -10824,12 +10749,481 @@ pushCmd.action(async (options, command) => {
|
|
|
10824
10749
|
}
|
|
10825
10750
|
});
|
|
10826
10751
|
|
|
10752
|
+
function isComponent(value) {
|
|
10753
|
+
return isRecord(value) && typeof value.name === "string" && Array.isArray(value.fields);
|
|
10754
|
+
}
|
|
10755
|
+
function isDatasource(value) {
|
|
10756
|
+
return isRecord(value) && typeof value.name === "string" && typeof value.slug === "string" && !Array.isArray(value.fields);
|
|
10757
|
+
}
|
|
10758
|
+
function isFolder(value) {
|
|
10759
|
+
return isRecord(value) && typeof value.name === "string" && typeof value.path === "string" && !Array.isArray(value.fields) && !("slug" in value);
|
|
10760
|
+
}
|
|
10761
|
+
function isFieldPlugin(value) {
|
|
10762
|
+
return isRecord(value) && typeof value.fieldType === "string" && "value" in value;
|
|
10763
|
+
}
|
|
10764
|
+
function isSchemaObject(value) {
|
|
10765
|
+
return isRecord(value) && ("blocks" in value || "datasources" in value || "folders" in value || "fieldPlugins" in value);
|
|
10766
|
+
}
|
|
10767
|
+
function collectSchemaExports(moduleExports) {
|
|
10768
|
+
const components = [];
|
|
10769
|
+
const datasources = [];
|
|
10770
|
+
const folders = [];
|
|
10771
|
+
const fieldPlugins = [];
|
|
10772
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10773
|
+
function collect(value) {
|
|
10774
|
+
if (isComponent(value)) {
|
|
10775
|
+
if (seen.has(value)) {
|
|
10776
|
+
return;
|
|
10777
|
+
}
|
|
10778
|
+
seen.add(value);
|
|
10779
|
+
components.push(value);
|
|
10780
|
+
} else if (isFolder(value)) {
|
|
10781
|
+
if (seen.has(value)) {
|
|
10782
|
+
return;
|
|
10783
|
+
}
|
|
10784
|
+
seen.add(value);
|
|
10785
|
+
folders.push(value);
|
|
10786
|
+
} else if (isDatasource(value)) {
|
|
10787
|
+
if (seen.has(value)) {
|
|
10788
|
+
return;
|
|
10789
|
+
}
|
|
10790
|
+
seen.add(value);
|
|
10791
|
+
datasources.push(value);
|
|
10792
|
+
} else if (isFieldPlugin(value)) {
|
|
10793
|
+
if (seen.has(value)) {
|
|
10794
|
+
return;
|
|
10795
|
+
}
|
|
10796
|
+
seen.add(value);
|
|
10797
|
+
fieldPlugins.push(value);
|
|
10798
|
+
}
|
|
10799
|
+
}
|
|
10800
|
+
for (const value of Object.values(moduleExports)) {
|
|
10801
|
+
if (isSchemaObject(value)) {
|
|
10802
|
+
for (const group of Object.values(value)) {
|
|
10803
|
+
if (isRecord(group)) {
|
|
10804
|
+
for (const entity of Object.values(group)) {
|
|
10805
|
+
collect(entity);
|
|
10806
|
+
}
|
|
10807
|
+
}
|
|
10808
|
+
}
|
|
10809
|
+
} else {
|
|
10810
|
+
collect(value);
|
|
10811
|
+
}
|
|
10812
|
+
}
|
|
10813
|
+
return { components, datasources, folders, fieldPlugins };
|
|
10814
|
+
}
|
|
10815
|
+
async function loadSchemaModule(entryPath) {
|
|
10816
|
+
const entryAbs = resolve(entryPath);
|
|
10817
|
+
try {
|
|
10818
|
+
await stat(entryAbs);
|
|
10819
|
+
} catch {
|
|
10820
|
+
throw new CommandError(`Schema entry file not found at "${entryPath}".`);
|
|
10821
|
+
}
|
|
10822
|
+
const { createJiti } = await import('jiti');
|
|
10823
|
+
const jiti = createJiti(import.meta.url, { interopDefault: true });
|
|
10824
|
+
return await jiti.import(entryAbs);
|
|
10825
|
+
}
|
|
10826
|
+
|
|
10827
|
+
async function validateSchema(schema) {
|
|
10828
|
+
const schemaPkg = await import('@storyblok/schema');
|
|
10829
|
+
return schemaPkg.validateSchema(schema);
|
|
10830
|
+
}
|
|
10831
|
+
async function validateStory(story, schema) {
|
|
10832
|
+
const schemaPkg = await import('@storyblok/schema');
|
|
10833
|
+
return schemaPkg.validateStory(story, schema);
|
|
10834
|
+
}
|
|
10835
|
+
async function loadSchemaEntry(entryPath, options = {}) {
|
|
10836
|
+
const entryMod = await loadSchemaModule(entryPath);
|
|
10837
|
+
const { components, datasources, fieldPlugins } = collectSchemaExports(entryMod);
|
|
10838
|
+
if (components.length === 0 && datasources.length === 0) {
|
|
10839
|
+
throw new CommandError(
|
|
10840
|
+
"No blocks or datasources found in the schema entry file. Verify the file exports schema definitions."
|
|
10841
|
+
);
|
|
10842
|
+
}
|
|
10843
|
+
if (options.requireBlocks && components.length === 0) {
|
|
10844
|
+
throw new CommandError(
|
|
10845
|
+
"No blocks found in the schema entry file. Story content cannot be validated against a schema that defines no blocks."
|
|
10846
|
+
);
|
|
10847
|
+
}
|
|
10848
|
+
const schema = { blocks: components, datasources, fieldPlugins };
|
|
10849
|
+
return { schema, entityCount: components.length + datasources.length };
|
|
10850
|
+
}
|
|
10851
|
+
|
|
10852
|
+
function filterIssuesByLevel(issues, level) {
|
|
10853
|
+
if (level === "warning") {
|
|
10854
|
+
return [...issues];
|
|
10855
|
+
}
|
|
10856
|
+
return issues.filter((issue) => issue.severity === "error");
|
|
10857
|
+
}
|
|
10858
|
+
function unitsInGroup(group) {
|
|
10859
|
+
if (group.ref.kind !== "schema") {
|
|
10860
|
+
return 1;
|
|
10861
|
+
}
|
|
10862
|
+
const definitions = /* @__PURE__ */ new Set();
|
|
10863
|
+
for (const issue of group.issues) {
|
|
10864
|
+
const [collection, index] = issue.path;
|
|
10865
|
+
definitions.add(
|
|
10866
|
+
typeof collection === "string" && index !== void 0 ? `${collection}.${index}` : "schema"
|
|
10867
|
+
);
|
|
10868
|
+
}
|
|
10869
|
+
return definitions.size;
|
|
10870
|
+
}
|
|
10871
|
+
function countIssues(result) {
|
|
10872
|
+
let errors = 0;
|
|
10873
|
+
let warnings = 0;
|
|
10874
|
+
let unitsWithIssues = 0;
|
|
10875
|
+
for (const group of result.groups) {
|
|
10876
|
+
for (const issue of group.issues) {
|
|
10877
|
+
if (issue.severity === "error") {
|
|
10878
|
+
errors += 1;
|
|
10879
|
+
} else {
|
|
10880
|
+
warnings += 1;
|
|
10881
|
+
}
|
|
10882
|
+
}
|
|
10883
|
+
unitsWithIssues += unitsInGroup(group);
|
|
10884
|
+
}
|
|
10885
|
+
return { errors, warnings, unitsWithIssues };
|
|
10886
|
+
}
|
|
10887
|
+
|
|
10888
|
+
function formatJson(result, level) {
|
|
10889
|
+
const { errors, warnings, unitsWithIssues } = countIssues(result);
|
|
10890
|
+
const fetchFailures = result.fetchFailures ?? 0;
|
|
10891
|
+
const listFailed = result.listFailed ?? false;
|
|
10892
|
+
const report = {
|
|
10893
|
+
ok: errors === 0 && fetchFailures === 0 && !listFailed,
|
|
10894
|
+
unit: result.unitNoun,
|
|
10895
|
+
unitsTotal: result.unitsTotal,
|
|
10896
|
+
unitsWithIssues,
|
|
10897
|
+
...result.filter ? { filter: result.filter } : {},
|
|
10898
|
+
// Only stated when it is the whole story: a listing that failed already
|
|
10899
|
+
// explains the empty population through `listFailed`.
|
|
10900
|
+
...result.filter && result.unitsTotal === 0 && !listFailed ? { noMatches: true } : {},
|
|
10901
|
+
errors,
|
|
10902
|
+
warnings,
|
|
10903
|
+
fetchFailures,
|
|
10904
|
+
// Only present when they carry information: an empty array or a null reason
|
|
10905
|
+
// is noise in a document a machine reads.
|
|
10906
|
+
...result.fetchErrors?.length ? { fetchErrors: result.fetchErrors } : {},
|
|
10907
|
+
listFailed,
|
|
10908
|
+
...listFailed && result.listError ? { listError: result.listError } : {},
|
|
10909
|
+
groups: result.groups.map((group) => ({ ...group, issues: filterIssuesByLevel(group.issues, level) })).filter((group) => group.issues.length > 0)
|
|
10910
|
+
};
|
|
10911
|
+
return JSON.stringify(report, null, 2);
|
|
10912
|
+
}
|
|
10913
|
+
|
|
10914
|
+
const SYMBOL = {
|
|
10915
|
+
error: chalk.red("\u2716"),
|
|
10916
|
+
warning: chalk.yellow("\u26A0")
|
|
10917
|
+
};
|
|
10918
|
+
function pluralize(count, noun) {
|
|
10919
|
+
return `${count} ${count === 1 ? noun : `${noun}s`}`;
|
|
10920
|
+
}
|
|
10921
|
+
function formatPretty(result, level) {
|
|
10922
|
+
const lines = [];
|
|
10923
|
+
for (const group of result.groups) {
|
|
10924
|
+
const visible = filterIssuesByLevel(group.issues, level);
|
|
10925
|
+
if (visible.length === 0) {
|
|
10926
|
+
continue;
|
|
10927
|
+
}
|
|
10928
|
+
lines.push(group.header);
|
|
10929
|
+
const codeWidth = Math.max(...visible.map((issue) => issue.code.length));
|
|
10930
|
+
for (const issue of visible) {
|
|
10931
|
+
const location = issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message;
|
|
10932
|
+
lines.push(` ${SYMBOL[issue.severity]} ${issue.code.padEnd(codeWidth)} ${location}`);
|
|
10933
|
+
}
|
|
10934
|
+
}
|
|
10935
|
+
const { errors, warnings, unitsWithIssues } = countIssues(result);
|
|
10936
|
+
const summarySymbol = errors > 0 ? chalk.red("\u2716") : warnings > 0 ? chalk.yellow("\u26A0") : chalk.green("\u2714");
|
|
10937
|
+
const unitNoun = result.unitsTotal === 1 ? result.unitNounSingular : result.unitNoun;
|
|
10938
|
+
const hidden = level === "error" && warnings > 0 ? chalk.dim(` (${pluralize(warnings, "warning")} hidden by --level error)`) : "";
|
|
10939
|
+
lines.push(
|
|
10940
|
+
`${summarySymbol} ${pluralize(errors, "error")}, ${pluralize(warnings, "warning")} across ${unitsWithIssues} of ${result.unitsTotal} ${unitNoun}${hidden}`
|
|
10941
|
+
);
|
|
10942
|
+
return lines.join("\n");
|
|
10943
|
+
}
|
|
10944
|
+
|
|
10945
|
+
function entityToHeader(entity) {
|
|
10946
|
+
const separator = entity.indexOf(":");
|
|
10947
|
+
if (separator === -1) {
|
|
10948
|
+
return entity;
|
|
10949
|
+
}
|
|
10950
|
+
const type = entity.slice(0, separator);
|
|
10951
|
+
const name = entity.slice(separator + 1);
|
|
10952
|
+
if (name === "") {
|
|
10953
|
+
return `<unnamed ${type}>`;
|
|
10954
|
+
}
|
|
10955
|
+
return `${name} (${type})`;
|
|
10956
|
+
}
|
|
10957
|
+
function entityToRef(entity) {
|
|
10958
|
+
const separator = entity.indexOf(":");
|
|
10959
|
+
const type = separator === -1 ? entity : entity.slice(0, separator);
|
|
10960
|
+
const name = separator === -1 ? void 0 : entity.slice(separator + 1);
|
|
10961
|
+
if (type === "block" || type === "datasource") {
|
|
10962
|
+
return { kind: type, ...name ? { name } : {} };
|
|
10963
|
+
}
|
|
10964
|
+
return { kind: "schema" };
|
|
10965
|
+
}
|
|
10966
|
+
function groupIssuesByEntity(issues) {
|
|
10967
|
+
const byEntity = /* @__PURE__ */ new Map();
|
|
10968
|
+
for (const issue of issues) {
|
|
10969
|
+
const existing = byEntity.get(issue.entity);
|
|
10970
|
+
if (existing) {
|
|
10971
|
+
existing.push(issue);
|
|
10972
|
+
} else {
|
|
10973
|
+
byEntity.set(issue.entity, [issue]);
|
|
10974
|
+
}
|
|
10975
|
+
}
|
|
10976
|
+
return [...byEntity].map(([entity, entityIssues]) => ({
|
|
10977
|
+
header: entityToHeader(entity),
|
|
10978
|
+
ref: entityToRef(entity),
|
|
10979
|
+
issues: entityIssues
|
|
10980
|
+
}));
|
|
10981
|
+
}
|
|
10982
|
+
|
|
10983
|
+
function writeValidationReport(reporter, result) {
|
|
10984
|
+
const { errors, warnings, unitsWithIssues } = countIssues(result);
|
|
10985
|
+
reporter.addSummary("validation", {
|
|
10986
|
+
total: result.unitsTotal,
|
|
10987
|
+
succeeded: result.unitsTotal - unitsWithIssues,
|
|
10988
|
+
failed: unitsWithIssues
|
|
10989
|
+
});
|
|
10990
|
+
reporter.addMeta("validation", {
|
|
10991
|
+
unitNoun: result.unitNoun,
|
|
10992
|
+
errors,
|
|
10993
|
+
warnings,
|
|
10994
|
+
unitsWithIssues,
|
|
10995
|
+
unitsTotal: result.unitsTotal,
|
|
10996
|
+
groups: result.groups
|
|
10997
|
+
});
|
|
10998
|
+
}
|
|
10999
|
+
|
|
11000
|
+
const LEVEL_OPTIONS = ["error", "warning"];
|
|
11001
|
+
const FORMAT_OPTIONS = ["pretty", "json"];
|
|
11002
|
+
function parseLevel(value) {
|
|
11003
|
+
if (!LEVEL_OPTIONS.includes(value)) {
|
|
11004
|
+
throw new CommandError(`Invalid --level "${value}". Expected one of: ${LEVEL_OPTIONS.join(", ")}.`);
|
|
11005
|
+
}
|
|
11006
|
+
return value;
|
|
11007
|
+
}
|
|
11008
|
+
function parseFormat(value) {
|
|
11009
|
+
if (!FORMAT_OPTIONS.includes(value)) {
|
|
11010
|
+
throw new CommandError(`Invalid --format "${value}". Expected one of: ${FORMAT_OPTIONS.join(", ")}.`);
|
|
11011
|
+
}
|
|
11012
|
+
return value;
|
|
11013
|
+
}
|
|
11014
|
+
|
|
11015
|
+
function storyHeader(story) {
|
|
11016
|
+
const slug = story.full_slug ?? story.slug ?? String(story.id);
|
|
11017
|
+
return `${slug} (story #${story.id})`;
|
|
11018
|
+
}
|
|
11019
|
+
function storyRef(story) {
|
|
11020
|
+
return {
|
|
11021
|
+
kind: "story",
|
|
11022
|
+
id: story.id,
|
|
11023
|
+
...story.full_slug ? { slug: story.full_slug } : {},
|
|
11024
|
+
...story.name ? { name: story.name } : {}
|
|
11025
|
+
};
|
|
11026
|
+
}
|
|
11027
|
+
storiesCommand.command("validate").description("Validate every story's draft content in a space against a local code-defined schema.").option("-s, --space <space>", "space ID").option("--schema <entry-file>", "Path to the TypeScript schema entry file").option("--starts-with <path>", 'Only validate stories whose path starts with this prefix. Example: --starts-with="en/blog/"').option("--level <level>", "Display threshold: error|warning", "warning").option("--format <format>", "Output format: pretty|json", "pretty").action(async (options, command) => {
|
|
11028
|
+
const { schema: schemaEntry } = options;
|
|
11029
|
+
const startsWith = options.startsWith === void 0 ? void 0 : normalizeStartsWith(options.startsWith) || void 0;
|
|
11030
|
+
const ui = getUI();
|
|
11031
|
+
const logger = getLogger();
|
|
11032
|
+
const reporter = getReporter();
|
|
11033
|
+
const { space, verbose } = command.optsWithGlobals();
|
|
11034
|
+
const { state } = session();
|
|
11035
|
+
const failFatal = (message) => {
|
|
11036
|
+
reporter.addSummary("validation", { total: 1, succeeded: 0, failed: 1 });
|
|
11037
|
+
handleError(new CommandError(message), verbose);
|
|
11038
|
+
};
|
|
11039
|
+
try {
|
|
11040
|
+
let level;
|
|
11041
|
+
let format;
|
|
11042
|
+
try {
|
|
11043
|
+
level = parseLevel(options.level);
|
|
11044
|
+
format = parseFormat(options.format);
|
|
11045
|
+
} catch (maybeError) {
|
|
11046
|
+
failFatal(toError(maybeError).message);
|
|
11047
|
+
return;
|
|
11048
|
+
}
|
|
11049
|
+
const isJson = format === "json";
|
|
11050
|
+
logger.info("Stories validate started", { space, schemaEntry, startsWith, level, format });
|
|
11051
|
+
if (!requireAuthentication(state, verbose)) {
|
|
11052
|
+
reporter.addSummary("validation", { total: 1, succeeded: 0, failed: 1 });
|
|
11053
|
+
return;
|
|
11054
|
+
}
|
|
11055
|
+
if (!space) {
|
|
11056
|
+
failFatal("Please provide the space as argument --space YOUR_SPACE_ID.");
|
|
11057
|
+
return;
|
|
11058
|
+
}
|
|
11059
|
+
if (!schemaEntry) {
|
|
11060
|
+
failFatal("Please provide the schema entry file with --schema <entry-file>.");
|
|
11061
|
+
return;
|
|
11062
|
+
}
|
|
11063
|
+
let schema;
|
|
11064
|
+
try {
|
|
11065
|
+
({ schema } = await loadSchemaEntry(schemaEntry, { requireBlocks: true }));
|
|
11066
|
+
} catch (maybeError) {
|
|
11067
|
+
failFatal(toError(maybeError).message);
|
|
11068
|
+
return;
|
|
11069
|
+
}
|
|
11070
|
+
const groups = [];
|
|
11071
|
+
let totalStories = 0;
|
|
11072
|
+
const fetchErrors = [];
|
|
11073
|
+
let listFailed = false;
|
|
11074
|
+
let listError;
|
|
11075
|
+
let progress;
|
|
11076
|
+
let listedTotal = 0;
|
|
11077
|
+
let foldersSkipped = 0;
|
|
11078
|
+
const startProgress = () => {
|
|
11079
|
+
if (isJson) {
|
|
11080
|
+
return void 0;
|
|
11081
|
+
}
|
|
11082
|
+
progress ??= ui.createProgressBar({ title: "Validating Stories...".padEnd(23) });
|
|
11083
|
+
return progress;
|
|
11084
|
+
};
|
|
11085
|
+
const syncProgressTotal = () => {
|
|
11086
|
+
const total = Math.max(listedTotal - foldersSkipped, 0);
|
|
11087
|
+
if (total === 0 && progress === void 0) {
|
|
11088
|
+
return;
|
|
11089
|
+
}
|
|
11090
|
+
startProgress()?.setTotal(total);
|
|
11091
|
+
};
|
|
11092
|
+
const stopProgress = () => {
|
|
11093
|
+
progress?.stop();
|
|
11094
|
+
ui.stopAllProgressBars();
|
|
11095
|
+
};
|
|
11096
|
+
if (!isJson) {
|
|
11097
|
+
ui.title(`${commands.STORIES}`, colorPalette.STORIES, "Validating stories...");
|
|
11098
|
+
}
|
|
11099
|
+
try {
|
|
11100
|
+
await pipeline$1(
|
|
11101
|
+
fetchStoriesStream({
|
|
11102
|
+
spaceId: space,
|
|
11103
|
+
params: { starts_with: startsWith },
|
|
11104
|
+
setTotalStories: (total) => {
|
|
11105
|
+
listedTotal = total;
|
|
11106
|
+
syncProgressTotal();
|
|
11107
|
+
},
|
|
11108
|
+
onPageError: (error, page, total) => {
|
|
11109
|
+
listFailed = true;
|
|
11110
|
+
listError = error.message;
|
|
11111
|
+
stopProgress();
|
|
11112
|
+
logger.error("Failed to list stories", { error: error.message, page, total });
|
|
11113
|
+
handleError(error, verbose, { page, total });
|
|
11114
|
+
}
|
|
11115
|
+
}),
|
|
11116
|
+
// Skip folders: they carry no content to validate, and are not part of
|
|
11117
|
+
// the population the summary counts.
|
|
11118
|
+
new Transform({
|
|
11119
|
+
objectMode: true,
|
|
11120
|
+
transform(story, _encoding, callback) {
|
|
11121
|
+
if (story.is_folder) {
|
|
11122
|
+
foldersSkipped += 1;
|
|
11123
|
+
syncProgressTotal();
|
|
11124
|
+
callback();
|
|
11125
|
+
return;
|
|
11126
|
+
}
|
|
11127
|
+
totalStories += 1;
|
|
11128
|
+
this.push(story);
|
|
11129
|
+
callback();
|
|
11130
|
+
}
|
|
11131
|
+
}),
|
|
11132
|
+
fetchStoryStream({
|
|
11133
|
+
spaceId: space,
|
|
11134
|
+
onStoryError: (error, story) => {
|
|
11135
|
+
fetchErrors.push({
|
|
11136
|
+
id: story.id,
|
|
11137
|
+
...story.full_slug ? { slug: story.full_slug } : {},
|
|
11138
|
+
message: error.message
|
|
11139
|
+
});
|
|
11140
|
+
progress?.increment();
|
|
11141
|
+
logger.error("Failed to fetch story", { error: error.message, storyId: story.id });
|
|
11142
|
+
handleError(error, verbose, { storyId: story.id });
|
|
11143
|
+
}
|
|
11144
|
+
}),
|
|
11145
|
+
new Writable({
|
|
11146
|
+
objectMode: true,
|
|
11147
|
+
async write(story, _encoding, callback) {
|
|
11148
|
+
try {
|
|
11149
|
+
const { issues } = await validateStory(story, schema);
|
|
11150
|
+
if (issues.length > 0) {
|
|
11151
|
+
groups.push({ header: storyHeader(story), ref: storyRef(story), issues });
|
|
11152
|
+
}
|
|
11153
|
+
progress?.increment();
|
|
11154
|
+
callback();
|
|
11155
|
+
} catch (maybeError) {
|
|
11156
|
+
callback(toError(maybeError));
|
|
11157
|
+
}
|
|
11158
|
+
}
|
|
11159
|
+
})
|
|
11160
|
+
);
|
|
11161
|
+
} catch (maybeError) {
|
|
11162
|
+
stopProgress();
|
|
11163
|
+
failFatal(toError(maybeError).message);
|
|
11164
|
+
return;
|
|
11165
|
+
}
|
|
11166
|
+
stopProgress();
|
|
11167
|
+
groups.sort((a, b) => {
|
|
11168
|
+
const left = a.ref.slug ?? a.header;
|
|
11169
|
+
const right = b.ref.slug ?? b.header;
|
|
11170
|
+
if (left !== right) {
|
|
11171
|
+
return left < right ? -1 : 1;
|
|
11172
|
+
}
|
|
11173
|
+
return (a.ref.id ?? 0) - (b.ref.id ?? 0);
|
|
11174
|
+
});
|
|
11175
|
+
const fetchFailures = fetchErrors.length;
|
|
11176
|
+
const result = {
|
|
11177
|
+
unitNoun: "stories",
|
|
11178
|
+
unitNounSingular: "story",
|
|
11179
|
+
unitsTotal: totalStories,
|
|
11180
|
+
groups,
|
|
11181
|
+
// Travels with the result so both formatters can say the population was
|
|
11182
|
+
// narrowed, rather than only the pretty one knowing.
|
|
11183
|
+
...startsWith === void 0 ? {} : { filter: { option: "--starts-with", value: startsWith } },
|
|
11184
|
+
fetchFailures,
|
|
11185
|
+
fetchErrors,
|
|
11186
|
+
listFailed,
|
|
11187
|
+
listError
|
|
11188
|
+
};
|
|
11189
|
+
writeValidationReport(reporter, result);
|
|
11190
|
+
reporter.addSummary("fetch", {
|
|
11191
|
+
total: totalStories,
|
|
11192
|
+
succeeded: totalStories - fetchFailures,
|
|
11193
|
+
failed: fetchFailures
|
|
11194
|
+
});
|
|
11195
|
+
if (listFailed) {
|
|
11196
|
+
reporter.addSummary("list", { total: 1, succeeded: 0, failed: 1 });
|
|
11197
|
+
}
|
|
11198
|
+
const { errors, warnings } = countIssues(result);
|
|
11199
|
+
logger.info("Stories validate finished", { errors, warnings, stories: totalStories, fetchFailures, listFailed });
|
|
11200
|
+
if (isJson) {
|
|
11201
|
+
ui.writeMachineOutput(formatJson(result, level));
|
|
11202
|
+
}
|
|
11203
|
+
if (listFailed) {
|
|
11204
|
+
if (!isJson) {
|
|
11205
|
+
ui.error("Listing stories failed; the space was not fully validated.");
|
|
11206
|
+
}
|
|
11207
|
+
return;
|
|
11208
|
+
}
|
|
11209
|
+
if (!isJson) {
|
|
11210
|
+
ui.log(formatPretty(result, level));
|
|
11211
|
+
if (result.filter && totalStories === 0) {
|
|
11212
|
+
ui.warn(`No stories matched ${result.filter.option} "${result.filter.value}"; nothing was validated.`);
|
|
11213
|
+
}
|
|
11214
|
+
if (fetchFailures > 0) {
|
|
11215
|
+
ui.warn(`${fetchFailures} story(s) could not be fetched and were not validated.`);
|
|
11216
|
+
}
|
|
11217
|
+
}
|
|
11218
|
+
process.exitCode = errors > 0 || fetchFailures > 0 ? 1 : 0;
|
|
11219
|
+
} finally {
|
|
11220
|
+
reporter.finalize();
|
|
11221
|
+
}
|
|
11222
|
+
});
|
|
11223
|
+
|
|
10827
11224
|
const program$1 = getProgram();
|
|
10828
11225
|
const schemaCommand = program$1.command(commands.SCHEMA).description(`Manage your space's schema from code`);
|
|
10829
11226
|
|
|
10830
|
-
function isRecord(value) {
|
|
10831
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10832
|
-
}
|
|
10833
11227
|
const COMPONENT_STRIP_KEYS = /* @__PURE__ */ new Set([
|
|
10834
11228
|
"id",
|
|
10835
11229
|
"created_at",
|
|
@@ -11037,15 +11431,6 @@ function mapDatasourceToWire(datasource) {
|
|
|
11037
11431
|
return datasource;
|
|
11038
11432
|
}
|
|
11039
11433
|
|
|
11040
|
-
function isComponent(value) {
|
|
11041
|
-
return isRecord(value) && typeof value.name === "string" && Array.isArray(value.fields);
|
|
11042
|
-
}
|
|
11043
|
-
function isDatasource(value) {
|
|
11044
|
-
return isRecord(value) && typeof value.name === "string" && typeof value.slug === "string" && !Array.isArray(value.fields);
|
|
11045
|
-
}
|
|
11046
|
-
function isFolder(value) {
|
|
11047
|
-
return isRecord(value) && typeof value.name === "string" && typeof value.path === "string" && !Array.isArray(value.fields) && !("slug" in value);
|
|
11048
|
-
}
|
|
11049
11434
|
function buildLocalFolders(registered, derived) {
|
|
11050
11435
|
const byPath = /* @__PURE__ */ new Map();
|
|
11051
11436
|
const add = (displayPath, registeredLeaf) => {
|
|
@@ -11086,24 +11471,42 @@ function buildLocalFolders(registered, derived) {
|
|
|
11086
11471
|
}
|
|
11087
11472
|
return folders;
|
|
11088
11473
|
}
|
|
11089
|
-
function
|
|
11090
|
-
|
|
11091
|
-
|
|
11092
|
-
|
|
11093
|
-
|
|
11474
|
+
function assertUniqueIdentities(components, datasources) {
|
|
11475
|
+
const collisions = [];
|
|
11476
|
+
const collect = (label, values) => {
|
|
11477
|
+
const seen = /* @__PURE__ */ new Set();
|
|
11478
|
+
const reported = /* @__PURE__ */ new Set();
|
|
11479
|
+
for (const value of values) {
|
|
11480
|
+
if (typeof value !== "string") {
|
|
11481
|
+
continue;
|
|
11482
|
+
}
|
|
11483
|
+
if (seen.has(value) && !reported.has(value)) {
|
|
11484
|
+
reported.add(value);
|
|
11485
|
+
collisions.push(`${label} "${value}"`);
|
|
11486
|
+
}
|
|
11487
|
+
seen.add(value);
|
|
11488
|
+
}
|
|
11489
|
+
};
|
|
11490
|
+
collect("block name", components.map((component) => component.name));
|
|
11491
|
+
collect("datasource name", datasources.map((datasource) => datasource.name));
|
|
11492
|
+
collect("datasource slug", datasources.map((datasource) => datasource.slug));
|
|
11493
|
+
if (collisions.length > 0) {
|
|
11494
|
+
throw new CommandError(
|
|
11495
|
+
`Duplicate schema definitions: ${collisions.join(", ")}. Each block name, datasource name, and datasource slug must be unique; rename or remove the duplicate before pushing.`
|
|
11496
|
+
);
|
|
11497
|
+
}
|
|
11094
11498
|
}
|
|
11095
11499
|
function classifyExports(moduleExports) {
|
|
11096
|
-
const
|
|
11097
|
-
|
|
11098
|
-
const
|
|
11099
|
-
const registered = [];
|
|
11500
|
+
const { components, datasources, folders } = collectSchemaExports(moduleExports);
|
|
11501
|
+
assertUniqueIdentities(components, datasources);
|
|
11502
|
+
const registered = folders.map((folder) => folder.path);
|
|
11100
11503
|
const derived = [];
|
|
11101
|
-
|
|
11102
|
-
if (typeof
|
|
11103
|
-
derived.push(
|
|
11504
|
+
for (const component of components) {
|
|
11505
|
+
if (typeof component.folder === "string") {
|
|
11506
|
+
derived.push(component.folder);
|
|
11104
11507
|
}
|
|
11105
|
-
if (Array.isArray(
|
|
11106
|
-
for (const field of
|
|
11508
|
+
if (Array.isArray(component.fields)) {
|
|
11509
|
+
for (const field of component.fields) {
|
|
11107
11510
|
if (!isRecord(field) || !Array.isArray(field.allow)) {
|
|
11108
11511
|
continue;
|
|
11109
11512
|
}
|
|
@@ -11115,46 +11518,14 @@ function classifyExports(moduleExports) {
|
|
|
11115
11518
|
}
|
|
11116
11519
|
}
|
|
11117
11520
|
}
|
|
11118
|
-
|
|
11119
|
-
|
|
11120
|
-
|
|
11121
|
-
|
|
11122
|
-
|
|
11123
|
-
}
|
|
11124
|
-
seenComponents.add(value.name);
|
|
11125
|
-
data.components.push(mapBlockToWire(value));
|
|
11126
|
-
} else if (isFolder(value)) {
|
|
11127
|
-
registered.push(value.path);
|
|
11128
|
-
} else if (isDatasource(value)) {
|
|
11129
|
-
if (seenDatasources.has(value.name)) {
|
|
11130
|
-
return;
|
|
11131
|
-
}
|
|
11132
|
-
seenDatasources.add(value.name);
|
|
11133
|
-
data.datasources.push(mapDatasourceToWire(value));
|
|
11134
|
-
}
|
|
11135
|
-
}
|
|
11136
|
-
for (const value of Object.values(moduleExports)) {
|
|
11137
|
-
if (isSchemaObject(value)) {
|
|
11138
|
-
for (const group of Object.values(value)) {
|
|
11139
|
-
if (isRecord(group)) {
|
|
11140
|
-
for (const entity of Object.values(group)) {
|
|
11141
|
-
collect(entity);
|
|
11142
|
-
}
|
|
11143
|
-
}
|
|
11144
|
-
}
|
|
11145
|
-
} else {
|
|
11146
|
-
collect(value);
|
|
11147
|
-
}
|
|
11148
|
-
}
|
|
11149
|
-
data.folders = buildLocalFolders(registered, derived);
|
|
11150
|
-
return data;
|
|
11521
|
+
return {
|
|
11522
|
+
components: components.map(mapBlockToWire),
|
|
11523
|
+
folders: buildLocalFolders(registered, derived),
|
|
11524
|
+
datasources: datasources.map(mapDatasourceToWire)
|
|
11525
|
+
};
|
|
11151
11526
|
}
|
|
11152
11527
|
async function loadSchema(entryPath) {
|
|
11153
|
-
const
|
|
11154
|
-
const jiti = createJiti(import.meta.url, { interopDefault: true });
|
|
11155
|
-
const { resolve } = await import('pathe');
|
|
11156
|
-
const entryAbs = resolve(entryPath);
|
|
11157
|
-
const entryMod = await jiti.import(entryAbs);
|
|
11528
|
+
const entryMod = await loadSchemaModule(entryPath);
|
|
11158
11529
|
return classifyExports(entryMod);
|
|
11159
11530
|
}
|
|
11160
11531
|
|
|
@@ -12175,7 +12546,7 @@ schemaCommand.command("push <entry-file>").description("Push local TypeScript sc
|
|
|
12175
12546
|
const shouldGenerate = explicitMigrations || await confirm({
|
|
12176
12547
|
message: "Generate migration files for breaking changes?",
|
|
12177
12548
|
default: true
|
|
12178
|
-
});
|
|
12549
|
+
}, stderrPromptContext);
|
|
12179
12550
|
if (shouldGenerate) {
|
|
12180
12551
|
const migrationTimestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
12181
12552
|
const resolvedBase = resolvePath(basePath, "");
|
|
@@ -12199,7 +12570,7 @@ schemaCommand.command("push <entry-file>").description("Push local TypeScript sc
|
|
|
12199
12570
|
const renameConfirmed = await confirm({
|
|
12200
12571
|
message: "Are these renames correct?",
|
|
12201
12572
|
default: true
|
|
12202
|
-
});
|
|
12573
|
+
}, stderrPromptContext);
|
|
12203
12574
|
if (!renameConfirmed) {
|
|
12204
12575
|
comp.changes = comp.changes.map((c) => {
|
|
12205
12576
|
if (c.kind === "rename") {
|
|
@@ -12414,9 +12785,15 @@ function resolveGroupWhitelistRefs(whitelist, folderVarByUuid) {
|
|
|
12414
12785
|
function toDslField(field, folderVarByUuid) {
|
|
12415
12786
|
const { component_whitelist, component_group_whitelist, datasource_slug, restrict_components, restrict_type, ...rest } = field;
|
|
12416
12787
|
const out = { ...rest };
|
|
12417
|
-
const
|
|
12418
|
-
const
|
|
12419
|
-
|
|
12788
|
+
const restrictionDisabled = restrict_components === false;
|
|
12789
|
+
const groupRefs = restrictionDisabled ? void 0 : resolveGroupWhitelistRefs(component_group_whitelist, folderVarByUuid);
|
|
12790
|
+
const hasBlockNames = !restrictionDisabled && Array.isArray(component_whitelist) && component_whitelist.length > 0;
|
|
12791
|
+
if (restrictionDisabled) {
|
|
12792
|
+
out.restrict_components = false;
|
|
12793
|
+
if (restrict_type !== void 0) {
|
|
12794
|
+
out.restrict_type = restrict_type;
|
|
12795
|
+
}
|
|
12796
|
+
} else if (hasBlockNames) {
|
|
12420
12797
|
out.allow = component_whitelist;
|
|
12421
12798
|
} else if (groupRefs) {
|
|
12422
12799
|
out.allow = groupRefs;
|
|
@@ -12454,6 +12831,9 @@ function collectWhitelistFolderVars(schema, folderVarByUuid) {
|
|
|
12454
12831
|
if (!isRecord(field)) {
|
|
12455
12832
|
continue;
|
|
12456
12833
|
}
|
|
12834
|
+
if (field.restrict_components === false) {
|
|
12835
|
+
continue;
|
|
12836
|
+
}
|
|
12457
12837
|
const refs = resolveGroupWhitelistRefs(field.component_group_whitelist, folderVarByUuid);
|
|
12458
12838
|
if (refs) {
|
|
12459
12839
|
refs.forEach((ref) => vars.add(ref.code));
|
|
@@ -12579,7 +12959,7 @@ function generateSchemaFile(components, datasources, folders = []) {
|
|
|
12579
12959
|
const lines = [];
|
|
12580
12960
|
lines.push("import { defineSchema } from '@storyblok/schema';");
|
|
12581
12961
|
lines.push("import type { Schema as InferSchema, Story as InferStory } from '@storyblok/schema';");
|
|
12582
|
-
lines.push("import type { MapiStory as InferStoryMapi } from '@storyblok/schema';");
|
|
12962
|
+
lines.push(components.length > 0 ? "import type { BlockContent, MapiStory as InferStoryMapi } from '@storyblok/schema';" : "import type { MapiStory as InferStoryMapi } from '@storyblok/schema';");
|
|
12583
12963
|
lines.push("");
|
|
12584
12964
|
for (const { varName, fileName, segments } of components) {
|
|
12585
12965
|
const subPath = segments.length > 0 ? `${segments.join("/")}/` : "";
|
|
@@ -12618,8 +12998,21 @@ function generateSchemaFile(components, datasources, folders = []) {
|
|
|
12618
12998
|
lines.push("");
|
|
12619
12999
|
lines.push("export type Schema = InferSchema<typeof schema>;");
|
|
12620
13000
|
lines.push("export type Blocks = Schema['blocks'];");
|
|
12621
|
-
lines.push("export type
|
|
12622
|
-
lines.push("export type
|
|
13001
|
+
lines.push("export type FieldPlugins = Schema['fieldPlugins'];");
|
|
13002
|
+
lines.push("export type Story = InferStory<Blocks, FieldPlugins>;");
|
|
13003
|
+
lines.push("export type StoryMapi = InferStoryMapi<Blocks, FieldPlugins>;");
|
|
13004
|
+
if (components.length > 0) {
|
|
13005
|
+
lines.push("");
|
|
13006
|
+
lines.push('// Type a component\'s props by block name: `Block<"hero">`.');
|
|
13007
|
+
lines.push("export type Block<TName extends Blocks['name']> = BlockContent<");
|
|
13008
|
+
lines.push(" Extract<Blocks, { name: TName }>,");
|
|
13009
|
+
lines.push(" Blocks,");
|
|
13010
|
+
lines.push(" FieldPlugins");
|
|
13011
|
+
lines.push(">;");
|
|
13012
|
+
lines.push("");
|
|
13013
|
+
lines.push("// Loose union of every block's content, for a dynamic component dispatcher.");
|
|
13014
|
+
lines.push("export type AnyBlock = BlockContent<Blocks, Blocks, FieldPlugins>;");
|
|
13015
|
+
}
|
|
12623
13016
|
lines.push("");
|
|
12624
13017
|
return lines.join("\n");
|
|
12625
13018
|
}
|
|
@@ -13078,7 +13471,7 @@ schemaCommand.command("rollback [changeset-file]").description("Roll back a Stor
|
|
|
13078
13471
|
resolvedFile = await select({
|
|
13079
13472
|
message: "Select a changeset to roll back:",
|
|
13080
13473
|
choices: available.map((f) => ({ name: basename(f), value: f }))
|
|
13081
|
-
});
|
|
13474
|
+
}, stderrPromptContext);
|
|
13082
13475
|
}
|
|
13083
13476
|
let changeset;
|
|
13084
13477
|
try {
|
|
@@ -13104,7 +13497,7 @@ schemaCommand.command("rollback [changeset-file]").description("Roll back a Stor
|
|
|
13104
13497
|
const confirmed = await confirm({
|
|
13105
13498
|
message: `Apply rollback of ${ops.length} change(s) from ${basename(resolvedFile)}?`,
|
|
13106
13499
|
default: false
|
|
13107
|
-
});
|
|
13500
|
+
}, stderrPromptContext);
|
|
13108
13501
|
if (!confirmed) {
|
|
13109
13502
|
ui.info("Rollback cancelled.");
|
|
13110
13503
|
return;
|
|
@@ -13155,19 +13548,78 @@ schemaCommand.command("rollback [changeset-file]").description("Roll back a Stor
|
|
|
13155
13548
|
}
|
|
13156
13549
|
});
|
|
13157
13550
|
|
|
13551
|
+
schemaCommand.command("validate <entry-file>").description("Validate a local TypeScript schema definition. Static and fully offline \u2014 no login, no space, no API calls.").option("--level <level>", "Display threshold: error|warning", "warning").option("--format <format>", "Output format: pretty|json", "pretty").action(async (entryFile, options, command) => {
|
|
13552
|
+
const ui = getUI();
|
|
13553
|
+
const logger = getLogger();
|
|
13554
|
+
const reporter = getReporter();
|
|
13555
|
+
const { verbose } = command.optsWithGlobals();
|
|
13556
|
+
try {
|
|
13557
|
+
let level;
|
|
13558
|
+
let format;
|
|
13559
|
+
try {
|
|
13560
|
+
level = parseLevel(options.level);
|
|
13561
|
+
format = parseFormat(options.format);
|
|
13562
|
+
} catch (maybeError) {
|
|
13563
|
+
reporter.addSummary("validation", { total: 1, succeeded: 0, failed: 1 });
|
|
13564
|
+
handleError(toError(maybeError), verbose);
|
|
13565
|
+
return;
|
|
13566
|
+
}
|
|
13567
|
+
const isJson = format === "json";
|
|
13568
|
+
logger.info("Schema validate started", { entryFile, level, format });
|
|
13569
|
+
let loaded;
|
|
13570
|
+
try {
|
|
13571
|
+
loaded = await loadSchemaEntry(entryFile);
|
|
13572
|
+
} catch (maybeError) {
|
|
13573
|
+
const error = toError(maybeError);
|
|
13574
|
+
reporter.addSummary("validation", { total: 1, succeeded: 0, failed: 1 });
|
|
13575
|
+
handleError(error, verbose);
|
|
13576
|
+
logger.error("Schema validate failed to load entry file", { error: error.message });
|
|
13577
|
+
return;
|
|
13578
|
+
}
|
|
13579
|
+
const { issues } = await validateSchema(loaded.schema);
|
|
13580
|
+
const result = {
|
|
13581
|
+
unitNoun: "entities",
|
|
13582
|
+
unitNounSingular: "entity",
|
|
13583
|
+
unitsTotal: loaded.entityCount,
|
|
13584
|
+
groups: groupIssuesByEntity(issues)
|
|
13585
|
+
};
|
|
13586
|
+
if (isJson) {
|
|
13587
|
+
ui.writeMachineOutput(formatJson(result, level));
|
|
13588
|
+
} else {
|
|
13589
|
+
ui.title(commands.SCHEMA, colorPalette.SCHEMA, "Validating schema...");
|
|
13590
|
+
ui.log(formatPretty(result, level));
|
|
13591
|
+
}
|
|
13592
|
+
writeValidationReport(reporter, result);
|
|
13593
|
+
const { errors, warnings } = countIssues(result);
|
|
13594
|
+
logger.info("Schema validate finished", { errors, warnings, entities: result.unitsTotal });
|
|
13595
|
+
process.exitCode = errors > 0 ? 1 : 0;
|
|
13596
|
+
} finally {
|
|
13597
|
+
reporter.finalize();
|
|
13598
|
+
}
|
|
13599
|
+
});
|
|
13600
|
+
|
|
13158
13601
|
const program = getProgram();
|
|
13159
|
-
|
|
13160
|
-
|
|
13161
|
-
|
|
13602
|
+
const ui = getUI();
|
|
13603
|
+
ui.br();
|
|
13604
|
+
ui.title("Storyblok CLI", colorPalette.PRIMARY);
|
|
13605
|
+
ui.br();
|
|
13162
13606
|
program.on("command:*", () => {
|
|
13163
13607
|
console.error(`Invalid command: ${program.args.join(" ")}`);
|
|
13164
|
-
|
|
13165
|
-
program.
|
|
13166
|
-
process.
|
|
13608
|
+
console.error("");
|
|
13609
|
+
console.error(program.helpInformation());
|
|
13610
|
+
process.exitCode = 2;
|
|
13167
13611
|
});
|
|
13168
13612
|
try {
|
|
13169
|
-
program.
|
|
13613
|
+
await program.parseAsync(process.argv);
|
|
13170
13614
|
} catch (error) {
|
|
13171
|
-
|
|
13615
|
+
if (error instanceof CommanderError) {
|
|
13616
|
+
if (error.exitCode !== 0) {
|
|
13617
|
+
if (!process.exitCode) {
|
|
13618
|
+
process.exitCode = error.exitCode;
|
|
13619
|
+
}
|
|
13620
|
+
}
|
|
13621
|
+
} else {
|
|
13622
|
+
handleError(error);
|
|
13623
|
+
}
|
|
13172
13624
|
}
|
|
13173
13625
|
//# sourceMappingURL=index.mjs.map
|