@contentstack/cli-utilities 1.5.8 → 1.5.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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2023 Contentstack
3
+ Copyright (c) 2024 Contentstack
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/lib/cli-ux.js CHANGED
@@ -54,7 +54,9 @@ class CLIInterface {
54
54
  this.loading = !this.loading;
55
55
  }
56
56
  table(data, columns, options) {
57
+ core_1.ux.log('\n');
57
58
  core_1.ux.table(data, columns, options);
59
+ core_1.ux.log('\n');
58
60
  }
59
61
  async inquire(inquirePayload) {
60
62
  if (Array.isArray(inquirePayload)) {
@@ -32,7 +32,7 @@ class ManagementSDKInitiator {
32
32
  retryCondition: (error) => {
33
33
  // LINK https://github.com/contentstack/contentstack-javascript/blob/72fee8ad75ba7d1d5bab8489ebbbbbbaefb1c880/src/core/stack.js#L49
34
34
  if (error.response && error.response.status) {
35
- switch (error.status) {
35
+ switch (error.response.status) {
36
36
  case 401:
37
37
  case 429:
38
38
  case 408:
@@ -107,6 +107,10 @@ class ManagementSDKInitiator {
107
107
  option.authorization = '';
108
108
  }
109
109
  }
110
+ const earlyAccessHeaders = config_handler_1.default.get(`earlyAccessHeaders`);
111
+ if (earlyAccessHeaders && Object.keys(earlyAccessHeaders).length > 0) {
112
+ option.early_access = Object.values(earlyAccessHeaders);
113
+ }
110
114
  return (0, management_1.client)(option);
111
115
  }
112
116
  }
@@ -0,0 +1,36 @@
1
+ import { App, AppData } from '@contentstack/marketplace-sdk/types/marketplace/app';
2
+ import { ContentstackConfig, ContentstackClient, ContentstackToken } from '@contentstack/marketplace-sdk';
3
+ import { Installation } from '@contentstack/marketplace-sdk/types/marketplace/installation';
4
+ type ConfigType = Pick<ContentstackConfig, 'host' | 'endpoint' | 'retryDelay' | 'retryLimit'> & {
5
+ skipTokenValidity?: string;
6
+ };
7
+ type ContentstackMarketplaceConfig = ContentstackConfig;
8
+ type ContentstackMarketplaceClient = ContentstackClient;
9
+ declare class MarketplaceSDKInitiator {
10
+ private analyticsInfo;
11
+ /**
12
+ * The function returns a default configuration object for Contentstack API requests in TypeScript.
13
+ * @returns a default configuration object of type `ContentstackConfig`.
14
+ */
15
+ get defaultOptions(): ContentstackConfig;
16
+ init(context: any): void;
17
+ /**
18
+ * The function `refreshTokenHandler` returns a promise that resolves with a `ContentstackToken`
19
+ * object based on the `authorizationType` parameter.
20
+ * @param {string} authorizationType - The `authorizationType` parameter is a string that specifies
21
+ * the type of authorization being used. It can have one of the following values:
22
+ * @returns The refreshTokenHandler function returns a function that returns a Promise of type
23
+ * ContentstackToken.
24
+ */
25
+ refreshTokenHandler(authorizationType: string): () => Promise<ContentstackToken>;
26
+ /**
27
+ * The function creates a Contentstack SDK client with the provided configuration.
28
+ * @param config - The `config` parameter is an object that contains the following properties:
29
+ * @returns a Promise that resolves to a ContentstackClient object.
30
+ */
31
+ createAppSDKClient(config?: ConfigType): Promise<ContentstackClient>;
32
+ }
33
+ export declare const marketplaceSDKInitiator: MarketplaceSDKInitiator;
34
+ declare const marketplaceSDKClient: typeof marketplaceSDKInitiator.createAppSDKClient;
35
+ export { App, AppData, Installation, MarketplaceSDKInitiator, ContentstackMarketplaceConfig, ContentstackMarketplaceClient, };
36
+ export default marketplaceSDKClient;
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MarketplaceSDKInitiator = exports.marketplaceSDKInitiator = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const node_https_1 = require("node:https");
6
+ const marketplace_sdk_1 = require("@contentstack/marketplace-sdk");
7
+ const auth_handler_1 = tslib_1.__importDefault(require("./auth-handler"));
8
+ const config_handler_1 = tslib_1.__importDefault(require("./config-handler"));
9
+ class MarketplaceSDKInitiator {
10
+ /**
11
+ * The function returns a default configuration object for Contentstack API requests in TypeScript.
12
+ * @returns a default configuration object of type `ContentstackConfig`.
13
+ */
14
+ get defaultOptions() {
15
+ return {
16
+ headers: {},
17
+ retryLimit: 3,
18
+ timeout: 60000,
19
+ maxRequests: 10,
20
+ authtoken: '',
21
+ authorization: '',
22
+ // host: 'api.contentstack.io',
23
+ maxContentLength: 100000000,
24
+ maxBodyLength: 1000000000,
25
+ httpsAgent: new node_https_1.Agent({
26
+ timeout: 60000,
27
+ maxSockets: 100,
28
+ keepAlive: true,
29
+ maxFreeSockets: 10,
30
+ }),
31
+ retryDelay: Math.floor(Math.random() * (8000 - 3000 + 1) + 3000),
32
+ retryCondition: (error) => {
33
+ var _a;
34
+ if ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) {
35
+ if ([408].includes(error.response.status)) {
36
+ return true;
37
+ }
38
+ else {
39
+ return false;
40
+ }
41
+ }
42
+ },
43
+ retryDelayOptions: {
44
+ base: 1000,
45
+ customBackoff: () => 1,
46
+ },
47
+ };
48
+ }
49
+ init(context) {
50
+ this.analyticsInfo = context === null || context === void 0 ? void 0 : context.analyticsInfo;
51
+ }
52
+ /**
53
+ * The function `refreshTokenHandler` returns a promise that resolves with a `ContentstackToken`
54
+ * object based on the `authorizationType` parameter.
55
+ * @param {string} authorizationType - The `authorizationType` parameter is a string that specifies
56
+ * the type of authorization being used. It can have one of the following values:
57
+ * @returns The refreshTokenHandler function returns a function that returns a Promise of type
58
+ * ContentstackToken.
59
+ */
60
+ refreshTokenHandler(authorizationType) {
61
+ return () => {
62
+ return new Promise((resolve, reject) => {
63
+ if (authorizationType === 'BASIC') {
64
+ // NOTE Handle basic auth 401 here
65
+ reject(new Error('Session timed out, please login to proceed'));
66
+ }
67
+ else if (authorizationType === 'OAUTH') {
68
+ auth_handler_1.default
69
+ .compareOAuthExpiry(true)
70
+ .then(() => resolve({ authorization: `Bearer ${config_handler_1.default.get('oauthAccessToken')}` }))
71
+ .catch(reject);
72
+ }
73
+ else {
74
+ reject(new Error('You do not have permissions to perform this action, please login to proceed'));
75
+ }
76
+ });
77
+ };
78
+ }
79
+ /**
80
+ * The function creates a Contentstack SDK client with the provided configuration.
81
+ * @param config - The `config` parameter is an object that contains the following properties:
82
+ * @returns a Promise that resolves to a ContentstackClient object.
83
+ */
84
+ async createAppSDKClient(config) {
85
+ const authorizationType = config_handler_1.default.get('authorisationType');
86
+ const option = this.defaultOptions;
87
+ option.refreshToken = this.refreshTokenHandler(authorizationType);
88
+ if (config.host) {
89
+ option.host = config.host;
90
+ }
91
+ if (config.endpoint) {
92
+ option.endpoint = config.endpoint;
93
+ }
94
+ if (config.retryLimit) {
95
+ option.retryLimit = config.retryLimit;
96
+ }
97
+ if (config.retryDelay) {
98
+ option.retryDelay = config.retryDelay;
99
+ }
100
+ if (this.analyticsInfo) {
101
+ option.headers['X-CS-CLI'] = this.analyticsInfo;
102
+ }
103
+ if (authorizationType === 'BASIC') {
104
+ option.authtoken = config_handler_1.default.get('authtoken');
105
+ }
106
+ else if (authorizationType === 'OAUTH') {
107
+ if (!config.skipTokenValidity) {
108
+ await auth_handler_1.default.compareOAuthExpiry();
109
+ option.authorization = `Bearer ${config_handler_1.default.get('oauthAccessToken')}`;
110
+ }
111
+ }
112
+ return (0, marketplace_sdk_1.client)(option);
113
+ }
114
+ }
115
+ exports.MarketplaceSDKInitiator = MarketplaceSDKInitiator;
116
+ exports.marketplaceSDKInitiator = new MarketplaceSDKInitiator();
117
+ const marketplaceSDKClient = exports.marketplaceSDKInitiator.createAppSDKClient.bind(exports.marketplaceSDKInitiator);
118
+ exports.default = marketplaceSDKClient;
package/lib/helpers.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  export declare const isAuthenticated: () => boolean;
2
2
  export declare const doesBranchExist: (stack: any, branchName: any) => Promise<any>;
3
3
  export declare const isManagementTokenValid: (stackAPIKey: any, managementToken: any) => Promise<{
4
+ valid: boolean;
5
+ message?: undefined;
6
+ } | {
4
7
  valid: boolean;
5
8
  message: any;
6
9
  } | {
10
+ valid: string;
7
11
  message: string;
8
- valid?: undefined;
9
12
  }>;
package/lib/helpers.js CHANGED
@@ -21,7 +21,7 @@ const isManagementTokenValid = async (stackAPIKey, managementToken) => {
21
21
  try {
22
22
  const response = (_a = (await httpClient.get(`${_1.configHandler.get('region').cma}/v3/environments?limit=1`))) === null || _a === void 0 ? void 0 : _a.data;
23
23
  if (response === null || response === void 0 ? void 0 : response.environments) {
24
- return { valid: true, message: `valid token and stack api key` };
24
+ return { valid: true };
25
25
  }
26
26
  else if (response === null || response === void 0 ? void 0 : response.error_code) {
27
27
  return { valid: false, message: response.error_message };
@@ -31,7 +31,7 @@ const isManagementTokenValid = async (stackAPIKey, managementToken) => {
31
31
  }
32
32
  }
33
33
  catch (error) {
34
- return { message: `Failed to check the validity of the Management token. ${error}` };
34
+ return { valid: 'failedToCheck', message: `Failed to check the validity of the Management token. ${error}` };
35
35
  }
36
36
  };
37
37
  exports.isManagementTokenValid = isManagementTokenValid;
@@ -1,6 +1,9 @@
1
1
  import { AxiosRequestConfig, AxiosResponse } from 'axios';
2
2
  import { IHttpClient } from './client-interface';
3
3
  import { HttpResponse } from './http-response';
4
+ type HttpClientOptions = {
5
+ disableEarlyAccessHeaders?: boolean;
6
+ };
4
7
  export declare class HttpClient implements IHttpClient {
5
8
  /**
6
9
  * The request configuration.
@@ -10,6 +13,7 @@ export declare class HttpClient implements IHttpClient {
10
13
  * The request configuration.
11
14
  */
12
15
  private readonly axiosInstance;
16
+ private disableEarlyAccessHeaders;
13
17
  /**
14
18
  * The payload format for a JSON or form-url-encoded request.
15
19
  */
@@ -17,7 +21,7 @@ export declare class HttpClient implements IHttpClient {
17
21
  /**
18
22
  * Createa new pending HTTP request instance.
19
23
  */
20
- constructor(request?: AxiosRequestConfig);
24
+ constructor(request?: AxiosRequestConfig, options?: HttpClientOptions);
21
25
  /**
22
26
  * Create a reusable HttpClient instance.
23
27
  *
@@ -10,13 +10,14 @@ class HttpClient {
10
10
  /**
11
11
  * Createa new pending HTTP request instance.
12
12
  */
13
- constructor(request = {}) {
13
+ constructor(request = {}, options = {}) {
14
14
  /**
15
15
  * The payload format for a JSON or form-url-encoded request.
16
16
  */
17
17
  this.bodyFormat = 'json';
18
18
  this.request = request;
19
19
  this.axiosInstance = axios_1.default.create();
20
+ this.disableEarlyAccessHeaders = options.disableEarlyAccessHeaders || false;
20
21
  // Sets payload format as json by default
21
22
  this.asJson();
22
23
  }
@@ -309,7 +310,8 @@ class HttpClient {
309
310
  if ((_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.error_message) === null || _b === void 0 ? void 0 : _b.includes('access token is invalid or expired')) {
310
311
  const token = await this.refreshToken();
311
312
  this.headers(Object.assign(Object.assign({}, this.request.headers), { authorization: token.authorization }));
312
- return await this.axiosInstance(Object.assign(Object.assign({ url, method, withCredentials: true }, this.request), { data: this.prepareRequestPayload() }));
313
+ return await this.axiosInstance(Object.assign(Object.assign({ url,
314
+ method, withCredentials: true }, this.request), { data: this.prepareRequestPayload() }));
313
315
  }
314
316
  // Retry while Network timeout or Network Error
315
317
  if (!(message.includes('timeout') || message.includes('Network Error') || message.includes('getaddrinfo ENOTFOUND'))) {
@@ -317,11 +319,20 @@ class HttpClient {
317
319
  }
318
320
  if (counter < 1) {
319
321
  counter++;
320
- return await this.axiosInstance(Object.assign(Object.assign({ url, method, withCredentials: true }, this.request), { data: this.prepareRequestPayload() }));
322
+ return await this.axiosInstance(Object.assign(Object.assign({ url,
323
+ method, withCredentials: true }, this.request), { data: this.prepareRequestPayload() }));
321
324
  }
322
325
  return Promise.reject(error);
323
326
  });
324
- return await this.axiosInstance(Object.assign(Object.assign({ url, method, withCredentials: true }, this.request), { data: this.prepareRequestPayload() }));
327
+ if (!this.disableEarlyAccessHeaders) {
328
+ // Add early access header by default
329
+ const earlyAccessHeaders = config_handler_1.default.get(`earlyAccessHeaders`);
330
+ if (earlyAccessHeaders && Object.keys(earlyAccessHeaders).length > 0) {
331
+ this.headers({ 'x-header-ea': Object.values(earlyAccessHeaders).join(',') });
332
+ }
333
+ }
334
+ return await this.axiosInstance(Object.assign(Object.assign({ url,
335
+ method, withCredentials: true }, this.request), { data: this.prepareRequestPayload() }));
325
336
  }
326
337
  /**
327
338
  * Returns the request payload depending on the selected request payload format.
@@ -335,8 +346,9 @@ class HttpClient {
335
346
  return Promise.reject('Your session is timed out, please login to proceed');
336
347
  }
337
348
  else if (authorisationType === 'OAUTH') {
338
- return auth_handler_1.default.compareOAuthExpiry(true)
339
- .then(() => Promise.resolve({ authorization: `Bearer ${config_handler_1.default.get('oauthAccessToken')}`, }))
349
+ return auth_handler_1.default
350
+ .compareOAuthExpiry(true)
351
+ .then(() => Promise.resolve({ authorization: `Bearer ${config_handler_1.default.get('oauthAccessToken')}` }))
340
352
  .catch((error) => Promise.reject(error));
341
353
  }
342
354
  else {
package/lib/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import Logger from './logger';
2
+ import marketplaceSDKClient, { App, AppData, Installation, MarketplaceSDKInitiator, marketplaceSDKInitiator, ContentstackMarketplaceClient, ContentstackMarketplaceConfig } from './contentstack-marketplace-sdk';
2
3
  export { LoggerService } from './logger';
3
4
  export { default as cliux } from './cli-ux';
4
5
  export { default as CLIError } from './cli-error';
@@ -15,7 +16,8 @@ export * from './helpers';
15
16
  export * from './interfaces';
16
17
  export * from './date-time';
17
18
  export * from './add-locale';
19
+ export { App, AppData, Installation, marketplaceSDKClient, MarketplaceSDKInitiator, marketplaceSDKInitiator, ContentstackMarketplaceClient, ContentstackMarketplaceConfig, };
18
20
  export { Args, CommandHelp, Config, Errors, Flags, loadHelpClass, Help, HelpBase, HelpSection, HelpSectionRenderer, HelpSectionKeyValueTable, Hook, Interfaces, Parser, Plugin, run, toCached, tsPath, toStandardizedId, toConfiguredId, settings, Settings, flush, ux, execute, stderr, stdout, } from '@oclif/core';
19
- export { FlagInput, ArgInput } from '@oclif/core/lib/interfaces/parser';
21
+ export { FlagInput, ArgInput, FlagDefinition } from '@oclif/core/lib/interfaces/parser';
20
22
  export { default as TablePrompt } from './inquirer-table-prompt';
21
23
  export { Logger };
package/lib/index.js CHANGED
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Logger = exports.TablePrompt = exports.stdout = exports.stderr = exports.execute = exports.ux = exports.flush = exports.settings = exports.toConfiguredId = exports.toStandardizedId = exports.tsPath = exports.toCached = exports.run = exports.Plugin = exports.Parser = exports.Interfaces = exports.HelpBase = exports.Help = exports.loadHelpClass = exports.Flags = exports.Errors = exports.Config = exports.CommandHelp = exports.Args = exports.Command = exports.flags = exports.args = exports.NodeCrypto = exports.printFlagDeprecation = exports.managementSDKInitiator = exports.managementSDKClient = exports.configHandler = exports.authHandler = exports.messageHandler = exports.CLIError = exports.cliux = exports.LoggerService = void 0;
3
+ exports.Logger = exports.TablePrompt = exports.stdout = exports.stderr = exports.execute = exports.ux = exports.flush = exports.settings = exports.toConfiguredId = exports.toStandardizedId = exports.tsPath = exports.toCached = exports.run = exports.Plugin = exports.Parser = exports.Interfaces = exports.HelpBase = exports.Help = exports.loadHelpClass = exports.Flags = exports.Errors = exports.Config = exports.CommandHelp = exports.Args = exports.marketplaceSDKInitiator = exports.MarketplaceSDKInitiator = exports.marketplaceSDKClient = exports.Command = exports.flags = exports.args = exports.NodeCrypto = exports.printFlagDeprecation = exports.managementSDKInitiator = exports.managementSDKClient = exports.configHandler = exports.authHandler = exports.messageHandler = exports.CLIError = exports.cliux = exports.LoggerService = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const logger_1 = tslib_1.__importDefault(require("./logger"));
6
6
  exports.Logger = logger_1.default;
7
+ const contentstack_marketplace_sdk_1 = tslib_1.__importStar(require("./contentstack-marketplace-sdk"));
8
+ exports.marketplaceSDKClient = contentstack_marketplace_sdk_1.default;
9
+ Object.defineProperty(exports, "MarketplaceSDKInitiator", { enumerable: true, get: function () { return contentstack_marketplace_sdk_1.MarketplaceSDKInitiator; } });
10
+ Object.defineProperty(exports, "marketplaceSDKInitiator", { enumerable: true, get: function () { return contentstack_marketplace_sdk_1.marketplaceSDKInitiator; } });
7
11
  var logger_2 = require("./logger");
8
12
  Object.defineProperty(exports, "LoggerService", { enumerable: true, get: function () { return logger_2.LoggerService; } });
9
13
  var cli_ux_1 = require("./cli-ux");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contentstack/cli-utilities",
3
- "version": "1.5.8",
3
+ "version": "1.5.10",
4
4
  "description": "Utilities for contentstack projects",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -32,9 +32,10 @@
32
32
  "author": "contentstack",
33
33
  "license": "MIT",
34
34
  "dependencies": {
35
- "@contentstack/management": "~1.12.0",
35
+ "@contentstack/management": "~1.13.0",
36
+ "@contentstack/marketplace-sdk": "^1.0.1",
36
37
  "@oclif/core": "^2.9.3",
37
- "axios": "^1.6.0",
38
+ "axios": "^1.6.4",
38
39
  "chalk": "^4.0.0",
39
40
  "cli-cursor": "^3.1.0",
40
41
  "cli-table": "^0.3.11",
@@ -57,6 +58,7 @@
57
58
  "xdg-basedir": "^4.0.0"
58
59
  },
59
60
  "devDependencies": {
61
+ "@contentstack/cli-dev-dependencies": "^1.2.4",
60
62
  "@oclif/test": "^2.2.10",
61
63
  "@types/chai": "^4.2.18",
62
64
  "@types/inquirer": "^9.0.3",
@@ -68,7 +70,7 @@
68
70
  "chai": "^4.3.4",
69
71
  "eslint": "^8.18.0",
70
72
  "eslint-config-oclif": "^4.0.0",
71
- "eslint-config-oclif-typescript": "^0.2.0",
73
+ "eslint-config-oclif-typescript": "^3.0.8",
72
74
  "fancy-test": "^2.0.0",
73
75
  "globby": "^10.0.2",
74
76
  "mocha": "10.1.0",