contensis-cli 1.6.1-beta.2 → 1.6.1-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/index.js +58301 -11
  2. package/dist/index.js.map +4 -4
  3. package/dist/shell.js +58040 -52
  4. package/dist/shell.js.map +4 -4
  5. package/esbuild.config.js +8 -13
  6. package/package.json +3 -2
  7. package/src/commands/create.ts +48 -0
  8. package/src/commands/dev.ts +12 -2
  9. package/src/commands/globalOptions.ts +5 -3
  10. package/src/commands/import.ts +46 -5
  11. package/src/commands/push.ts +8 -1
  12. package/src/commands/set.ts +69 -1
  13. package/src/factories/RequestHandlerFactory.ts +19 -8
  14. package/src/localisation/en-GB.ts +22 -4
  15. package/src/mappers/DevRequests-to-RequestHanderCliArgs.ts +25 -17
  16. package/src/models/CliService.d.ts +5 -1
  17. package/src/providers/GitHubCliModuleProvider.ts +8 -8
  18. package/src/providers/HttpProvider.ts +2 -2
  19. package/src/providers/file-provider.ts +3 -0
  20. package/src/services/ContensisCliService.ts +265 -23
  21. package/src/services/ContensisDevService.ts +99 -35
  22. package/src/shell.ts +7 -1
  23. package/src/util/console.printer.ts +52 -0
  24. package/src/util/logger.ts +3 -4
  25. package/src/util/os.ts +5 -3
  26. package/src/version.ts +1 -1
  27. package/dist/commands/connect.js +0 -44
  28. package/dist/commands/connect.js.map +0 -7
  29. package/dist/commands/copy.js +0 -78
  30. package/dist/commands/copy.js.map +0 -7
  31. package/dist/commands/create.js +0 -170
  32. package/dist/commands/create.js.map +0 -7
  33. package/dist/commands/dev.js +0 -78
  34. package/dist/commands/dev.js.map +0 -7
  35. package/dist/commands/diff.js +0 -57
  36. package/dist/commands/diff.js.map +0 -7
  37. package/dist/commands/execute.js +0 -103
  38. package/dist/commands/execute.js.map +0 -7
  39. package/dist/commands/get.js +0 -330
  40. package/dist/commands/get.js.map +0 -7
  41. package/dist/commands/globalOptions.js +0 -252
  42. package/dist/commands/globalOptions.js.map +0 -7
  43. package/dist/commands/import.js +0 -229
  44. package/dist/commands/import.js.map +0 -7
  45. package/dist/commands/index.js +0 -107
  46. package/dist/commands/index.js.map +0 -7
  47. package/dist/commands/list.js +0 -195
  48. package/dist/commands/list.js.map +0 -7
  49. package/dist/commands/login.js +0 -55
  50. package/dist/commands/login.js.map +0 -7
  51. package/dist/commands/push.js +0 -229
  52. package/dist/commands/push.js.map +0 -7
  53. package/dist/commands/remove.js +0 -193
  54. package/dist/commands/remove.js.map +0 -7
  55. package/dist/commands/set.js +0 -180
  56. package/dist/commands/set.js.map +0 -7
  57. package/dist/commands/update.js +0 -70
  58. package/dist/commands/update.js.map +0 -7
  59. package/dist/factories/RequestHandlerFactory.js +0 -221
  60. package/dist/factories/RequestHandlerFactory.js.map +0 -7
  61. package/dist/localisation/en-GB.js +0 -552
  62. package/dist/localisation/en-GB.js.map +0 -7
  63. package/dist/mappers/ContensisCliService-to-RequestHanderSiteConfigYaml.js +0 -56
  64. package/dist/mappers/ContensisCliService-to-RequestHanderSiteConfigYaml.js.map +0 -7
  65. package/dist/mappers/DevInit-to-CIWorkflow.js +0 -409
  66. package/dist/mappers/DevInit-to-CIWorkflow.js.map +0 -7
  67. package/dist/mappers/DevInit-to-RolePermissions.js +0 -56
  68. package/dist/mappers/DevInit-to-RolePermissions.js.map +0 -7
  69. package/dist/mappers/DevRequests-to-RequestHanderCliArgs.js +0 -161
  70. package/dist/mappers/DevRequests-to-RequestHanderCliArgs.js.map +0 -7
  71. package/dist/mappers/MixedFileData.js +0 -83
  72. package/dist/mappers/MixedFileData.js.map +0 -7
  73. package/dist/models/AppError.d.js +0 -2
  74. package/dist/models/AppError.d.js.map +0 -7
  75. package/dist/models/Cache.d.js +0 -2
  76. package/dist/models/Cache.d.js.map +0 -7
  77. package/dist/models/CliService.d.js +0 -17
  78. package/dist/models/CliService.d.js.map +0 -7
  79. package/dist/models/DevService.d.js +0 -17
  80. package/dist/models/DevService.d.js.map +0 -7
  81. package/dist/models/JsModules.d.js +0 -2
  82. package/dist/models/JsModules.d.js.map +0 -7
  83. package/dist/providers/CredentialProvider.js +0 -126
  84. package/dist/providers/CredentialProvider.js.map +0 -7
  85. package/dist/providers/GitHubCliModuleProvider.js +0 -115
  86. package/dist/providers/GitHubCliModuleProvider.js.map +0 -7
  87. package/dist/providers/HttpProvider.js +0 -73
  88. package/dist/providers/HttpProvider.js.map +0 -7
  89. package/dist/providers/ManifestProvider.js +0 -50
  90. package/dist/providers/ManifestProvider.js.map +0 -7
  91. package/dist/providers/SessionCacheProvider.js +0 -132
  92. package/dist/providers/SessionCacheProvider.js.map +0 -7
  93. package/dist/providers/file-provider.js +0 -174
  94. package/dist/providers/file-provider.js.map +0 -7
  95. package/dist/services/ContensisAuthService.js +0 -88
  96. package/dist/services/ContensisAuthService.js.map +0 -7
  97. package/dist/services/ContensisCliService.js +0 -2598
  98. package/dist/services/ContensisCliService.js.map +0 -7
  99. package/dist/services/ContensisDevService.js +0 -387
  100. package/dist/services/ContensisDevService.js.map +0 -7
  101. package/dist/services/ContensisRoleService.js +0 -112
  102. package/dist/services/ContensisRoleService.js.map +0 -7
  103. package/dist/util/api-ids.js +0 -110
  104. package/dist/util/api-ids.js.map +0 -7
  105. package/dist/util/assert.js +0 -62
  106. package/dist/util/assert.js.map +0 -7
  107. package/dist/util/console.printer.js +0 -425
  108. package/dist/util/console.printer.js.map +0 -7
  109. package/dist/util/csv.formatter.js +0 -118
  110. package/dist/util/csv.formatter.js.map +0 -7
  111. package/dist/util/debug.js +0 -29
  112. package/dist/util/debug.js.map +0 -7
  113. package/dist/util/diff.js +0 -118
  114. package/dist/util/diff.js.map +0 -7
  115. package/dist/util/dotenv.js +0 -56
  116. package/dist/util/dotenv.js.map +0 -7
  117. package/dist/util/error.js +0 -36
  118. package/dist/util/error.js.map +0 -7
  119. package/dist/util/fetch.js +0 -69
  120. package/dist/util/fetch.js.map +0 -7
  121. package/dist/util/find.js +0 -39
  122. package/dist/util/find.js.map +0 -7
  123. package/dist/util/git.js +0 -145
  124. package/dist/util/git.js.map +0 -7
  125. package/dist/util/gitignore.js +0 -61
  126. package/dist/util/gitignore.js.map +0 -7
  127. package/dist/util/html.formatter.js +0 -70
  128. package/dist/util/html.formatter.js.map +0 -7
  129. package/dist/util/index.js +0 -68
  130. package/dist/util/index.js.map +0 -7
  131. package/dist/util/json.formatter.js +0 -66
  132. package/dist/util/json.formatter.js.map +0 -7
  133. package/dist/util/logger.js +0 -304
  134. package/dist/util/logger.js.map +0 -7
  135. package/dist/util/os.js +0 -46
  136. package/dist/util/os.js.map +0 -7
  137. package/dist/util/timers.js +0 -49
  138. package/dist/util/timers.js.map +0 -7
  139. package/dist/util/xml.formatter.js +0 -62
  140. package/dist/util/xml.formatter.js.map +0 -7
  141. package/dist/util/yaml.js +0 -44
  142. package/dist/util/yaml.js.map +0 -7
  143. package/dist/version.js +0 -29
  144. package/dist/version.js.map +0 -7
@@ -1,2598 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to2, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to2, key) && key !== except)
16
- __defProp(to2, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to2;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var ContensisCliService_exports = {};
30
- __export(ContensisCliService_exports, {
31
- cliCommand: () => cliCommand,
32
- default: () => ContensisCliService_default
33
- });
34
- module.exports = __toCommonJS(ContensisCliService_exports);
35
- var import_await_to_js = __toESM(require("await-to-js"));
36
- var import_chalk = __toESM(require("chalk"));
37
- var import_fs = __toESM(require("fs"));
38
- var import_inquirer = __toESM(require("inquirer"));
39
- var import_node_fetch = __toESM(require("node-fetch"));
40
- var import_path = __toESM(require("path"));
41
- var import_rfdc = __toESM(require("rfdc"));
42
- var import_migratortron = require("migratortron");
43
- var import_ContensisAuthService = __toESM(require("./ContensisAuthService"));
44
- var import_en_GB = require("../localisation/en-GB");
45
- var import_MixedFileData = require("../mappers/MixedFileData");
46
- var import_SessionCacheProvider = __toESM(require("../providers/SessionCacheProvider"));
47
- var import_CredentialProvider = __toESM(require("../providers/CredentialProvider"));
48
- var import_util = require("../util");
49
- var import_api_ids = require("../util/api-ids");
50
- var import_assert = require("../util/assert");
51
- var import_console = require("../util/console.printer");
52
- var import_csv = require("../util/csv.formatter");
53
- var import_html = require("../util/html.formatter");
54
- var import_json = require("../util/json.formatter");
55
- var import_xml = require("../util/xml.formatter");
56
- var import_debug = require("../util/debug");
57
- var import_diff = require("../util/diff");
58
- var import_find = require("../util/find");
59
- var import_logger = require("../util/logger");
60
- var import_timers = require("../util/timers");
61
- let insecurePasswordWarningShown = false;
62
- class ContensisCli {
63
- static quit = (error) => {
64
- process.removeAllListeners("exit");
65
- const exitCode = error ? 1 : 0;
66
- process.exit(exitCode);
67
- };
68
- format;
69
- output;
70
- session;
71
- auth;
72
- command;
73
- contensis;
74
- contensisOpts;
75
- currentProject;
76
- debug = (0, import_debug.isDebug)();
77
- sourceAlias;
78
- targetEnv;
79
- urls;
80
- log = import_logger.Logger;
81
- messages = import_en_GB.LogMessages;
82
- verb;
83
- noun;
84
- thirdArg;
85
- get cache() {
86
- return this.session.Get();
87
- }
88
- get currentEnv() {
89
- return this.cache.currentEnvironment || "";
90
- }
91
- set currentEnv(currentEnvironment) {
92
- this.session.Update({ currentEnvironment });
93
- }
94
- get env() {
95
- const currentEnvironment = this.currentEnv;
96
- const environments = this.cache.environments || {};
97
- if (!currentEnvironment) return {};
98
- else if (environments[currentEnvironment])
99
- return environments[currentEnvironment];
100
- else {
101
- return {
102
- history: [],
103
- lastUserId: "",
104
- projects: [],
105
- versionStatus: "latest"
106
- };
107
- }
108
- }
109
- constructor(args, outputOpts, contensisOpts = {}) {
110
- var _a;
111
- const [exe, script, verb = "", noun = "", ...restArgs] = args;
112
- this.verb = verb == null ? void 0 : verb.toLowerCase();
113
- this.noun = noun == null ? void 0 : noun.toLowerCase();
114
- this.thirdArg = restArgs == null ? void 0 : restArgs[0];
115
- const commandText = `${this.verb} ${this.noun} ${restArgs ? restArgs.join(" ") : ""}`.trim();
116
- this.session = new import_SessionCacheProvider.default();
117
- this.contensisOpts = contensisOpts;
118
- if (Array.isArray((_a = this.contensisOpts.query) == null ? void 0 : _a.fields)) {
119
- this.contensisOpts.query.fields = (0, import_api_ids.sanitiseIds)(
120
- this.contensisOpts.query.fields
121
- );
122
- }
123
- this.format = outputOpts == null ? void 0 : outputOpts.format;
124
- this.output = (outputOpts == null ? void 0 : outputOpts.output) ? import_path.default.isAbsolute(outputOpts.output) ? outputOpts.output : import_path.default.join(process.cwd(), outputOpts.output) : void 0;
125
- const currentEnvironment = (outputOpts == null ? void 0 : outputOpts.alias) || this.currentEnv;
126
- const environments = this.cache.environments || {};
127
- this.currentEnv = currentEnvironment;
128
- const env = this.env;
129
- if (outputOpts == null ? void 0 : outputOpts.projectId) env.currentProject = outputOpts.projectId;
130
- if (outputOpts == null ? void 0 : outputOpts.user) env.lastUserId = outputOpts.user;
131
- if (outputOpts == null ? void 0 : outputOpts.password) env.passwordFallback = outputOpts.password;
132
- if (outputOpts == null ? void 0 : outputOpts.clientId) env.lastUserId = outputOpts.clientId;
133
- if (outputOpts == null ? void 0 : outputOpts.sharedSecret)
134
- if (outputOpts.sharedSecret.startsWith("-"))
135
- throw new Error(
136
- `Shared secret option provided a value of ${outputOpts.sharedSecret}`
137
- );
138
- else env.passwordFallback = outputOpts.sharedSecret;
139
- this.currentProject = (env == null ? void 0 : env.currentProject) || "null";
140
- this.sourceAlias = (outputOpts == null ? void 0 : outputOpts.sourceAlias) || currentEnvironment;
141
- if (currentEnvironment) {
142
- this.urls = (0, import_util.url)(currentEnvironment, (env == null ? void 0 : env.currentProject) || "website");
143
- }
144
- this.command = {
145
- commandText,
146
- options: outputOpts,
147
- createdDate: (/* @__PURE__ */ new Date()).toISOString(),
148
- invokedBy: env == null ? void 0 : env.lastUserId
149
- };
150
- if (currentEnvironment) {
151
- env.history = [this.command];
152
- if (commandText) {
153
- environments[currentEnvironment] = env;
154
- this.session.Update({
155
- currentEnvironment,
156
- environments,
157
- history: [commandText]
158
- });
159
- }
160
- }
161
- }
162
- PrintEnvironments = async () => {
163
- const { log, messages } = this;
164
- const { currentEnvironment, environments = {} } = this.cache;
165
- const envKeys = Object.keys(environments).sort();
166
- log.success(messages.envs.found(envKeys.length));
167
- await this.HandleFormattingAndOutput(envKeys, () => {
168
- for (const env of envKeys) {
169
- console.log(` - ${currentEnvironment === env ? "* " : ""}${env}`);
170
- }
171
- });
172
- if (envKeys.length === 0 || !currentEnvironment) {
173
- log.help(messages.envs.tip());
174
- }
175
- };
176
- RemoveEnvironment = async (env) => {
177
- const { log, messages, session } = this;
178
- const { currentEnvironment, environments = {} } = this.cache;
179
- const envKeys = Object.keys(environments);
180
- log.success(messages.envs.found(envKeys.length));
181
- if (environments[env]) {
182
- session.RemoveEnv(env);
183
- const lastUserId = environments[env].lastUserId;
184
- if (lastUserId) {
185
- const [err, credentials] = await new import_CredentialProvider.default({
186
- userId: environments[env].lastUserId,
187
- alias: env
188
- }).Init();
189
- if (!err && credentials) await credentials.Delete();
190
- }
191
- log.success(messages.envs.removed(env));
192
- await this.HandleFormattingAndOutput(environments[env], () => log.line());
193
- } else {
194
- log.warning(messages.envs.notFound(env));
195
- }
196
- const nextCurrentEnv = currentEnvironment === env ? void 0 : currentEnvironment;
197
- if (envKeys.length === 0 || !nextCurrentEnv) log.help(messages.envs.tip());
198
- return nextCurrentEnv;
199
- };
200
- Connect = async (environment) => {
201
- var _a;
202
- const { log, messages, session } = this;
203
- if (environment) {
204
- this.currentEnv = environment;
205
- this.urls = (0, import_util.url)(environment, "website");
206
- const [fetchErr, response] = await (0, import_await_to_js.default)((0, import_node_fetch.default)(this.urls.cms));
207
- if (response && (response == null ? void 0 : response.status) < 400) {
208
- log.success(messages.connect.connected(environment));
209
- session.UpdateEnv(this.env, environment);
210
- if ((_a = this.env) == null ? void 0 : _a.lastUserId) {
211
- await this.PrintProjects();
212
- } else {
213
- log.warning(messages.projects.noList());
214
- log.help(messages.connect.tip());
215
- }
216
- } else {
217
- log.error(
218
- messages.connect.unreachable(this.urls.cms, (response == null ? void 0 : response.status) || 0)
219
- );
220
- }
221
- } else {
222
- log.error(messages.connect.noEnv());
223
- }
224
- };
225
- ConnectContensis = async ({ commit = false } = {}) => {
226
- var _a, _b, _c;
227
- if (!this.contensis) {
228
- const { contensisOpts, currentEnv, env, log, messages } = this;
229
- const userId = env == null ? void 0 : env.lastUserId;
230
- const isGuidId = userId && (0, import_assert.isUuid)(userId);
231
- if (currentEnv && userId) {
232
- const credentials = await this.GetCredentials(
233
- userId,
234
- env.passwordFallback
235
- );
236
- const cachedPassword = (_a = credentials == null ? void 0 : credentials.current) == null ? void 0 : _a.password;
237
- if (cachedPassword) {
238
- this.contensis = new import_migratortron.ContensisMigrationService(
239
- {
240
- ...contensisOpts,
241
- source: {
242
- url: ((_b = this.urls) == null ? void 0 : _b.cms) || "",
243
- username: !isGuidId ? userId : void 0,
244
- password: !isGuidId ? cachedPassword : void 0,
245
- clientId: isGuidId ? userId : void 0,
246
- sharedSecret: isGuidId ? cachedPassword : void 0,
247
- project: (env == null ? void 0 : env.currentProject) || "",
248
- assetHostname: (_c = this.urls) == null ? void 0 : _c.previewWeb
249
- },
250
- concurrency: typeof contensisOpts.concurrency !== "undefined" ? contensisOpts.concurrency : 3,
251
- outputProgress: true
252
- },
253
- !commit
254
- );
255
- }
256
- } else {
257
- if (!currentEnv) log.help(messages.connect.help());
258
- if (!userId) log.help(messages.connect.tip());
259
- }
260
- }
261
- return this.contensis;
262
- };
263
- ConnectContensisImport = async ({
264
- commit = false,
265
- noSource = false,
266
- fromFile,
267
- importData
268
- }) => {
269
- var _a, _b, _c, _d, _e, _f;
270
- const source = fromFile || importData || noSource ? "user-input" : "contensis";
271
- const mixedData = fromFile ? await new import_MixedFileData.MixedFileData().readFile(fromFile) : importData;
272
- const { contensisOpts, currentEnv, env, log, messages, sourceAlias } = this;
273
- const environments = this.cache.environments || {};
274
- const sourceEnvironment = environments[sourceAlias || ""] || {};
275
- const sourceCms = "source" in contensisOpts && contensisOpts.source || {};
276
- const sourceUserId = sourceCms.clientId || sourceCms.username || sourceEnvironment.lastUserId;
277
- const sourceProjectId = sourceCms.project || sourceEnvironment.currentProject || "website";
278
- const isSourceGuidId = sourceUserId && (0, import_assert.isUuid)(sourceUserId);
279
- const sourceUrls = (0, import_util.url)(sourceAlias || "", sourceProjectId);
280
- const sourcePassword = sourceCms.sharedSecret || sourceCms.password || sourceEnvironment.passwordFallback;
281
- const targetUserId = env == null ? void 0 : env.lastUserId;
282
- const isTargetGuidId = targetUserId && (0, import_assert.isUuid)(targetUserId);
283
- if (sourceUserId && currentEnv && targetUserId) {
284
- const sourceCredentials = await this.GetCredentials(
285
- sourceUserId,
286
- sourcePassword,
287
- sourceAlias,
288
- false
289
- );
290
- const cachedSourcePassword = (_a = sourceCredentials == null ? void 0 : sourceCredentials.current) == null ? void 0 : _a.password;
291
- const targetCredentials = await this.GetCredentials(
292
- targetUserId,
293
- env.passwordFallback
294
- );
295
- const cachedTargetPassword = (_b = targetCredentials == null ? void 0 : targetCredentials.current) == null ? void 0 : _b.password;
296
- if (cachedSourcePassword && cachedTargetPassword) {
297
- if (source === "user-input") {
298
- this.contensis = new import_migratortron.ContensisMigrationService(
299
- {
300
- concurrency: 2,
301
- outputProgress: true,
302
- ...contensisOpts,
303
- target: {
304
- url: ((_c = this.urls) == null ? void 0 : _c.cms) || "",
305
- username: !isTargetGuidId ? targetUserId : void 0,
306
- password: !isTargetGuidId ? cachedTargetPassword : void 0,
307
- clientId: isTargetGuidId ? targetUserId : void 0,
308
- sharedSecret: isTargetGuidId ? cachedTargetPassword : void 0,
309
- targetProjects: [env.currentProject || ""],
310
- assetHostname: (_d = this.urls) == null ? void 0 : _d.previewWeb
311
- },
312
- ...mixedData || {}
313
- },
314
- !commit
315
- );
316
- } else if (source === "contensis") {
317
- this.contensis = new import_migratortron.ContensisMigrationService(
318
- {
319
- concurrency: 2,
320
- outputProgress: true,
321
- ...contensisOpts,
322
- source: {
323
- url: sourceUrls.cms || "",
324
- username: !isSourceGuidId ? sourceUserId : void 0,
325
- password: !isSourceGuidId ? cachedSourcePassword : void 0,
326
- clientId: isSourceGuidId ? sourceUserId : void 0,
327
- sharedSecret: isSourceGuidId ? cachedSourcePassword : void 0,
328
- project: sourceProjectId,
329
- assetHostname: sourceUrls.previewWeb
330
- },
331
- target: {
332
- url: ((_e = this.urls) == null ? void 0 : _e.cms) || "",
333
- username: !isTargetGuidId ? targetUserId : void 0,
334
- password: !isTargetGuidId ? cachedTargetPassword : void 0,
335
- clientId: isTargetGuidId ? targetUserId : void 0,
336
- sharedSecret: isTargetGuidId ? cachedTargetPassword : void 0,
337
- targetProjects: [env.currentProject || ""],
338
- assetHostname: (_f = this.urls) == null ? void 0 : _f.previewWeb
339
- }
340
- },
341
- !commit
342
- );
343
- }
344
- }
345
- } else {
346
- if (!currentEnv) log.help(messages.connect.help());
347
- if (!targetUserId) log.help(messages.connect.tip());
348
- }
349
- return this.contensis;
350
- };
351
- GetCredentials = async (userId, password, currentEnv = this.currentEnv, saveCurrentEnv = true) => {
352
- const { log, messages } = this;
353
- if (userId) {
354
- const [credentialError, credentials] = await new import_CredentialProvider.default(
355
- { userId, alias: currentEnv },
356
- password
357
- ).Init();
358
- if (credentialError && !credentials.current) {
359
- log.error(
360
- `Unable to find credentials for user ${userId} at ${currentEnv}`,
361
- credentialError
362
- );
363
- return;
364
- }
365
- if (credentials.remarks.secure !== true) {
366
- if (!insecurePasswordWarningShown) {
367
- log.warning(messages.login.insecurePassword());
368
- insecurePasswordWarningShown = true;
369
- }
370
- } else {
371
- const env = this.cache.environments[currentEnv];
372
- env.passwordFallback = void 0;
373
- this.session.UpdateEnv(env, currentEnv, saveCurrentEnv);
374
- }
375
- return credentials;
376
- }
377
- };
378
- Login = async (userId, {
379
- password = "",
380
- promptPassword = true,
381
- sharedSecret = "",
382
- silent = false,
383
- attempt = 1
384
- } = {}) => {
385
- var _a, _b, _c, _d;
386
- let inputPassword = password || sharedSecret;
387
- if (!inputPassword)
388
- inputPassword = (0, import_assert.isSharedSecret)(this.env.passwordFallback) || (0, import_assert.isPassword)(this.env.passwordFallback) || "";
389
- const { messages } = this;
390
- if (userId) {
391
- const { currentEnv, env } = this;
392
- if (currentEnv) {
393
- const credentials = await this.GetCredentials(userId, inputPassword);
394
- if (credentials) {
395
- const cachedPassword = (0, import_assert.isPassword)((_a = credentials.current) == null ? void 0 : _a.password);
396
- const cachedSecret = (0, import_assert.isSharedSecret)((_b = credentials.current) == null ? void 0 : _b.password);
397
- if (!cachedPassword && !cachedSecret && promptPassword) {
398
- ({ inputPassword } = await import_inquirer.default.prompt([
399
- {
400
- type: "password",
401
- message: messages.login.passwordPrompt(currentEnv, userId),
402
- name: "inputPassword",
403
- mask: "*",
404
- prefix: void 0
405
- }
406
- ]));
407
- }
408
- if (inputPassword || cachedPassword || cachedSecret) {
409
- this.auth = new import_ContensisAuthService.default({
410
- username: userId,
411
- password: inputPassword || cachedPassword,
412
- projectId: (env == null ? void 0 : env.currentProject) || "website",
413
- rootUrl: ((_c = this.urls) == null ? void 0 : _c.cms) || "",
414
- clientId: userId,
415
- clientSecret: sharedSecret || cachedSecret
416
- });
417
- const [authError, bearerToken] = await (0, import_await_to_js.default)(this.auth.BearerToken());
418
- if (bearerToken) {
419
- env.authToken = bearerToken;
420
- env.lastUserId = userId;
421
- env.passwordFallback = credentials.remarks.secure !== true ? (_d = credentials.current) == null ? void 0 : _d.password : void 0;
422
- this.session.UpdateEnv(env);
423
- if (inputPassword) await credentials.Save(inputPassword);
424
- if (sharedSecret) await credentials.Save(sharedSecret);
425
- if (!silent) {
426
- import_logger.Logger.success(messages.login.success(currentEnv, userId));
427
- await this.PrintProjects();
428
- }
429
- } else if (authError) {
430
- import_logger.Logger.error(authError.toString());
431
- env.authToken = "";
432
- env.lastUserId = "";
433
- env.passwordFallback = void 0;
434
- this.session.UpdateEnv(env);
435
- if ((cachedPassword || cachedSecret) && credentials.remarks.secure) {
436
- await credentials.Delete();
437
- return await this.Login(userId, { password, sharedSecret });
438
- } else {
439
- throw new Error(messages.login.failed(currentEnv, userId));
440
- }
441
- }
442
- return env.authToken;
443
- } else {
444
- import_logger.Logger.error(messages.login.passwordPrompt());
445
- if (attempt < 2)
446
- return await this.Login(userId, { attempt: attempt + 1 });
447
- }
448
- }
449
- } else {
450
- import_logger.Logger.error(messages.login.noEnv());
451
- }
452
- } else {
453
- import_logger.Logger.error(messages.login.noUserId());
454
- }
455
- };
456
- PrintContensisVersion = async () => {
457
- const { log, messages } = this;
458
- const contensis = await this.ConnectContensis();
459
- if (contensis) {
460
- const [projectsErr, projects] = await (0, import_await_to_js.default)(
461
- contensis.projects.GetSourceProjects()
462
- );
463
- if (Array.isArray(projects)) {
464
- await this.HandleFormattingAndOutput(
465
- contensis.contensisVersion,
466
- () => log.raw(log.highlightText(contensis.contensisVersion))
467
- );
468
- }
469
- if (projectsErr) {
470
- log.error(messages.projects.noList());
471
- log.error(projectsErr.message);
472
- }
473
- }
474
- };
475
- PrintBearerToken = async () => {
476
- const { log, messages } = this;
477
- const contensis = await this.ConnectContensis();
478
- if (contensis) {
479
- const [error, token] = await (0, import_await_to_js.default)(
480
- contensis.content.source.repo.BearerToken()
481
- );
482
- if (token) {
483
- await this.HandleFormattingAndOutput(
484
- token,
485
- () => log.raw(log.highlightText(token))
486
- );
487
- }
488
- if (error) {
489
- log.error(messages.projects.noList());
490
- log.error(error.message);
491
- }
492
- }
493
- };
494
- PrintProjects = async () => {
495
- const { currentProject, log, messages, session } = this;
496
- const contensis = await this.ConnectContensis();
497
- if (contensis) {
498
- const [projectsErr, projects] = await (0, import_await_to_js.default)(
499
- contensis.projects.GetSourceProjects()
500
- );
501
- if (Array.isArray(projects)) {
502
- const nextCurrentProject = currentProject && currentProject !== "null" ? currentProject : projects.some((p) => p.id === "website") ? "website" : void 0;
503
- session.UpdateEnv({
504
- projects: projects.map((p) => ({
505
- id: p.id,
506
- primaryLanguage: p.primaryLanguage
507
- })),
508
- currentProject: nextCurrentProject
509
- });
510
- log.success(messages.projects.list());
511
- log.raw("");
512
- await this.HandleFormattingAndOutput(projects, () => {
513
- for (const project of projects.sort(
514
- (a, b) => a.id.localeCompare(b.id)
515
- )) {
516
- let color;
517
- try {
518
- color = import_chalk.default.keyword(project.color);
519
- } catch (ex) {
520
- import_logger.Logger.debug(`${ex}`);
521
- color = import_chalk.default.white;
522
- }
523
- console.log(
524
- `${nextCurrentProject === project.id ? `>> ${log.boldText(color(project.id))}` : ` ${color(project.id)}`} ${log.infoText(
525
- `[${project.supportedLanguages.map(
526
- (l) => l === project.primaryLanguage ? `*${log.boldText(l)}` : l
527
- ).join(" ")}]`
528
- )}`
529
- );
530
- }
531
- });
532
- if (!this.SetProject(nextCurrentProject))
533
- log.warning(messages.projects.tip());
534
- }
535
- if (projectsErr) {
536
- log.error(messages.projects.noList());
537
- log.error(projectsErr.message);
538
- }
539
- }
540
- };
541
- PrintProject = async (projectId = this.currentProject) => {
542
- const { log, messages } = this;
543
- const contensis = await this.ConnectContensis();
544
- if (contensis) {
545
- const [projectsErr, projects] = await (0, import_await_to_js.default)(
546
- contensis.projects.GetSourceProjects()
547
- );
548
- const foundProject = projects == null ? void 0 : projects.find(
549
- (p) => p.id.toLowerCase() === projectId.toLowerCase()
550
- );
551
- if (foundProject) {
552
- log.raw("");
553
- await this.HandleFormattingAndOutput(foundProject, log.object);
554
- }
555
- if (projectsErr) {
556
- log.error(messages.projects.noList());
557
- log.error(projectsErr.message);
558
- }
559
- }
560
- };
561
- SetProject = (projectId = "website") => {
562
- var _a;
563
- const { env, log, messages, session } = this;
564
- let nextProjectId;
565
- if ((env == null ? void 0 : env.projects.length) > 0 && (env == null ? void 0 : env.lastUserId)) {
566
- nextProjectId = (_a = env.projects.find(
567
- (p) => p.id.toLowerCase() === projectId.toLowerCase()
568
- )) == null ? void 0 : _a.id;
569
- if (nextProjectId) {
570
- env.currentProject = nextProjectId;
571
- session.UpdateEnv(env);
572
- log.success(messages.projects.set(projectId));
573
- log.raw("");
574
- } else {
575
- log.error(messages.projects.failedSet(projectId));
576
- }
577
- } else {
578
- log.warning(messages.projects.noList());
579
- log.help(messages.connect.tip());
580
- }
581
- return nextProjectId;
582
- };
583
- SetVersion = (versionStatus) => {
584
- const { env, log, messages, session } = this;
585
- if (!["latest", "published"].includes(versionStatus)) {
586
- log.error(messages.version.invalid(versionStatus));
587
- return false;
588
- }
589
- if (!env) {
590
- log.help(messages.version.noEnv());
591
- return false;
592
- }
593
- if ((env == null ? void 0 : env.projects.length) > 0 && (env == null ? void 0 : env.lastUserId)) {
594
- session.UpdateEnv({ versionStatus });
595
- log.success(messages.version.set(this.currentEnv, versionStatus));
596
- return true;
597
- } else {
598
- log.warning(messages.projects.noList());
599
- log.help(messages.connect.tip());
600
- return false;
601
- }
602
- };
603
- PrintApiKeys = async () => {
604
- const { currentEnv, log, messages } = this;
605
- const contensis = await this.ConnectContensis();
606
- if (contensis) {
607
- const [keysErr, apiKeys] = await contensis.apiKeys.GetKeys();
608
- if (Array.isArray(apiKeys)) {
609
- log.success(messages.keys.list(currentEnv));
610
- await this.HandleFormattingAndOutput(apiKeys, () => {
611
- for (const {
612
- id,
613
- sharedSecret,
614
- name,
615
- description,
616
- dateModified,
617
- modifiedBy
618
- } of apiKeys) {
619
- console.log(
620
- ` - ${name}${description ? ` (${description})` : ""} [${dateModified.toString().substring(0, 10)} ${modifiedBy}]`
621
- );
622
- console.log(` ${id}`);
623
- console.log(` ${sharedSecret}`);
624
- }
625
- });
626
- }
627
- if (keysErr) {
628
- log.error(messages.keys.noList(currentEnv));
629
- log.error((0, import_json.jsonFormatter)(keysErr));
630
- }
631
- }
632
- };
633
- CreateApiKey = async (name, description = "") => {
634
- const { currentEnv, log, messages } = this;
635
- const contensis = await this.ConnectContensis();
636
- if (contensis) {
637
- const [err, key] = await contensis.apiKeys.CreateKey(name, description);
638
- if (key) {
639
- log.success(messages.keys.created(currentEnv, name));
640
- console.log(
641
- ` - ${import_chalk.default.bold(key.name)} [${key.dateModified.toString().substring(0, 10)} ${key.modifiedBy}]`
642
- );
643
- if (key.description)
644
- console.log(` ${log.infoText(key.description)}`);
645
- console.log(` ${import_chalk.default.bold.grey`id`}: ${key.id}`);
646
- console.log(
647
- ` ${import_chalk.default.bold.grey`sharedSecret`}: ${key.sharedSecret}`
648
- );
649
- console.log("");
650
- log.help(messages.keys.tip());
651
- }
652
- if (err) {
653
- log.error(messages.keys.failedCreate(currentEnv, name), err);
654
- }
655
- }
656
- };
657
- RemoveApiKey = async (id) => {
658
- const { currentEnv, log, messages } = this;
659
- const contensis = await this.ConnectContensis({ commit: true });
660
- if (contensis) {
661
- const [err] = await contensis.apiKeys.RemoveKey(id);
662
- if (!err) {
663
- log.success(messages.keys.removed(currentEnv, id));
664
- console.log("");
665
- } else {
666
- log.error(messages.keys.failedRemove(currentEnv, id), err);
667
- }
668
- }
669
- };
670
- PrintRoles = async () => {
671
- const { currentEnv, log, messages } = this;
672
- const contensis = await this.ConnectContensis();
673
- if (contensis) {
674
- const [rolesErr, roles] = await (0, import_await_to_js.default)(contensis.roles.GetRoles());
675
- if (Array.isArray(roles)) {
676
- log.success(messages.roles.list(currentEnv));
677
- if (!roles.length) log.help(messages.roles.noneExist());
678
- await this.HandleFormattingAndOutput(roles, () => {
679
- var _a, _b, _c, _d, _e;
680
- for (const {
681
- id,
682
- name,
683
- description,
684
- enabled,
685
- assignments,
686
- permissions
687
- } of roles) {
688
- const color = enabled ? (s) => s : log.infoText;
689
- console.log(color(` - ${import_chalk.default.bold(name)} ${log.infoText(id)}`));
690
- if (description) console.log(log.infoText(` ${description}`));
691
- if (enabled === false)
692
- console.log(` ${import_chalk.default.bold.grey("enabled")}: false`);
693
- if ((_a = assignments.groups) == null ? void 0 : _a.length)
694
- console.log(
695
- ` ${import_chalk.default.bold.grey("groups")}: ${assignments.groups.join(
696
- ", "
697
- )}`
698
- );
699
- if ((_b = assignments.users) == null ? void 0 : _b.length)
700
- console.log(
701
- ` ${import_chalk.default.bold.grey("users")}: ${assignments.users.join(
702
- ", "
703
- )}`
704
- );
705
- if ((_c = assignments.apiKeys) == null ? void 0 : _c.length)
706
- console.log(
707
- ` ${import_chalk.default.bold.grey("keys")}: ${assignments.apiKeys.join(
708
- ", "
709
- )}`
710
- );
711
- if ((_d = permissions.entries) == null ? void 0 : _d.length) {
712
- console.log(` ${import_chalk.default.bold.grey("entries")}:`);
713
- for (const p of permissions.entries)
714
- console.log(
715
- ` ${p.id}: ${log.infoText(
716
- p.actions.length > 2 ? p.actions.length : p.actions.join(", ")
717
- )}`
718
- );
719
- }
720
- if ((_e = permissions.contentTypes) == null ? void 0 : _e.length)
721
- console.log(
722
- ` ${import_chalk.default.bold.grey(
723
- "contentTypes"
724
- )}: ${permissions.contentTypes.map(
725
- (p) => {
726
- var _a2, _b2;
727
- return `${p.id} [${(_a2 = p.actions) == null ? void 0 : _a2.join(",")}] ${((_b2 = p.languages) == null ? void 0 : _b2.join(" ")) || ""}`;
728
- }
729
- ).join(", ")}`
730
- );
731
- }
732
- });
733
- }
734
- if (rolesErr) {
735
- log.error(messages.roles.noList(currentEnv));
736
- log.error((0, import_json.jsonFormatter)(rolesErr));
737
- }
738
- }
739
- };
740
- PrintRole = async (roleNameOrId) => {
741
- const { currentEnv, log, messages } = this;
742
- const contensis = await this.ConnectContensis();
743
- if (contensis) {
744
- const [rolesErr, roles] = await (0, import_await_to_js.default)(contensis.roles.GetRoles());
745
- if (Array.isArray(roles)) {
746
- log.success(messages.roles.list(currentEnv));
747
- const role = (0, import_find.findByIdOrName)(roles, roleNameOrId);
748
- if (role) await this.HandleFormattingAndOutput(role, log.object);
749
- else log.error(messages.roles.failedGet(currentEnv, roleNameOrId));
750
- }
751
- if (rolesErr) {
752
- log.error(messages.roles.noList(currentEnv));
753
- log.error((0, import_json.jsonFormatter)(rolesErr));
754
- }
755
- }
756
- };
757
- CreateRole = async (role) => {
758
- const { currentEnv, log, messages } = this;
759
- const contensis = await this.ConnectContensis();
760
- if (contensis) {
761
- const [err, created] = await contensis.roles.CreateRole(role);
762
- if (created) {
763
- log.success(
764
- messages.roles.created(currentEnv, role.id || role.name || "")
765
- );
766
- await this.HandleFormattingAndOutput(created, log.object);
767
- log.help(messages.roles.tip());
768
- return role.id;
769
- }
770
- if (err) {
771
- log.error(
772
- messages.roles.failedCreate(currentEnv, role.id || role.name || ""),
773
- err
774
- );
775
- }
776
- }
777
- };
778
- UpdateRole = async (roleNameOrId, role) => {
779
- const { currentEnv, log, messages } = this;
780
- const contensis = await this.ConnectContensis();
781
- if (contensis) {
782
- const [rolesErr, roles] = await (0, import_await_to_js.default)(contensis.roles.GetRoles());
783
- if (Array.isArray(roles)) {
784
- log.success(messages.roles.list(currentEnv));
785
- const existingRole = (0, import_find.findByIdOrName)(roles, roleNameOrId, true);
786
- if (existingRole) {
787
- log.info(messages.roles.setPayload());
788
- log.object(role);
789
- log.raw(``);
790
- const [updateErr, updated] = await contensis.roles.UpdateRole(
791
- existingRole.id,
792
- role
793
- );
794
- if (updateErr)
795
- log.error(messages.roles.failedSet(currentEnv, roleNameOrId));
796
- else {
797
- log.success(messages.roles.set());
798
- await this.HandleFormattingAndOutput(updated, log.object);
799
- }
800
- } else {
801
- log.error(messages.roles.failedGet(currentEnv, roleNameOrId));
802
- }
803
- }
804
- if (rolesErr) {
805
- log.error(messages.roles.noList(currentEnv));
806
- log.error((0, import_json.jsonFormatter)(rolesErr));
807
- }
808
- }
809
- };
810
- RemoveRole = async (roleNameOrId) => {
811
- const { currentEnv, log, messages } = this;
812
- const contensis = await this.ConnectContensis();
813
- if (contensis) {
814
- log.line();
815
- if (contensis.isPreview) {
816
- log.success(messages.migrate.preview());
817
- } else {
818
- log.warning(messages.migrate.commit());
819
- }
820
- const [rolesErr, roles] = await (0, import_await_to_js.default)(contensis.roles.GetRoles());
821
- if (Array.isArray(roles)) {
822
- log.success(messages.roles.list(currentEnv));
823
- const existingRole = (0, import_find.findByIdOrName)(roles, roleNameOrId, true);
824
- if (existingRole) {
825
- const [deleteErr] = await contensis.roles.RemoveRole(existingRole.id);
826
- if (deleteErr)
827
- log.error(messages.roles.failedRemove(currentEnv, roleNameOrId));
828
- else log.success(messages.roles.removed(currentEnv, roleNameOrId));
829
- } else {
830
- log.error(messages.roles.failedGet(currentEnv, roleNameOrId));
831
- }
832
- }
833
- if (rolesErr) {
834
- log.error(messages.roles.noList(currentEnv));
835
- log.error((0, import_json.jsonFormatter)(rolesErr));
836
- }
837
- }
838
- };
839
- PrintTagGroup = async (groupId) => {
840
- const { currentEnv, log, messages } = this;
841
- const contensis = await this.ConnectContensis();
842
- if (contensis) {
843
- const [groupsErr, groups] = await contensis.tags.GetTagGroups({
844
- id: groupId
845
- });
846
- if (Array.isArray(groups)) {
847
- log.success(messages.taggroups.list(currentEnv, groups.length));
848
- if (groups.length)
849
- await this.HandleFormattingAndOutput(groups[0], () => {
850
- log.raw("");
851
- log.object(groups[0]);
852
- });
853
- else log.error(messages.taggroups.failedGet(currentEnv, groupId));
854
- }
855
- if (groupsErr)
856
- log.error(messages.taggroups.noList(currentEnv), groupsErr);
857
- }
858
- };
859
- PrintTagGroups = async (query) => {
860
- const { currentEnv, log, messages } = this;
861
- const contensis = await this.ConnectContensis();
862
- if (contensis) {
863
- const [groupsErr, groups] = await contensis.tags.GetTagGroups({
864
- q: query
865
- });
866
- if (Array.isArray(groups)) {
867
- log.success(messages.taggroups.list(currentEnv, groups.length));
868
- if (!groups.length) log.help(messages.taggroups.noneExist());
869
- await this.HandleFormattingAndOutput(groups, () => {
870
- for (const { version, ...group } of groups) {
871
- log.raw("");
872
- log.object(group);
873
- }
874
- });
875
- }
876
- if (groupsErr)
877
- log.error(messages.taggroups.noList(currentEnv), groupsErr);
878
- }
879
- };
880
- ImportTagGroups = async ({
881
- commit,
882
- fromFile,
883
- getBy,
884
- data,
885
- tags,
886
- save
887
- }) => {
888
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
889
- const { currentEnv, currentProject, log, messages } = this;
890
- let importData;
891
- if (tags) {
892
- importData = new import_MixedFileData.MixedFileData();
893
- importData.tags = tags;
894
- importData.tagGroups = data || [];
895
- }
896
- const contensis = await this.ConnectContensisImport({
897
- commit,
898
- fromFile,
899
- importData
900
- });
901
- if (contensis) {
902
- log.line();
903
- if (contensis.isPreview) {
904
- log.success(messages.migrate.preview());
905
- } else {
906
- log.warning(messages.migrate.commit());
907
- }
908
- const method = (tags == null ? void 0 : tags.length) ? contensis.tags.MigrateTags : contensis.tags.MigrateTagGroups;
909
- const [err, result] = await (0, import_await_to_js.default)(method(getBy));
910
- if (err) (0, import_logger.logError)(err);
911
- else {
912
- const { tags: tags2 } = contensis.content.targets[currentProject];
913
- await this.HandleFormattingAndOutput(
914
- save ? [
915
- ...tags2.migrateGroups.map((g) => g.toJSON()),
916
- ...tags2.migrateTags.map((t) => t.toJSON())
917
- ] : result,
918
- () => {
919
- }
920
- );
921
- }
922
- const tagsToMigrate = ((_b = (_a = result == null ? void 0 : result.tagsToMigrate) == null ? void 0 : _a[currentProject]) == null ? void 0 : _b.totalCount) || 0;
923
- const groupsToMigrate = ((_d = (_c = result == null ? void 0 : result.groupsToMigrate) == null ? void 0 : _c[currentProject]) == null ? void 0 : _d.totalCount) || 0;
924
- const tagsCommitted = (((_e = result == null ? void 0 : result.tagsResult) == null ? void 0 : _e.created) || 0) + (((_f = result == null ? void 0 : result.tagsResult) == null ? void 0 : _f.updated) || 0);
925
- const groupsCommitted = (((_g = result == null ? void 0 : result.groupsResult) == null ? void 0 : _g.created) || 0) + (((_h = result == null ? void 0 : result.groupsResult) == null ? void 0 : _h.updated) || 0);
926
- if (!err && !((_i = result.errors) == null ? void 0 : _i.length) && (!commit && tagsToMigrate + groupsToMigrate || commit && tagsCommitted + groupsCommitted)) {
927
- log.success(
928
- messages.taggroups.imported(
929
- currentEnv,
930
- commit,
931
- commit ? groupsCommitted : groupsToMigrate,
932
- commit ? tagsCommitted : tagsToMigrate
933
- )
934
- );
935
- if (!commit) {
936
- log.raw(``);
937
- log.help(messages.migrate.commitTip());
938
- }
939
- } else {
940
- log.error(
941
- messages.taggroups.failedCreate(currentEnv, data == null ? void 0 : data[0].name),
942
- err
943
- );
944
- }
945
- if (tagsCommitted)
946
- log.success(messages.tags.imported(currentEnv, commit, tagsCommitted));
947
- } else {
948
- log.warning(messages.models.noList(currentProject));
949
- log.help(messages.connect.tip());
950
- }
951
- };
952
- RemoveTagGroup = async (groupId, commit = false) => {
953
- var _a;
954
- const { currentEnv, currentProject, log, messages } = this;
955
- const contensis = await this.ConnectContensisImport({
956
- commit
957
- });
958
- if (contensis) {
959
- log.line();
960
- if (contensis.isPreview) {
961
- log.success(messages.migrate.preview("DELETE"));
962
- } else {
963
- log.warning(messages.migrate.commit("DELETE"));
964
- }
965
- const result = await contensis.tags.DeleteTagGroups({ id: groupId });
966
- await this.HandleFormattingAndOutput(result, () => {
967
- var _a2;
968
- log.raw("");
969
- log.object((_a2 = result.existing[currentProject].groups) == null ? void 0 : _a2[0]);
970
- });
971
- if ((_a = result.errors) == null ? void 0 : _a.length) {
972
- log.error(
973
- messages.taggroups.failedRemove(currentEnv, groupId),
974
- result.errors[0]
975
- );
976
- } else {
977
- log.success(
978
- messages.taggroups.removed(currentEnv, groupId, !contensis.isPreview)
979
- );
980
- if (!commit) {
981
- log.raw(``);
982
- log.help(messages.migrate.commitTip());
983
- }
984
- }
985
- }
986
- };
987
- PrintTag = async (getBy, withDependents = false) => {
988
- const { currentEnv, log, messages } = this;
989
- const contensis = await this.ConnectContensis();
990
- if (contensis) {
991
- const [tagsErr, result] = await contensis.tags.GetTags(getBy, {
992
- withDependents
993
- });
994
- if (Array.isArray(result)) {
995
- const { tags, tagGroups } = new import_MixedFileData.MixedFileData(result);
996
- log.success(messages.tags.list(currentEnv, tags.length));
997
- if (tags)
998
- await this.HandleFormattingAndOutput(result, () => {
999
- for (const tag of tags) {
1000
- log.raw("");
1001
- log.object(tag);
1002
- }
1003
- if (tagGroups.length) {
1004
- log.raw("");
1005
- log.success(
1006
- messages.taggroups.list(currentEnv, tagGroups.length)
1007
- );
1008
- for (const group of tagGroups) {
1009
- log.raw("");
1010
- log.object(group);
1011
- }
1012
- }
1013
- });
1014
- else log.error(messages.tags.failedGet(currentEnv));
1015
- }
1016
- if (tagsErr) log.error(messages.tags.noList(currentEnv), tagsErr);
1017
- }
1018
- };
1019
- PrintTags = async (getBy, withDependents = false) => {
1020
- const { currentEnv, log, messages } = this;
1021
- const contensis = await this.ConnectContensis();
1022
- if (contensis) {
1023
- const [tagsErr, result] = await contensis.tags.GetTags(getBy, {
1024
- withDependents
1025
- });
1026
- if (Array.isArray(result)) {
1027
- const { tags, tagGroups } = new import_MixedFileData.MixedFileData(result);
1028
- log.success(messages.tags.list(currentEnv, tags.length));
1029
- if (!tags.length) log.help(messages.tags.noneExist());
1030
- await this.HandleFormattingAndOutput(result, () => {
1031
- for (const { version, ...tag } of tags) {
1032
- log.raw("");
1033
- log.object(tag);
1034
- }
1035
- if (tagGroups.length) {
1036
- log.raw("");
1037
- log.success(messages.taggroups.list(currentEnv, tagGroups.length));
1038
- for (const { version, ...group } of tagGroups) {
1039
- log.raw("");
1040
- log.object(group);
1041
- }
1042
- }
1043
- });
1044
- }
1045
- if (tagsErr) log.error(messages.tags.noList(currentEnv), tagsErr);
1046
- }
1047
- };
1048
- ImportTags = async ({
1049
- commit,
1050
- fromFile,
1051
- getBy,
1052
- data,
1053
- save
1054
- }) => {
1055
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1056
- const { currentEnv, currentProject, log, messages } = this;
1057
- let importData;
1058
- if (data) {
1059
- importData = new import_MixedFileData.MixedFileData();
1060
- importData.tags = data;
1061
- importData.tagGroups = [...new Set(data.map((t) => t.groupId))].map(
1062
- (id) => ({
1063
- id
1064
- })
1065
- );
1066
- }
1067
- const contensis = await this.ConnectContensisImport({
1068
- commit,
1069
- fromFile,
1070
- importData
1071
- });
1072
- if (contensis) {
1073
- log.line();
1074
- if (contensis.isPreview) {
1075
- log.success(messages.migrate.preview());
1076
- } else {
1077
- log.warning(messages.migrate.commit());
1078
- }
1079
- contensis.payload.tags = data;
1080
- const [err, result] = await (0, import_await_to_js.default)(contensis.tags.MigrateTags(getBy));
1081
- if (err) (0, import_logger.logError)(err);
1082
- else {
1083
- const { tags } = contensis.content.targets[currentProject];
1084
- await this.HandleFormattingAndOutput(
1085
- save ? [
1086
- ...tags.migrateGroups.map((g) => g.toJSON()),
1087
- ...tags.migrateTags.map((t) => t.toJSON())
1088
- ] : result,
1089
- () => {
1090
- }
1091
- );
1092
- }
1093
- if (!err && !((_a = result.errors) == null ? void 0 : _a.length) && (!commit && result.tagsToMigrate[currentProject].totalCount || commit && (((_b = result.tagsResult) == null ? void 0 : _b.created) || ((_c = result.tagsResult) == null ? void 0 : _c.updated)))) {
1094
- log.success(
1095
- messages.tags.imported(
1096
- currentEnv,
1097
- commit,
1098
- commit ? (((_d = result.tagsResult) == null ? void 0 : _d.created) || 0) + (((_e = result.tagsResult) == null ? void 0 : _e.updated) || 0) : result.tagsToMigrate[currentProject].totalCount
1099
- )
1100
- );
1101
- if (!commit) {
1102
- log.raw(``);
1103
- log.help(messages.migrate.commitTip());
1104
- }
1105
- } else {
1106
- const noChanges = ((_g = (_f = result == null ? void 0 : result.tagsToMigrate) == null ? void 0 : _f[currentProject]) == null ? void 0 : _g["no change"]) && ((_h = result == null ? void 0 : result.tagsToMigrate) == null ? void 0 : _h[currentProject].totalCount) === 0 && ((_i = result == null ? void 0 : result.groupsToMigrate) == null ? void 0 : _i[currentProject].totalCount) === 0;
1107
- if (noChanges && !err && !((_j = result.errors) == null ? void 0 : _j.length)) {
1108
- log.help(messages.tags.noChange(currentEnv));
1109
- } else {
1110
- log.error(
1111
- messages.tags.failedCreate(
1112
- currentEnv,
1113
- (data == null ? void 0 : data.length) === 1 ? data == null ? void 0 : data[0].label["en-GB"] : void 0
1114
- ),
1115
- err
1116
- );
1117
- }
1118
- }
1119
- } else {
1120
- log.warning(messages.models.noList(currentProject));
1121
- log.help(messages.connect.tip());
1122
- }
1123
- };
1124
- RemoveTags = async (getBy, commit = false) => {
1125
- var _a, _b;
1126
- const { currentEnv, currentProject, log, messages } = this;
1127
- this.contensisOpts.concurrency = 1;
1128
- const contensis = await this.ConnectContensisImport({
1129
- commit,
1130
- noSource: true
1131
- });
1132
- if (contensis) {
1133
- log.line();
1134
- if (contensis.isPreview) {
1135
- log.success(messages.migrate.preview("DELETE"));
1136
- } else {
1137
- log.warning(messages.migrate.commit("DELETE"));
1138
- }
1139
- const result = await contensis.tags.DeleteTags(getBy);
1140
- const deleted = (commit ? (_a = result.tagsResult) == null ? void 0 : _a.deleted : result.tagsToMigrate[currentProject].delete) || 0;
1141
- await this.HandleFormattingAndOutput(result, () => {
1142
- const tags = result.existing[currentProject].tags;
1143
- for (const { version, ...tag } of tags || []) {
1144
- const { status, error } = result.tagsToMigrate.tagIds[tag.groupId][tag.id][currentProject];
1145
- log.raw("");
1146
- log.object({
1147
- ...tag,
1148
- status,
1149
- error
1150
- });
1151
- }
1152
- });
1153
- if ((_b = result.errors) == null ? void 0 : _b.length) {
1154
- log.error(
1155
- messages.tags.failedRemove(currentEnv, result.errors.length),
1156
- result.errors
1157
- );
1158
- } else {
1159
- log.success(
1160
- messages.tags.removed(currentEnv, deleted, !contensis.isPreview)
1161
- );
1162
- if (!commit && deleted) {
1163
- log.raw(``);
1164
- log.help(messages.migrate.commitTip());
1165
- }
1166
- }
1167
- }
1168
- };
1169
- PrintWorkflows = async () => {
1170
- const { currentEnv, log, messages } = this;
1171
- const contensis = await this.ConnectContensis();
1172
- if (contensis) {
1173
- const [workflowsErr, workflows] = await contensis.content.source.workflows.GetWorkflows();
1174
- if (Array.isArray(workflows)) {
1175
- log.success(messages.workflows.list(currentEnv));
1176
- if (!workflows.length) log.help(messages.workflows.noneExist());
1177
- const stringFromLanguageObject = (o) => {
1178
- var _a;
1179
- return (_a = Object.values(o || {})) == null ? void 0 : _a[0];
1180
- };
1181
- await this.HandleFormattingAndOutput(workflows, () => {
1182
- for (const {
1183
- id,
1184
- name,
1185
- description,
1186
- states,
1187
- eventGroups,
1188
- isSystem
1189
- } of workflows) {
1190
- const color = isSystem ? (s) => s : log.infoText;
1191
- console.log(
1192
- color(
1193
- ` - ${import_chalk.default.bold(
1194
- stringFromLanguageObject(name)
1195
- )} ${log.infoText(id)}`
1196
- )
1197
- );
1198
- if (description)
1199
- console.log(
1200
- log.infoText(` ${stringFromLanguageObject(description)}`)
1201
- );
1202
- if (isSystem === false)
1203
- console.log(` ${import_chalk.default.bold.grey("isSystem")}: false`);
1204
- if (states == null ? void 0 : states.length)
1205
- console.log(
1206
- ` ${import_chalk.default.bold.grey("states")}: ${states.map((state) => state.id).join(", ")}`
1207
- );
1208
- if (eventGroups == null ? void 0 : eventGroups.length)
1209
- console.log(
1210
- ` ${import_chalk.default.bold.grey("eventGroups")}: ${eventGroups.map((evtGrp) => evtGrp.id).join(", ")}`
1211
- );
1212
- }
1213
- });
1214
- }
1215
- if (workflowsErr) {
1216
- log.error(messages.workflows.noList(currentEnv));
1217
- log.error((0, import_json.jsonFormatter)(workflowsErr));
1218
- }
1219
- }
1220
- };
1221
- PrintWorkflow = async (workflowNameOrId) => {
1222
- const { currentEnv, log, messages } = this;
1223
- const contensis = await this.ConnectContensis();
1224
- if (contensis) {
1225
- const [workflowsErr, workflows] = await contensis.content.source.workflows.GetWorkflows();
1226
- if (Array.isArray(workflows)) {
1227
- log.success(messages.workflows.list(currentEnv));
1228
- const workflow = (0, import_find.findByIdOrName)(workflows, workflowNameOrId);
1229
- if (workflow)
1230
- await this.HandleFormattingAndOutput(workflow, log.object);
1231
- else
1232
- log.error(messages.workflows.failedGet(currentEnv, workflowNameOrId));
1233
- }
1234
- if (workflowsErr) {
1235
- log.error(messages.workflows.noList(currentEnv));
1236
- log.error((0, import_json.jsonFormatter)(workflowsErr));
1237
- }
1238
- }
1239
- };
1240
- CreateProject = async (project) => {
1241
- const { currentEnv, log, messages } = this;
1242
- const contensis = await this.ConnectContensis();
1243
- if (contensis) {
1244
- const [err, created] = await contensis.projects.CreateProject(project);
1245
- if (created) {
1246
- log.success(messages.projects.created(currentEnv, project.id));
1247
- await this.HandleFormattingAndOutput(created, () => {
1248
- this.SetProject(project.id);
1249
- this.PrintProjects();
1250
- });
1251
- return project.id;
1252
- }
1253
- if (err) {
1254
- log.error(messages.projects.failedCreate(currentEnv, project.id), err);
1255
- }
1256
- }
1257
- };
1258
- UpdateProject = async (project) => {
1259
- const { currentEnv, currentProject, log, messages } = this;
1260
- const contensis = await this.ConnectContensis();
1261
- if (contensis) {
1262
- const [err, updated] = await contensis.projects.UpdateProject({
1263
- id: currentProject,
1264
- ...project
1265
- });
1266
- if (updated) {
1267
- log.success(messages.projects.updated(currentEnv, currentProject));
1268
- await this.HandleFormattingAndOutput(updated, log.object);
1269
- return updated.id;
1270
- }
1271
- if (err) {
1272
- log.error(
1273
- messages.projects.failedUpdate(currentEnv, currentProject),
1274
- err
1275
- );
1276
- }
1277
- }
1278
- };
1279
- PrintContentModels = async (modelIds = [], opts) => {
1280
- const { currentProject, log, messages } = this;
1281
- const contensis = await this.ConnectContensis();
1282
- if (contensis) {
1283
- const models = await contensis.models.contentModels();
1284
- const contentTypes = await contensis.models.contentTypes();
1285
- const components = await contensis.models.components();
1286
- const tagGroups = await contensis.models.tagGroups();
1287
- const returnModels = (modelIds == null ? void 0 : modelIds.length) ? models == null ? void 0 : models.filter(
1288
- (m) => modelIds.some((id) => id.toLowerCase() === m.id.toLowerCase())
1289
- ) : void 0;
1290
- const exportResources = [];
1291
- if (opts.export) {
1292
- const contentTypeIds = Array.from(
1293
- /* @__PURE__ */ new Set([
1294
- ...(returnModels || models || []).map((m) => m.id),
1295
- ...(returnModels || models || []).map((m) => {
1296
- var _a, _b;
1297
- return ((_b = (_a = m.dependencies) == null ? void 0 : _a.contentTypes) == null ? void 0 : _b.map((c) => c[0])) || [];
1298
- }).flat()
1299
- ])
1300
- );
1301
- const componentIds = Array.from(
1302
- new Set(
1303
- (returnModels || models || []).map((m) => {
1304
- var _a, _b;
1305
- return ((_b = (_a = m.dependencies) == null ? void 0 : _a.components) == null ? void 0 : _b.map((c) => c[0])) || [];
1306
- }).flat()
1307
- )
1308
- );
1309
- const tagGroupIds = Array.from(
1310
- new Set(
1311
- (returnModels || models || []).map((m) => {
1312
- var _a, _b;
1313
- return ((_b = (_a = m.dependencies) == null ? void 0 : _a.tagGroups) == null ? void 0 : _b.map((g) => g[0])) || [];
1314
- }).flat()
1315
- )
1316
- );
1317
- exportResources.push(
1318
- ...contentTypes.filter(
1319
- (c) => contentTypeIds.map((i) => i.toLowerCase()).includes(c.id.toLowerCase())
1320
- ),
1321
- ...components.filter(
1322
- (c) => componentIds.map((i) => i.toLowerCase()).includes(c.id.toLowerCase())
1323
- ),
1324
- ...tagGroups.filter(
1325
- (g) => tagGroupIds.map((i) => i.toLowerCase()).includes(g.id.toLowerCase())
1326
- )
1327
- );
1328
- }
1329
- if (Array.isArray(returnModels)) {
1330
- log.success(messages.models.list(currentProject));
1331
- await this.HandleFormattingAndOutput(
1332
- opts.export ? exportResources : returnModels,
1333
- () => {
1334
- var _a, _b;
1335
- for (const model of returnModels) {
1336
- const draft = (0, import_rfdc.default)()(model);
1337
- if (!opts.requiredBy) {
1338
- delete draft.dependencyOf;
1339
- if ((_a = draft.dependencies) == null ? void 0 : _a.contentTypes)
1340
- draft.dependencies.contentTypes.forEach((id) => id.pop());
1341
- if ((_b = draft.dependencies) == null ? void 0 : _b.components)
1342
- draft.dependencies.components.forEach((id) => id.pop());
1343
- }
1344
- log.raw("");
1345
- log.object(draft);
1346
- }
1347
- log.raw("");
1348
- }
1349
- );
1350
- } else {
1351
- log.success(
1352
- messages.models.get(currentProject, (models == null ? void 0 : models.length.toString()) || "0")
1353
- );
1354
- log.raw("");
1355
- if (models == null ? void 0 : models.length) {
1356
- await this.HandleFormattingAndOutput(
1357
- opts.export ? exportResources : models,
1358
- () => {
1359
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
1360
- for (const model of models) {
1361
- const components2 = ((_a = model.components) == null ? void 0 : _a.length) || 0;
1362
- const contentTypes2 = ((_b = model.contentTypes) == null ? void 0 : _b.length) || 0;
1363
- const tagGroups2 = ((_c = model.tagGroups) == null ? void 0 : _c.length) || 0;
1364
- const defaults = (((_d = model.defaults) == null ? void 0 : _d.length) || 0) + (((_e = model.nodes) == null ? void 0 : _e.length) || 0);
1365
- const dependencies = (((_g = (_f = model.dependencies) == null ? void 0 : _f.components) == null ? void 0 : _g.length) || 0) + (((_i = (_h = model.dependencies) == null ? void 0 : _h.contentTypes) == null ? void 0 : _i.length) || 0) + (((_k = (_j = model.dependencies) == null ? void 0 : _j.tagGroups) == null ? void 0 : _k.length) || 0);
1366
- const dependencyOf = (((_m = (_l = model.dependencyOf) == null ? void 0 : _l.components) == null ? void 0 : _m.length) || 0) + (((_o = (_n = model.dependencyOf) == null ? void 0 : _n.contentTypes) == null ? void 0 : _o.length) || 0);
1367
- const hasAny = components2 + contentTypes2 + tagGroups2 + dependencies + dependencyOf;
1368
- log.raw(
1369
- ` - ${log.highlightText(log.boldText(model.id))} ${hasAny ? log.infoText(
1370
- `{ ${components2 ? `components: ${components2}, ` : ""}${contentTypes2 ? `contentTypes: ${contentTypes2}, ` : ""}${tagGroups2 ? `tagGroups: ${tagGroups2}, ` : ""}${defaults ? `defaults: ${defaults}, ` : ""}${dependencies ? `references: ${dependencies}, ` : ""}${dependencyOf ? `required by: ${dependencyOf}` : ""} }`
1371
- ) : ""}`
1372
- );
1373
- }
1374
- log.raw("");
1375
- }
1376
- );
1377
- }
1378
- }
1379
- }
1380
- };
1381
- ImportContentModels = async ({
1382
- commit,
1383
- fromFile
1384
- }) => {
1385
- const { currentProject, log, messages } = this;
1386
- const contensis = await this.ConnectContensisImport({
1387
- commit,
1388
- fromFile
1389
- });
1390
- if (contensis) {
1391
- log.line();
1392
- if (contensis.isPreview) {
1393
- log.success(messages.migrate.preview());
1394
- } else {
1395
- log.warning(messages.migrate.commit());
1396
- }
1397
- const [migrateErr, result] = await contensis.MigrateContentModels();
1398
- if (migrateErr) (0, import_logger.logError)(migrateErr);
1399
- else
1400
- await this.HandleFormattingAndOutput(result, () => {
1401
- if (!result.committed) {
1402
- log.raw(log.boldText(`
1403
- Content types:`));
1404
- if (!result.contentTypes) log.info(`- None returned
1405
- `);
1406
- else (0, import_console.printModelMigrationAnalysis)(this, result.contentTypes);
1407
- log.raw(log.boldText(`
1408
- Components:`));
1409
- if (!result.components) log.info(`- None returned
1410
- `);
1411
- else (0, import_console.printModelMigrationAnalysis)(this, result.components);
1412
- if (result.tagGroups && Object.keys(result.tagGroups).length) {
1413
- log.raw(log.boldText(`
1414
- Tag Groups:`));
1415
- (0, import_console.printModelMigrationAnalysis)(this, result.tagGroups);
1416
- }
1417
- if (result.defaults && Object.keys(result.defaults).length) {
1418
- log.raw(log.boldText(`
1419
- Defaults:`));
1420
- (0, import_console.printModelMigrationAnalysis)(this, result.defaults);
1421
- }
1422
- if (result.nodes && Object.keys(result.nodes).length) {
1423
- log.raw(log.boldText(`
1424
- Nodes:`));
1425
- (0, import_console.printModelMigrationAnalysis)(this, result.nodes);
1426
- }
1427
- if (result.errors) {
1428
- log.raw(log.boldText(`
1429
- Errors:`));
1430
- log.object(result.errors);
1431
- }
1432
- } else {
1433
- const { modelsResult = {} } = result;
1434
- log.raw(log.boldText(`
1435
- Content types:`));
1436
- (0, import_console.printModelMigrationResult)(
1437
- this,
1438
- modelsResult[currentProject].contentTypes
1439
- );
1440
- if (Object.values(modelsResult[currentProject].components).some(
1441
- (r) => r.length > 0
1442
- )) {
1443
- log.raw(log.boldText(`
1444
- Components:`));
1445
- (0, import_console.printModelMigrationResult)(
1446
- this,
1447
- modelsResult[currentProject].components
1448
- );
1449
- }
1450
- if (Object.values(modelsResult[currentProject].tagGroups || {}).some(
1451
- (r) => r.length > 0
1452
- )) {
1453
- log.raw(log.boldText(`
1454
- Tag Groups:`));
1455
- (0, import_console.printModelMigrationResult)(
1456
- this,
1457
- modelsResult[currentProject].tagGroups
1458
- );
1459
- }
1460
- if (Object.values(modelsResult[currentProject].defaults || {}).some(
1461
- (r) => r.length > 0
1462
- )) {
1463
- log.raw(log.boldText(`
1464
- Defaults:`));
1465
- (0, import_console.printModelMigrationResult)(
1466
- this,
1467
- modelsResult[currentProject].defaults
1468
- );
1469
- }
1470
- if (Object.values(modelsResult[currentProject].nodes || {}).some(
1471
- (r) => r.length > 0
1472
- )) {
1473
- log.raw(log.boldText(`
1474
- Nodes:`));
1475
- (0, import_console.printModelMigrationResult)(
1476
- this,
1477
- modelsResult[currentProject].nodes
1478
- );
1479
- }
1480
- }
1481
- });
1482
- } else {
1483
- log.warning(messages.models.noList(currentProject));
1484
- log.help(messages.connect.tip());
1485
- }
1486
- };
1487
- PrintContentTypes = async () => {
1488
- const { currentProject, log, messages } = this;
1489
- const contensis = await this.ConnectContensis();
1490
- if (contensis) {
1491
- const contentTypes = await contensis.models.contentTypes();
1492
- if (Array.isArray(contentTypes)) {
1493
- log.success(messages.contenttypes.list(currentProject));
1494
- await this.HandleFormattingAndOutput(contentTypes, () => {
1495
- var _a;
1496
- for (const contentType of contentTypes) {
1497
- const fieldsLength = ((_a = contentType.fields) == null ? void 0 : _a.length) || 0;
1498
- console.log(
1499
- ` - ${contentType.id} [${fieldsLength} field${fieldsLength !== 1 ? "s" : ""}]`
1500
- );
1501
- }
1502
- });
1503
- }
1504
- }
1505
- };
1506
- PrintContentType = async (contentTypeId) => {
1507
- const { currentProject, log, messages } = this;
1508
- const contensis = await this.ConnectContensis();
1509
- if (contensis) {
1510
- const contentTypes = await contensis.models.contentTypes();
1511
- if (Array.isArray(contentTypes)) {
1512
- const contentType = contentTypes.find(
1513
- (c) => c.id.toLowerCase() === contentTypeId.toLowerCase()
1514
- );
1515
- if (contentType) {
1516
- log.success(
1517
- messages.contenttypes.get(currentProject, contentType.id)
1518
- );
1519
- await this.HandleFormattingAndOutput(contentType, log.object);
1520
- } else {
1521
- log.error(
1522
- messages.contenttypes.failedGet(currentProject, contentTypeId)
1523
- );
1524
- }
1525
- }
1526
- }
1527
- };
1528
- RemoveContentTypes = async (contentTypeIds, commit = false) => {
1529
- const { currentProject, log, messages } = this;
1530
- const contensis = await this.ConnectContensisImport({
1531
- commit,
1532
- noSource: true
1533
- });
1534
- if (contensis) {
1535
- const [err, result] = await contensis.DeleteContentTypes(contentTypeIds);
1536
- if (err) {
1537
- log.error(
1538
- messages.contenttypes.failedRemove(
1539
- currentProject,
1540
- contentTypeIds.join(", ")
1541
- ),
1542
- err
1543
- );
1544
- } else {
1545
- log.success(
1546
- messages.contenttypes.removed(
1547
- currentProject,
1548
- contentTypeIds.join(", "),
1549
- !contensis.isPreview
1550
- )
1551
- );
1552
- await this.HandleFormattingAndOutput(result, log.object);
1553
- if (!commit) log.help(messages.migrate.commitTip());
1554
- }
1555
- }
1556
- };
1557
- ImportContentTypes = async ({
1558
- commit,
1559
- fromFile
1560
- }, contentTypeIds = []) => {
1561
- const { currentProject, log, messages } = this;
1562
- let importData;
1563
- if (fromFile) importData = await new import_MixedFileData.MixedFileData().readFile(fromFile);
1564
- const contensis = await this.ConnectContensisImport({
1565
- commit,
1566
- noSource: !!fromFile
1567
- });
1568
- if (contensis) {
1569
- if (fromFile)
1570
- for (const contentType of importData.models) {
1571
- contentType.projectId = currentProject;
1572
- delete contentType.uuid;
1573
- const [err, , createStatus] = await contensis.models.targets[currentProject].repo.UpsertContentType(false, contentType);
1574
- if (err) log.error(err.message, err);
1575
- if (createStatus) {
1576
- log.success(
1577
- messages.contenttypes.created(
1578
- currentProject,
1579
- contentType.id,
1580
- createStatus
1581
- )
1582
- );
1583
- await this.HandleFormattingAndOutput(contentType, () => {
1584
- });
1585
- }
1586
- }
1587
- else {
1588
- const result = await contensis.simpleMigration.Migrate(
1589
- contentTypeIds,
1590
- []
1591
- );
1592
- await this.HandleFormattingAndOutput(result, log.object);
1593
- }
1594
- if (!commit) log.help(messages.migrate.commitTip());
1595
- }
1596
- };
1597
- DiffModels = async ({
1598
- fromFile
1599
- }, modelIds = []) => {
1600
- const { log } = this;
1601
- let importData;
1602
- if (fromFile) importData = await new import_MixedFileData.MixedFileData().readFile(fromFile);
1603
- const contensis = await this.ConnectContensisImport({ fromFile });
1604
- if (contensis) {
1605
- const [err, result] = await (0, import_await_to_js.default)(
1606
- contensis.models.Diff(
1607
- importData.models.length ? importData.models : modelIds
1608
- )
1609
- );
1610
- if (err) log.error(err.message, err);
1611
- if (result)
1612
- await this.HandleFormattingAndOutput(result, () => {
1613
- var _a;
1614
- log.success(
1615
- `Queried models ${log.infoText(
1616
- `"${(_a = result.query.modelIds) == null ? void 0 : _a.join(", ")}"`
1617
- )}
1618
- `
1619
- );
1620
- if (result.committed === false) {
1621
- log.raw(log.boldText(`Content types:`));
1622
- if (!result.contentTypes) log.info(`- None returned
1623
- `);
1624
- else (0, import_console.printModelMigrationAnalysis)(this, result.contentTypes);
1625
- log.raw(log.boldText(`
1626
- Components:`));
1627
- if (!result.components) log.info(`- None returned
1628
- `);
1629
- else (0, import_console.printModelMigrationAnalysis)(this, result.components);
1630
- }
1631
- });
1632
- }
1633
- };
1634
- PrintComponents = async () => {
1635
- const { currentProject, log, messages } = this;
1636
- const contensis = await this.ConnectContensis();
1637
- if (contensis) {
1638
- const components = await contensis.models.components();
1639
- if (Array.isArray(components)) {
1640
- log.success(messages.components.list(currentProject));
1641
- await this.HandleFormattingAndOutput(components, () => {
1642
- var _a;
1643
- for (const component of components) {
1644
- const fieldsLength = ((_a = component.fields) == null ? void 0 : _a.length) || 0;
1645
- console.log(
1646
- ` - ${component.id} [${fieldsLength} field${fieldsLength !== 1 ? "s" : ""}]`
1647
- );
1648
- }
1649
- });
1650
- }
1651
- }
1652
- };
1653
- PrintComponent = async (componentId) => {
1654
- const { currentProject, log, messages } = this;
1655
- const contensis = await this.ConnectContensis();
1656
- if (contensis) {
1657
- const components = await contensis.models.components();
1658
- if (Array.isArray(components)) {
1659
- const component = components.find(
1660
- (c) => c.id.toLowerCase() === componentId.toLowerCase()
1661
- );
1662
- if (component) {
1663
- log.success(messages.components.get(currentProject, component.id));
1664
- await this.HandleFormattingAndOutput(component, log.object);
1665
- } else {
1666
- log.error(messages.components.failedGet(currentProject, componentId));
1667
- }
1668
- }
1669
- }
1670
- };
1671
- RemoveComponents = async (componentIds, commit = false) => {
1672
- const { currentProject, log, messages } = this;
1673
- const contensis = await this.ConnectContensisImport({
1674
- commit,
1675
- noSource: true
1676
- });
1677
- if (contensis) {
1678
- const [err, result] = await contensis.DeleteContentTypes(
1679
- void 0,
1680
- componentIds
1681
- );
1682
- if (err) {
1683
- log.error(
1684
- messages.components.failedRemove(
1685
- currentProject,
1686
- componentIds.join(", ")
1687
- ),
1688
- err
1689
- );
1690
- } else {
1691
- log.success(
1692
- messages.components.removed(
1693
- currentProject,
1694
- componentIds.join(", "),
1695
- !contensis.isPreview
1696
- )
1697
- );
1698
- await this.HandleFormattingAndOutput(result, log.object);
1699
- if (!commit) log.help(messages.migrate.commitTip());
1700
- }
1701
- }
1702
- };
1703
- ImportComponents = async ({
1704
- commit,
1705
- fromFile
1706
- }, componentIds = []) => {
1707
- const { currentProject, log, messages } = this;
1708
- let importData;
1709
- if (fromFile) importData = await new import_MixedFileData.MixedFileData().readFile(fromFile);
1710
- const contensis = await this.ConnectContensisImport({
1711
- commit,
1712
- noSource: !!fromFile
1713
- });
1714
- if (contensis) {
1715
- if (fromFile)
1716
- for (const component of importData.models) {
1717
- component.projectId = currentProject;
1718
- delete component.uuid;
1719
- const [err, , createStatus] = await contensis.models.targets[currentProject].repo.UpsertComponent(false, component);
1720
- if (err) log.error(err.message, err);
1721
- if (createStatus) {
1722
- log.success(
1723
- messages.components.created(
1724
- currentProject,
1725
- component.id,
1726
- createStatus
1727
- )
1728
- );
1729
- await this.HandleFormattingAndOutput(component, () => {
1730
- });
1731
- }
1732
- }
1733
- else {
1734
- const result = await contensis.simpleMigration.Migrate(
1735
- [],
1736
- componentIds
1737
- );
1738
- await this.HandleFormattingAndOutput(result, log.object);
1739
- }
1740
- if (!commit) log.help(messages.migrate.commitTip());
1741
- }
1742
- };
1743
- RemoveEntries = async (commit = false) => {
1744
- var _a, _b, _c;
1745
- const { currentEnv, currentProject, log, messages } = this;
1746
- this.contensisOpts.concurrency = 1;
1747
- const contensis = await this.ConnectContensisImport({
1748
- commit,
1749
- noSource: true
1750
- });
1751
- if (contensis) {
1752
- if (contensis.isPreview) {
1753
- console.log(log.successText(` -- PREVIEW -- `));
1754
- } else {
1755
- console.log(log.warningText(` *** COMMITTING DELETE *** `));
1756
- }
1757
- const [err, result] = await contensis.DeleteEntries();
1758
- if (result)
1759
- await this.HandleFormattingAndOutput(result, () => {
1760
- (0, import_console.printEntriesMigrateResult)(this, result, {
1761
- action: "delete",
1762
- showAll: true
1763
- });
1764
- });
1765
- if (!err && (!commit && result.entriesToMigrate[currentProject].totalCount || commit && ((_a = result.migrateResult) == null ? void 0 : _a.deleted))) {
1766
- log.success(messages.entries.removed(currentEnv, commit));
1767
- if (!commit) {
1768
- log.raw(``);
1769
- log.help(messages.migrate.commitTip());
1770
- }
1771
- } else {
1772
- log.error(messages.entries.failedRemove(currentEnv), err);
1773
- if (!((_c = (_b = result == null ? void 0 : result.entriesToMigrate) == null ? void 0 : _b[currentProject]) == null ? void 0 : _c.totalCount))
1774
- log.help(messages.entries.notFound(currentEnv));
1775
- }
1776
- }
1777
- };
1778
- GetEntries = async ({
1779
- withDependents = false
1780
- } = {}) => {
1781
- const { currentProject, log, messages } = this;
1782
- const contensis = await this.ConnectContensis();
1783
- if (contensis) {
1784
- log.line();
1785
- const entries = await contensis.GetEntries({ withDependents });
1786
- const nodes = contensis.content.source.nodes.raw;
1787
- const combinedOutput = [...entries, ...nodes];
1788
- await this.HandleFormattingAndOutput(combinedOutput, () => {
1789
- var _a, _b;
1790
- (0, import_migratortron.logEntitiesTable)({
1791
- entries,
1792
- projectId: currentProject,
1793
- fields: (_a = contensis.payload.query) == null ? void 0 : _a.fields
1794
- });
1795
- if (nodes.length)
1796
- (0, import_migratortron.logEntitiesTable)({
1797
- nodes,
1798
- projectId: currentProject,
1799
- fields: (_b = contensis.payload.query) == null ? void 0 : _b.fields
1800
- });
1801
- });
1802
- } else {
1803
- log.warning(messages.models.noList(currentProject));
1804
- log.help(messages.connect.tip());
1805
- }
1806
- };
1807
- ImportEntries = async ({
1808
- commit,
1809
- fromFile,
1810
- logOutput,
1811
- saveEntries,
1812
- data
1813
- }) => {
1814
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
1815
- const { currentEnv, currentProject, log, messages } = this;
1816
- let importData;
1817
- if (data) importData = new import_MixedFileData.MixedFileData(data);
1818
- const contensis = await this.ConnectContensisImport({
1819
- commit,
1820
- fromFile,
1821
- importData
1822
- });
1823
- if (contensis) {
1824
- log.line();
1825
- if (contensis.isPreview) {
1826
- log.success(messages.migrate.preview());
1827
- } else {
1828
- log.warning(messages.migrate.commit());
1829
- }
1830
- const [err, result] = await contensis.MigrateEntries();
1831
- if (err) (0, import_logger.logError)(err);
1832
- else {
1833
- const { entries, nodes, tags } = contensis.content.targets[currentProject];
1834
- const output = saveEntries ? (
1835
- // include entries and dependent nodes (or tags) when saving entries
1836
- [
1837
- ((_a = entries.migrate) == null ? void 0 : _a.map((me) => me.toJSON())) || [],
1838
- nodes.migrateNodes.map((mn) => mn.node),
1839
- tags.migrateTags.map((mt) => mt.toJSON()),
1840
- tags.migrateGroups.map((mg) => mg.toJSON())
1841
- ].flat()
1842
- ) : result;
1843
- await this.HandleFormattingAndOutput(output, () => {
1844
- (0, import_console.printEntriesMigrateResult)(this, result, {
1845
- showAll: logOutput === "all",
1846
- showDiff: logOutput === "all" || logOutput === "changes",
1847
- showChanged: logOutput === "changes"
1848
- });
1849
- if (["all", "changes"].includes(logOutput) && nodes.migrateNodes.length)
1850
- (0, import_console.printNodeTreeOutput)(
1851
- this,
1852
- {
1853
- ...nodes.rootAncestor,
1854
- status: "no change",
1855
- children: nodes.migrateNodes
1856
- },
1857
- logOutput
1858
- );
1859
- });
1860
- }
1861
- if (!err && !((_b = result.errors) == null ? void 0 : _b.length) && (!commit && result.entriesToMigrate[currentProject].totalCount || commit && (((_c = result.migrateResult) == null ? void 0 : _c.created) || ((_d = result.migrateResult) == null ? void 0 : _d.updated)))) {
1862
- log.success(
1863
- messages.entries.imported(
1864
- currentEnv,
1865
- commit,
1866
- commit ? (((_e = result.migrateResult) == null ? void 0 : _e.created) || 0) + (((_f = result.migrateResult) == null ? void 0 : _f.updated) || 0) : result.entriesToMigrate[currentProject].totalCount,
1867
- commit ? (((_g = result.nodesResult) == null ? void 0 : _g.created) || 0) + (((_h = result.nodesResult) == null ? void 0 : _h.updated) || 0) : ((_i = result.nodesToMigrate) == null ? void 0 : _i[currentProject].totalCount) || 0,
1868
- commit ? (((_j = result.tagsResult) == null ? void 0 : _j.created) || 0) + (((_k = result.tagsResult) == null ? void 0 : _k.updated) || 0) : ((_l = result.tagsToMigrate) == null ? void 0 : _l[currentProject].totalCount) || 0
1869
- )
1870
- );
1871
- if (!commit) {
1872
- log.raw(``);
1873
- log.help(messages.migrate.commitTip());
1874
- }
1875
- } else {
1876
- const noChanges = Object.values(((_m = result == null ? void 0 : result.entriesToMigrate) == null ? void 0 : _m[currentProject]) || {}).every(
1877
- (status) => typeof status === "number" || (status["no change"] || 0) > 0
1878
- ) && ((_n = result == null ? void 0 : result.entriesToMigrate) == null ? void 0 : _n[currentProject].totalCount) === 0;
1879
- if (noChanges && !err && !((_o = result == null ? void 0 : result.migrateResult) == null ? void 0 : _o.errors) && !((_p = result == null ? void 0 : result.nodesResult) == null ? void 0 : _p.errors) && !((_q = result == null ? void 0 : result.tagsResult) == null ? void 0 : _q.errors)) {
1880
- log.help(messages.entries.noChange(currentEnv));
1881
- } else {
1882
- log.error(messages.entries.failedImport(currentEnv), err);
1883
- if (!((_s = (_r = result == null ? void 0 : result.entriesToMigrate) == null ? void 0 : _r[currentProject]) == null ? void 0 : _s.totalCount))
1884
- log.help(messages.entries.notFound(currentEnv));
1885
- }
1886
- }
1887
- } else {
1888
- log.warning(messages.models.noList(currentProject));
1889
- log.help(messages.connect.tip());
1890
- }
1891
- };
1892
- CopyEntryField = async ({
1893
- commit,
1894
- fromFile,
1895
- logOutput,
1896
- saveEntries
1897
- }) => {
1898
- var _a, _b, _c, _d, _e, _f, _g, _h;
1899
- const { currentEnv, currentProject, log, messages } = this;
1900
- const contensis = await this.ConnectContensisImport({
1901
- commit,
1902
- fromFile
1903
- });
1904
- if (contensis) {
1905
- log.line();
1906
- if (contensis.isPreview) {
1907
- log.success(messages.migrate.preview());
1908
- } else {
1909
- log.warning(messages.migrate.commit());
1910
- }
1911
- const [err, result] = await (0, import_await_to_js.default)(
1912
- contensis.content.copy.MigrateFieldContent()
1913
- );
1914
- if (err) (0, import_logger.logError)(err);
1915
- if (result) {
1916
- const output = saveEntries ? (_a = contensis.content.copy.targets[currentProject].entries.migrate) == null ? void 0 : _a.map(
1917
- (me) => me.toJSON()
1918
- ) : result;
1919
- await this.HandleFormattingAndOutput(output, () => {
1920
- (0, import_console.printEntriesMigrateResult)(this, result, {
1921
- showAll: logOutput === "all",
1922
- showDiff: logOutput === "all" || logOutput === "changes",
1923
- showChanged: logOutput === "changes"
1924
- });
1925
- });
1926
- }
1927
- if (result && !err && !((_b = result.errors) == null ? void 0 : _b.length) && (!commit && result.entriesToMigrate[currentProject].totalCount || commit && (((_c = result.migrateResult) == null ? void 0 : _c.created) || ((_d = result.migrateResult) == null ? void 0 : _d.updated)))) {
1928
- log.success(
1929
- messages.entries.imported(
1930
- currentEnv,
1931
- commit,
1932
- commit ? (((_e = result.migrateResult) == null ? void 0 : _e.created) || 0) + (((_f = result.migrateResult) == null ? void 0 : _f.updated) || 0) : result.entriesToMigrate[currentProject].totalCount
1933
- )
1934
- );
1935
- if (!commit) {
1936
- log.raw(``);
1937
- log.help(messages.migrate.commitTip());
1938
- }
1939
- } else {
1940
- log.error(messages.entries.failedImport(currentEnv), err);
1941
- if (!((_h = (_g = result == null ? void 0 : result.entriesToMigrate) == null ? void 0 : _g[currentProject]) == null ? void 0 : _h.totalCount))
1942
- log.help(messages.entries.notFound(currentEnv));
1943
- }
1944
- } else {
1945
- log.warning(messages.models.noList(currentProject));
1946
- log.help(messages.connect.tip());
1947
- }
1948
- };
1949
- UpdateEntryField = async ({
1950
- commit,
1951
- fromFile,
1952
- logOutput,
1953
- saveEntries
1954
- }) => {
1955
- var _a, _b, _c, _d, _e, _f, _g, _h;
1956
- const { currentEnv, currentProject, log, messages } = this;
1957
- const contensis = await this.ConnectContensisImport({
1958
- commit,
1959
- fromFile
1960
- });
1961
- if (contensis) {
1962
- log.line();
1963
- if (contensis.isPreview) {
1964
- log.success(messages.entries.update.preview());
1965
- } else {
1966
- log.warning(messages.entries.update.commit());
1967
- }
1968
- const [err, result] = await (0, import_await_to_js.default)(
1969
- contensis.content.update.UpdateFieldContent()
1970
- );
1971
- if (err) (0, import_logger.logError)(err);
1972
- if (result) {
1973
- const output = saveEntries ? (_a = contensis.content.update.targets[currentProject].entries.migrate) == null ? void 0 : _a.map((me) => me.toJSON()) : result;
1974
- await this.HandleFormattingAndOutput(output, () => {
1975
- (0, import_console.printEntriesMigrateResult)(this, result, {
1976
- action: "update",
1977
- showAll: logOutput === "all",
1978
- showDiff: logOutput === "all" || logOutput === "changes",
1979
- showChanged: logOutput === "changes"
1980
- });
1981
- });
1982
- }
1983
- if (result && !err && !((_b = result.errors) == null ? void 0 : _b.length) && (!commit && result.entriesToMigrate[currentProject].totalCount || commit && (((_c = result.migrateResult) == null ? void 0 : _c.created) || ((_d = result.migrateResult) == null ? void 0 : _d.updated)))) {
1984
- log.success(
1985
- messages.entries.update.success(
1986
- currentEnv,
1987
- commit,
1988
- commit ? (((_e = result.migrateResult) == null ? void 0 : _e.created) || 0) + (((_f = result.migrateResult) == null ? void 0 : _f.updated) || 0) : result.entriesToMigrate[currentProject].totalCount
1989
- )
1990
- );
1991
- if (!commit) {
1992
- log.raw(``);
1993
- log.help(messages.migrate.commitTip());
1994
- }
1995
- } else {
1996
- log.error(messages.entries.update.failed(currentEnv), err);
1997
- if (!((_h = (_g = result == null ? void 0 : result.entriesToMigrate) == null ? void 0 : _g[currentProject]) == null ? void 0 : _h.totalCount))
1998
- log.help(messages.entries.notFound(currentEnv));
1999
- }
2000
- } else {
2001
- log.warning(messages.models.noList(currentProject));
2002
- log.help(messages.connect.tip());
2003
- }
2004
- };
2005
- GetNodes = async (rootPath, depth = 0) => {
2006
- const { currentProject, log, messages } = this;
2007
- const contensis = await this.ConnectContensis();
2008
- if (contensis) {
2009
- log.line();
2010
- const [err, nodes] = await (0, import_await_to_js.default)(contensis.nodes.GetNodes(rootPath, depth));
2011
- if (err) {
2012
- log.error(messages.nodes.failedGet(currentProject), err);
2013
- return;
2014
- }
2015
- const root = contensis.nodes.source.nodes.tree;
2016
- log.success(messages.nodes.get(currentProject, rootPath, depth));
2017
- await this.HandleFormattingAndOutput(nodes, () => {
2018
- log.object({ ...root, children: void 0, language: void 0 });
2019
- (0, import_console.printNodeTreeOutput)(this, root);
2020
- });
2021
- } else {
2022
- log.warning(messages.models.noList(currentProject));
2023
- log.help(messages.connect.tip());
2024
- }
2025
- };
2026
- ImportNodes = async ({
2027
- commit,
2028
- fromFile,
2029
- logOutput,
2030
- logLimit
2031
- }) => {
2032
- var _a, _b, _c, _d, _e, _f, _g;
2033
- const { currentEnv, currentProject, log, messages } = this;
2034
- const contensis = await this.ConnectContensisImport({
2035
- commit,
2036
- fromFile
2037
- });
2038
- if (contensis) {
2039
- log.line();
2040
- if (contensis.isPreview) {
2041
- log.success(messages.migrate.preview());
2042
- } else {
2043
- log.warning(messages.migrate.commit());
2044
- }
2045
- const [err, result] = await contensis.MigrateNodes();
2046
- if (err) log.raw(``);
2047
- else
2048
- await this.HandleFormattingAndOutput(result, () => {
2049
- const migrateTree = contensis.nodes.targets[currentProject].nodes.migrateNodesTreeView;
2050
- (0, import_console.printNodeTreeOutput)(this, migrateTree, logOutput, logLimit);
2051
- (0, import_console.printNodesMigrateResult)(this, result, {
2052
- showAll: logOutput === "all",
2053
- showChanged: logOutput === "changes"
2054
- });
2055
- });
2056
- const nodesMigrateCount = (_a = result == null ? void 0 : result.nodesToMigrate) == null ? void 0 : _a[currentProject].totalCount;
2057
- const nodesCreated = ((_b = result == null ? void 0 : result.nodesResult) == null ? void 0 : _b["created"]) || 0;
2058
- const nodesUpdated = ((_c = result == null ? void 0 : result.nodesResult) == null ? void 0 : _c["updated"]) || 0;
2059
- const nodesErrored = ((_d = result == null ? void 0 : result.nodesResult) == null ? void 0 : _d["errors"]) || 0;
2060
- const noChanges = ((_e = result == null ? void 0 : result.nodesToMigrate) == null ? void 0 : _e[currentProject]["no change"]) && nodesMigrateCount === 0;
2061
- if (!err && (!((_f = result.errors) == null ? void 0 : _f.length) || this.contensisOpts.ignoreErrors) && (!commit && nodesMigrateCount || commit && (nodesCreated || nodesUpdated || ((_g = result.errors) == null ? void 0 : _g.length)))) {
2062
- let totalCount;
2063
- if (commit) {
2064
- const created = typeof nodesCreated === "number" ? nodesCreated : 0;
2065
- const updated = typeof nodesUpdated === "number" ? nodesUpdated : 0;
2066
- totalCount = created + updated;
2067
- } else {
2068
- totalCount = typeof nodesMigrateCount === "number" ? nodesMigrateCount : 0;
2069
- }
2070
- log.success(messages.nodes.imported(currentEnv, commit, totalCount));
2071
- log.raw(``);
2072
- if (!commit) {
2073
- log.help(messages.nodes.commitTip());
2074
- }
2075
- } else {
2076
- if (noChanges && !err && !nodesErrored) {
2077
- log.help(messages.nodes.noChange(currentEnv));
2078
- } else {
2079
- log.error(messages.nodes.failedImport(currentEnv), err);
2080
- if (!nodesMigrateCount) log.help(messages.nodes.notFound(currentEnv));
2081
- }
2082
- }
2083
- } else {
2084
- log.warning(messages.models.noList(currentProject));
2085
- log.help(messages.connect.tip());
2086
- }
2087
- };
2088
- RemoveNodes = async (commit = false) => {
2089
- var _a, _b, _c;
2090
- const { currentEnv, currentProject, log, messages } = this;
2091
- const contensis = await this.ConnectContensisImport({
2092
- commit,
2093
- noSource: true
2094
- });
2095
- if (contensis) {
2096
- if (contensis.isPreview) {
2097
- console.log(log.successText(` -- PREVIEW -- `));
2098
- } else {
2099
- console.log(log.warningText(` *** COMMITTING DELETE *** `));
2100
- }
2101
- const [err, result] = await contensis.DeleteNodes();
2102
- if (result) {
2103
- await this.HandleFormattingAndOutput(result, () => {
2104
- (0, import_console.printNodeTreeOutput)(
2105
- this,
2106
- contensis.nodes.targets[currentProject].nodes.migrateNodesTreeView
2107
- );
2108
- });
2109
- }
2110
- if (!err && (!commit && result.nodesToMigrate[currentProject].totalCount || commit && ((_a = result.nodesResult) == null ? void 0 : _a.deleted))) {
2111
- log.success(
2112
- messages.nodes.removed(currentEnv, commit, contensis.nodes.rootPath)
2113
- );
2114
- log.raw(``);
2115
- if (!commit) {
2116
- log.help(messages.nodes.commitTip());
2117
- }
2118
- } else {
2119
- log.error(messages.nodes.failedRemove(currentEnv), err);
2120
- if (!((_c = (_b = result == null ? void 0 : result.nodesToMigrate) == null ? void 0 : _b[currentProject]) == null ? void 0 : _c.totalCount))
2121
- log.help(messages.nodes.notFound(currentEnv));
2122
- }
2123
- }
2124
- };
2125
- PrintWebhookSubscriptions = async (subscriptionIdsOrNames) => {
2126
- const { currentEnv, log, messages } = this;
2127
- const contensis = await this.ConnectContensis();
2128
- if (contensis) {
2129
- const [webhooksErr, webhooks] = await contensis.subscriptions.webhooks.GetSubscriptions();
2130
- const filteredResults = (subscriptionIdsOrNames == null ? void 0 : subscriptionIdsOrNames.length) ? webhooks == null ? void 0 : webhooks.filter(
2131
- (w) => (subscriptionIdsOrNames == null ? void 0 : subscriptionIdsOrNames.some(
2132
- (idname) => {
2133
- var _a;
2134
- return (_a = w.name) == null ? void 0 : _a.toLowerCase().includes(idname.toLowerCase());
2135
- }
2136
- )) || (subscriptionIdsOrNames == null ? void 0 : subscriptionIdsOrNames.some(
2137
- (id) => id.toLowerCase() === w.id.toLowerCase()
2138
- ))
2139
- ) : webhooks;
2140
- if (Array.isArray(filteredResults)) {
2141
- log.success(messages.webhooks.list(currentEnv));
2142
- if (!(webhooks == null ? void 0 : webhooks.length)) log.warning(messages.webhooks.noneExist());
2143
- else {
2144
- await this.HandleFormattingAndOutput(filteredResults, () => {
2145
- for (const {
2146
- id,
2147
- description,
2148
- method,
2149
- name,
2150
- version,
2151
- url: url2,
2152
- enabled,
2153
- topics,
2154
- templates,
2155
- headers
2156
- } of filteredResults) {
2157
- console.log(
2158
- log.infoText(
2159
- ` ${import_chalk.default.bold.white`- ${name}`} ${id} [${(version.modified || version.created).toString().substring(0, 10)} ${version.modifiedBy || version.createdBy}]`
2160
- )
2161
- );
2162
- if (description) console.log(log.infoText` ${description}`);
2163
- console.log(` ${log.infoText`[${method}]`} ${url2}`);
2164
- if (headers && Object.keys(headers).length) {
2165
- console.log(` ${log.infoText`headers`}:`);
2166
- for (const [key, { value, secret }] of Object.entries(headers))
2167
- console.log(
2168
- ` ${import_chalk.default.bold.gray(key)}: ${secret ? "\u{1F910}" : value}`
2169
- );
2170
- }
2171
- if (topics == null ? void 0 : topics.length)
2172
- if ((topics == null ? void 0 : topics.length) === 1)
2173
- console.log(
2174
- ` ${log.infoText`topics`}: ${topics.map((t) => JSON.stringify(t)).join(" ").replaceAll('"', "").replaceAll(",", " ").replaceAll("{", "").replaceAll("}", "")}`
2175
- );
2176
- else {
2177
- console.log(` ${log.infoText`topics`}:`);
2178
- log.objectRecurse(topics, 1, " ");
2179
- }
2180
- if (templates && Object.keys(templates).length)
2181
- console.log(
2182
- ` ${log.infoText`templates`}: ${Object.keys(
2183
- templates
2184
- ).join(" ")}`
2185
- );
2186
- if (enabled === false)
2187
- console.log(` ${log.infoText`enabled`}: ${enabled}`);
2188
- }
2189
- });
2190
- }
2191
- }
2192
- if (webhooksErr) {
2193
- log.error(messages.webhooks.noList(currentEnv));
2194
- log.error((0, import_json.jsonFormatter)(webhooksErr));
2195
- }
2196
- }
2197
- };
2198
- PrintBlocks = async () => {
2199
- const { currentEnv, env, log, messages } = this;
2200
- const contensis = await this.ConnectContensis();
2201
- if (contensis) {
2202
- const [err, blocks] = await contensis.blocks.GetBlocks();
2203
- if (Array.isArray(blocks) && blocks.length) {
2204
- await this.HandleFormattingAndOutput(blocks, () => {
2205
- log.success(messages.blocks.list(currentEnv, env.currentProject));
2206
- for (const {
2207
- id,
2208
- description,
2209
- branches,
2210
- liveVersion,
2211
- madeLive,
2212
- versionsSinceLive
2213
- } of blocks) {
2214
- console.log(
2215
- ` - ${id}${description ? ` (${description})` : ""}${madeLive ? ` [${madeLive.toString().substring(0, 10)} v${liveVersion}]` : ""}${versionsSinceLive ? log.warningText(` +${versionsSinceLive}`) : ""}`
2216
- );
2217
- for (const branch of branches)
2218
- console.log(
2219
- log.infoText(` [${branch.id}]: ${branch.status}`)
2220
- );
2221
- }
2222
- });
2223
- return blocks;
2224
- }
2225
- if (err) {
2226
- log.error(messages.blocks.noList(currentEnv, env.currentProject));
2227
- }
2228
- }
2229
- };
2230
- PrintBlockVersions = async (blockId, branch, version) => {
2231
- const { currentEnv, env, log, messages } = this;
2232
- const contensis = await this.ConnectContensis();
2233
- if (contensis) {
2234
- const [err, blocks] = await contensis.blocks.GetBlockVersions(
2235
- blockId,
2236
- branch,
2237
- version
2238
- );
2239
- if (err || (blocks == null ? void 0 : blocks.length) === 0) {
2240
- log.warning(
2241
- messages.blocks.noGet(
2242
- blockId,
2243
- branch,
2244
- version,
2245
- currentEnv,
2246
- env.currentProject
2247
- )
2248
- );
2249
- log.help(messages.blocks.noGetTip());
2250
- } else if (blocks) {
2251
- await this.HandleFormattingAndOutput(blocks, () => {
2252
- log.success(
2253
- messages.blocks.get(
2254
- blockId,
2255
- branch,
2256
- version,
2257
- currentEnv,
2258
- env.currentProject
2259
- )
2260
- );
2261
- for (const block of blocks)
2262
- (0, import_console.printBlockVersion)(
2263
- this,
2264
- block,
2265
- !version ? {
2266
- showImage: false,
2267
- showSource: true,
2268
- showStaticPaths: false,
2269
- showStatus: false
2270
- } : void 0
2271
- );
2272
- });
2273
- return blocks;
2274
- }
2275
- }
2276
- };
2277
- PushBlock = async (block) => {
2278
- const { currentEnv, env, log, messages } = this;
2279
- log.info(
2280
- messages.blocks.tryPush(
2281
- block.id,
2282
- block.source.branch,
2283
- currentEnv,
2284
- env.currentProject
2285
- )
2286
- );
2287
- console.log((0, import_json.jsonFormatter)(block));
2288
- const contensis = await this.ConnectContensis();
2289
- if (contensis) {
2290
- const [err, blockVersion] = await contensis.blocks.PushBlockVersion(block);
2291
- if (!err) {
2292
- log.success(
2293
- messages.blocks.pushed(
2294
- block.id,
2295
- block.source.branch,
2296
- currentEnv,
2297
- env.currentProject
2298
- )
2299
- );
2300
- }
2301
- if (blockVersion) {
2302
- await this.HandleFormattingAndOutput(blockVersion, () => {
2303
- (0, import_console.printBlockVersion)(this, blockVersion);
2304
- });
2305
- }
2306
- if (err)
2307
- throw new Error(
2308
- messages.blocks.failedPush(block.id, currentEnv, env.currentProject)
2309
- );
2310
- } else {
2311
- throw new Error(
2312
- messages.blocks.failedPush(block.id, currentEnv, env.currentProject)
2313
- );
2314
- }
2315
- };
2316
- GetLatestBlockVersion = async (blockId, branch = "default") => {
2317
- var _a;
2318
- const { contensis, log, messages } = this;
2319
- const [getErr, blockVersions] = await (contensis == null ? void 0 : contensis.blocks.GetBlockVersions(blockId, branch)) || [];
2320
- if (getErr) {
2321
- return [getErr, void 0];
2322
- }
2323
- let blockVersionNo = "latest";
2324
- try {
2325
- blockVersionNo = `${(_a = blockVersions == null ? void 0 : blockVersions[0]) == null ? void 0 : _a.version.versionNo}`;
2326
- if (!Number.isNaN(blockVersionNo) && Number(blockVersionNo) > 0)
2327
- return [null, blockVersionNo];
2328
- else throw new Error(`'${blockVersionNo}' is not a valid version number`);
2329
- } catch (parseVersionEx) {
2330
- log.info(
2331
- `Request for blockId: ${blockId}, branch: ${branch}, version: latest`
2332
- );
2333
- log.info(
2334
- `Get block versions response was: ${(0, import_assert.tryStringify)(blockVersions)}`
2335
- );
2336
- log.error(messages.blocks.failedParsingVersion());
2337
- return [parseVersionEx, void 0];
2338
- }
2339
- };
2340
- ExecuteBlockAction = async (action, blockId, version = "latest") => {
2341
- const { currentEnv, env, log, messages } = this;
2342
- const contensis = await this.ConnectContensis();
2343
- if (contensis) {
2344
- let actionOnBlockVersion = version;
2345
- if (action === "release" && version === "latest") {
2346
- const [getErr, blockVersion2] = await this.GetLatestBlockVersion(blockId);
2347
- if (getErr) {
2348
- throw new Error(
2349
- `${messages.blocks.noList(
2350
- currentEnv,
2351
- env.currentProject
2352
- )} (${getErr})`
2353
- );
2354
- } else if (blockVersion2) {
2355
- actionOnBlockVersion = blockVersion2;
2356
- }
2357
- }
2358
- const [err, blockVersion] = await contensis.blocks.BlockAction(
2359
- blockId,
2360
- action,
2361
- actionOnBlockVersion
2362
- );
2363
- if (blockVersion) {
2364
- await this.HandleFormattingAndOutput(blockVersion, () => {
2365
- log.success(
2366
- messages.blocks.actionComplete(
2367
- action,
2368
- blockId,
2369
- currentEnv,
2370
- env.currentProject
2371
- )
2372
- );
2373
- (0, import_console.printBlockVersion)(this, blockVersion);
2374
- });
2375
- }
2376
- if (err) {
2377
- log.error((0, import_json.jsonFormatter)(err));
2378
- throw new Error(
2379
- messages.blocks.actionFailed(
2380
- action,
2381
- blockId,
2382
- currentEnv,
2383
- env.currentProject
2384
- )
2385
- );
2386
- }
2387
- }
2388
- };
2389
- PrintBlockLogs = async (blockId, branch, version, dataCenter, follow = false) => {
2390
- const { currentEnv, env, log, messages } = this;
2391
- const contensis = await this.ConnectContensis();
2392
- if (contensis) {
2393
- log.success(
2394
- messages.blocks.getLogs(blockId, branch, currentEnv, env.currentProject)
2395
- );
2396
- const [err, blockLogs] = await contensis.blocks.GetBlockLogs({
2397
- blockId,
2398
- branchId: branch,
2399
- version,
2400
- dataCenter
2401
- });
2402
- if (err) {
2403
- log.error(
2404
- messages.blocks.failedGetLogs(blockId, currentEnv, env.currentProject)
2405
- );
2406
- log.error((0, import_json.jsonFormatter)(err));
2407
- } else if (blockLogs) {
2408
- const removeTrailingNewline = (logs) => logs.endsWith("\n") ? logs.slice(0, logs.length - 1) : logs;
2409
- const renderLogs = removeTrailingNewline(blockLogs);
2410
- await this.HandleFormattingAndOutput(renderLogs, () => {
2411
- console.log(
2412
- ` - ${blockId} ${branch} ${Number(version) ? `v${version}` : version} ${dataCenter ? `[${dataCenter}]` : ""}`
2413
- );
2414
- log.line();
2415
- console.log(log.infoText(renderLogs));
2416
- });
2417
- let following = follow;
2418
- let alreadyShown = blockLogs;
2419
- let needsNewLine = false;
2420
- let counter = 0;
2421
- const listeners = process.listeners("SIGINT");
2422
- process.removeAllListeners("SIGINT");
2423
- process.on("SIGINT", () => {
2424
- import_logger.Logger.warning(
2425
- messages.blocks.stopFollow(blockId, currentEnv, env.currentProject)
2426
- );
2427
- stopFollowing();
2428
- });
2429
- const delay = (0, import_timers.promiseDelay)(5 * 1e3, null);
2430
- const stopFollowing = () => {
2431
- following = false;
2432
- delay.cancel();
2433
- process.removeAllListeners("SIGINT");
2434
- for (const listener of listeners)
2435
- process.addListener("SIGINT", listener);
2436
- };
2437
- while (following) {
2438
- if (counter++ > 300) {
2439
- import_logger.Logger.warning(
2440
- messages.blocks.timeoutFollow(
2441
- blockId,
2442
- currentEnv,
2443
- env.currentProject
2444
- )
2445
- );
2446
- stopFollowing();
2447
- }
2448
- await delay.wait();
2449
- const [lastErr, lastLogs] = following ? await contensis.blocks.GetBlockLogs({
2450
- blockId,
2451
- branchId: branch,
2452
- version,
2453
- dataCenter
2454
- }) : [null, null];
2455
- if (lastLogs) {
2456
- const difference = (0, import_diff.diffLogStrings)(lastLogs, alreadyShown);
2457
- if (difference) {
2458
- if (needsNewLine) {
2459
- console.log("");
2460
- }
2461
- const render = removeTrailingNewline(difference);
2462
- console.log(log.infoText(render));
2463
- alreadyShown += `${render}
2464
- `;
2465
- needsNewLine = false;
2466
- } else {
2467
- process.stdout.write(".");
2468
- needsNewLine = true;
2469
- }
2470
- } else if (lastErr) {
2471
- process.stdout.write("x");
2472
- needsNewLine = true;
2473
- }
2474
- }
2475
- }
2476
- }
2477
- };
2478
- PrintProxies = async (proxyId) => {
2479
- const { currentEnv, env, log, messages } = this;
2480
- const contensis = await this.ConnectContensis();
2481
- if (contensis) {
2482
- const [err, proxies] = await contensis.proxies.GetProxies(
2483
- proxyId
2484
- );
2485
- if (Array.isArray(proxies)) {
2486
- await this.HandleFormattingAndOutput(proxies, () => {
2487
- log.success(messages.proxies.list(currentEnv, env.currentProject));
2488
- for (const { id, name, description, endpoints, version } of proxies) {
2489
- console.log(
2490
- ` - ${name} [${version.versionNo}] ${id} ${log.infoText`${description}`}`
2491
- );
2492
- for (const [language, endpoint] of Object.entries(
2493
- endpoints
2494
- ))
2495
- console.log(
2496
- ` - ${log.infoText`language: ${language}
2497
- server: ${endpoint.server}
2498
- headers.host: ${endpoint.headers.host}
2499
- ssl: ${endpoint.ssl}`}`
2500
- );
2501
- }
2502
- });
2503
- }
2504
- if (err) {
2505
- log.error(messages.proxies.noList(currentEnv, env.currentProject));
2506
- log.error((0, import_json.jsonFormatter)(err));
2507
- }
2508
- }
2509
- };
2510
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2511
- PrintRenderers = async (rendererId) => {
2512
- const { currentEnv, env, log, messages } = this;
2513
- const contensis = await this.ConnectContensis();
2514
- if (contensis) {
2515
- const [err, renderers] = await contensis.renderers.GetRenderers();
2516
- if (Array.isArray(renderers)) {
2517
- await this.HandleFormattingAndOutput(renderers, () => {
2518
- log.success(messages.renderers.list(currentEnv, env.currentProject));
2519
- for (const {
2520
- id,
2521
- description,
2522
- assignedContentTypes,
2523
- rules,
2524
- version
2525
- } of renderers) {
2526
- console.log(
2527
- ` - ${id} [${version.versionNo}] ${log.infoText`${description}`}`
2528
- );
2529
- if (assignedContentTypes == null ? void 0 : assignedContentTypes.length)
2530
- console.log(
2531
- log.infoText` assignedContentTypes: ${assignedContentTypes.join(
2532
- ", "
2533
- )}`
2534
- );
2535
- for (const rule of rules)
2536
- if (rule.return)
2537
- console.log(
2538
- log.infoText` ${rule.return.endpointId ? "endpointId" : "blockId"}: ${rule.return.endpointId || rule.return.blockId}`
2539
- );
2540
- }
2541
- });
2542
- return renderers;
2543
- }
2544
- if (err) {
2545
- log.error(messages.renderers.noList(currentEnv, env.currentProject));
2546
- log.error((0, import_json.jsonFormatter)(err));
2547
- }
2548
- }
2549
- };
2550
- HandleFormattingAndOutput = async (obj, logFn) => {
2551
- var _a, _b;
2552
- const { format, log, messages, output } = this;
2553
- const fields = (_b = (_a = this.contensis) == null ? void 0 : _a.payload.query) == null ? void 0 : _b.fields;
2554
- if (!format) {
2555
- logFn(obj);
2556
- } else if (format === "csv") {
2557
- log.raw("");
2558
- log.raw(log.infoText(await (0, import_csv.csvFormatter)((0, import_json.limitFields)(obj, fields))));
2559
- } else if (format === "html") {
2560
- log.raw("");
2561
- log.raw(log.infoText((0, import_html.htmlFormatter)((0, import_json.limitFields)(obj, fields))));
2562
- } else if (format === "xml") {
2563
- log.raw("");
2564
- log.raw(log.infoText((0, import_xml.xmlFormatter)((0, import_json.limitFields)(obj, fields))));
2565
- } else if (format === "json") {
2566
- log.raw("");
2567
- log.raw(log.infoText((0, import_json.jsonFormatter)(obj, fields)));
2568
- }
2569
- log.raw("");
2570
- if (output) {
2571
- let writeString = "";
2572
- const isText = !(0, import_assert.tryParse)(obj) && typeof obj === "string";
2573
- if (format === "csv") {
2574
- writeString = await (0, import_csv.csvFormatter)((0, import_json.limitFields)(obj, fields));
2575
- } else if (format === "html") {
2576
- writeString = (0, import_html.htmlFormatter)((0, import_json.limitFields)(obj, fields));
2577
- } else if (format === "xml") {
2578
- writeString = (0, import_xml.xmlFormatter)((0, import_json.limitFields)(obj, fields));
2579
- } else
2580
- writeString = isText ? obj : (0, import_json.jsonFormatter)(obj, fields);
2581
- if (writeString) {
2582
- import_fs.default.writeFileSync(output, writeString);
2583
- log.success(messages.app.fileOutput(isText ? "text" : format, output));
2584
- } else {
2585
- log.info(messages.app.noFileOutput());
2586
- }
2587
- }
2588
- };
2589
- }
2590
- const cliCommand = (commandArgs, outputOpts, contensisOpts = {}) => {
2591
- return new ContensisCli(["", "", ...commandArgs], outputOpts, contensisOpts);
2592
- };
2593
- var ContensisCliService_default = ContensisCli;
2594
- // Annotate the CommonJS export names for ESM import in node:
2595
- 0 && (module.exports = {
2596
- cliCommand
2597
- });
2598
- //# sourceMappingURL=ContensisCliService.js.map