@hubspot/local-dev-lib 0.0.4 → 0.0.6

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 (178) hide show
  1. package/api/customObjects.d.ts +7 -0
  2. package/api/customObjects.js +48 -0
  3. package/api/designManager.d.ts +13 -0
  4. package/api/designManager.js +21 -0
  5. package/api/fileManager.d.ts +5 -0
  6. package/api/fileManager.js +62 -0
  7. package/api/fileMapper.d.ts +10 -0
  8. package/api/fileMapper.js +104 -0
  9. package/api/functions.d.ts +4 -0
  10. package/api/functions.js +32 -0
  11. package/api/hubdb.d.ts +10 -0
  12. package/api/hubdb.js +61 -0
  13. package/api/lighthouseScore.d.ts +5 -0
  14. package/api/lighthouseScore.js +29 -0
  15. package/api/localDevAuth.d.ts +12 -0
  16. package/api/localDevAuth.js +38 -0
  17. package/api/marketplaceValidation.d.ts +5 -0
  18. package/api/marketplaceValidation.js +29 -0
  19. package/api/projects.d.ts +27 -0
  20. package/api/projects.js +126 -0
  21. package/api/sandboxHubs.d.ts +6 -0
  22. package/api/sandboxHubs.js +50 -0
  23. package/api/sandboxSync.d.ts +4 -0
  24. package/api/sandboxSync.js +35 -0
  25. package/api/secrets.d.ts +8 -0
  26. package/api/secrets.js +40 -0
  27. package/api/validateHubl.d.ts +2 -0
  28. package/api/validateHubl.js +18 -0
  29. package/config/CLIConfiguration.d.ts +22 -16
  30. package/config/CLIConfiguration.js +39 -9
  31. package/config/configFile.d.ts +4 -4
  32. package/config/configFile.js +2 -2
  33. package/config/configUtils.d.ts +8 -8
  34. package/config/config_DEPRECATED.d.ts +78 -0
  35. package/config/config_DEPRECATED.js +636 -0
  36. package/config/environment.d.ts +2 -3
  37. package/config/environment.js +11 -17
  38. package/config/index.d.ts +38 -0
  39. package/config/index.js +232 -0
  40. package/constants/api.d.ts +17 -0
  41. package/constants/api.js +20 -0
  42. package/constants/auth.d.ts +13 -0
  43. package/constants/auth.js +8 -1
  44. package/constants/config.d.ts +0 -4
  45. package/constants/config.js +1 -5
  46. package/constants/environments.d.ts +1 -0
  47. package/constants/environments.js +1 -0
  48. package/constants/extensions.d.ts +2 -0
  49. package/constants/extensions.js +4 -1
  50. package/constants/files.d.ts +16 -0
  51. package/constants/files.js +17 -1
  52. package/enums/build.d.ts +36 -0
  53. package/enums/build.js +39 -0
  54. package/enums/deploy.d.ts +11 -0
  55. package/enums/deploy.js +14 -0
  56. package/enums/project.d.ts +6 -0
  57. package/enums/project.js +9 -0
  58. package/errors/HubSpotAuthError.d.ts +8 -2
  59. package/errors/HubSpotAuthError.js +14 -0
  60. package/errors/apiErrors.d.ts +9 -0
  61. package/errors/apiErrors.js +182 -0
  62. package/errors/errors_DEPRECATED.d.ts +7 -0
  63. package/errors/errors_DEPRECATED.js +73 -0
  64. package/errors/fileSystemErrors.d.ts +1 -7
  65. package/errors/standardErrors.d.ts +7 -1
  66. package/errors/standardErrors.js +20 -23
  67. package/http/getAxiosConfig.d.ts +6 -0
  68. package/http/getAxiosConfig.js +22 -0
  69. package/http/index.d.ts +18 -0
  70. package/http/index.js +175 -0
  71. package/lang/en.lyaml +247 -0
  72. package/lib/cms/functions.d.ts +13 -0
  73. package/lib/cms/functions.js +181 -0
  74. package/lib/cms/handleFieldsJS.d.ts +2 -1
  75. package/lib/cms/handleFieldsJS.js +4 -3
  76. package/lib/cms/modules.js +3 -3
  77. package/lib/cms/processFieldsJs.d.ts +1 -0
  78. package/lib/cms/processFieldsJs.js +122 -0
  79. package/lib/cms/templates.d.ts +25 -0
  80. package/lib/cms/templates.js +62 -0
  81. package/lib/cms/themes.js +2 -2
  82. package/lib/cms/uploadFolder.d.ts +18 -0
  83. package/lib/cms/uploadFolder.js +182 -0
  84. package/lib/cms/watch.d.ts +20 -0
  85. package/lib/cms/watch.js +194 -0
  86. package/lib/customObjects.d.ts +5 -0
  87. package/lib/customObjects.js +36 -0
  88. package/lib/environment.d.ts +2 -1
  89. package/lib/fileMapper.d.ts +13 -0
  90. package/lib/fileMapper.js +322 -0
  91. package/lib/github.d.ts +6 -3
  92. package/lib/github.js +36 -27
  93. package/lib/gitignore.js +1 -46
  94. package/lib/hubdb.d.ts +16 -0
  95. package/lib/hubdb.js +130 -0
  96. package/lib/ignoreRules.d.ts +3 -0
  97. package/lib/ignoreRules.js +69 -0
  98. package/lib/logging/git.d.ts +2 -0
  99. package/lib/logging/git.js +54 -0
  100. package/lib/logging/logger.d.ts +44 -0
  101. package/lib/logging/logger.js +146 -0
  102. package/lib/logging/logs.d.ts +22 -0
  103. package/lib/logging/logs.js +82 -0
  104. package/lib/logging/table.d.ts +3 -0
  105. package/lib/logging/table.js +47 -0
  106. package/lib/oauth.d.ts +7 -0
  107. package/lib/oauth.js +44 -0
  108. package/lib/path.d.ts +2 -1
  109. package/lib/path.js +8 -3
  110. package/lib/personalAccessKey.d.ts +13 -0
  111. package/lib/personalAccessKey.js +135 -0
  112. package/lib/sandboxes.d.ts +14 -0
  113. package/lib/sandboxes.js +71 -0
  114. package/lib/trackUsage.d.ts +1 -0
  115. package/lib/trackUsage.js +53 -0
  116. package/lib/validate.d.ts +2 -0
  117. package/lib/validate.js +40 -0
  118. package/models/OAuth2Manager.d.ts +34 -0
  119. package/models/OAuth2Manager.js +126 -0
  120. package/package.json +25 -13
  121. package/types/Accounts.d.ts +66 -21
  122. package/types/Activity.d.ts +20 -0
  123. package/types/Activity.js +2 -0
  124. package/types/Api.d.ts +2 -0
  125. package/types/Api.js +2 -0
  126. package/types/Build.d.ts +41 -0
  127. package/types/Build.js +2 -0
  128. package/types/CLIOptions.d.ts +5 -0
  129. package/types/ComponentStructure.d.ts +20 -0
  130. package/types/ComponentStructure.js +2 -0
  131. package/types/Config.d.ts +17 -4
  132. package/types/Deploy.d.ts +42 -0
  133. package/types/Deploy.js +2 -0
  134. package/types/Error.d.ts +32 -7
  135. package/types/FileManager.d.ts +66 -0
  136. package/types/FileManager.js +2 -0
  137. package/types/Files.d.ts +33 -1
  138. package/types/Functions.d.ts +40 -0
  139. package/types/Functions.js +2 -0
  140. package/types/Github.d.ts +6 -0
  141. package/types/Http.d.ts +33 -0
  142. package/types/Http.js +2 -0
  143. package/types/Hubdb.d.ts +90 -0
  144. package/types/Hubdb.js +2 -0
  145. package/types/HublValidation.d.ts +59 -0
  146. package/types/HublValidation.js +2 -0
  147. package/types/Lighthouse.d.ts +25 -0
  148. package/types/Lighthouse.js +2 -0
  149. package/types/MarketplaceValidation.d.ts +28 -0
  150. package/types/MarketplaceValidation.js +2 -0
  151. package/types/Project.d.ts +38 -0
  152. package/types/Project.js +2 -0
  153. package/types/Sandbox.d.ts +165 -0
  154. package/types/Sandbox.js +2 -0
  155. package/types/Schemas.d.ts +42 -0
  156. package/types/Schemas.js +2 -0
  157. package/utils/{modules.d.ts → cms/modules.d.ts} +1 -1
  158. package/utils/{modules.js → cms/modules.js} +3 -3
  159. package/utils/getAccountIdentifier.d.ts +10 -0
  160. package/utils/getAccountIdentifier.js +40 -0
  161. package/utils/git.d.ts +7 -2
  162. package/utils/git.js +54 -7
  163. package/utils/lang.d.ts +4 -0
  164. package/utils/lang.js +9 -2
  165. package/utils/notify.d.ts +1 -0
  166. package/utils/notify.js +42 -0
  167. package/utils/objectUtils.d.ts +8 -0
  168. package/utils/objectUtils.js +33 -0
  169. package/constants/index.d.ts +0 -16
  170. package/constants/index.js +0 -12
  171. package/http/requestOptions.d.ts +0 -20
  172. package/http/requestOptions.js +0 -27
  173. package/lib/cms/index.d.ts +0 -10
  174. package/lib/cms/index.js +0 -13
  175. package/lib/index.d.ts +0 -11
  176. package/lib/index.js +0 -14
  177. /package/utils/{fieldsJS.d.ts → cms/fieldsJS.d.ts} +0 -0
  178. /package/utils/{fieldsJS.js → cms/fieldsJS.js} +0 -0
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.throwApiUploadError = exports.throwApiError = exports.throwApiStatusCodeError = exports.throwStatusCodeError = exports.isSpecifiedHubSpotAuthError = exports.isGatingError = exports.isMissingScopeError = void 0;
4
+ const api_1 = require("../constants/api");
5
+ const lang_1 = require("../utils/lang");
6
+ const standardErrors_1 = require("./standardErrors");
7
+ function isApiStatusCodeError(err) {
8
+ return (err.name === 'StatusCodeError' ||
9
+ (err.statusCode && err.statusCode >= 100 && err.statusCode < 600));
10
+ }
11
+ function isMissingScopeError(err) {
12
+ return Boolean(err.name === 'StatusCodeError' &&
13
+ err.statusCode === 403 &&
14
+ err.error &&
15
+ err.error.category === 'MISSING_SCOPES');
16
+ }
17
+ exports.isMissingScopeError = isMissingScopeError;
18
+ function isGatingError(err) {
19
+ return Boolean(err.name === 'StatusCodeError' &&
20
+ err.statusCode === 403 &&
21
+ err.error &&
22
+ err.error.category === 'GATED');
23
+ }
24
+ exports.isGatingError = isGatingError;
25
+ function isApiUploadValidationError(err) {
26
+ return Boolean(err.statusCode === 400 &&
27
+ err.response &&
28
+ err.response.body &&
29
+ (err.response.body.message || err.response.body.errors));
30
+ }
31
+ function isSpecifiedHubSpotAuthError(err, { statusCode, category, subCategory }) {
32
+ const statusCodeErr = !statusCode || err.statusCode === statusCode;
33
+ const categoryErr = !category || err.category === category;
34
+ const subCategoryErr = !subCategory || err.subCategory === subCategory;
35
+ return (err.name === 'HubSpotAuthError' &&
36
+ statusCodeErr &&
37
+ categoryErr &&
38
+ subCategoryErr);
39
+ }
40
+ exports.isSpecifiedHubSpotAuthError = isSpecifiedHubSpotAuthError;
41
+ function parseValidationErrors(responseBody = { errors: [], message: '' }) {
42
+ const errorMessages = [];
43
+ const { errors, message } = responseBody;
44
+ if (message) {
45
+ errorMessages.push(message);
46
+ }
47
+ if (errors) {
48
+ const specificErrors = errors.map(error => {
49
+ let errorMessage = error.message;
50
+ if (error.errorTokens && error.errorTokens.line) {
51
+ errorMessage = `line ${error.errorTokens.line}: ${errorMessage}`;
52
+ }
53
+ return errorMessage;
54
+ });
55
+ errorMessages.push(...specificErrors);
56
+ }
57
+ return errorMessages;
58
+ }
59
+ function logValidationErrors(error) {
60
+ const { response = { body: undefined } } = error;
61
+ const validationErrorMessages = parseValidationErrors(response.body);
62
+ if (validationErrorMessages.length) {
63
+ (0, standardErrors_1.throwError)(new Error(validationErrorMessages.join(' '), { cause: error }));
64
+ }
65
+ }
66
+ function throwStatusCodeError(error, context = {}) {
67
+ const { statusCode, message, response } = error;
68
+ const errorData = JSON.stringify({
69
+ statusCode,
70
+ message,
71
+ url: response.request.href,
72
+ method: response.request.method,
73
+ response: response.body,
74
+ headers: response.headers,
75
+ context,
76
+ });
77
+ throw new Error(errorData, { cause: error });
78
+ }
79
+ exports.throwStatusCodeError = throwStatusCodeError;
80
+ function throwApiStatusCodeError(error, context) {
81
+ const i18nKey = 'errors.api';
82
+ const { statusCode } = error;
83
+ const { method } = error.options || {};
84
+ const { projectName } = context;
85
+ const isPutOrPost = method === 'PUT' || method === 'POST';
86
+ const action = method && (api_1.HTTP_METHOD_VERBS[method] || api_1.HTTP_METHOD_VERBS.DEFAULT);
87
+ const preposition = (method && api_1.HTTP_METHOD_PREPOSITIONS[method]) ||
88
+ api_1.HTTP_METHOD_PREPOSITIONS.DEFAULT;
89
+ const request = context.request
90
+ ? `${action} ${preposition} "${context.request}"`
91
+ : action;
92
+ const messageDetail = request && context.accountId
93
+ ? (0, lang_1.i18n)(`${i18nKey}.messageDetail`, {
94
+ request,
95
+ accountId: context.accountId,
96
+ })
97
+ : 'request';
98
+ const errorMessage = [];
99
+ if (isPutOrPost && context.payload) {
100
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.unableToUpload`, { payload: context.payload }));
101
+ }
102
+ const isProjectMissingScopeError = isMissingScopeError(error) && projectName;
103
+ const isProjectGatingError = isGatingError(error) && projectName;
104
+ switch (statusCode) {
105
+ case 400:
106
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.400`, { messageDetail }));
107
+ break;
108
+ case 401:
109
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.401`, { messageDetail }));
110
+ break;
111
+ case 403:
112
+ if (isProjectMissingScopeError) {
113
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.403MissingScope`, {
114
+ accountId: context.accountId || '',
115
+ }));
116
+ }
117
+ else if (isProjectGatingError) {
118
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.403Gating`, {
119
+ accountId: context.accountId || '',
120
+ }));
121
+ }
122
+ else {
123
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.403`, { messageDetail }));
124
+ }
125
+ break;
126
+ case 404:
127
+ if (context.request) {
128
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.404Request`, {
129
+ action: action || 'request',
130
+ request: context.request,
131
+ account: context.accountId || '',
132
+ }));
133
+ }
134
+ else {
135
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.404`, { messageDetail }));
136
+ }
137
+ break;
138
+ case 429:
139
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.429`, { messageDetail }));
140
+ break;
141
+ case 503:
142
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.503`, { messageDetail }));
143
+ break;
144
+ default:
145
+ if (statusCode && statusCode >= 500 && statusCode < 600) {
146
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.500Generic`, { messageDetail }));
147
+ }
148
+ else if (statusCode && statusCode >= 400 && statusCode < 500) {
149
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.400Generic`, { messageDetail }));
150
+ }
151
+ else {
152
+ errorMessage.push((0, lang_1.i18n)(`${i18nKey}.codes.generic`, { messageDetail }));
153
+ }
154
+ break;
155
+ }
156
+ if (error?.error?.message &&
157
+ !isProjectMissingScopeError &&
158
+ !isProjectGatingError) {
159
+ errorMessage.push(error.error.message);
160
+ }
161
+ if (error.error && error.error.errors) {
162
+ error.error.errors.forEach(err => {
163
+ errorMessage.push('\n- ' + err.message);
164
+ });
165
+ }
166
+ (0, standardErrors_1.throwError)(new Error(errorMessage.join(' '), { cause: error }));
167
+ }
168
+ exports.throwApiStatusCodeError = throwApiStatusCodeError;
169
+ function throwApiError(error, context) {
170
+ if (isApiStatusCodeError(error)) {
171
+ throwApiStatusCodeError(error, context);
172
+ }
173
+ (0, standardErrors_1.throwError)(error);
174
+ }
175
+ exports.throwApiError = throwApiError;
176
+ function throwApiUploadError(error, context) {
177
+ if (isApiUploadValidationError(error)) {
178
+ logValidationErrors(error);
179
+ }
180
+ throwApiError(error, context);
181
+ }
182
+ exports.throwApiUploadError = throwApiUploadError;
@@ -0,0 +1,7 @@
1
+ import { BaseError, FileSystemErrorContext } from '../types/Error';
2
+ type ErrorContext = {
3
+ accountId?: number;
4
+ };
5
+ export declare function logErrorInstance(error: BaseError, context?: ErrorContext): void;
6
+ export declare function logFileSystemErrorInstance(error: BaseError, context: FileSystemErrorContext): void;
7
+ export {};
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.logFileSystemErrorInstance = exports.logErrorInstance = void 0;
4
+ function isSystemError(err) {
5
+ return err.errno != null && err.code != null && err.syscall != null;
6
+ }
7
+ function debugErrorAndContext(error, context) {
8
+ if (error.name === 'StatusCodeError') {
9
+ const { statusCode, message, response } = error;
10
+ console.debug('Error: %o', {
11
+ statusCode,
12
+ message,
13
+ url: response.request.href,
14
+ method: response.request.method,
15
+ response: response.body,
16
+ headers: response.headers,
17
+ });
18
+ }
19
+ else {
20
+ console.debug('Error: %o', error);
21
+ }
22
+ console.debug('Context: %o', context);
23
+ }
24
+ function logErrorInstance(error, context) {
25
+ // SystemError
26
+ if (isSystemError(error)) {
27
+ console.error(`A system error has occurred: ${error.message}`);
28
+ debugErrorAndContext(error, context);
29
+ return;
30
+ }
31
+ if (error instanceof Error ||
32
+ error.message ||
33
+ error.reason) {
34
+ // Error or Error subclass
35
+ const name = error.name || 'Error';
36
+ const message = [`A ${name} has occurred.`];
37
+ [error.message, error.reason].forEach(msg => {
38
+ if (msg) {
39
+ message.push(msg);
40
+ }
41
+ });
42
+ console.error(message.join(' '));
43
+ }
44
+ else {
45
+ // Unknown errors
46
+ console.error(`An unknown error has occurred.`);
47
+ }
48
+ debugErrorAndContext(error, context);
49
+ }
50
+ exports.logErrorInstance = logErrorInstance;
51
+ function logFileSystemErrorInstance(error, context) {
52
+ let fileAction = '';
53
+ if (context.read) {
54
+ fileAction = 'reading from';
55
+ }
56
+ else if (context.write) {
57
+ fileAction = 'writing to';
58
+ }
59
+ else {
60
+ fileAction = 'accessing';
61
+ }
62
+ const filepath = context.filepath
63
+ ? `"${context.filepath}"`
64
+ : 'a file or folder';
65
+ const message = [`An error occurred while ${fileAction} ${filepath}.`];
66
+ // Many `fs` errors will be `SystemError`s
67
+ if (isSystemError(error)) {
68
+ message.push(`This is the result of a system error: ${error.message}`);
69
+ }
70
+ console.error(message.join(' '));
71
+ debugErrorAndContext(error, context);
72
+ }
73
+ exports.logFileSystemErrorInstance = logFileSystemErrorInstance;
@@ -1,8 +1,2 @@
1
- import { BaseError } from '../types/Error';
2
- type FileSystemErrorContext = {
3
- filepath: string;
4
- write?: boolean;
5
- read?: boolean;
6
- };
1
+ import { BaseError, FileSystemErrorContext } from '../types/Error';
7
2
  export declare function throwFileSystemError(error: BaseError, context: FileSystemErrorContext): void;
8
- export {};
@@ -1,4 +1,4 @@
1
- import { BaseError } from '../types/Error';
1
+ import { BaseError, StatusCodeError } from '../types/Error';
2
2
  export declare function isSystemError(err: BaseError): boolean;
3
3
  export declare function isFatalError(err: BaseError): boolean;
4
4
  /**
@@ -13,6 +13,12 @@ export declare function throwErrorWithMessage(identifier: string, interpolation?
13
13
  export declare function throwTypeErrorWithMessage(identifier: string, interpolation?: {
14
14
  [key: string]: string | number;
15
15
  }, cause?: BaseError): never;
16
+ /**
17
+ * @throws
18
+ */
19
+ export declare function throwAuthErrorWithMessage(identifier: string, interpolation?: {
20
+ [key: string]: string | number;
21
+ }, cause?: StatusCodeError): never;
16
22
  /**
17
23
  * @throws
18
24
  */
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.throwError = exports.throwTypeErrorWithMessage = exports.throwErrorWithMessage = exports.isFatalError = exports.isSystemError = void 0;
3
+ exports.throwError = exports.throwAuthErrorWithMessage = exports.throwTypeErrorWithMessage = exports.throwErrorWithMessage = exports.isFatalError = exports.isSystemError = void 0;
4
4
  const HubSpotAuthError_1 = require("./HubSpotAuthError");
5
5
  const lang_1 = require("../utils/lang");
6
+ const apiErrors_1 = require("./apiErrors");
6
7
  function isSystemError(err) {
7
8
  return err.errno != null && err.code != null && err.syscall != null;
8
9
  }
@@ -11,46 +12,42 @@ function isFatalError(err) {
11
12
  return err instanceof HubSpotAuthError_1.HubSpotAuthError;
12
13
  }
13
14
  exports.isFatalError = isFatalError;
15
+ function genericThrowErrorWithMessage(ErrorType, identifier, interpolation, cause) {
16
+ const message = (0, lang_1.i18n)(`errors.${identifier}`, interpolation);
17
+ if (cause) {
18
+ throw new ErrorType(message, { cause });
19
+ }
20
+ throw new ErrorType(message);
21
+ }
14
22
  /**
15
23
  * @throws
16
24
  */
17
25
  function throwErrorWithMessage(identifier, interpolation, cause) {
18
- const message = (0, lang_1.i18n)(`errors.${identifier}`, interpolation);
19
- if (cause) {
20
- throw new Error(message, { cause });
21
- }
22
- throw new Error(message);
26
+ genericThrowErrorWithMessage(Error, identifier, interpolation, cause);
23
27
  }
24
28
  exports.throwErrorWithMessage = throwErrorWithMessage;
25
29
  /**
26
30
  * @throws
27
31
  */
28
32
  function throwTypeErrorWithMessage(identifier, interpolation, cause) {
29
- const message = (0, lang_1.i18n)(`errors.${identifier}`, interpolation);
30
- if (cause) {
31
- throw new TypeError(message, { cause });
32
- }
33
- throw new TypeError(message);
33
+ genericThrowErrorWithMessage(TypeError, identifier, interpolation, cause);
34
34
  }
35
35
  exports.throwTypeErrorWithMessage = throwTypeErrorWithMessage;
36
- function throwStatusCodeError(error) {
37
- const { statusCode, message, response } = error;
38
- const errorData = JSON.stringify({
39
- statusCode,
40
- message,
41
- url: response.request.href,
42
- method: response.request.method,
43
- response: response.body,
44
- headers: response.headers,
45
- });
46
- throw new Error(errorData, { cause: error });
36
+ /**
37
+ * @throws
38
+ */
39
+ function throwAuthErrorWithMessage(identifier, interpolation, cause) {
40
+ genericThrowErrorWithMessage(
41
+ // @ts-expect-error HubSpotAuthError is not callable
42
+ HubSpotAuthError_1.HubSpotAuthError, identifier, interpolation, cause);
47
43
  }
44
+ exports.throwAuthErrorWithMessage = throwAuthErrorWithMessage;
48
45
  /**
49
46
  * @throws
50
47
  */
51
48
  function throwError(error) {
52
49
  if (error.name === 'StatusCodeError') {
53
- throwStatusCodeError(error);
50
+ (0, apiErrors_1.throwStatusCodeError)(error);
54
51
  }
55
52
  else {
56
53
  // Error or Error subclass
@@ -0,0 +1,6 @@
1
+ import { AxiosConfigOptions } from '../types/Http';
2
+ import { AxiosRequestConfig } from 'axios';
3
+ export declare const DEFAULT_USER_AGENT_HEADERS: {
4
+ 'User-Agent': string;
5
+ };
6
+ export declare function getAxiosConfig(options: AxiosConfigOptions): AxiosRequestConfig;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getAxiosConfig = exports.DEFAULT_USER_AGENT_HEADERS = void 0;
4
+ const package_json_1 = require("../package.json");
5
+ const config_1 = require("../config");
6
+ const urls_1 = require("../lib/urls");
7
+ exports.DEFAULT_USER_AGENT_HEADERS = {
8
+ 'User-Agent': `HubSpot Local Dev Lib/${package_json_1.version}`,
9
+ };
10
+ function getAxiosConfig(options) {
11
+ const { env, localHostOverride, ...rest } = options;
12
+ const { httpTimeout, httpUseLocalhost } = (0, config_1.getAndLoadConfigIfNeeded)();
13
+ return {
14
+ baseURL: (0, urls_1.getHubSpotApiOrigin)(env, localHostOverride ? false : httpUseLocalhost),
15
+ headers: {
16
+ ...exports.DEFAULT_USER_AGENT_HEADERS,
17
+ },
18
+ timeout: httpTimeout || 15000,
19
+ ...rest,
20
+ };
21
+ }
22
+ exports.getAxiosConfig = getAxiosConfig;
@@ -0,0 +1,18 @@
1
+ import { LogCallbacksArg } from '../types/LogCallbacks';
2
+ import { HttpOptions } from '../types/Http';
3
+ import { AxiosResponse } from 'axios';
4
+ declare function getRequest<T>(accountId: number, options: HttpOptions): Promise<T>;
5
+ declare function postRequest<T>(accountId: number, options: HttpOptions): Promise<T>;
6
+ declare function putRequest<T>(accountId: number, options: HttpOptions): Promise<T>;
7
+ declare function patchRequest<T>(accountId: number, options: HttpOptions): Promise<T>;
8
+ declare function deleteRequest<T>(accountId: number, options: HttpOptions): Promise<T>;
9
+ declare const getRequestStreamCallbackKeys: string[];
10
+ declare const http: {
11
+ get: typeof getRequest;
12
+ post: typeof postRequest;
13
+ put: typeof putRequest;
14
+ patch: typeof patchRequest;
15
+ delete: typeof deleteRequest;
16
+ getOctetStream: (accountId: number, options: HttpOptions, destPath: string, logCallbacks?: LogCallbacksArg<typeof getRequestStreamCallbackKeys>) => Promise<AxiosResponse>;
17
+ };
18
+ export default http;
package/http/index.js ADDED
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const path_1 = __importDefault(require("path"));
7
+ const fs_extra_1 = __importDefault(require("fs-extra"));
8
+ const content_disposition_1 = __importDefault(require("content-disposition"));
9
+ const config_1 = require("../config");
10
+ const getAxiosConfig_1 = require("./getAxiosConfig");
11
+ const personalAccessKey_1 = require("../lib/personalAccessKey");
12
+ const oauth_1 = require("../lib/oauth");
13
+ const standardErrors_1 = require("../errors/standardErrors");
14
+ const logger_1 = require("../utils/logger");
15
+ const axios_1 = __importDefault(require("axios"));
16
+ async function withOauth(accountId, accountConfig, axiosConfig) {
17
+ const { headers } = axiosConfig;
18
+ const oauth = (0, oauth_1.getOauthManager)(accountId, accountConfig);
19
+ if (!oauth) {
20
+ (0, standardErrors_1.throwErrorWithMessage)('http.index.withOauth', { accountId });
21
+ }
22
+ const accessToken = await oauth.accessToken();
23
+ return {
24
+ ...axiosConfig,
25
+ headers: {
26
+ ...headers,
27
+ Authorization: `Bearer ${accessToken}`,
28
+ },
29
+ };
30
+ }
31
+ async function withPersonalAccessKey(accountId, axiosConfig) {
32
+ const { headers } = axiosConfig;
33
+ const accessToken = await (0, personalAccessKey_1.accessTokenForPersonalAccessKey)(accountId);
34
+ return {
35
+ ...axiosConfig,
36
+ headers: {
37
+ ...headers,
38
+ Authorization: `Bearer ${accessToken}`,
39
+ },
40
+ };
41
+ }
42
+ function withPortalId(portalId, axiosConfig) {
43
+ const { params } = axiosConfig;
44
+ return {
45
+ ...axiosConfig,
46
+ params: {
47
+ ...params,
48
+ portalId,
49
+ },
50
+ };
51
+ }
52
+ async function withAuth(accountId, options) {
53
+ const accountConfig = (0, config_1.getAccountConfig)(accountId);
54
+ if (!accountConfig) {
55
+ (0, standardErrors_1.throwErrorWithMessage)('http.index.withAuth', { accountId });
56
+ }
57
+ const { env, authType, apiKey } = accountConfig;
58
+ const axiosConfig = withPortalId(accountId, (0, getAxiosConfig_1.getAxiosConfig)({ env, ...options }));
59
+ if (authType === 'personalaccesskey') {
60
+ return withPersonalAccessKey(accountId, axiosConfig);
61
+ }
62
+ if (authType === 'oauth2') {
63
+ return withOauth(accountId, accountConfig, axiosConfig);
64
+ }
65
+ const { params } = axiosConfig;
66
+ return {
67
+ ...axiosConfig,
68
+ params: {
69
+ ...params,
70
+ hapikey: apiKey,
71
+ },
72
+ };
73
+ }
74
+ function addQueryParams(configOptions, queryParams = {}) {
75
+ const { params } = configOptions;
76
+ return {
77
+ ...configOptions,
78
+ params: {
79
+ ...queryParams,
80
+ ...params,
81
+ },
82
+ };
83
+ }
84
+ async function getRequest(accountId, options) {
85
+ const { query, ...rest } = options;
86
+ const axiosConfig = addQueryParams(rest, query);
87
+ const configWithAuth = await withAuth(accountId, axiosConfig);
88
+ const { data } = await (0, axios_1.default)(configWithAuth);
89
+ return data;
90
+ }
91
+ async function postRequest(accountId, options) {
92
+ const configWithAuth = await withAuth(accountId, options);
93
+ const { data } = await (0, axios_1.default)({ ...configWithAuth, method: 'post' });
94
+ return data;
95
+ }
96
+ async function putRequest(accountId, options) {
97
+ const configWithAuth = await withAuth(accountId, options);
98
+ const { data } = await (0, axios_1.default)({ ...configWithAuth, method: 'put' });
99
+ return data;
100
+ }
101
+ async function patchRequest(accountId, options) {
102
+ const configWithAuth = await withAuth(accountId, options);
103
+ const { data } = await (0, axios_1.default)({ ...configWithAuth, method: 'put' });
104
+ return data;
105
+ }
106
+ async function deleteRequest(accountId, options) {
107
+ const configWithAuth = await withAuth(accountId, options);
108
+ const { data } = await (0, axios_1.default)({ ...configWithAuth, method: 'delete' });
109
+ return data;
110
+ }
111
+ const getRequestStreamCallbackKeys = ['onWrite'];
112
+ function createGetRequestStream(contentType) {
113
+ return async (accountId, options, destPath, logCallbacks) => {
114
+ const { query, ...rest } = options;
115
+ const axiosConfig = addQueryParams(rest, query);
116
+ const logger = (0, logger_1.makeTypedLogger)(logCallbacks, 'http.index.createGetRequestStream');
117
+ // eslint-disable-next-line no-async-promise-executor
118
+ return new Promise(async (resolve, reject) => {
119
+ try {
120
+ const { headers, ...opts } = await withAuth(accountId, axiosConfig);
121
+ const res = await (0, axios_1.default)({
122
+ ...opts,
123
+ headers: {
124
+ ...headers,
125
+ accept: contentType,
126
+ },
127
+ responseType: 'stream',
128
+ });
129
+ if (res.status >= 200 && res.status < 300) {
130
+ let filepath = destPath;
131
+ if (fs_extra_1.default.existsSync(destPath)) {
132
+ const stat = fs_extra_1.default.statSync(destPath);
133
+ if (stat.isDirectory()) {
134
+ const { parameters } = content_disposition_1.default.parse(res.headers['content-disposition'] || '');
135
+ filepath = path_1.default.join(destPath, parameters.filename);
136
+ }
137
+ }
138
+ try {
139
+ fs_extra_1.default.ensureFileSync(filepath);
140
+ }
141
+ catch (err) {
142
+ reject(err);
143
+ }
144
+ const writeStream = fs_extra_1.default.createWriteStream(filepath, {
145
+ encoding: 'binary',
146
+ });
147
+ res.data.pipe(writeStream);
148
+ writeStream.on('error', err => {
149
+ reject(err);
150
+ });
151
+ writeStream.on('close', async () => {
152
+ logger('onWrite', { filepath });
153
+ resolve(res);
154
+ });
155
+ }
156
+ else {
157
+ reject(res);
158
+ }
159
+ }
160
+ catch (err) {
161
+ reject(err);
162
+ }
163
+ });
164
+ };
165
+ }
166
+ const getOctetStream = createGetRequestStream('application/octet-stream');
167
+ const http = {
168
+ get: getRequest,
169
+ post: postRequest,
170
+ put: putRequest,
171
+ patch: patchRequest,
172
+ delete: deleteRequest,
173
+ getOctetStream,
174
+ };
175
+ exports.default = http;