@contentstack/cli-utilities 2.0.0-beta.1 → 2.0.0-beta.10

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 (37) hide show
  1. package/lib/auth-handler.d.ts +5 -2
  2. package/lib/auth-handler.js +29 -29
  3. package/lib/chalk.d.ts +15 -0
  4. package/lib/chalk.js +66 -0
  5. package/lib/cli-ux.js +23 -10
  6. package/lib/config-handler.js +4 -4
  7. package/lib/constants/logging.js +2 -2
  8. package/lib/content-type-utils.d.ts +2 -2
  9. package/lib/content-type-utils.js +10 -8
  10. package/lib/contentstack-management-sdk.js +14 -4
  11. package/lib/contentstack-marketplace-sdk.d.ts +2 -2
  12. package/lib/contentstack-marketplace-sdk.js +1 -1
  13. package/lib/fs-utility/core.d.ts +0 -1
  14. package/lib/fs-utility/core.js +2 -6
  15. package/lib/fs-utility/helper.js +2 -3
  16. package/lib/helpers.d.ts +3 -1
  17. package/lib/helpers.js +14 -4
  18. package/lib/http-client/client.d.ts +2 -2
  19. package/lib/http-client/client.js +22 -2
  20. package/lib/http-client/http-response.d.ts +1 -1
  21. package/lib/http-client/http-response.js +1 -0
  22. package/lib/index.d.ts +3 -1
  23. package/lib/index.js +4 -1
  24. package/lib/inquirer-table-prompt.d.ts +49 -28
  25. package/lib/inquirer-table-prompt.js +144 -136
  26. package/lib/interfaces/index.d.ts +3 -1
  27. package/lib/logger/cli-error-handler.js +1 -1
  28. package/lib/logger/log.js +4 -4
  29. package/lib/logger/session-path.d.ts +5 -0
  30. package/lib/logger/session-path.js +18 -3
  31. package/lib/message-handler.d.ts +0 -3
  32. package/lib/message-handler.js +6 -10
  33. package/lib/progress-summary/cli-progress-manager.js +39 -35
  34. package/lib/progress-summary/summary-manager.js +30 -30
  35. package/lib/proxy-helper.d.ts +42 -1
  36. package/lib/proxy-helper.js +183 -32
  37. package/package.json +29 -28
@@ -23,7 +23,10 @@ declare class AuthHandler {
23
23
  private allAuthConfigItems;
24
24
  private oauthHandler;
25
25
  private managementAPIClient;
26
+ /** True while an OAuth access-token refresh is running (for logging/diagnostics; correctness uses `oauthRefreshInFlight`). */
26
27
  private isRefreshingToken;
28
+ /** Serialize OAuth refresh so concurrent API calls await the same refresh instead of proceeding with a stale token. */
29
+ private oauthRefreshInFlight;
27
30
  private cmaHost;
28
31
  set host(contentStackHost: any);
29
32
  constructor();
@@ -45,8 +48,8 @@ declare class AuthHandler {
45
48
  getAuthorisationType(): Promise<any>;
46
49
  isAuthorisationTypeBasic(): Promise<boolean>;
47
50
  isAuthorisationTypeOAuth(): Promise<boolean>;
48
- checkExpiryAndRefresh: (force?: boolean) => Promise<void | object>;
49
- compareOAuthExpiry(force?: boolean): Promise<void | object>;
51
+ checkExpiryAndRefresh: (force?: boolean) => Promise<void>;
52
+ compareOAuthExpiry(force?: boolean): Promise<void>;
50
53
  restoreOAuthConfig(): void;
51
54
  }
52
55
  declare const _default: AuthHandler;
@@ -22,7 +22,10 @@ class AuthHandler {
22
22
  this.cmaHost = this.getCmaHost();
23
23
  }
24
24
  constructor() {
25
+ /** True while an OAuth access-token refresh is running (for logging/diagnostics; correctness uses `oauthRefreshInFlight`). */
25
26
  this.isRefreshingToken = false; // Flag to track if a refresh operation is in progress
27
+ /** Serialize OAuth refresh so concurrent API calls await the same refresh instead of proceeding with a stale token. */
28
+ this.oauthRefreshInFlight = null;
26
29
  this.checkExpiryAndRefresh = (force = false) => this.compareOAuthExpiry(force);
27
30
  this.OAuthAppId = process.env.OAUTH_APP_ID || '6400aa06db64de001a31c8a9';
28
31
  this.OAuthClientId = process.env.OAUTH_CLIENT_ID || 'Ie0FEfTzlfAHL4xM';
@@ -329,44 +332,41 @@ class AuthHandler {
329
332
  return config_handler_1.default.get(this.authorisationTypeKeyName) === this.authorisationTypeOAUTHValue ? true : false;
330
333
  }
331
334
  async compareOAuthExpiry(force = false) {
332
- // Avoid recursive refresh operations
333
- if (this.isRefreshingToken) {
334
- cli_ux_1.default.print('Refresh operation already in progress');
335
- return Promise.resolve();
336
- }
337
335
  const oauthDateTime = config_handler_1.default.get(this.oauthDateTimeKeyName);
338
336
  const authorisationType = config_handler_1.default.get(this.authorisationTypeKeyName);
339
337
  if (oauthDateTime && authorisationType === this.authorisationTypeOAUTHValue) {
340
338
  const now = new Date();
341
339
  const oauthDate = new Date(oauthDateTime);
342
- const oauthValidUpto = new Date();
343
- oauthValidUpto.setTime(oauthDate.getTime() + 59 * 60 * 1000);
344
- if (force) {
345
- cli_ux_1.default.print('Forcing token refresh...');
346
- return this.refreshToken();
340
+ const oauthValidUpto = new Date(oauthDate.getTime() + 59 * 60 * 1000);
341
+ const tokenExpired = oauthValidUpto <= now;
342
+ const shouldRefresh = force || tokenExpired;
343
+ if (!shouldRefresh) {
344
+ return Promise.resolve();
347
345
  }
348
- else {
349
- if (oauthValidUpto > now) {
350
- return Promise.resolve();
351
- }
352
- else {
353
- cli_ux_1.default.print('Token expired, refreshing the token');
354
- // Set the flag before refreshing the token
355
- this.isRefreshingToken = true;
356
- try {
357
- await this.refreshToken();
358
- }
359
- catch (error) {
360
- cli_ux_1.default.error('Error refreshing token');
361
- throw error;
346
+ if (this.oauthRefreshInFlight) {
347
+ return this.oauthRefreshInFlight;
348
+ }
349
+ this.isRefreshingToken = true;
350
+ this.oauthRefreshInFlight = (async () => {
351
+ try {
352
+ if (force) {
353
+ cli_ux_1.default.print('Forcing token refresh...');
362
354
  }
363
- finally {
364
- // Reset the flag after refresh operation is completed
365
- this.isRefreshingToken = false;
355
+ else {
356
+ cli_ux_1.default.print('Token expired, refreshing the token');
366
357
  }
367
- return Promise.resolve();
358
+ await this.refreshToken();
368
359
  }
369
- }
360
+ catch (error) {
361
+ cli_ux_1.default.error('Error refreshing token');
362
+ throw error;
363
+ }
364
+ finally {
365
+ this.isRefreshingToken = false;
366
+ this.oauthRefreshInFlight = null;
367
+ }
368
+ })();
369
+ return this.oauthRefreshInFlight;
370
370
  }
371
371
  else {
372
372
  cli_ux_1.default.print('No OAuth configuration set.');
package/lib/chalk.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Chalk 5 is ESM-only. We load it via dynamic import and cache for use in CommonJS.
3
+ *
4
+ * More than one physical copy of this package can load in one process (e.g. pnpm).
5
+ * Cache on globalThis via Symbol.for so loadChalk() from any copy warms getChalk() for all.
6
+ */
7
+ export type ChalkInstance = typeof import('chalk').default;
8
+ /**
9
+ * Load chalk (ESM) and cache it. Call this once during CLI init before any chalk usage.
10
+ */
11
+ export declare function loadChalk(): Promise<ChalkInstance>;
12
+ /**
13
+ * Get the cached chalk instance. Must call loadChalk() first (e.g. in init hook).
14
+ */
15
+ export declare function getChalk(): ChalkInstance;
package/lib/chalk.js ADDED
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.loadChalk = loadChalk;
37
+ exports.getChalk = getChalk;
38
+ const chalkGlobal = Symbol.for('@contentstack/cli-utilities/chalk');
39
+ function readCached() {
40
+ return globalThis[chalkGlobal];
41
+ }
42
+ function writeCached(chalkInstance) {
43
+ globalThis[chalkGlobal] = chalkInstance;
44
+ }
45
+ /**
46
+ * Load chalk (ESM) and cache it. Call this once during CLI init before any chalk usage.
47
+ */
48
+ async function loadChalk() {
49
+ let chalkInstance = readCached();
50
+ if (!chalkInstance) {
51
+ const chalkModule = await Promise.resolve().then(() => __importStar(require('chalk')));
52
+ chalkInstance = chalkModule.default;
53
+ writeCached(chalkInstance);
54
+ }
55
+ return chalkInstance;
56
+ }
57
+ /**
58
+ * Get the cached chalk instance. Must call loadChalk() first (e.g. in init hook).
59
+ */
60
+ function getChalk() {
61
+ const chalkInstance = readCached();
62
+ if (!chalkInstance) {
63
+ throw new Error('Chalk not loaded. Ensure loadChalk() is called during init (e.g. in utils-init hook).');
64
+ }
65
+ return chalkInstance;
66
+ }
package/lib/cli-ux.js CHANGED
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Command = exports.Args = exports.Flags = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
5
+ const chalk_1 = require("./chalk");
6
6
  const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
7
7
  const core_1 = require("@oclif/core");
8
8
  Object.defineProperty(exports, "Args", { enumerable: true, get: function () { return core_1.Args; } });
@@ -27,7 +27,8 @@ class CLIInterface {
27
27
  }
28
28
  print(message, opts) {
29
29
  if (opts) {
30
- let chalkFn = chalk_1.default;
30
+ const chalk = (0, chalk_1.getChalk)();
31
+ let chalkFn = chalk;
31
32
  if (opts.color)
32
33
  chalkFn = chalkFn[opts.color];
33
34
  if (opts.bold)
@@ -38,10 +39,10 @@ class CLIInterface {
38
39
  core_1.ux.stdout(message_handler_1.default.parse(message));
39
40
  }
40
41
  success(message) {
41
- core_1.ux.stdout(chalk_1.default.green(message_handler_1.default.parse(message)));
42
+ core_1.ux.stdout((0, chalk_1.getChalk)().green(message_handler_1.default.parse(message)));
42
43
  }
43
44
  error(message, ...params) {
44
- core_1.ux.stdout(chalk_1.default.red(message_handler_1.default.parse(message) + (params && params.length > 0 ? ': ' : '')), ...params);
45
+ core_1.ux.stdout((0, chalk_1.getChalk)().red(message_handler_1.default.parse(message) + (params && params.length > 0 ? ': ' : '')), ...params);
45
46
  }
46
47
  loader(message = '') {
47
48
  if (!this.loading) {
@@ -56,13 +57,25 @@ class CLIInterface {
56
57
  cli_table_1.default.render(headers, data, flags, options);
57
58
  }
58
59
  async inquire(inquirePayload) {
59
- if (Array.isArray(inquirePayload)) {
60
- return inquirer_1.default.prompt(inquirePayload);
60
+ var _a, _b;
61
+ try {
62
+ if (Array.isArray(inquirePayload)) {
63
+ return (await inquirer_1.default.prompt(inquirePayload));
64
+ }
65
+ else {
66
+ inquirePayload.message = message_handler_1.default.parse(inquirePayload.message);
67
+ const result = (await inquirer_1.default.prompt(inquirePayload));
68
+ return result[inquirePayload.name];
69
+ }
61
70
  }
62
- else {
63
- inquirePayload.message = message_handler_1.default.parse(inquirePayload.message);
64
- const result = await inquirer_1.default.prompt(inquirePayload);
65
- return result[inquirePayload.name];
71
+ catch (err) {
72
+ const isExitPrompt = (err === null || err === void 0 ? void 0 : err.name) === 'ExitPromptError' ||
73
+ ((_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.includes('SIGINT')) ||
74
+ ((_b = err === null || err === void 0 ? void 0 : err.message) === null || _b === void 0 ? void 0 : _b.includes('force closed'));
75
+ if (isExitPrompt) {
76
+ process.exit(130);
77
+ }
78
+ throw err;
66
79
  }
67
80
  }
68
81
  async prompt(message, options) {
@@ -5,7 +5,7 @@ const conf_1 = tslib_1.__importDefault(require("conf"));
5
5
  const has_1 = tslib_1.__importDefault(require("lodash/has"));
6
6
  const uuid_1 = require("uuid");
7
7
  const fs_1 = require("fs");
8
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
8
+ const chalk_1 = require("./chalk");
9
9
  const _1 = require(".");
10
10
  const ENC_KEY = process.env.ENC_KEY || 'encryptionKey';
11
11
  const ENCRYPT_CONF = (0, has_1.default)(process.env, 'ENCRYPT_CONF') ? process.env.ENCRYPT_CONF === 'true' : true;
@@ -77,7 +77,7 @@ class Config {
77
77
  }
78
78
  safeDeleteConfigIfInvalid(configFilePath) {
79
79
  if ((0, fs_1.existsSync)(configFilePath) && !this.isConfigFileValid(configFilePath)) {
80
- console.warn(chalk_1.default.yellow(`Warning: Detected corrupted config at ${configFilePath}. Removing...`));
80
+ console.warn((0, chalk_1.getChalk)().yellow(`Warning: Detected corrupted config at ${configFilePath}. Removing...`));
81
81
  (0, fs_1.unlinkSync)(configFilePath);
82
82
  }
83
83
  }
@@ -137,7 +137,7 @@ class Config {
137
137
  this.getEncryptedConfig(oldConfigData, true);
138
138
  }
139
139
  catch (_error) {
140
- _1.cliux.print(chalk_1.default.red('Error: Config file is corrupted'));
140
+ _1.cliux.print((0, chalk_1.getChalk)().red('Error: Config file is corrupted'));
141
141
  _1.cliux.print(_error);
142
142
  process.exit(1);
143
143
  }
@@ -188,7 +188,7 @@ class Config {
188
188
  }
189
189
  catch (__error) {
190
190
  // console.trace(error.message)
191
- _1.cliux.print(chalk_1.default.red('Error: Config file is corrupted'));
191
+ _1.cliux.print((0, chalk_1.getChalk)().red('Error: Config file is corrupted'));
192
192
  _1.cliux.print(_error);
193
193
  process.exit(1);
194
194
  }
@@ -5,7 +5,7 @@ exports.logLevels = {
5
5
  error: 0,
6
6
  warn: 1,
7
7
  info: 2,
8
- success: 2,
8
+ success: 2, // Maps to info level but with different type
9
9
  debug: 3,
10
10
  verbose: 4,
11
11
  };
@@ -13,7 +13,7 @@ exports.logLevels = {
13
13
  exports.levelColors = {
14
14
  error: 'red',
15
15
  warn: 'yellow',
16
- success: 'green',
16
+ success: 'green', // Custom color for success
17
17
  info: 'white',
18
18
  debug: 'blue',
19
19
  };
@@ -2,6 +2,6 @@
2
2
  * Reads all content type schema files from a directory
3
3
  * @param dirPath - Path to content types directory
4
4
  * @param ignoredFiles - Files to ignore (defaults to schema.json, .DS_Store, __master.json, __priority.json)
5
- * @returns Array of content type schemas
5
+ * @returns Array of content type schemas (empty if the path is missing or has no eligible files)
6
6
  */
7
- export declare function readContentTypeSchemas(dirPath: string, ignoredFiles?: string[]): Record<string, unknown>[] | null;
7
+ export declare function readContentTypeSchemas(dirPath: string, ignoredFiles?: string[]): Record<string, unknown>[];
@@ -1,19 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readContentTypeSchemas = void 0;
3
+ exports.readContentTypeSchemas = readContentTypeSchemas;
4
+ const node_fs_1 = require("node:fs");
4
5
  const node_path_1 = require("node:path");
5
- const fs_utility_1 = require("./fs-utility");
6
6
  /**
7
7
  * Reads all content type schema files from a directory
8
8
  * @param dirPath - Path to content types directory
9
9
  * @param ignoredFiles - Files to ignore (defaults to schema.json, .DS_Store, __master.json, __priority.json)
10
- * @returns Array of content type schemas
10
+ * @returns Array of content type schemas (empty if the path is missing or has no eligible files)
11
11
  */
12
12
  function readContentTypeSchemas(dirPath, ignoredFiles = ['schema.json', '.DS_Store', '__master.json', '__priority.json', 'field_rules_uid.json']) {
13
- const fsUtil = new fs_utility_1.FsUtility();
14
- const files = fsUtil.readdir(dirPath);
13
+ if (!(0, node_fs_1.existsSync)(dirPath)) {
14
+ return [];
15
+ }
16
+ const files = (0, node_fs_1.readdirSync)(dirPath);
15
17
  if (!files || files.length === 0) {
16
- return null;
18
+ return [];
17
19
  }
18
20
  const contentTypes = [];
19
21
  for (const file of files) {
@@ -27,7 +29,8 @@ function readContentTypeSchemas(dirPath, ignoredFiles = ['schema.json', '.DS_Sto
27
29
  }
28
30
  try {
29
31
  const filePath = (0, node_path_1.resolve)(dirPath, file);
30
- const contentType = fsUtil.readFile(filePath);
32
+ const raw = (0, node_fs_1.readFileSync)(filePath, 'utf8');
33
+ const contentType = JSON.parse(raw);
31
34
  if (contentType) {
32
35
  contentTypes.push(contentType);
33
36
  }
@@ -39,4 +42,3 @@ function readContentTypeSchemas(dirPath, ignoredFiles = ['schema.json', '.DS_Sto
39
42
  }
40
43
  return contentTypes;
41
44
  }
42
- exports.readContentTypeSchemas = readContentTypeSchemas;
@@ -15,15 +15,21 @@ class ManagementSDKInitiator {
15
15
  this.analyticsInfo = context === null || context === void 0 ? void 0 : context.analyticsInfo;
16
16
  }
17
17
  async createAPIClient(config) {
18
- // Get proxy configuration with priority: Environment variables > Global config
19
- const proxyConfig = (0, proxy_helper_1.getProxyConfig)();
18
+ // Resolve host so NO_PROXY applies even when config.host is omitted (e.g. from region.cma)
19
+ const host = (0, proxy_helper_1.resolveRequestHost)(config);
20
+ // NO_PROXY has priority over HTTP_PROXY/HTTPS_PROXY and config-set proxy
21
+ const proxyConfig = (0, proxy_helper_1.getProxyConfigForHost)(host);
22
+ // When NO_PROXY matches, strip proxy env so SDK/axios cannot pick up HTTP_PROXY for this process.
23
+ if (host && (0, proxy_helper_1.shouldBypassProxy)(host)) {
24
+ (0, proxy_helper_1.clearProxyEnv)();
25
+ }
20
26
  const option = {
21
- host: config.host,
27
+ host: config.host || host || undefined,
22
28
  maxContentLength: config.maxContentLength || 100000000,
23
29
  maxBodyLength: config.maxBodyLength || 1000000000,
24
30
  maxRequests: 10,
25
31
  retryLimit: 3,
26
- timeout: proxyConfig ? 10000 : 60000,
32
+ timeout: proxyConfig ? 10000 : 60000, // 10s timeout with proxy, 60s without
27
33
  delayMs: config.delayMs,
28
34
  httpsAgent: new node_https_1.Agent({
29
35
  maxSockets: 100,
@@ -106,6 +112,10 @@ class ManagementSDKInitiator {
106
112
  if (proxyConfig) {
107
113
  option.proxy = proxyConfig;
108
114
  }
115
+ else if (host && (0, proxy_helper_1.shouldBypassProxy)(host)) {
116
+ option.proxy = false;
117
+ }
118
+ // When host is in NO_PROXY, do not add proxy to option at all
109
119
  if (config.endpoint) {
110
120
  option.endpoint = config.endpoint;
111
121
  }
@@ -1,6 +1,6 @@
1
- import { App, AppData } from '@contentstack/marketplace-sdk/types/marketplace/app';
1
+ import type { App, AppData } from '@contentstack/marketplace-sdk/types/marketplace/app';
2
2
  import { ContentstackConfig, ContentstackClient, ContentstackToken } from '@contentstack/marketplace-sdk';
3
- import { Installation } from '@contentstack/marketplace-sdk/types/marketplace/installation';
3
+ import type { Installation } from '@contentstack/marketplace-sdk/types/marketplace/installation';
4
4
  type ConfigType = Pick<ContentstackConfig, 'host' | 'endpoint' | 'retryDelay' | 'retryLimit'> & {
5
5
  skipTokenValidity?: string;
6
6
  };
@@ -23,7 +23,7 @@ class MarketplaceSDKInitiator {
23
23
  maxContentLength: 100000000,
24
24
  maxBodyLength: 1000000000,
25
25
  httpsAgent: new node_https_1.Agent({
26
- timeout: 60000,
26
+ timeout: 60000, // active socket keepalive for 60 seconds
27
27
  maxSockets: 100,
28
28
  keepAlive: true,
29
29
  maxFreeSockets: 10,
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import { Chunk, PageInfo, WriteFileOptions, FsConstructorOptions, ChunkFilesGetterType } from './types';
3
2
  export default class FsUtility {
4
3
  private isArray;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getFileList = exports.getDirectories = void 0;
3
+ exports.getDirectories = getDirectories;
4
+ exports.getFileList = getFileList;
4
5
  const tslib_1 = require("tslib");
5
6
  const mkdirp_1 = tslib_1.__importDefault(require("mkdirp"));
6
7
  const keys_1 = tslib_1.__importDefault(require("lodash/keys"));
@@ -336,11 +337,9 @@ class FsUtility {
336
337
  this.pageInfo.after = index || 0;
337
338
  this.pageInfo.before = 1;
338
339
  }
339
- /* eslint-disable unicorn/consistent-destructuring */
340
340
  if (!(0, isEmpty_1.default)(this.readIndexer[this.pageInfo.after + 1])) {
341
341
  this.pageInfo.hasNextPage = true;
342
342
  }
343
- /* eslint-disable unicorn/consistent-destructuring */
344
343
  if (!(0, isEmpty_1.default)(this.readIndexer[this.pageInfo.after - 1])) {
345
344
  this.pageInfo.hasPreviousPage = true;
346
345
  }
@@ -358,7 +357,6 @@ function getDirectories(source) {
358
357
  .filter((dirent) => dirent.isDirectory())
359
358
  .map((dirent) => dirent.name);
360
359
  }
361
- exports.getDirectories = getDirectories;
362
360
  async function getFileList(dirName, onlyName = true) {
363
361
  if (!(0, node_fs_1.existsSync)(dirName))
364
362
  return [];
@@ -366,7 +364,6 @@ async function getFileList(dirName, onlyName = true) {
366
364
  const items = (0, node_fs_1.readdirSync)(dirName, { withFileTypes: true });
367
365
  for (const item of items) {
368
366
  if (item.isDirectory()) {
369
- /* eslint-disable no-await-in-loop */
370
367
  files = [...files, ...(await getFileList(`${dirName}/${item.name}`))];
371
368
  }
372
369
  else {
@@ -375,4 +372,3 @@ async function getFileList(dirName, onlyName = true) {
375
372
  }
376
373
  return files;
377
374
  }
378
- exports.getFileList = getFileList;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getMetaData = exports.mapKeyAndVal = void 0;
3
+ exports.mapKeyAndVal = mapKeyAndVal;
4
+ exports.getMetaData = getMetaData;
4
5
  const tslib_1 = require("tslib");
5
6
  const map_1 = tslib_1.__importDefault(require("lodash/map"));
6
7
  const omit_1 = tslib_1.__importDefault(require("lodash/omit"));
@@ -22,7 +23,6 @@ function mapKeyAndVal(array, keyName, omitKeys = []) {
22
23
  return { [row[keyName]]: (0, omit_1.default)(row, omitKeys) };
23
24
  }));
24
25
  }
25
- exports.mapKeyAndVal = mapKeyAndVal;
26
26
  function getMetaData(array, pickKeys, handler) {
27
27
  if (handler instanceof Function)
28
28
  handler(array);
@@ -30,4 +30,3 @@ function getMetaData(array, pickKeys, handler) {
30
30
  return;
31
31
  return (0, map_1.default)(array, (row) => (0, pick_1.default)(row, pickKeys));
32
32
  }
33
- exports.getMetaData = getMetaData;
package/lib/helpers.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ContentstackClient } from '.';
2
2
  export declare const isAuthenticated: () => boolean;
3
3
  export declare const doesBranchExist: (stack: any, branchName: any) => Promise<any>;
4
- export declare const getBranchFromAlias: (stack: ReturnType<ContentstackClient['stack']>, branchAlias: string) => Promise<string>;
4
+ export declare const getBranchFromAlias: (stack: ReturnType<ContentstackClient["stack"]>, branchAlias: string) => Promise<string>;
5
5
  export declare const isManagementTokenValid: (stackAPIKey: any, managementToken: any) => Promise<{
6
6
  valid: boolean;
7
7
  message?: undefined;
@@ -43,6 +43,8 @@ export declare function getAuthenticationMethod(): string;
43
43
  * @param authenticationMethod - Optional authentication method
44
44
  * @returns Context object with all session-level metadata
45
45
  */
46
+ export declare function generateUid(): string;
47
+ export declare function generateShortUid(): string;
46
48
  export declare function createLogContext(commandId: string, apiKey: string, authenticationMethod?: string): {
47
49
  command: string;
48
50
  module: string;
package/lib/helpers.js CHANGED
@@ -1,9 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createLogContext = exports.getAuthenticationMethod = exports.clearProgressModuleSetting = exports.redactObject = exports.formatError = exports.validateRegex = exports.validateFileName = exports.validateUids = exports.sanitizePath = exports.escapeRegExp = exports.validatePath = exports.createDeveloperHubUrl = exports.isManagementTokenValid = exports.getBranchFromAlias = exports.doesBranchExist = exports.isAuthenticated = void 0;
3
+ exports.redactObject = exports.formatError = exports.validateRegex = exports.validateFileName = exports.validateUids = exports.sanitizePath = exports.escapeRegExp = exports.validatePath = exports.createDeveloperHubUrl = exports.isManagementTokenValid = exports.getBranchFromAlias = exports.doesBranchExist = exports.isAuthenticated = void 0;
4
+ exports.clearProgressModuleSetting = clearProgressModuleSetting;
5
+ exports.getAuthenticationMethod = getAuthenticationMethod;
6
+ exports.generateUid = generateUid;
7
+ exports.generateShortUid = generateShortUid;
8
+ exports.createLogContext = createLogContext;
4
9
  const tslib_1 = require("tslib");
5
10
  const recheck_1 = require("recheck");
6
11
  const traverse_1 = tslib_1.__importDefault(require("traverse"));
12
+ const uuid_1 = require("uuid");
13
+ const short_uuid_1 = require("short-uuid");
7
14
  const auth_handler_1 = tslib_1.__importDefault(require("./auth-handler"));
8
15
  const _1 = require(".");
9
16
  const proxy_helper_1 = require("./proxy-helper");
@@ -251,7 +258,6 @@ function clearProgressModuleSetting() {
251
258
  _1.configHandler.set('log', logConfig);
252
259
  }
253
260
  }
254
- exports.clearProgressModuleSetting = clearProgressModuleSetting;
255
261
  /**
256
262
  * Get authentication method from config
257
263
  * @returns Authentication method string ('OAuth', 'Basic Auth', or empty string)
@@ -268,7 +274,6 @@ function getAuthenticationMethod() {
268
274
  // Return empty string if unknown
269
275
  return '';
270
276
  }
271
- exports.getAuthenticationMethod = getAuthenticationMethod;
272
277
  /**
273
278
  * Creates a standardized context object for logging
274
279
  * This context contains all session-level metadata that should be in session.json
@@ -279,6 +284,12 @@ exports.getAuthenticationMethod = getAuthenticationMethod;
279
284
  * @param authenticationMethod - Optional authentication method
280
285
  * @returns Context object with all session-level metadata
281
286
  */
287
+ function generateUid() {
288
+ return (0, uuid_1.v4)();
289
+ }
290
+ function generateShortUid() {
291
+ return (0, short_uuid_1.generate)();
292
+ }
282
293
  function createLogContext(commandId, apiKey, authenticationMethod) {
283
294
  // Store apiKey in configHandler so it's available for session.json
284
295
  if (apiKey) {
@@ -296,4 +307,3 @@ function createLogContext(commandId, apiKey, authenticationMethod) {
296
307
  authenticationMethod: authMethod,
297
308
  };
298
309
  }
299
- exports.createLogContext = createLogContext;
@@ -229,8 +229,8 @@ export declare class HttpClient implements IHttpClient {
229
229
  * Get the axios instance for interceptor access
230
230
  */
231
231
  get interceptors(): {
232
- request: import("axios").AxiosInterceptorManager<import("axios").InternalAxiosRequestConfig<any>>;
233
- response: import("axios").AxiosInterceptorManager<AxiosResponse<any, any, {}>>;
232
+ request: import("axios").AxiosInterceptorManager<import("axios").InternalAxiosRequestConfig>;
233
+ response: import("axios").AxiosInterceptorManager<AxiosResponse>;
234
234
  };
235
235
  /**
236
236
  * Returns the request payload depending on the selected request payload format.
@@ -7,6 +7,22 @@ const http_response_1 = require("./http-response");
7
7
  const config_handler_1 = tslib_1.__importDefault(require("../config-handler"));
8
8
  const auth_handler_1 = tslib_1.__importDefault(require("../auth-handler"));
9
9
  const proxy_helper_1 = require("../proxy-helper");
10
+ /**
11
+ * Derive request host from baseURL or url for NO_PROXY checks.
12
+ */
13
+ function getRequestHost(baseURL, url) {
14
+ const toTry = [baseURL, url].filter(Boolean);
15
+ for (const u of toTry) {
16
+ try {
17
+ const parsed = new URL(u.startsWith('http') ? u : `https://${u}`);
18
+ return parsed.hostname || undefined;
19
+ }
20
+ catch (_a) {
21
+ // ignore
22
+ }
23
+ }
24
+ return undefined;
25
+ }
10
26
  class HttpClient {
11
27
  /**
12
28
  * Createa new pending HTTP request instance.
@@ -340,12 +356,16 @@ class HttpClient {
340
356
  this.headers({ 'x-header-ea': Object.values(earlyAccessHeaders).join(',') });
341
357
  }
342
358
  }
343
- // Configure proxy if available (priority: request.proxy > getProxyConfig())
359
+ // Configure proxy if available. NO_PROXY has priority; fall back to region CMA for host resolution.
344
360
  if (!this.request.proxy) {
345
- const proxyConfig = (0, proxy_helper_1.getProxyConfig)();
361
+ const host = getRequestHost(this.request.baseURL, url) || (0, proxy_helper_1.resolveRequestHost)({});
362
+ const proxyConfig = (0, proxy_helper_1.getProxyConfigForHost)(host);
346
363
  if (proxyConfig) {
347
364
  this.request.proxy = proxyConfig;
348
365
  }
366
+ else if (host && (0, proxy_helper_1.shouldBypassProxy)(host)) {
367
+ this.request.proxy = false;
368
+ }
349
369
  }
350
370
  return await this.axiosInstance(Object.assign(Object.assign({ url,
351
371
  method, withCredentials: true }, this.request), { data: this.prepareRequestPayload() }));
@@ -1,5 +1,5 @@
1
1
  import { AxiosResponse, AxiosResponseHeaders, RawAxiosResponseHeaders } from 'axios';
2
- export declare class HttpResponse<ResponseType = any> {
2
+ export declare class HttpResponse<_ResponseType = any> {
3
3
  /**
4
4
  * The Axios response object.
5
5
  */
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HttpResponse = void 0;
4
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
4
5
  class HttpResponse {
5
6
  /**
6
7
  * Wrap the given Axios `response` into a new response instance.
package/lib/index.d.ts CHANGED
@@ -22,8 +22,10 @@ export * from './path-validator';
22
22
  export { default as CLITable, TableFlags, TableHeader, TableOptions, TableData } from './cli-table';
23
23
  export { App, AppData, Installation, marketplaceSDKClient, MarketplaceSDKInitiator, marketplaceSDKInitiator, ContentstackMarketplaceClient, ContentstackMarketplaceConfig, };
24
24
  export { Args, CommandHelp, Config, Errors, Flags, loadHelpClass, Help, HelpBase, HelpSection, HelpSectionRenderer, HelpSectionKeyValueTable, Hook, Interfaces, Parser, Plugin, run, toStandardizedId, toConfiguredId, settings, Settings, flush, ux, execute, } from '@oclif/core';
25
- export { FlagInput, ArgInput, FlagDefinition } from '@oclif/core/lib/interfaces/parser';
25
+ export type { FlagInput, ArgInput, FlagDefinition } from '@oclif/core/lib/interfaces/parser';
26
26
  export { default as TablePrompt } from './inquirer-table-prompt';
27
+ export { loadChalk, getChalk } from './chalk';
28
+ export type { ChalkInstance } from './chalk';
27
29
  export { Logger };
28
30
  export { default as authenticationHandler } from './authentication-handler';
29
31
  export { v2Logger as log, cliErrorHandler, handleAndLogError, getLogPath, getSessionLogPath } from './logger/log';