qcobjects-cli 2.4.47 → 2.4.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/VERSION CHANGED
@@ -1 +1 @@
1
- 2.4.47
1
+ 2.4.49
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qcobjects-cli",
3
- "version": "2.4.47",
3
+ "version": "2.4.49",
4
4
  "description": "qcobjects cli command line tool",
5
5
  "main": "src/index.cjs",
6
6
  "module": "src/index.mjs",
@@ -31,23 +31,25 @@
31
31
  "use strict";
32
32
 
33
33
  const path = require("path");
34
- const absolutePath = path.resolve( __dirname, "./" );
34
+ const absolutePath = path.resolve(__dirname, "./");
35
35
 
36
36
  const fs = require("fs");
37
37
  const mime = require("mime");
38
- require(absolutePath+"/org.quickcorp.qcobjects.main.file.js");
39
- require(absolutePath+ "/org.qcobjects.common.pipelog.js");
40
-
41
-
42
- let ImportMicroservice = function (microservicePackage){
43
- var standardPath = findPackageNodePath(microservicePackage) || findPackageNodePath(microservicePackage+".js");
44
- if (standardPath !== null){
45
- Import (microservicePackage);
38
+ require(absolutePath + "/org.quickcorp.qcobjects.main.file.js");
39
+ require(absolutePath + "/org.qcobjects.common.pipelog.js");
40
+
41
+ let ImportMicroservice = function (microservicePackage) {
42
+ var _ret_;
43
+ var standardPath = findPackageNodePath(microservicePackage) || findPackageNodePath(microservicePackage + ".js");
44
+ if (standardPath !== null) {
45
+ _ret_ = Import(microservicePackage);
46
46
  } else {
47
- Import (absolutePath+"/backend/"+microservicePackage);
47
+ _ret_ = Import(absolutePath + "/backend/" + microservicePackage);
48
48
  }
49
+ return _ret_;
49
50
  };
50
51
 
52
+
51
53
  Package("org.quickcorp.qcobjects.main.http.server",[
52
54
 
53
55
  class BackendMicroservice extends InheritClass {
@@ -56,20 +58,26 @@ Package("org.quickcorp.qcobjects.main.http.server",[
56
58
  basePath=CONFIG.get("basePath"),
57
59
  body=null,
58
60
  stream=null,
59
- server=null,
60
61
  request=null
61
62
  }){
62
63
  super(...arguments);
63
64
 
64
- logger.debug("Executing Legacy HTTP BackendMicroservice ");
65
+ logger.debug("Initializing Legacy BackendMicroservice...");
65
66
  let microservice = this;
67
+ if (typeof this.body === "undefined") {
68
+ this.body = null;
69
+ }
70
+ if (typeof body !== "undefined"){
71
+ this.body = body;
72
+ }
66
73
  this.cors();
74
+ microservice.stream = stream;
67
75
  microservice.req.on("data", (data) => {
68
76
  // data from POST, GET
69
77
  var requestMethod = request.method.toLowerCase();
70
78
  var supportedMethods = {"post":microservice.post,
71
79
  };
72
- if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) {
80
+ if (Object.hasOwnProperty.call(supportedMethods,requestMethod)) {
73
81
  supportedMethods[requestMethod].call(microservice,data);
74
82
  }
75
83
  });
@@ -85,51 +93,74 @@ Package("org.quickcorp.qcobjects.main.http.server",[
85
93
  "trace":microservice.trace,
86
94
  "patch":microservice.patch
87
95
  };
88
- if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) {
96
+ if (Object.hasOwnProperty.call(supportedMethods,requestMethod)) {
89
97
  supportedMethods[requestMethod].call(microservice);
90
98
  }
91
99
 
92
100
 
93
101
  }
94
102
 
95
- cors(){
96
- if (this.route.cors){
97
- let {allow_origins,allow_credentials,allow_methods,allow_headers} = this.route.cors;
103
+ cors() {
104
+ if (this.route.cors) {
105
+ logger.debug("Validating CORS...");
106
+ let {
107
+ allow_origins,
108
+ allow_credentials,
109
+ allow_methods,
110
+ allow_headers
111
+ } = this.route.cors;
98
112
  var microservice = this;
99
- if (typeof microservice.headers !== "object"){
113
+ if (typeof microservice.headers !== "object") {
100
114
  microservice.headers = {};
101
115
  }
102
- if (typeof allow_origins !== "undefined"){
116
+ if (typeof microservice.route.responseHeaders !== "object") {
117
+ microservice.route.responseHeaders = {};
118
+ }
119
+ if (typeof allow_origins !== "undefined") {
120
+ logger.debug("CORS: allow_origins available. Validating origins...");
103
121
  // an example of allow_origins is ['https://example.com','http://www.example.com']
104
- if (allow_origins =="*" || (typeof microservice.request.headers.origin == "undefined") || [...allow_origins].indexOf(microservice.request.headers.origin)!== -1){
122
+ if (allow_origins === "*" || (typeof microservice.request.headers.origin === "undefined") || [...allow_origins].indexOf(microservice.request.headers.origin) !== -1) {
105
123
  // for compatibility with all browsers allways return a wildcard when the origin is allowed
106
- microservice.headers["Access-Control-Allow-Origin"] = "*";
124
+ logger.debug("CORS: Adding header Access-Control-Allow-Origin=*");
125
+ microservice.route.responseHeaders["Access-Control-Allow-Origin"] = "*";
107
126
  } else {
108
- logger.debug("Origin is not allowed: " + microservice.request.headers.origin);
109
- logger.debug("Forcing to finish the response...");
127
+ logger.debug("CORS: Origin is not allowed: " + microservice.request.headers.origin);
128
+ logger.debug("CORS: Forcing to finish the response...");
110
129
  this.body = {};
111
130
  try {
112
131
  this.done();
113
- } catch (e){}
132
+ } catch (e) {
133
+ logger.debug(`It was not possible to finish the call to the microservice: ${e}`);
134
+ }
114
135
  }
115
136
  } else {
116
- microservice.headers["Access-Control-Allow-Origin"] = "*";
137
+ logger.debug("CORS: no allow_origins available. Allowing all origins...");
138
+ logger.debug("CORS: Adding header Access-Control-Allow-Origin=*");
139
+ microservice.route.responseHeaders["Access-Control-Allow-Origin"] = "*";
117
140
  }
118
- if (typeof allow_credentials !== "undefined"){
119
- microservice.headers["Access-Control-Allow-Credentials"] = allow_credentials.toString();
141
+ if (typeof allow_credentials !== "undefined") {
142
+ logger.debug(`CORS: allow_credentials present. Allowing ${allow_credentials}...`);
143
+ microservice.route.responseHeaders["Access-Control-Allow-Credentials"] = allow_credentials.toString();
120
144
  } else {
121
- microservice.headers["Access-Control-Allow-Credentials"] = "true";
145
+ logger.debug("CORS: No allow_credentials present. Allowing all credentials.");
146
+ microservice.route.responseHeaders["Access-Control-Allow-Credentials"] = "true";
122
147
  }
123
- if (typeof allow_methods !== "undefined"){
124
- microservice.headers["Access-Control-Allow-Methods"] = [...allow_methods].join(",");
148
+ if (typeof allow_methods !== "undefined") {
149
+ logger.debug(`CORS: allow_methods present. Allowing ${allow_methods}...`);
150
+ microservice.route.responseHeaders["Access-Control-Allow-Methods"] = [...allow_methods].join(",");
125
151
  } else {
126
- microservice.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS, POST";
152
+ logger.debug("CORS: No allow_methods present. Allowing only GET, OPTIONS and POST");
153
+ microservice.route.responseHeaders["Access-Control-Allow-Methods"] = "GET, OPTIONS, POST";
127
154
  }
128
- if (typeof allow_headers !== "undefined"){
129
- microservice.headers["Access-Control-Allow-Headers"] = [...allow_headers].join(",");
155
+ if (typeof allow_headers !== "undefined") {
156
+ logger.debug(`CORS: allow_headers present. Allowing ${allow_headers}...`);
157
+ microservice.route.responseHeaders["Access-Control-Allow-Headers"] = [...allow_headers].join(",");
130
158
  } else {
131
- microservice.headers["Access-Control-Allow-Headers"] = "*";
159
+ logger.debug(`CORS: No allow_headers present. Allowing all headers...`);
160
+ microservice.route.responseHeaders["Access-Control-Allow-Headers"] = "*";
132
161
  }
162
+ } else {
163
+ logger.debug("No CORS validation available. You can specify cors in CONFIG.backend.routes[].cors");
133
164
  }
134
165
  }
135
166
  head(formData){this.done();}
@@ -145,7 +176,8 @@ Package("org.quickcorp.qcobjects.main.http.server",[
145
176
  stream.write(JSON.stringify(this.body));
146
177
  stream.end();
147
178
  } catch (e){
148
- logger.debug("Something wrong writing the response for microservice"+e.toString());
179
+ logger.debug(`Something wrong writing the response for microservice: ${e}`);
180
+ throw Error(e);
149
181
  }
150
182
  }
151
183
  done(){
@@ -154,8 +186,8 @@ Package("org.quickcorp.qcobjects.main.http.server",[
154
186
  try {
155
187
  stream.writeHead(200, microservice.headers);
156
188
  } catch (e){
157
- logger.debug("Something went wront while sending headers in http...");
158
- logger.debug(e.toString());
189
+ logger.debug(`Something went wront while sending headers in http... ${e}`);
190
+ throw Error(e);
159
191
  }
160
192
  if (microservice.body != null){
161
193
  microservice.finishWithBody.call(microservice,stream);
@@ -169,17 +201,17 @@ Package("org.quickcorp.qcobjects.main.http.server",[
169
201
  class HTTPServerResponse extends InheritClass {
170
202
  constructor ({
171
203
  headers={
172
- ":status": 200,
204
+ "status": 200,
173
205
  "content-type": "text/html"
174
206
  },
175
- body="",
176
- request=null,
177
- fileDispatcher=null,
178
- stream=null
179
- }){
207
+ body = "",
208
+ request = null,
209
+ fileDispatcher = null,
210
+ stream = null
211
+ }) {
180
212
  super(...arguments);
181
213
  var self = this;
182
- self.stream = self.stream;
214
+ self.stream = stream;
183
215
  self._generateResponse();
184
216
 
185
217
  }
@@ -219,18 +251,30 @@ Package("org.quickcorp.qcobjects.main.http.server",[
219
251
 
220
252
  // This catches any errors that happen while creating the readable stream (usually invalid names)
221
253
  readStream.on("error", function(err) {
254
+ const headers = {
255
+ "status": 500,
256
+ "content-type": mime.getType(fileName)
257
+ };
258
+ stream.setHeader("content-type", headers["content-type"]);
259
+ stream.setHeader("status", headers["status"]);
260
+ stream.write(`<h1>500 - INTERNAL SERVER ERROR</h1>
261
+ <p>${err}</p>
262
+ `);
263
+
222
264
  stream.end(err);
223
265
  });
224
266
 
225
267
  } catch (e){
226
268
  if (e.errno==-2){
227
269
  const headers = {
228
- ":status": 404,
229
- "content-type": "text/html"
270
+ "status": 404,
271
+ "content-type": mime.getType(fileName)
230
272
  };
273
+ stream.setHeader("content-type", headers["content-type"]);
274
+ stream.setHeader("status", headers["status"]);
231
275
  stream.write("<h1>404 - FILE NOT FOUND</h1>");
232
276
  stream.on("close", () => {
233
- console.log("closing file", fileName);
277
+ logger.debug("closing file " + fileName);
234
278
  });
235
279
  stream.end();
236
280
  }
@@ -245,16 +289,14 @@ Package("org.quickcorp.qcobjects.main.http.server",[
245
289
  response.headers = headers;
246
290
  var stream = response.stream;
247
291
  if (isTemplate){
248
- logger.debug("TEMPLATE");
249
292
  response.body = body;
250
- // stream.respond(response.headers);
293
+ Object.keys(headers).map((header)=>stream.setHeader(header, headers[header]));
251
294
  stream.write(response.body);
252
295
  stream.end();
253
- } else if (headers[":status"]==200){
254
- response.sendFile(stream,templateURI);
296
+ } else if (headers["status"] == 200 || headers[":status"] == 200) {
297
+ response.sendFile(stream, templateURI);
255
298
  } else {
256
- logger.debug("NONE ");
257
- // stream.respond(response.headers);
299
+ Object.keys(headers).map((header)=>stream.setHeader(header, headers[header]));
258
300
  stream.end();
259
301
  }
260
302
  }
@@ -265,40 +307,39 @@ Package("org.quickcorp.qcobjects.main.http.server",[
265
307
  },
266
308
 
267
309
  class HTTPServerRequest extends InheritClass {
268
- constructor ({
269
- scriptname="",
270
- path="",
271
- method="",
272
- url="",
273
- headers=null,
274
- flags=null,
275
- protocol= null,
276
- slashes= null,
277
- auth= null,
278
- host= null,
279
- port= null,
280
- hostname= null,
281
- hash= null,
282
- search= "",
283
- query= "",
284
- pathname= "",
285
- href= ""
286
- }){
310
+ constructor({
311
+ scriptname = "",
312
+ path = "",
313
+ method = "",
314
+ url = "",
315
+ headers = null,
316
+ flags = null,
317
+ protocol = null,
318
+ slashes = null,
319
+ auth = null,
320
+ host = null,
321
+ port = null,
322
+ hostname = null,
323
+ hash = null,
324
+ search = "",
325
+ query = "",
326
+ pathname = "",
327
+ href = ""
328
+ }) {
287
329
  super(...arguments);
288
330
  }
289
331
  },
290
332
 
291
333
  class HTTPServer extends InheritClass {
292
- constructor ({
293
- request=null,
294
- response="",
295
- server=null,
296
- scriptname="",
297
- interceptorInstances=[]
298
- }){
334
+ constructor({
335
+ request = null,
336
+ response = "",
337
+ server = null,
338
+ scriptname = "",
339
+ interceptorInstances = []
340
+ }) {
299
341
  super(...arguments);
300
342
 
301
- let oHTTPServer = this;
302
343
  const welcometo = "Welcome to \n";
303
344
  const instructions = "QCObjects Legacy HTTPServer \n";
304
345
  const logo = " .d88888b. .d8888b. .d88888b. 888 d8b 888 \r\nd88P\" \"Y88bd88P Y88bd88P\" \"Y88b888 Y8P 888 \r\n888 888888 888888 888888 888 \r\n888 888888 888 88888888b. 8888 .d88b. .d8888b888888.d8888b \r\n888 888888 888 888888 \"88b \"888d8P Y8bd88P\" 888 88K \r\n888 Y8b 888888 888888 888888 888 88888888888888 888 \"Y8888b. \r\nY88b.Y8b88PY88b d88PY88b. .d88P888 d88P 888Y8b. Y88b. Y88b. X88 \r\n \"Y888888\" \"Y8888P\" \"Y88888P\" 88888P\" 888 \"Y8888 \"Y8888P \"Y888 88888P' \r\n Y8b 888 \r\n d88P \r\n 888P\" ";
@@ -310,43 +351,40 @@ Package("org.quickcorp.qcobjects.main.http.server",[
310
351
  logger.info("Go to: \n"+this.showPossibleURL());
311
352
 
312
353
  const http = require("http");
313
-
314
- oHTTPServer.server = http.createServer((req, res) => {
315
-
354
+ this.server = http.createServer((req, res) => {
355
+ logger.debug("Legacy Server Instantiated.");
316
356
  });
317
357
 
318
- var server = oHTTPServer.server;
319
-
320
- server.on("error", (err) => console.error(err));
358
+ this.server.on("error", (err) => console.error(err));
321
359
 
322
360
  if (global.get("backendAvailable")){
323
361
  logger.info("Loading backend interceptors...");
324
- let interceptors = CONFIG.get("backend",{}).interceptors;
325
- if (typeof interceptors !== "undefined"){
362
+ let interceptors = CONFIG.get("backend", {}).interceptors;
363
+ if (typeof interceptors !== "undefined") {
326
364
  logger.info("Backend Interceptors Available");
327
- interceptors.map(interceptor=>{
328
- ImportMicroservice (interceptor.microservice);
329
- var interceptorClassFactory = ClassFactory(interceptor.microservice+".Interceptor");
330
- var interceptorInstance = New(interceptorClassFactory,{
331
- domain:CONFIG.get("domain"),
332
- basePath:CONFIG.get("basePath"),
333
- projectPath:CONFIG.get("projectPath"),
334
- interceptor:interceptor,
335
- server:server
365
+ interceptors.map(interceptor => {
366
+ ImportMicroservice(interceptor.microservice);
367
+ var interceptorClassFactory = ClassFactory(interceptor.microservice + ".Interceptor");
368
+ var interceptorInstance = New(interceptorClassFactory, {
369
+ domain: CONFIG.get("domain"),
370
+ basePath: CONFIG.get("basePath"),
371
+ projectPath: CONFIG.get("projectPath"),
372
+ interceptor: interceptor,
373
+ server: this.server
336
374
  });
337
- oHTTPServer.interceptorInstances.push(interceptorInstance);
375
+ this.interceptorInstances.push(interceptorInstance);
338
376
  });
339
377
  }
340
378
  }
341
379
 
342
- server.on("request", (req, res) => {
380
+ this.server.on("request", (req, res) => {
343
381
 
344
382
  let request = Object.assign(New(HTTPServerRequest),require("url").parse(req.url));
345
383
  request.headers = req.headers;
346
384
  this.request = request;
347
385
  this.request.method = req.method;
348
386
  this.request.path = req.url;
349
- server.setMaxListeners(9999999999);
387
+ this.server.setMaxListeners(9999999999);
350
388
  CONFIG.set("backendTimeout",CONFIG.get("backendTimeout") || 20000);
351
389
  var timeoutHandler = ()=>{
352
390
  // end the stream on timeout
@@ -364,15 +402,14 @@ Package("org.quickcorp.qcobjects.main.http.server",[
364
402
  } else {
365
403
  logger.debug("Session was normally finishing...");
366
404
  }
367
- }catch (e){
368
- logger.debug("An unhandled error occurred during timeout catching...");
369
- logger.debug(e.message);
405
+ } catch (e) {
406
+ logger.debug(`An unhandled error occurred during timeout catching: ${e}`);
370
407
  }
371
- server.removeListener("timeout",timeoutHandler);
408
+ this.server.removeListener("timeout",timeoutHandler);
372
409
 
373
410
  };
374
411
  if (!res.destroyed){
375
- server.setTimeout(CONFIG.get("backendTimeout"), timeoutHandler);
412
+ this.server.setTimeout(CONFIG.get("backendTimeout"), timeoutHandler);
376
413
  }
377
414
 
378
415
  if (this.request.pathname.indexOf(".")<0){
@@ -384,32 +421,54 @@ Package("org.quickcorp.qcobjects.main.http.server",[
384
421
 
385
422
  logger.debug((new PipeLog()).pipe(this.request));
386
423
 
387
- if (global.get("backendAvailable")){
388
- logger.info("Backend Legacy Microservices Available");
389
- let routes = CONFIG.get("backend").routes;
390
- let selectedRoute = routes.filter(route=>{let standardRoutePath = route.path.replace(/{(.*?)}/g,"(?<$1>.*)");return (new RegExp(standardRoutePath,"g")).test(request.path);});
391
- if (selectedRoute.length>0){
392
- selectedRoute.map(route=>{
393
- let standardRoutePath = route.path.replace(/{(.*?)}/g,"(?<$1>.*)"); //allowing {param}
394
- let selectedRouteParams = {...[...request.path.matchAll((new RegExp( standardRoutePath ,"g")))][0]["groups"]};
395
- ImportMicroservice (route.microservice);
396
- var microServiceClassFactory = ClassFactory(route.microservice+".Microservice");
397
- this.response = New(microServiceClassFactory,{
398
- domain:CONFIG.get("domain"),
399
- basePath:CONFIG.get("basePath"),
400
- projectPath:CONFIG.get("projectPath"),
401
- route:route,
402
- routeParams:selectedRouteParams,
403
- server:server,
404
- stream:res,
405
- req:req,
406
- request:request
424
+ if (global.get("backendAvailable")) {
425
+ logger.info("Backend Legacy Microservices Available...");
426
+
427
+ logger.info("Loading backend routes...");
428
+ let routes = CONFIG.get("backend", {}).routes;
429
+ let selectedRoute = routes.filter(route => {
430
+ let standardRoutePath = route.path.replace(/{(.*?)}/g, "(?<$1>.*)");
431
+ return (new RegExp(standardRoutePath, "g")).test(request.path);
432
+ });
433
+ if (selectedRoute.length > 0) {
434
+ selectedRoute.map(route => {
435
+ let standardRoutePath = route.path.replace(/{(.*?)}/g, "(?<$1>.*)"); //allowing {param}
436
+ console.log(standardRoutePath);
437
+ let selectedRouteParams = {
438
+ ...[...request.path.matchAll((new RegExp(standardRoutePath, "g")))][0]["groups"]
439
+ };
440
+ ImportMicroservice(route.microservice).then (()=>{
441
+ logger.debug(`Trying to execute ${route.microservice + ".Microservice"}...`);
442
+ var microServiceClassFactory = ClassFactory(route.microservice + ".Microservice");
443
+ if (typeof microServiceClassFactory !== "undefined"){
444
+ const server = this.server;
445
+ this.response = New(microServiceClassFactory, {
446
+ domain: CONFIG.get("domain"),
447
+ basePath: CONFIG.get("basePath"),
448
+ projectPath: CONFIG.get("projectPath"),
449
+ route: route,
450
+ routeParams: selectedRouteParams,
451
+ server: server,
452
+ stream: res,
453
+ req:req,
454
+ request: request
455
+ });
456
+
457
+ } else {
458
+ throw Error (`${route.microservice + ".Microservice"} not defined.`);
459
+ }
460
+ }).catch (e=> {
461
+ throw Error (e);
407
462
  });
408
463
  });
409
464
  } else {
410
465
  this.response = New(HTTPServerResponse,{
411
- server:server,
466
+ domain: CONFIG.get("domain"),
467
+ basePath: CONFIG.get("basePath"),
468
+ projectPath: CONFIG.get("projectPath"),
469
+ server:this.server,
412
470
  stream:res,
471
+ req:req,
413
472
  request:this.request
414
473
  });
415
474
  }
@@ -418,8 +477,9 @@ Package("org.quickcorp.qcobjects.main.http.server",[
418
477
  // ...
419
478
 
420
479
  this.response = New(HTTPServerResponse,{
421
- server:server,
480
+ server:this.server,
422
481
  stream:res,
482
+ req:req,
423
483
  request:this.request
424
484
  });
425
485
 
@@ -434,9 +494,9 @@ Package("org.quickcorp.qcobjects.main.http.server",[
434
494
  var _ret_ = "";
435
495
  var os = require("os");
436
496
  var ifaces = os.networkInterfaces();
437
- Object.keys(ifaces).forEach(function (iface){
438
- ifaces[iface].map(function (ipGroup){
439
- _ret_ += iface +": " + (new PipeLog()).pipe(ipGroup)+"\n";
497
+ Object.keys(ifaces).forEach(function (iface) {
498
+ ifaces[iface].map(function (ipGroup) {
499
+ _ret_ += iface + ": " + (new PipeLog()).pipe(ipGroup) + "\n";
440
500
  });
441
501
  });
442
502
  return _ret_;