@hubspot/local-dev-lib 0.1.0 → 0.1.1-experimental.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/LICENSE +12 -0
  2. package/README.md +17 -0
  3. package/api/appsDev.d.ts +6 -0
  4. package/api/appsDev.js +29 -0
  5. package/api/customObjects.d.ts +8 -7
  6. package/api/customObjects.js +13 -16
  7. package/api/designManager.d.ts +4 -13
  8. package/api/designManager.js +6 -9
  9. package/api/developerTestAccounts.d.ts +7 -0
  10. package/api/developerTestAccounts.js +48 -0
  11. package/api/fileManager.d.ts +6 -5
  12. package/api/fileManager.js +13 -12
  13. package/api/fileMapper.d.ts +8 -7
  14. package/api/fileMapper.js +19 -18
  15. package/api/fileTransport.d.ts +4 -0
  16. package/api/fileTransport.js +39 -0
  17. package/api/functions.d.ts +7 -4
  18. package/api/functions.js +22 -11
  19. package/api/github.d.ts +7 -9
  20. package/api/github.js +31 -13
  21. package/api/hubdb.d.ts +11 -10
  22. package/api/hubdb.js +28 -22
  23. package/api/lighthouseScore.d.ts +4 -4
  24. package/api/lighthouseScore.js +9 -12
  25. package/api/localDevAuth.d.ts +7 -15
  26. package/api/localDevAuth.js +28 -13
  27. package/api/marketplaceValidation.d.ts +4 -4
  28. package/api/marketplaceValidation.js +8 -11
  29. package/api/projects.d.ts +31 -24
  30. package/api/projects.js +166 -45
  31. package/api/sandboxHubs.d.ts +6 -4
  32. package/api/sandboxHubs.js +10 -11
  33. package/api/sandboxSync.d.ts +4 -4
  34. package/api/sandboxSync.js +4 -13
  35. package/api/secrets.d.ts +6 -8
  36. package/api/secrets.js +9 -12
  37. package/api/validateHubl.d.ts +2 -1
  38. package/api/validateHubl.js +3 -6
  39. package/config/CLIConfiguration.d.ts +13 -10
  40. package/config/CLIConfiguration.js +129 -77
  41. package/config/configFile.js +12 -18
  42. package/config/configUtils.d.ts +2 -21
  43. package/config/configUtils.js +5 -4
  44. package/config/config_DEPRECATED.d.ts +6 -8
  45. package/config/config_DEPRECATED.js +79 -25
  46. package/config/environment.js +5 -4
  47. package/config/getAccountIdentifier.d.ts +2 -0
  48. package/config/getAccountIdentifier.js +15 -0
  49. package/config/index.d.ts +10 -7
  50. package/config/index.js +83 -55
  51. package/constants/config.d.ts +15 -1
  52. package/constants/config.js +17 -3
  53. package/constants/environments.d.ts +1 -0
  54. package/constants/environments.js +1 -0
  55. package/constants/extensions.d.ts +2 -0
  56. package/constants/extensions.js +3 -1
  57. package/constants/files.d.ts +2 -2
  58. package/constants/files.js +3 -3
  59. package/errors/errors_DEPRECATED.d.ts +1 -5
  60. package/errors/errors_DEPRECATED.js +2 -2
  61. package/errors/index.d.ts +18 -0
  62. package/errors/index.js +63 -0
  63. package/http/addQueryParams.d.ts +2 -0
  64. package/http/addQueryParams.js +14 -0
  65. package/http/getAxiosConfig.d.ts +6 -3
  66. package/http/getAxiosConfig.js +51 -7
  67. package/http/index.d.ts +11 -12
  68. package/http/index.js +35 -41
  69. package/http/unauthed.d.ts +14 -0
  70. package/http/unauthed.js +38 -0
  71. package/lang/en.json +374 -368
  72. package/lib/archive.d.ts +2 -8
  73. package/lib/archive.js +34 -30
  74. package/lib/cms/functions.d.ts +7 -12
  75. package/lib/cms/functions.js +49 -51
  76. package/lib/cms/handleFieldsJS.js +16 -14
  77. package/lib/cms/modules.d.ts +5 -15
  78. package/lib/cms/modules.js +116 -42
  79. package/lib/cms/processFieldsJs.js +10 -33
  80. package/lib/cms/templates.d.ts +43 -3
  81. package/lib/cms/templates.js +53 -11
  82. package/lib/cms/uploadFolder.d.ts +3 -14
  83. package/lib/cms/uploadFolder.js +58 -42
  84. package/lib/cms/validate.js +1 -1
  85. package/lib/cms/watch.d.ts +2 -18
  86. package/lib/cms/watch.js +63 -68
  87. package/lib/customObjects.js +4 -15
  88. package/lib/fileManager.d.ts +2 -0
  89. package/lib/fileManager.js +184 -0
  90. package/lib/fileMapper.d.ts +4 -15
  91. package/lib/fileMapper.js +68 -82
  92. package/lib/fs.d.ts +1 -1
  93. package/lib/fs.js +10 -6
  94. package/lib/github.d.ts +9 -14
  95. package/lib/github.js +61 -29
  96. package/lib/gitignore.d.ts +2 -0
  97. package/lib/gitignore.js +21 -4
  98. package/lib/hubdb.d.ts +3 -2
  99. package/lib/hubdb.js +11 -9
  100. package/lib/{logging/logger.d.ts → logger.d.ts} +20 -8
  101. package/{utils → lib}/notify.js +2 -2
  102. package/lib/oauth.d.ts +2 -5
  103. package/lib/oauth.js +14 -25
  104. package/lib/path.d.ts +3 -0
  105. package/lib/path.js +46 -1
  106. package/lib/personalAccessKey.d.ts +7 -10
  107. package/lib/personalAccessKey.js +74 -47
  108. package/lib/portManager.d.ts +3 -5
  109. package/lib/portManager.js +18 -6
  110. package/lib/text.d.ts +1 -0
  111. package/lib/text.js +9 -1
  112. package/lib/trackUsage.js +18 -11
  113. package/lib/urls.js +5 -1
  114. package/models/FileSystemError.d.ts +6 -0
  115. package/models/FileSystemError.js +47 -0
  116. package/models/HubSpotHttpError.d.ts +24 -0
  117. package/models/HubSpotHttpError.js +197 -0
  118. package/models/OAuth2Manager.d.ts +5 -27
  119. package/models/OAuth2Manager.js +41 -64
  120. package/package.json +19 -18
  121. package/types/Accounts.d.ts +90 -3
  122. package/types/Apps.d.ts +77 -0
  123. package/types/Archive.d.ts +9 -0
  124. package/types/Archive.js +2 -0
  125. package/types/Build.d.ts +4 -2
  126. package/types/ComponentStructure.d.ts +30 -10
  127. package/types/Config.d.ts +19 -2
  128. package/types/Deploy.d.ts +3 -2
  129. package/types/DesignManager.d.ts +10 -0
  130. package/types/DesignManager.js +2 -0
  131. package/types/Error.d.ts +11 -6
  132. package/types/FieldsJS.d.ts +1 -0
  133. package/types/FieldsJS.js +2 -0
  134. package/types/FileManager.d.ts +12 -7
  135. package/types/Files.d.ts +43 -4
  136. package/types/Functions.d.ts +52 -0
  137. package/types/Github.d.ts +12 -0
  138. package/types/Http.d.ts +12 -12
  139. package/types/Hubdb.d.ts +9 -0
  140. package/types/Lang.d.ts +3 -0
  141. package/types/MarketplaceValidation.d.ts +7 -3
  142. package/types/Migration.d.ts +28 -0
  143. package/types/Migration.js +10 -0
  144. package/types/Modules.d.ts +11 -0
  145. package/types/PortManager.d.ts +7 -0
  146. package/types/Project.d.ts +30 -0
  147. package/types/ProjectLog.d.ts +9 -0
  148. package/types/ProjectLog.js +2 -0
  149. package/types/Sandbox.d.ts +37 -47
  150. package/types/Schemas.d.ts +12 -0
  151. package/types/Secrets.d.ts +3 -0
  152. package/types/Secrets.js +2 -0
  153. package/types/developerTestAccounts.d.ts +13 -0
  154. package/types/developerTestAccounts.js +2 -0
  155. package/utils/PortManagerServer.d.ts +6 -7
  156. package/utils/PortManagerServer.js +22 -16
  157. package/utils/{getAccountIdentifier.d.ts → accounts.d.ts} +0 -6
  158. package/utils/{getAccountIdentifier.js → accounts.js} +1 -13
  159. package/utils/cms/fieldsJS.d.ts +1 -2
  160. package/utils/cms/modules.js +2 -2
  161. package/utils/detectPort.js +3 -3
  162. package/utils/git.d.ts +1 -7
  163. package/utils/git.js +2 -18
  164. package/utils/lang.d.ts +1 -5
  165. package/errors/apiErrors.d.ts +0 -19
  166. package/errors/apiErrors.js +0 -179
  167. package/errors/fileSystemErrors.d.ts +0 -5
  168. package/errors/fileSystemErrors.js +0 -31
  169. package/errors/standardErrors.d.ts +0 -27
  170. package/errors/standardErrors.js +0 -59
  171. package/lang/lang/en.json +0 -383
  172. package/lib/logging/git.d.ts +0 -2
  173. package/lib/logging/git.js +0 -54
  174. package/lib/logging/logs.d.ts +0 -22
  175. package/lib/logging/logs.js +0 -86
  176. package/lib/logging/table.d.ts +0 -3
  177. package/lib/logging/table.js +0 -47
  178. package/lib/sandboxes.d.ts +0 -14
  179. package/lib/sandboxes.js +0 -71
  180. package/models/HubSpotAuthError.d.ts +0 -12
  181. package/models/HubSpotAuthError.js +0 -20
  182. package/types/LogCallbacks.d.ts +0 -6
  183. package/utils/logger.d.ts +0 -11
  184. package/utils/logger.js +0 -23
  185. package/utils/objectUtils.d.ts +0 -8
  186. package/utils/objectUtils.js +0 -33
  187. /package/{utils → lib}/escapeRegExp.d.ts +0 -0
  188. /package/{utils → lib}/escapeRegExp.js +0 -0
  189. /package/lib/{logging/logger.js → logger.js} +0 -0
  190. /package/{utils → lib}/notify.d.ts +0 -0
  191. /package/types/{LogCallbacks.js → Apps.js} +0 -0
package/lib/hubdb.js CHANGED
@@ -9,11 +9,11 @@ const fs_extra_1 = __importDefault(require("fs-extra"));
9
9
  const prettier_1 = __importDefault(require("prettier"));
10
10
  const hubdb_1 = require("../api/hubdb");
11
11
  const path_2 = require("./path");
12
- const standardErrors_1 = require("../errors/standardErrors");
12
+ const lang_1 = require("../utils/lang");
13
13
  const i18nKey = 'lib.hubdb';
14
14
  function validateJsonPath(src) {
15
15
  if (path_1.default.extname(src) !== '.json') {
16
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.invalidJsonPath`);
16
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.invalidJsonPath`));
17
17
  }
18
18
  }
19
19
  function validateJsonFile(src) {
@@ -22,10 +22,12 @@ function validateJsonFile(src) {
22
22
  stats = fs_extra_1.default.statSync(src);
23
23
  }
24
24
  catch (err) {
25
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.invalidJsonFile`, { src }, err);
25
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.invalidJsonFile`, { src }), {
26
+ cause: err,
27
+ });
26
28
  }
27
29
  if (!stats.isFile()) {
28
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.invalidJsonFile`, { src });
30
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.invalidJsonFile`, { src }));
29
31
  }
30
32
  validateJsonPath(src);
31
33
  }
@@ -42,7 +44,7 @@ async function addRowsToHubDbTable(accountId, tableId, rows = []) {
42
44
  if (rowsToUpdate.length > 0) {
43
45
  await (0, hubdb_1.createRows)(accountId, tableId, rowsToUpdate);
44
46
  }
45
- const { rowCount } = await (0, hubdb_1.publishTable)(accountId, tableId);
47
+ const { data: { rowCount }, } = await (0, hubdb_1.publishTable)(accountId, tableId);
46
48
  return {
47
49
  tableId,
48
50
  rowCount,
@@ -53,7 +55,7 @@ async function createHubDbTable(accountId, src) {
53
55
  validateJsonFile(src);
54
56
  const table = fs_extra_1.default.readJsonSync(src);
55
57
  const { rows, ...schema } = table;
56
- const { id } = await (0, hubdb_1.createTable)(accountId, schema);
58
+ const { data: { id }, } = await (0, hubdb_1.createTable)(accountId, schema);
57
59
  return addRowsToHubDbTable(accountId, id, rows);
58
60
  }
59
61
  exports.createHubDbTable = createHubDbTable;
@@ -96,15 +98,15 @@ async function fetchAllRows(accountId, tableId) {
96
98
  let rows = [];
97
99
  let after = null;
98
100
  do {
99
- const response = await (0, hubdb_1.fetchRows)(accountId, tableId, after ? { after } : undefined);
100
- const { paging, results } = response;
101
+ const axiosResponse = await (0, hubdb_1.fetchRows)(accountId, tableId, after ? { after } : undefined);
102
+ const { paging, results } = axiosResponse.data;
101
103
  rows = rows.concat(results);
102
104
  after = paging && paging.next ? paging.next.after : null;
103
105
  } while (after !== null);
104
106
  return rows;
105
107
  }
106
108
  async function downloadHubDbTable(accountId, tableId, dest) {
107
- const table = await (0, hubdb_1.fetchTable)(accountId, tableId);
109
+ const { data: table } = await (0, hubdb_1.fetchTable)(accountId, tableId);
108
110
  dest = path_1.default.resolve((0, path_2.getCwd)(), dest || `${table.name}.hubdb.json`);
109
111
  if (fs_extra_1.default.pathExistsSync(dest)) {
110
112
  validateJsonFile(dest);
@@ -1,4 +1,4 @@
1
- import chalk from 'chalk';
1
+ import { Chalk } from 'chalk';
2
2
  export declare const LOG_LEVEL: {
3
3
  NONE: number;
4
4
  DEBUG: number;
@@ -10,14 +10,26 @@ export declare const LOG_LEVEL: {
10
10
  * Chalk styles for logger strings.
11
11
  */
12
12
  export declare const Styles: {
13
- debug: chalk.Chalk;
14
- log: chalk.Chalk;
15
- success: chalk.Chalk;
16
- info: chalk.Chalk;
17
- warn: chalk.Chalk;
18
- error: chalk.Chalk;
13
+ debug: Chalk & {
14
+ supportsColor: import("chalk").ColorSupport;
15
+ };
16
+ log: Chalk & {
17
+ supportsColor: import("chalk").ColorSupport;
18
+ };
19
+ success: Chalk & {
20
+ supportsColor: import("chalk").ColorSupport;
21
+ };
22
+ info: Chalk & {
23
+ supportsColor: import("chalk").ColorSupport;
24
+ };
25
+ warn: Chalk & {
26
+ supportsColor: import("chalk").ColorSupport;
27
+ };
28
+ error: Chalk & {
29
+ supportsColor: import("chalk").ColorSupport;
30
+ };
19
31
  };
20
- export declare function stylize(label: string, style: (...text: unknown[]) => string, args: any[]): any[];
32
+ export declare function stylize(label: string, style: Chalk, args: any[]): any[];
21
33
  export declare class Logger {
22
34
  error(...args: any[]): void;
23
35
  warn(...args: any[]): void;
@@ -7,7 +7,7 @@ exports.triggerNotify = void 0;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const moment_1 = __importDefault(require("moment"));
9
9
  const debounce_1 = __importDefault(require("debounce"));
10
- const standardErrors_1 = require("../errors/standardErrors");
10
+ const lang_1 = require("../utils/lang");
11
11
  const i18nKey = 'utils.notify';
12
12
  const notifyQueue = [];
13
13
  const notifyPromises = [];
@@ -37,7 +37,7 @@ function notifyFilePath(filePathToNotify, outputToWrite) {
37
37
  fs_1.default.appendFileSync(filePathToNotify, outputToWrite);
38
38
  }
39
39
  catch (e) {
40
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.filePath`, { filePath: filePathToNotify }, e);
40
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.filePath`, { filePath: filePathToNotify }), { cause: e });
41
41
  }
42
42
  }
43
43
  }
package/lib/oauth.d.ts CHANGED
@@ -1,7 +1,4 @@
1
- import OAuth2Manager from '../models/OAuth2Manager';
1
+ import { OAuth2Manager } from '../models/OAuth2Manager';
2
2
  import { FlatAccountFields } from '../types/Accounts';
3
- import { LogCallbacksArg } from '../types/LogCallbacks';
4
3
  export declare function getOauthManager(accountId: number, accountConfig: FlatAccountFields): OAuth2Manager | undefined;
5
- declare const addOauthToAccountConfigCallbackKeys: string[];
6
- export declare function addOauthToAccountConfig(oauth: OAuth2Manager, logCallbacks: LogCallbacksArg<typeof addOauthToAccountConfigCallbackKeys>): void;
7
- export {};
4
+ export declare function addOauthToAccountConfig(oauth: OAuth2Manager): void;
package/lib/oauth.js CHANGED
@@ -1,45 +1,34 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.addOauthToAccountConfig = exports.getOauthManager = void 0;
7
- const OAuth2Manager_1 = __importDefault(require("../models/OAuth2Manager"));
4
+ const OAuth2Manager_1 = require("../models/OAuth2Manager");
8
5
  const auth_1 = require("../constants/auth");
9
- const standardErrors_1 = require("../errors/standardErrors");
10
- const logger_1 = require("../utils/logger");
11
- const logger_2 = require("../utils/logger");
12
- const getAccountIdentifier_1 = require("../utils/getAccountIdentifier");
6
+ const logger_1 = require("./logger");
7
+ const getAccountIdentifier_1 = require("../config/getAccountIdentifier");
13
8
  const config_1 = require("../config");
9
+ const lang_1 = require("../utils/lang");
14
10
  const i18nKey = 'lib.oauth';
15
11
  const oauthManagers = new Map();
16
12
  function writeOauthTokenInfo(accountConfig) {
17
13
  const accountId = (0, getAccountIdentifier_1.getAccountIdentifier)(accountConfig);
18
- (0, logger_1.debug)(`${i18nKey}.writeTokenInfo`, { portalId: accountId || '' });
14
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.writeTokenInfo`, { portalId: accountId || '' }));
19
15
  (0, config_1.updateAccountConfig)(accountConfig);
20
16
  (0, config_1.writeConfig)();
21
17
  }
22
18
  function getOauthManager(accountId, accountConfig) {
23
19
  if (!oauthManagers.has(accountId)) {
24
- oauthManagers.set(accountId, OAuth2Manager_1.default.fromConfig(accountConfig, () => writeOauthTokenInfo(accountConfig)));
20
+ oauthManagers.set(accountId, OAuth2Manager_1.OAuth2Manager.fromConfig(accountConfig, () => writeOauthTokenInfo(accountConfig)));
25
21
  }
26
22
  return oauthManagers.get(accountId);
27
23
  }
28
24
  exports.getOauthManager = getOauthManager;
29
- const addOauthToAccountConfigCallbackKeys = ['init', 'success'];
30
- function addOauthToAccountConfig(oauth, logCallbacks) {
31
- const logger = (0, logger_2.makeTypedLogger)(logCallbacks);
32
- logger('init', `${i18nKey}.addOauthToAccountConfig.init`);
33
- try {
34
- (0, config_1.updateAccountConfig)({
35
- ...oauth.toObj(),
36
- authType: auth_1.AUTH_METHODS.oauth.value,
37
- });
38
- (0, config_1.writeConfig)();
39
- logger('success', `${i18nKey}.addOauthToAccountConfig.success`);
40
- }
41
- catch (err) {
42
- (0, standardErrors_1.throwError)(err);
43
- }
25
+ function addOauthToAccountConfig(oauth) {
26
+ logger_1.logger.log((0, lang_1.i18n)(`${i18nKey}.addOauthToAccountConfig.init`));
27
+ (0, config_1.updateAccountConfig)({
28
+ ...oauth.account,
29
+ authType: auth_1.AUTH_METHODS.oauth.value,
30
+ });
31
+ (0, config_1.writeConfig)();
32
+ logger_1.logger.success((0, lang_1.i18n)(`${i18nKey}.addOauthToAccountConfig.success`));
44
33
  }
45
34
  exports.addOauthToAccountConfig = addOauthToAccountConfig;
package/lib/path.d.ts CHANGED
@@ -9,3 +9,6 @@ export declare function getExt(filepath: string): string;
9
9
  export declare function getAllowedExtensions(allowList?: Array<string>): Set<string>;
10
10
  export declare function isAllowedExtension(filepath: string, allowList?: Array<string>): boolean;
11
11
  export declare function getAbsoluteFilePath(_path: string): string;
12
+ export declare function sanitizeFileName(fileName: string): string;
13
+ export declare function isValidPath(_path: string): boolean;
14
+ export declare function untildify(pathWithTilde: string): string;
package/lib/path.js CHANGED
@@ -3,10 +3,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getAbsoluteFilePath = exports.isAllowedExtension = exports.getAllowedExtensions = exports.getExt = exports.getCwd = exports.splitHubSpotPath = exports.splitLocalPath = exports.convertToLocalFileSystemPath = exports.convertToUnixPath = void 0;
6
+ exports.untildify = exports.isValidPath = exports.sanitizeFileName = exports.getAbsoluteFilePath = exports.isAllowedExtension = exports.getAllowedExtensions = exports.getExt = exports.getCwd = exports.splitHubSpotPath = exports.splitLocalPath = exports.convertToLocalFileSystemPath = exports.convertToUnixPath = void 0;
7
7
  const path_1 = __importDefault(require("path"));
8
8
  const unixify_1 = __importDefault(require("unixify"));
9
9
  const extensions_1 = require("../constants/extensions");
10
+ const os_1 = __importDefault(require("os"));
10
11
  function convertToUnixPath(_path) {
11
12
  return (0, unixify_1.default)(path_1.default.normalize(_path));
12
13
  }
@@ -87,3 +88,47 @@ function getAbsoluteFilePath(_path) {
87
88
  return path_1.default.resolve(getCwd(), _path);
88
89
  }
89
90
  exports.getAbsoluteFilePath = getAbsoluteFilePath;
91
+ // Reserved names (Windows specific)
92
+ const reservedNames = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
93
+ // Based on the node-sanitize-filename package: https://github.com/parshap/node-sanitize-filename/blob/master/index.js
94
+ function sanitizeFileName(fileName) {
95
+ // Windows invalid/control characters
96
+ // eslint-disable-next-line no-control-regex
97
+ const invalidChars = /[<>:"/|?*\x00-\x1F]/g;
98
+ //Replace invalid characters with dash
99
+ let sanitizedFileName = fileName.replace(invalidChars, '-');
100
+ // Removes trailing periods and spaces for Windows
101
+ sanitizedFileName = sanitizedFileName.replace(/[. ]+$/, '');
102
+ //Reserved names check for Windows
103
+ if (reservedNames.test(sanitizedFileName)) {
104
+ sanitizedFileName = `-${sanitizedFileName}`;
105
+ }
106
+ return sanitizedFileName;
107
+ }
108
+ exports.sanitizeFileName = sanitizeFileName;
109
+ // Based on the node-sanitize-filename package: https://github.com/parshap/node-sanitize-filename/blob/master/index.js
110
+ function isValidPath(_path) {
111
+ // Invalid characters excluding forward slash
112
+ // eslint-disable-next-line no-control-regex
113
+ const invalidChars = /[<>:"|?*\x00-\x1F]/;
114
+ const baseName = path_1.default.basename(_path);
115
+ if (invalidChars.test(baseName)) {
116
+ return false;
117
+ }
118
+ if (reservedNames.test(baseName)) {
119
+ return false;
120
+ }
121
+ return true;
122
+ }
123
+ exports.isValidPath = isValidPath;
124
+ // Based on the untildify package: https://github.com/sindresorhus/untildify/blob/main/index.js
125
+ function untildify(pathWithTilde) {
126
+ const homeDirectory = os_1.default.homedir();
127
+ if (typeof pathWithTilde !== 'string') {
128
+ throw new TypeError(`Expected a string, got ${typeof pathWithTilde}`);
129
+ }
130
+ return homeDirectory
131
+ ? pathWithTilde.replace(/^~(?=$|\/|\\)/, homeDirectory)
132
+ : pathWithTilde;
133
+ }
134
+ exports.untildify = untildify;
@@ -1,13 +1,10 @@
1
1
  import { CLIAccount } from '../types/Accounts';
2
2
  import { Environment } from '../types/Config';
3
- type AccessToken = {
4
- portalId: number;
5
- accessToken: string;
6
- expiresAt: string;
7
- scopeGroups: Array<string>;
8
- encodedOAuthRefreshToken: string;
9
- };
3
+ import { AccessToken } from '../types/Accounts';
10
4
  export declare function getAccessToken(personalAccessKey: string, env?: Environment, accountId?: number): Promise<AccessToken>;
11
- export declare function accessTokenForPersonalAccessKey(accountId: number): Promise<string | undefined>;
12
- export declare const updateConfigWithPersonalAccessKey: (personalAccessKey: string, env?: Environment, name?: string, makeDefault?: boolean) => Promise<CLIAccount | null>;
13
- export {};
5
+ export declare function accessTokenForPersonalAccessKey(accountId: number, forceRefresh?: boolean): Promise<string | undefined>;
6
+ export declare function enabledFeaturesForPersonalAccessKey(accountId: number): Promise<{
7
+ [key: string]: number;
8
+ } | undefined>;
9
+ export declare function scopesOnAccessToken(accountId: number): Promise<Array<string>>;
10
+ export declare function updateConfigWithAccessToken(token: AccessToken, personalAccessKey: string, env?: Environment, name?: string, makeDefault?: boolean): Promise<CLIAccount | null>;
@@ -3,44 +3,42 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.updateConfigWithPersonalAccessKey = exports.accessTokenForPersonalAccessKey = exports.getAccessToken = void 0;
6
+ exports.updateConfigWithAccessToken = exports.scopesOnAccessToken = exports.enabledFeaturesForPersonalAccessKey = exports.accessTokenForPersonalAccessKey = exports.getAccessToken = void 0;
7
7
  const moment_1 = __importDefault(require("moment"));
8
8
  const environments_1 = require("../constants/environments");
9
9
  const auth_1 = require("../constants/auth");
10
- const standardErrors_1 = require("../errors/standardErrors");
11
10
  const localDevAuth_1 = require("../api/localDevAuth");
12
11
  const sandboxHubs_1 = require("../api/sandboxHubs");
13
12
  const config_1 = require("../config");
13
+ const config_2 = require("../constants/config");
14
+ const developerTestAccounts_1 = require("../api/developerTestAccounts");
15
+ const logger_1 = require("./logger");
16
+ const CLIConfiguration_1 = require("../config/CLIConfiguration");
17
+ const lang_1 = require("../utils/lang");
18
+ const errors_1 = require("../errors");
14
19
  const i18nKey = 'lib.personalAccessKey';
15
20
  const refreshRequests = new Map();
16
21
  function getRefreshKey(personalAccessKey, expiration) {
17
22
  return `${personalAccessKey}-${expiration || 'fresh'}`;
18
23
  }
19
24
  async function getAccessToken(personalAccessKey, env = environments_1.ENVIRONMENTS.PROD, accountId) {
20
- let response;
21
- try {
22
- response = await (0, localDevAuth_1.fetchAccessToken)(personalAccessKey, env, accountId);
23
- }
24
- catch (e) {
25
- const error = e;
26
- if (error.response) {
27
- (0, standardErrors_1.throwAuthErrorWithMessage)(`${i18nKey}.errors.invalidPersonalAccessKey`, { errorMessage: error.response.data.message || '' }, error);
28
- }
29
- else {
30
- (0, standardErrors_1.throwError)(e);
31
- }
32
- }
25
+ const axiosResponse = await (0, localDevAuth_1.fetchAccessToken)(personalAccessKey, env, accountId);
26
+ const response = axiosResponse.data;
33
27
  return {
34
28
  portalId: response.hubId,
35
29
  accessToken: response.oauthAccessToken,
36
30
  expiresAt: (0, moment_1.default)(response.expiresAtMillis).toISOString(),
37
31
  scopeGroups: response.scopeGroups,
32
+ enabledFeatures: response.enabledFeatures,
38
33
  encodedOAuthRefreshToken: response.encodedOAuthRefreshToken,
34
+ hubName: response.hubName,
35
+ accountType: response.accountType,
39
36
  };
40
37
  }
41
38
  exports.getAccessToken = getAccessToken;
42
39
  async function refreshAccessToken(personalAccessKey, env = environments_1.ENVIRONMENTS.PROD, accountId) {
43
- const { accessToken, expiresAt } = await getAccessToken(personalAccessKey, env, accountId);
40
+ const accessTokenResponse = await getAccessToken(personalAccessKey, env, accountId);
41
+ const { accessToken, expiresAt } = accessTokenResponse;
44
42
  const config = (0, config_1.getAccountConfig)(accountId);
45
43
  (0, config_1.updateAccountConfig)({
46
44
  env,
@@ -52,20 +50,20 @@ async function refreshAccessToken(personalAccessKey, env = environments_1.ENVIRO
52
50
  },
53
51
  });
54
52
  (0, config_1.writeConfig)();
55
- return accessToken;
53
+ return accessTokenResponse;
56
54
  }
57
55
  async function getNewAccessToken(accountId, personalAccessKey, expiresAt, env) {
58
56
  const key = getRefreshKey(personalAccessKey, expiresAt);
59
57
  if (refreshRequests.has(key)) {
60
58
  return refreshRequests.get(key);
61
59
  }
62
- let accessToken;
60
+ let accessTokenResponse;
63
61
  try {
64
62
  const refreshAccessPromise = refreshAccessToken(personalAccessKey, env, accountId);
65
63
  if (key) {
66
64
  refreshRequests.set(key, refreshAccessPromise);
67
65
  }
68
- accessToken = await refreshAccessPromise;
66
+ accessTokenResponse = await refreshAccessPromise;
69
67
  }
70
68
  catch (e) {
71
69
  if (key) {
@@ -73,64 +71,93 @@ async function getNewAccessToken(accountId, personalAccessKey, expiresAt, env) {
73
71
  }
74
72
  throw e;
75
73
  }
76
- return accessToken;
74
+ return accessTokenResponse;
75
+ }
76
+ async function getNewAccessTokenByAccountId(accountId) {
77
+ const account = (0, config_1.getAccountConfig)(accountId);
78
+ if (!account) {
79
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.accountNotFound`, { accountId }));
80
+ }
81
+ const { auth, personalAccessKey, env } = account;
82
+ const accessTokenResponse = await getNewAccessToken(accountId, personalAccessKey, auth?.tokenInfo?.expiresAt, env);
83
+ return accessTokenResponse;
77
84
  }
78
- async function accessTokenForPersonalAccessKey(accountId) {
85
+ async function accessTokenForPersonalAccessKey(accountId, forceRefresh = false) {
79
86
  const account = (0, config_1.getAccountConfig)(accountId);
80
87
  if (!account) {
81
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.accountNotFound`, { accountId });
88
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.accountNotFound`, { accountId }));
82
89
  }
83
90
  const { auth, personalAccessKey, env } = account;
84
91
  const authTokenInfo = auth && auth.tokenInfo;
85
92
  const authDataExists = authTokenInfo && auth?.tokenInfo?.accessToken;
86
93
  if (!authDataExists ||
94
+ forceRefresh ||
87
95
  (0, moment_1.default)().add(5, 'minutes').isAfter((0, moment_1.default)(authTokenInfo.expiresAt))) {
88
- return getNewAccessToken(accountId, personalAccessKey, authTokenInfo && authTokenInfo.expiresAt, env);
96
+ return getNewAccessToken(accountId, personalAccessKey, authTokenInfo && authTokenInfo.expiresAt, env).then(tokenInfo => tokenInfo.accessToken);
89
97
  }
90
98
  return auth?.tokenInfo?.accessToken;
91
99
  }
92
100
  exports.accessTokenForPersonalAccessKey = accessTokenForPersonalAccessKey;
93
- // Adds an account to the config using authType: personalAccessKey
94
- const updateConfigWithPersonalAccessKey = async (personalAccessKey, env, name, makeDefault = false) => {
101
+ async function enabledFeaturesForPersonalAccessKey(accountId) {
102
+ const accessTokenResponse = await getNewAccessTokenByAccountId(accountId);
103
+ return accessTokenResponse?.enabledFeatures;
104
+ }
105
+ exports.enabledFeaturesForPersonalAccessKey = enabledFeaturesForPersonalAccessKey;
106
+ async function scopesOnAccessToken(accountId) {
107
+ return (await getNewAccessTokenByAccountId(accountId)).scopeGroups;
108
+ }
109
+ exports.scopesOnAccessToken = scopesOnAccessToken;
110
+ async function updateConfigWithAccessToken(token, personalAccessKey, env, name, makeDefault = false) {
111
+ const { portalId, accessToken, expiresAt, accountType } = token;
95
112
  const accountEnv = env || (0, config_1.getEnv)(name);
96
- let token;
113
+ let parentAccountId;
97
114
  try {
98
- token = await getAccessToken(personalAccessKey, accountEnv);
115
+ if (accountType === config_2.HUBSPOT_ACCOUNT_TYPES.STANDARD_SANDBOX ||
116
+ accountType === config_2.HUBSPOT_ACCOUNT_TYPES.DEVELOPMENT_SANDBOX) {
117
+ const { data: sandboxDataResponse } = await (0, sandboxHubs_1.fetchSandboxHubData)(accessToken, portalId, accountEnv);
118
+ if (sandboxDataResponse.parentHubId) {
119
+ parentAccountId = sandboxDataResponse.parentHubId;
120
+ }
121
+ }
99
122
  }
100
123
  catch (err) {
101
- (0, standardErrors_1.throwError)(err);
124
+ // Log error but do not throw
125
+ if ((0, errors_1.isHubSpotHttpError)(err)) {
126
+ logger_1.logger.debug(err.message);
127
+ }
128
+ logger_1.logger.debug(err);
102
129
  }
103
- const { portalId, accessToken, expiresAt } = token;
104
- let hubInfo;
105
130
  try {
106
- hubInfo = await (0, sandboxHubs_1.fetchSandboxHubData)(accessToken, portalId, accountEnv);
131
+ if (accountType === config_2.HUBSPOT_ACCOUNT_TYPES.DEVELOPER_TEST) {
132
+ const { data: developerTestAccountResponse } = await (0, developerTestAccounts_1.fetchDeveloperTestAccountData)(accessToken, portalId, accountEnv);
133
+ if (developerTestAccountResponse) {
134
+ parentAccountId = developerTestAccountResponse.parentPortalId;
135
+ }
136
+ }
107
137
  }
108
138
  catch (err) {
109
- // Ignore error, returns 404 if account is not a sandbox
110
- }
111
- let sandboxAccountType = null;
112
- let parentAccountId = null;
113
- if (hubInfo) {
114
- if (hubInfo.type !== undefined) {
115
- sandboxAccountType = hubInfo.type === null ? 'STANDARD' : hubInfo.type;
116
- }
117
- if (hubInfo.parentHubId) {
118
- parentAccountId = hubInfo.parentHubId;
139
+ // Log error but do not throw
140
+ if ((0, errors_1.isHubSpotHttpError)(err)) {
141
+ logger_1.logger.debug(err.message);
119
142
  }
143
+ logger_1.logger.debug(err);
120
144
  }
121
- const updatedConfig = (0, config_1.updateAccountConfig)({
145
+ const updatedAccount = (0, config_1.updateAccountConfig)({
122
146
  accountId: portalId,
147
+ accountType,
123
148
  personalAccessKey,
124
149
  name,
125
150
  authType: auth_1.PERSONAL_ACCESS_KEY_AUTH_METHOD.value,
126
151
  tokenInfo: { accessToken, expiresAt },
127
- sandboxAccountType,
128
152
  parentAccountId,
153
+ env: accountEnv,
129
154
  });
130
- (0, config_1.writeConfig)();
155
+ if (!CLIConfiguration_1.CLIConfiguration.isActive()) {
156
+ (0, config_1.writeConfig)();
157
+ }
131
158
  if (makeDefault && name) {
132
159
  (0, config_1.updateDefaultAccount)(name);
133
160
  }
134
- return updatedConfig;
135
- };
136
- exports.updateConfigWithPersonalAccessKey = updateConfigWithPersonalAccessKey;
161
+ return updatedAccount;
162
+ }
163
+ exports.updateConfigWithAccessToken = updateConfigWithAccessToken;
@@ -1,13 +1,11 @@
1
+ import { RequestPortsData } from '../types/PortManager';
1
2
  export declare const BASE_URL: string;
3
+ export declare function isPortManagerPortAvailable(): Promise<boolean>;
4
+ export declare function isPortManagerServerRunning(): Promise<boolean>;
2
5
  export declare function startPortManagerServer(): Promise<void>;
3
6
  export declare function stopPortManagerServer(): Promise<void>;
4
- type RequestPortsData = {
5
- instanceId: string;
6
- port?: number;
7
- };
8
7
  export declare function requestPorts(portData: Array<RequestPortsData>): Promise<{
9
8
  [instanceId: string]: number;
10
9
  }>;
11
10
  export declare function deleteServerInstance(serverInstanceId: string): Promise<void>;
12
11
  export declare function portManagerHasActiveServers(): Promise<boolean>;
13
- export {};
@@ -3,20 +3,32 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.portManagerHasActiveServers = exports.deleteServerInstance = exports.requestPorts = exports.stopPortManagerServer = exports.startPortManagerServer = exports.BASE_URL = void 0;
6
+ exports.portManagerHasActiveServers = exports.deleteServerInstance = exports.requestPorts = exports.stopPortManagerServer = exports.startPortManagerServer = exports.isPortManagerServerRunning = exports.isPortManagerPortAvailable = exports.BASE_URL = void 0;
7
7
  const axios_1 = __importDefault(require("axios"));
8
- const PortManagerServer_1 = __importDefault(require("../utils/PortManagerServer"));
9
- const detectPort_1 = require("../utils/detectPort");
8
+ const PortManagerServer_1 = require("../utils/PortManagerServer");
10
9
  const ports_1 = require("../constants/ports");
10
+ const detectPort_1 = require("../utils/detectPort");
11
+ const logger_1 = require("./logger");
11
12
  exports.BASE_URL = `http://localhost:${ports_1.PORT_MANAGER_SERVER_PORT}`;
13
+ async function isPortManagerPortAvailable() {
14
+ return ((await (0, detectPort_1.detectPort)(ports_1.PORT_MANAGER_SERVER_PORT)) === ports_1.PORT_MANAGER_SERVER_PORT);
15
+ }
16
+ exports.isPortManagerPortAvailable = isPortManagerPortAvailable;
12
17
  async function isPortManagerServerRunning() {
13
- const port = await (0, detectPort_1.detectPort)(ports_1.PORT_MANAGER_SERVER_PORT);
14
- return port !== ports_1.PORT_MANAGER_SERVER_PORT;
18
+ try {
19
+ const { data } = await axios_1.default.get(`${exports.BASE_URL}${PortManagerServer_1.HEALTH_CHECK_PATH}`);
20
+ return data.status === PortManagerServer_1.SERVICE_HEALTHY;
21
+ }
22
+ catch (e) {
23
+ logger_1.logger.debug(e);
24
+ return false;
25
+ }
15
26
  }
27
+ exports.isPortManagerServerRunning = isPortManagerServerRunning;
16
28
  async function startPortManagerServer() {
17
29
  const isRunning = await isPortManagerServerRunning();
18
30
  if (!isRunning) {
19
- await PortManagerServer_1.default.init();
31
+ await PortManagerServer_1.PortManagerServer.init();
20
32
  }
21
33
  }
22
34
  exports.startPortManagerServer = startPortManagerServer;
package/lib/text.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export declare function commaSeparatedValues(arr: Array<string>, conjunction?: null | string, ifempty?: string): string;
2
+ export declare function toKebabCase(str: string): string;
package/lib/text.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.commaSeparatedValues = void 0;
3
+ exports.toKebabCase = exports.commaSeparatedValues = void 0;
4
4
  function commaSeparatedValues(arr, conjunction = 'and', ifempty = '') {
5
5
  const l = arr.length;
6
6
  if (!l)
@@ -14,3 +14,11 @@ function commaSeparatedValues(arr, conjunction = 'and', ifempty = '') {
14
14
  return arr.join(', ');
15
15
  }
16
16
  exports.commaSeparatedValues = commaSeparatedValues;
17
+ function toKebabCase(str) {
18
+ return (str
19
+ .replace(/[.,/#!$%^&*;:{}=\-_'"`~()]/g, '')
20
+ .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) || [])
21
+ .join('-')
22
+ .toLowerCase();
23
+ }
24
+ exports.toKebabCase = toKebabCase;
package/lib/trackUsage.js CHANGED
@@ -6,10 +6,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.trackUsage = void 0;
7
7
  const axios_1 = __importDefault(require("axios"));
8
8
  const getAxiosConfig_1 = require("../http/getAxiosConfig");
9
- const logger_1 = require("../utils/logger");
10
- const http_1 = __importDefault(require("../http"));
9
+ const logger_1 = require("./logger");
10
+ const http_1 = require("../http");
11
11
  const config_1 = require("../config");
12
12
  const fileMapper_1 = require("../api/fileMapper");
13
+ const lang_1 = require("../utils/lang");
13
14
  const i18nKey = 'lib.trackUsage';
14
15
  async function trackUsage(eventName, eventClass, meta = {}, accountId) {
15
16
  const usageEvent = {
@@ -31,17 +32,23 @@ async function trackUsage(eventName, eventClass, meta = {}, accountId) {
31
32
  analyticsEndpoint = 'vscode-extension-usage';
32
33
  break;
33
34
  default:
34
- (0, logger_1.debug)(`${i18nKey}.invalidEvent`, { eventName });
35
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.invalidEvent`, { eventName }));
35
36
  }
36
37
  const path = `${fileMapper_1.FILE_MAPPER_API_PATH}/${analyticsEndpoint}`;
37
38
  const accountConfig = accountId && (0, config_1.getAccountConfig)(accountId);
38
39
  if (accountConfig && accountConfig.authType === 'personalaccesskey') {
39
- (0, logger_1.debug)(`${i18nKey}.sendingEventAuthenticated`);
40
- return http_1.default.post(accountId, {
41
- url: `${path}/authenticated`,
42
- data: usageEvent,
43
- resolveWithFullResponse: true,
44
- });
40
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.sendingEventAuthenticated`));
41
+ try {
42
+ await http_1.http.post(accountId, {
43
+ url: `${path}/authenticated`,
44
+ data: usageEvent,
45
+ resolveWithFullResponse: true,
46
+ });
47
+ return;
48
+ }
49
+ catch (e) {
50
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.retryingEventUnauthenticated`));
51
+ }
45
52
  }
46
53
  const env = (0, config_1.getEnv)(accountId);
47
54
  const axiosConfig = (0, getAxiosConfig_1.getAxiosConfig)({
@@ -50,7 +57,7 @@ async function trackUsage(eventName, eventClass, meta = {}, accountId) {
50
57
  data: usageEvent,
51
58
  resolveWithFullResponse: true,
52
59
  });
53
- (0, logger_1.debug)(`${i18nKey}.sendingEventUnauthenticated`);
54
- (0, axios_1.default)({ ...axiosConfig, method: 'post' });
60
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.sendingEventUnauthenticated`));
61
+ return (0, axios_1.default)({ ...axiosConfig, method: 'post' });
55
62
  }
56
63
  exports.trackUsage = trackUsage;
package/lib/urls.js CHANGED
@@ -11,7 +11,11 @@ function getEnvUrlString(env) {
11
11
  const getHubSpotWebsiteOrigin = (env) => `https://app.hubspot${getEnvUrlString(env)}.com`;
12
12
  exports.getHubSpotWebsiteOrigin = getHubSpotWebsiteOrigin;
13
13
  function getHubSpotApiOrigin(env, useLocalHost) {
14
- let domain = process.env.HUBAPI_DOMAIN_OVERRIDE;
14
+ let domain;
15
+ const domainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
16
+ if (domainOverride && typeof domainOverride === 'string') {
17
+ domain = `${domainOverride}${getEnvUrlString(env)}`;
18
+ }
15
19
  if (!domain || typeof domain !== 'string') {
16
20
  domain = `${useLocalHost ? 'local' : 'api'}.hubapi${getEnvUrlString(env)}`;
17
21
  }