@zcatalyst/transport 0.0.1 → 0.0.3

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 (55) hide show
  1. package/LICENCE +55 -1
  2. package/README.md +266 -0
  3. package/dist-cjs/fetch-handler.js +269 -0
  4. package/dist-cjs/http-handler.js +404 -0
  5. package/dist-cjs/index.browser.js +23 -0
  6. package/dist-cjs/index.js +34 -0
  7. package/dist-cjs/utils/clonable-stream.js +107 -0
  8. package/dist-cjs/utils/constants.js +55 -0
  9. package/dist-cjs/utils/enums.js +22 -0
  10. package/dist-cjs/utils/errors.js +10 -0
  11. package/dist-cjs/utils/form-data.js +223 -0
  12. package/dist-cjs/utils/helpers.js +10 -0
  13. package/dist-cjs/utils/interfaces.js +2 -0
  14. package/dist-cjs/utils/request-agent.js +22 -0
  15. package/dist-cjs/utils/request-timeout.js +14 -0
  16. package/dist-es/fetch-handler.js +261 -0
  17. package/dist-es/http-handler.js +362 -0
  18. package/dist-es/index.browser.js +13 -0
  19. package/dist-es/index.js +21 -0
  20. package/dist-es/utils/clonable-stream.js +104 -0
  21. package/dist-es/utils/constants.js +52 -0
  22. package/dist-es/utils/enums.js +19 -0
  23. package/dist-es/utils/errors.js +6 -0
  24. package/dist-es/utils/form-data.js +218 -0
  25. package/dist-es/utils/helpers.js +7 -0
  26. package/dist-es/utils/interfaces.js +1 -0
  27. package/dist-es/utils/request-agent.js +19 -0
  28. package/dist-es/utils/request-timeout.js +11 -0
  29. package/dist-types/fetch-handler.d.ts +149 -0
  30. package/dist-types/http-handler.d.ts +79 -0
  31. package/dist-types/index.browser.d.ts +29 -0
  32. package/dist-types/index.d.ts +36 -0
  33. package/dist-types/ts3.4/fetch-handler.d.ts +149 -0
  34. package/dist-types/ts3.4/http-handler.d.ts +79 -0
  35. package/dist-types/ts3.4/index.browser.d.ts +29 -0
  36. package/dist-types/ts3.4/index.d.ts +36 -0
  37. package/dist-types/ts3.4/utils/clonable-stream.d.ts +75 -0
  38. package/dist-types/ts3.4/utils/constants.d.ts +11 -0
  39. package/dist-types/ts3.4/utils/enums.d.ts +16 -0
  40. package/dist-types/ts3.4/utils/errors.d.ts +11 -0
  41. package/dist-types/ts3.4/utils/form-data.d.ts +285 -0
  42. package/dist-types/ts3.4/utils/helpers.d.ts +13 -0
  43. package/dist-types/ts3.4/utils/interfaces.d.ts +68 -0
  44. package/dist-types/ts3.4/utils/request-agent.d.ts +12 -0
  45. package/dist-types/ts3.4/utils/request-timeout.d.ts +13 -0
  46. package/dist-types/utils/clonable-stream.d.ts +75 -0
  47. package/dist-types/utils/constants.d.ts +11 -0
  48. package/dist-types/utils/enums.d.ts +16 -0
  49. package/dist-types/utils/errors.d.ts +11 -0
  50. package/dist-types/utils/form-data.d.ts +285 -0
  51. package/dist-types/utils/helpers.d.ts +13 -0
  52. package/dist-types/utils/interfaces.d.ts +68 -0
  53. package/dist-types/utils/request-agent.d.ts +12 -0
  54. package/dist-types/utils/request-timeout.d.ts +13 -0
  55. package/package.json +37 -7
@@ -0,0 +1,404 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.AuthorizedHttpClient = exports.HttpClient = exports.DefaultHttpResponse = void 0;
40
+ const auth_admin_1 = require("@zcatalyst/auth-admin");
41
+ const utils_1 = require("@zcatalyst/utils");
42
+ const http_1 = __importDefault(require("http"));
43
+ const https_1 = __importDefault(require("https"));
44
+ const web_1 = require("node:stream/web");
45
+ const querystring_1 = require("querystring");
46
+ const stream_1 = require("stream");
47
+ const url_1 = require("url");
48
+ const util_1 = require("util");
49
+ const package_json_1 = __importDefault(require("../package.json"));
50
+ const { version } = package_json_1.default;
51
+ const errors_1 = require("./utils/errors");
52
+ const form_data_1 = __importDefault(require("./utils/form-data"));
53
+ const helpers_1 = require("./utils/helpers");
54
+ const request_agent_1 = __importDefault(require("./utils/request-agent"));
55
+ const { IS_LOCAL, USER_KEY_NAME, CREDENTIAL_USER, CATALYST_ORIGIN, USER_AGENT, APM_INSIGHT, ACCEPT_HEADER, REQ_RETRY_THRESHOLD, IS_APM } = utils_1.CONSTANTS;
56
+ class DefaultHttpResponse {
57
+ constructor(resp) {
58
+ this.statusCode = resp.statusCode;
59
+ this.headers = resp.headers;
60
+ this.config = resp.config;
61
+ this.resp = resp;
62
+ }
63
+ get data() {
64
+ switch (this.config.expecting) {
65
+ case "string":
66
+ if (this.resp.data === undefined) {
67
+ throw new errors_1.CatalystAPIError('UNPARSABLE_RESPONSE', `Error while processing response data. Raw server ` +
68
+ `response: "${this.resp.data}". Status code: "${this.statusCode}".`, '', this.statusCode);
69
+ }
70
+ return this.resp.data;
71
+ case "buffer":
72
+ if (this.resp.buffer === undefined) {
73
+ throw new errors_1.CatalystAPIError('UNPARSABLE_RESPONSE', `Error while processing response buffer. Raw server ` +
74
+ `response: "${this.resp.data}". Status code: "${this.statusCode}".`, '', this.statusCode);
75
+ }
76
+ return this.resp.buffer;
77
+ case "raw":
78
+ return this.resp.stream;
79
+ default:
80
+ try {
81
+ return JSON.parse(this.resp.data);
82
+ }
83
+ catch (e) {
84
+ throw new errors_1.CatalystAPIError('UNPARSABLE_RESPONSE', `Error while parsing response data: "${(0, util_1.inspect)(e)}". Raw server ` +
85
+ `response: "${this.resp.data}". Status code: "${this.statusCode}".`, '', this.statusCode);
86
+ }
87
+ }
88
+ }
89
+ }
90
+ exports.DefaultHttpResponse = DefaultHttpResponse;
91
+ function rejectWithContext(reject, statusCode, data) {
92
+ try {
93
+ const catalystError = JSON.parse(data);
94
+ reject({
95
+ statusCode,
96
+ code: catalystError.data.error_code,
97
+ message: catalystError.data.message
98
+ });
99
+ return;
100
+ }
101
+ catch {
102
+ reject({
103
+ statusCode,
104
+ message: (0, util_1.inspect)(data)
105
+ });
106
+ }
107
+ }
108
+ async function streamToBuffer(stream) {
109
+ const chunks = [];
110
+ return new Promise((resolve, reject) => {
111
+ stream.destroyed && reject('Invalid response stream');
112
+ stream.on('data', (chunk) => {
113
+ chunks.push(chunk);
114
+ });
115
+ stream.on('error', reject);
116
+ stream.on('end', () => resolve(Buffer.concat(chunks)));
117
+ });
118
+ }
119
+ function constructFormData(data) {
120
+ const formData = new form_data_1.default();
121
+ const keyData = Object.keys(data);
122
+ keyData.forEach((key) => {
123
+ formData.append(key, data[key]);
124
+ });
125
+ return formData;
126
+ }
127
+ async function _finalizeRequest(resolve, reject, response) {
128
+ if (response.statusCode === undefined) {
129
+ reject(new errors_1.CatalystAPIError('UNKNOWN_STATUSCODE', 'unable to obtain status code from response', response));
130
+ return;
131
+ }
132
+ if (response.statusCode >= 200 && response.statusCode < 300) {
133
+ resolve(response);
134
+ return;
135
+ }
136
+ if (response.stream?.pipe === undefined) {
137
+ rejectWithContext(reject, response.statusCode, response.data);
138
+ return;
139
+ }
140
+ try {
141
+ if (response.stream !== undefined && response.data === undefined) {
142
+ const responseBuffer = await streamToBuffer(response.stream);
143
+ response.data = responseBuffer.toString();
144
+ }
145
+ if (response.statusCode === 404) {
146
+ rejectWithContext(reject, response.statusCode, response.data || 'Not Found');
147
+ }
148
+ else if (response.statusCode === 403) {
149
+ rejectWithContext(reject, response.statusCode, response.data || 'Access Denied');
150
+ }
151
+ else if (response.statusCode === 401) {
152
+ rejectWithContext(reject, response.statusCode, response.data || 'Unauthorized');
153
+ }
154
+ else {
155
+ rejectWithContext(reject, response.statusCode, response.data || 'Unknown response');
156
+ }
157
+ }
158
+ catch (e) {
159
+ const errMsg = e instanceof Error ? e.message : (0, util_1.inspect)(e);
160
+ rejectWithContext(reject, response.statusCode, errMsg);
161
+ }
162
+ }
163
+ function _appendQueryData(url, data) {
164
+ if (data && Object.keys(data).length > 0) {
165
+ url += url.includes('?') ? '&' : '?';
166
+ url += (0, querystring_1.stringify)(data);
167
+ }
168
+ return url;
169
+ }
170
+ async function _request(transport, options, config, data, retryCount = 0) {
171
+ const clonedData = data === undefined
172
+ ? undefined
173
+ : config.type !== "file"
174
+ ?
175
+ data
176
+ :
177
+ data.createClone();
178
+ return new Promise(async (resolve, reject) => {
179
+ const retryRequest = async (err) => {
180
+ utils_1.LOGGER.warn('>>> RETRYING REQUEST ');
181
+ if (retryCount++ === REQ_RETRY_THRESHOLD) {
182
+ reject(err);
183
+ return;
184
+ }
185
+ try {
186
+ options.agent = new request_agent_1.default((0, helpers_1.isHttps)(config.url), options.hostname, true).agent;
187
+ const resp = await _request(transport, options, config, clonedData, retryCount);
188
+ resolve(resp);
189
+ }
190
+ catch (e) {
191
+ reject(e);
192
+ }
193
+ };
194
+ const startTimeStamp = Date.now();
195
+ const req = transport.request(options, async (res) => {
196
+ if (req.destroyed) {
197
+ return;
198
+ }
199
+ const response = {
200
+ headers: res.headers,
201
+ request: req,
202
+ stream: res,
203
+ statusCode: res.statusCode,
204
+ config
205
+ };
206
+ utils_1.LOGGER.debug(`>>> HTTP REQUEST : ${req.method?.toUpperCase()} ${req.protocol}//${req.host}${req.path}`);
207
+ process.env.ZC_SECURE?.toLowerCase() === 'override' &&
208
+ utils_1.LOGGER.fine(`>>> REQUEST HEADERS : ${JSON.stringify(options.headers)}`);
209
+ utils_1.LOGGER.debug(`<<< HTTP RESPONSE : ${res.statusCode} : ${Date.now() - startTimeStamp} ms`);
210
+ process.env.ZC_SECURE?.toLowerCase() === 'override' &&
211
+ utils_1.LOGGER.fine(`<<< RESPONSE HEADERS : ${JSON.stringify(res.headers)}`);
212
+ if (config.expecting === "raw") {
213
+ return _finalizeRequest(resolve, reject, response);
214
+ }
215
+ try {
216
+ const responseBuffer = await streamToBuffer(res);
217
+ response.data = responseBuffer.toString();
218
+ response.buffer = responseBuffer;
219
+ }
220
+ catch (err) {
221
+ if (req.destroyed || (config.abortSignal && config.abortSignal.aborted)) {
222
+ req.destroy();
223
+ return;
224
+ }
225
+ reject(err);
226
+ }
227
+ _finalizeRequest(resolve, reject, response);
228
+ });
229
+ req.on('error', (err) => {
230
+ utils_1.LOGGER.debug(`>>> HTTP REQUEST : ${req.method?.toUpperCase()} ${req.protocol}//${req.host}${req.path}`);
231
+ process.env.ZC_SECURE?.toLowerCase() === 'override' &&
232
+ utils_1.LOGGER.fine(`>>> REQUEST HEADERS : ${JSON.stringify(options.headers)}`);
233
+ utils_1.LOGGER.debug(`<<< HTTP REQUEST ERROR : ${(0, util_1.inspect)(err)} : ${Date.now() - startTimeStamp} ms`);
234
+ if (req.destroyed || config.type === "raw") {
235
+ return reject(err);
236
+ }
237
+ retryRequest(err);
238
+ });
239
+ if (data === undefined) {
240
+ req.end();
241
+ return;
242
+ }
243
+ if (config.type !== "file" && config.type !== "raw") {
244
+ req.write(data);
245
+ req.end();
246
+ return;
247
+ }
248
+ if (data instanceof web_1.ReadableStream) {
249
+ data = webStreamToNodeStream(data);
250
+ }
251
+ if (typeof data === 'string' || Buffer.isBuffer(data)) {
252
+ req.write(data);
253
+ req.end();
254
+ return;
255
+ }
256
+ data.on('error', (er) => {
257
+ reject(er);
258
+ req.end();
259
+ });
260
+ data.pipe(req).on('finish', req.end);
261
+ });
262
+ }
263
+ function webStreamToNodeStream(webStream) {
264
+ const reader = webStream.getReader();
265
+ return new stream_1.Readable({
266
+ async read() {
267
+ const { done, value } = await reader.read();
268
+ if (done) {
269
+ this.push(null);
270
+ }
271
+ else {
272
+ this.push(value);
273
+ }
274
+ }
275
+ });
276
+ }
277
+ async function sendRequest(config, componentName, componentVersion) {
278
+ let data;
279
+ let userAgent = USER_AGENT.PREFIX + version;
280
+ if (componentName) {
281
+ userAgent += ` ${componentName}/${componentVersion || 'unknown'}`;
282
+ }
283
+ let headers = Object.assign({
284
+ [USER_AGENT.KEY]: userAgent
285
+ }, config.headers);
286
+ if (config.data !== undefined) {
287
+ switch (config.type) {
288
+ case "json":
289
+ data = JSON.stringify(config.data);
290
+ headers['Content-Type'] = 'application/json';
291
+ break;
292
+ case "file":
293
+ data = constructFormData(config.data);
294
+ headers = data.getHeaders(headers);
295
+ break;
296
+ case "raw":
297
+ data = config.data;
298
+ if (headers['Content-Type'] === undefined) {
299
+ headers['Content-Type'] = 'application/octet-stream';
300
+ }
301
+ break;
302
+ default:
303
+ data = (0, querystring_1.stringify)(config.data);
304
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
305
+ headers['Content-Length'] = Buffer.byteLength(data) + '';
306
+ }
307
+ }
308
+ const origin = config.origin || CATALYST_ORIGIN;
309
+ config.url = config.url || new url_1.URL(config.path || '', origin).href;
310
+ if (config.qs !== undefined) {
311
+ config.url = _appendQueryData(config.url, config.qs);
312
+ }
313
+ const parsedUrl = new url_1.URL(config.url);
314
+ if (parsedUrl.hostname === null) {
315
+ throw new errors_1.CatalystAPIError('UNPARSABLE_CONFIG', 'Hostname cannot be null', config.path, 400);
316
+ }
317
+ const isHttpsProtocol = (0, helpers_1.isHttps)(parsedUrl);
318
+ const requestAgent = new request_agent_1.default(isHttpsProtocol, parsedUrl.hostname, false);
319
+ parsedUrl.searchParams?.sort();
320
+ const options = {
321
+ hostname: parsedUrl.hostname,
322
+ port: parsedUrl.port,
323
+ path: parsedUrl.pathname + parsedUrl.search,
324
+ method: config.method,
325
+ headers,
326
+ agent: requestAgent.agent
327
+ };
328
+ const transport = isHttpsProtocol ? https_1.default : http_1.default;
329
+ return _request(transport, options, config, data);
330
+ }
331
+ class HttpClient {
332
+ constructor(app) {
333
+ this.app = app;
334
+ }
335
+ async send(req, apmTrackerName, componentVersion) {
336
+ req.headers = Object.assign({}, req.headers);
337
+ req.qs = Object.assign({}, req.qs);
338
+ req.retry = req.retry || true;
339
+ if (this.app !== undefined && req.service !== "external") {
340
+ const user = this.app.credential.getCurrentUser();
341
+ req.headers = (0, auth_admin_1.addDefaultAppHeaders)(req.headers, this.app.config);
342
+ req.headers[USER_KEY_NAME] = this.app.credential.getCurrentUserType();
343
+ if (IS_LOCAL === 'true') {
344
+ switch (user) {
345
+ case CREDENTIAL_USER.admin:
346
+ req.origin =
347
+ 'https://' +
348
+ CATALYST_ORIGIN.replace('https://', '').replace('http://', '');
349
+ break;
350
+ case CREDENTIAL_USER.user:
351
+ req.origin = 'https://' + this.app.config.projectDomain;
352
+ break;
353
+ }
354
+ }
355
+ if (req.service === "baas") {
356
+ req.headers[ACCEPT_HEADER.KEY] =
357
+ ACCEPT_HEADER.VALUE + ', ' + (req.headers[ACCEPT_HEADER.KEY] || '');
358
+ }
359
+ req.path =
360
+ (0, utils_1.getServicePath)(req.service) + `/project/${this.app.config.projectId}` + req.path;
361
+ }
362
+ try {
363
+ let resp;
364
+ if (req.track && apmTrackerName && IS_APM === 'true') {
365
+ try {
366
+ const apminsight = await Promise.resolve().then(() => __importStar(require('apminsight')));
367
+ resp = await apminsight.startTracker(APM_INSIGHT.tracker_name, apmTrackerName, () => sendRequest(req, apmTrackerName, componentVersion));
368
+ }
369
+ catch (err) {
370
+ throw new errors_1.CatalystAPIError('APM_TRACKER_ERROR', 'To enable APM tracking locally, please download the apminsight package from the UI and place it in the node_modules directory of your project.', err, 400);
371
+ }
372
+ }
373
+ else {
374
+ resp = await sendRequest(req, apmTrackerName, componentVersion);
375
+ }
376
+ return new DefaultHttpResponse(resp);
377
+ }
378
+ catch (err) {
379
+ if (err instanceof Error) {
380
+ throw new errors_1.CatalystAPIError('REQUEST_FAILURE', err.message, err, err.message.includes('ECONNREFUSED') ? 503 : 400);
381
+ }
382
+ throw err;
383
+ }
384
+ }
385
+ }
386
+ exports.HttpClient = HttpClient;
387
+ class AuthorizedHttpClient extends HttpClient {
388
+ constructor(app, component) {
389
+ super(app);
390
+ if (component) {
391
+ this.componentName = component.getComponentName();
392
+ this.componentVersion = component.getComponentVersion?.();
393
+ }
394
+ }
395
+ async send(request) {
396
+ const requestCopy = Object.assign({ user: CREDENTIAL_USER.user }, request);
397
+ requestCopy.headers = Object.assign({}, request.headers);
398
+ if (request.auth !== false) {
399
+ await this.app?.authenticateRequest(requestCopy);
400
+ }
401
+ return await super.send(requestCopy, this.componentName, this.componentVersion);
402
+ }
403
+ }
404
+ exports.AuthorizedHttpClient = AuthorizedHttpClient;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CatalystAPIError = exports.ResponseType = exports.RequestType = exports.Handler = exports.PrefixedCatalystError = exports.CONSTANTS = exports.CatalystService = void 0;
4
+ const fetch_handler_1 = require("./fetch-handler");
5
+ var utils_1 = require("@zcatalyst/utils");
6
+ Object.defineProperty(exports, "CatalystService", { enumerable: true, get: function () { return utils_1.CatalystService; } });
7
+ Object.defineProperty(exports, "CONSTANTS", { enumerable: true, get: function () { return utils_1.CONSTANTS; } });
8
+ var utils_2 = require("@zcatalyst/utils");
9
+ Object.defineProperty(exports, "PrefixedCatalystError", { enumerable: true, get: function () { return utils_2.PrefixedCatalystError; } });
10
+ class Handler {
11
+ constructor(app, component) {
12
+ this.component = component;
13
+ }
14
+ async send(options) {
15
+ return (await fetch_handler_1.ResponseHandler.send(options, this.component?.getComponentName(), this.component?.getComponentVersion?.()));
16
+ }
17
+ }
18
+ exports.Handler = Handler;
19
+ var enums_1 = require("./utils/enums");
20
+ Object.defineProperty(exports, "RequestType", { enumerable: true, get: function () { return enums_1.RequestType; } });
21
+ Object.defineProperty(exports, "ResponseType", { enumerable: true, get: function () { return enums_1.ResponseType; } });
22
+ var errors_1 = require("./utils/errors");
23
+ Object.defineProperty(exports, "CatalystAPIError", { enumerable: true, get: function () { return errors_1.CatalystAPIError; } });
@@ -0,0 +1,34 @@
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
+ exports.FormData = exports.CatalystAPIError = exports.ResponseType = exports.RequestType = exports.Handler = exports.PrefixedCatalystError = exports.CONSTANTS = exports.CatalystService = void 0;
7
+ const auth_admin_1 = require("@zcatalyst/auth-admin");
8
+ const http_handler_1 = require("./http-handler");
9
+ const form_data_1 = __importDefault(require("./utils/form-data"));
10
+ exports.FormData = form_data_1.default;
11
+ var utils_1 = require("@zcatalyst/utils");
12
+ Object.defineProperty(exports, "CatalystService", { enumerable: true, get: function () { return utils_1.CatalystService; } });
13
+ Object.defineProperty(exports, "CONSTANTS", { enumerable: true, get: function () { return utils_1.CONSTANTS; } });
14
+ var utils_2 = require("@zcatalyst/utils");
15
+ Object.defineProperty(exports, "PrefixedCatalystError", { enumerable: true, get: function () { return utils_2.PrefixedCatalystError; } });
16
+ class Handler {
17
+ constructor(app, component) {
18
+ if (!app) {
19
+ app = new auth_admin_1.ZCAuth().getDefaultCredentials();
20
+ }
21
+ this.app = app;
22
+ this.component = component;
23
+ }
24
+ async send(options) {
25
+ const _httpRequester = new http_handler_1.AuthorizedHttpClient(this.app, this.component);
26
+ return (await _httpRequester.send(options));
27
+ }
28
+ }
29
+ exports.Handler = Handler;
30
+ var enums_1 = require("./utils/enums");
31
+ Object.defineProperty(exports, "RequestType", { enumerable: true, get: function () { return enums_1.RequestType; } });
32
+ Object.defineProperty(exports, "ResponseType", { enumerable: true, get: function () { return enums_1.ResponseType; } });
33
+ var errors_1 = require("./utils/errors");
34
+ Object.defineProperty(exports, "CatalystAPIError", { enumerable: true, get: function () { return errors_1.CatalystAPIError; } });
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const process_1 = require("process");
4
+ const stream_1 = require("stream");
5
+ function clonePiped(that) {
6
+ if (--that._clonesCount === 0 && !that.destroyed) {
7
+ that._original?.pipe(that);
8
+ that._original = undefined;
9
+ }
10
+ }
11
+ function _destroy(error, callback) {
12
+ if (!error) {
13
+ this.push(null);
14
+ this.end();
15
+ }
16
+ (0, process_1.nextTick)(callback, error);
17
+ }
18
+ function forwardDestroy(src, dest) {
19
+ function destroy(err) {
20
+ src.removeListener('close', onClose);
21
+ dest.destroy(err);
22
+ }
23
+ function onClose() {
24
+ dest.end();
25
+ }
26
+ src.on('error', destroy);
27
+ src.on('close', onClose);
28
+ }
29
+ class StreamClone extends stream_1.PassThrough {
30
+ constructor(parent) {
31
+ super({ objectMode: parent.readableObjectMode });
32
+ this.parent = parent;
33
+ forwardDestroy(parent, this);
34
+ parent._internalPipe = true;
35
+ parent.pipe(this);
36
+ parent._internalPipe = false;
37
+ this.on('newListener', this.onDataClone);
38
+ this.once('resume', this.onResumeClone);
39
+ }
40
+ onDataClone(event, _listener) {
41
+ if (event === 'data' || event === 'readable' || event === 'close') {
42
+ (0, process_1.nextTick)(clonePiped, this.parent);
43
+ this.removeListener('newListener', this.onDataClone);
44
+ this.removeListener('resume', this.onResumeClone);
45
+ }
46
+ }
47
+ onResumeClone() {
48
+ this.removeListener('newListener', this.onDataClone);
49
+ this.removeListener('resume', this.onResumeClone);
50
+ (0, process_1.nextTick)(clonePiped, this.parent);
51
+ }
52
+ clone() {
53
+ return this.parent.clone();
54
+ }
55
+ isCloneable(stream) {
56
+ return stream instanceof CloneableStream || stream instanceof StreamClone;
57
+ }
58
+ }
59
+ class CloneableStream extends stream_1.PassThrough {
60
+ constructor(stream) {
61
+ super({ objectMode: stream.readableObjectMode });
62
+ this._original = stream;
63
+ this._clonesCount = 1;
64
+ this._internalPipe = false;
65
+ forwardDestroy(stream, this);
66
+ this.on('newListener', this.onData);
67
+ this.on('resume', this.onResume);
68
+ this._hasListener = true;
69
+ this._destroy = _destroy;
70
+ }
71
+ onData(event, _listener) {
72
+ if (event === 'data' || event === 'readable') {
73
+ this._hasListener = false;
74
+ this.removeListener('newListener', this.onData);
75
+ this.removeListener('resume', this.onResume);
76
+ (0, process_1.nextTick)(clonePiped, this);
77
+ }
78
+ }
79
+ onResume() {
80
+ this._hasListener = false;
81
+ this.removeListener('newListener', this.onData);
82
+ this.removeListener('resume', this.onResume);
83
+ (0, process_1.nextTick)(clonePiped, this);
84
+ }
85
+ resume() {
86
+ if (this._internalPipe) {
87
+ return this;
88
+ }
89
+ stream_1.PassThrough.prototype.resume.call(this);
90
+ return this;
91
+ }
92
+ clone() {
93
+ if (!this._original) {
94
+ throw new Error('already started');
95
+ }
96
+ this._clonesCount++;
97
+ this.removeListener('newListener', this.onData);
98
+ this.removeListener('resume', this.onResume);
99
+ const clone = new StreamClone(this);
100
+ if (this._hasListener) {
101
+ this.on('newListener', this.onData);
102
+ this.on('resume', this.onResume);
103
+ }
104
+ return clone;
105
+ }
106
+ }
107
+ exports.default = CloneableStream;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HTTP_CODE_REV_MAP = exports.ZD_CSRPARAM = exports.X_ZCSRF_TOKEN = exports.REQUEST_PROPERTY = exports.HTTP_HEADER_MAP = exports.HTTP_CODE_MAP = void 0;
4
+ exports.HTTP_CODE_MAP = {
5
+ OK: {
6
+ CODE: 200,
7
+ TEXT: 'OK'
8
+ },
9
+ NO_CONTENT: {
10
+ CODE: 204,
11
+ TEXT: 'NO CONTENT'
12
+ },
13
+ INTERNAL_SERVER_ERROR: {
14
+ CODE: 500,
15
+ TEXT: 'INTERNAL SERVER ERROR'
16
+ },
17
+ RESOURCE_NOT_FOUND: {
18
+ CODE: 404,
19
+ TEXT: 'RESOURCE NOT FOUND'
20
+ },
21
+ BAD_REQUEST: {
22
+ CODE: 400,
23
+ TEXT: 'BAD REQUEST'
24
+ },
25
+ UNAUTHORIZED: {
26
+ CODE: 401,
27
+ TEXT: 'UNAUTHORIZED'
28
+ },
29
+ CONFLICT: {
30
+ CODE: 409,
31
+ TEXT: 'CONFLICT, MAY BE YOU ARE TRYING TO CREATE A RESOURCE THAT ALREADY EXIST!'
32
+ },
33
+ FORBIDDEN: {
34
+ CODE: 403,
35
+ TEXT: 'FORBIDDEN, MAY BE YOUR USAGE REACHED MAX ALLOWED LIMIT!'
36
+ },
37
+ UNEXPECTED: {
38
+ CODE: 101,
39
+ TEXT: 'UNEXPECTED RESPONSE FOUND'
40
+ }
41
+ };
42
+ exports.HTTP_HEADER_MAP = {
43
+ CONTENT_JSON: 'application/json; charset=utf-8',
44
+ AUTHORIZATION_KEY: 'Authorization'
45
+ };
46
+ exports.REQUEST_PROPERTY = {
47
+ BLOB: 'blob'
48
+ };
49
+ exports.X_ZCSRF_TOKEN = 'X-ZCSRF-TOKEN';
50
+ exports.ZD_CSRPARAM = 'zd_csrparam';
51
+ const HTTP_CODE_REV_MAP = {};
52
+ exports.HTTP_CODE_REV_MAP = HTTP_CODE_REV_MAP;
53
+ const HTTP_CODE_MAP_KEYS = Object.keys(exports.HTTP_CODE_MAP);
54
+ for (const KEY of HTTP_CODE_MAP_KEYS)
55
+ HTTP_CODE_REV_MAP[exports.HTTP_CODE_MAP[KEY].CODE] = exports.HTTP_CODE_MAP[KEY];
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FormDataKeys = exports.RequestType = exports.ResponseType = void 0;
4
+ var ResponseType;
5
+ (function (ResponseType) {
6
+ ResponseType["RAW"] = "raw";
7
+ ResponseType["JSON"] = "json";
8
+ ResponseType["STRING"] = "string";
9
+ ResponseType["BUFFER"] = "buffer";
10
+ })(ResponseType || (exports.ResponseType = ResponseType = {}));
11
+ var RequestType;
12
+ (function (RequestType) {
13
+ RequestType["FILE"] = "file";
14
+ RequestType["JSON"] = "json";
15
+ RequestType["URL_ENCODED"] = "url_encoded";
16
+ RequestType["RAW"] = "raw";
17
+ })(RequestType || (exports.RequestType = RequestType = {}));
18
+ var FormDataKeys;
19
+ (function (FormDataKeys) {
20
+ FormDataKeys["CODE"] = "code";
21
+ FormDataKeys["FILE_NAME"] = "file_name";
22
+ })(FormDataKeys || (exports.FormDataKeys = FormDataKeys = {}));
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CatalystAPIError = void 0;
4
+ const utils_1 = require("@zcatalyst/utils");
5
+ class CatalystAPIError extends utils_1.PrefixedCatalystError {
6
+ constructor(code, message, value, statusCode) {
7
+ super('app', code, message, value, statusCode);
8
+ }
9
+ }
10
+ exports.CatalystAPIError = CatalystAPIError;