@carbonorm/carbonnode 3.5.8 → 3.6.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 (79) hide show
  1. package/dist/api/orm/builders/ConditionBuilder.d.ts +1 -0
  2. package/dist/index.cjs.js +1251 -997
  3. package/dist/index.cjs.js.map +1 -1
  4. package/dist/index.esm.js +1253 -999
  5. package/dist/index.esm.js.map +1 -1
  6. package/package.json +2 -5
  7. package/scripts/generateRestBindings.cjs +1 -1
  8. package/scripts/generateRestBindings.ts +1 -1
  9. package/src/api/executors/HttpExecutor.ts +1 -3
  10. package/src/api/executors/SqlExecutor.ts +2 -1
  11. package/src/api/orm/builders/ConditionBuilder.ts +20 -9
  12. package/src/api/orm/queries/DeleteQueryBuilder.ts +1 -0
  13. package/src/api/orm/queries/PostQueryBuilder.ts +1 -0
  14. package/src/api/orm/queries/SelectQueryBuilder.ts +1 -0
  15. package/src/api/orm/queries/UpdateQueryBuilder.ts +1 -0
  16. package/dist/api/builders/queryHelpers.d.ts +0 -4
  17. package/dist/api/builders/sqlBuilder.d.ts +0 -33
  18. package/dist/api/carbonSqlExecutor.d.ts +0 -17
  19. package/dist/api/interfaces/ormInterfaces.d.ts +0 -87
  20. package/dist/api/orm/SqlBuilder.d.ts +0 -17
  21. package/dist/api/rest/Blog_Categories.d.ts +0 -37
  22. package/dist/api/rest/Blog_Categories.test.d.ts +0 -11
  23. package/dist/api/rest/Blog_Images.d.ts +0 -37
  24. package/dist/api/rest/Blog_Images.test.d.ts +0 -15
  25. package/dist/api/rest/Blog_Post_Categories.d.ts +0 -37
  26. package/dist/api/rest/Blog_Post_Categories.test.d.ts +0 -13
  27. package/dist/api/rest/Blog_Post_Tags.d.ts +0 -37
  28. package/dist/api/rest/Blog_Post_Tags.test.d.ts +0 -13
  29. package/dist/api/rest/Blog_Posts.d.ts +0 -37
  30. package/dist/api/rest/Blog_Posts.test.d.ts +0 -21
  31. package/dist/api/rest/Blog_Tags.d.ts +0 -37
  32. package/dist/api/rest/Blog_Tags.test.d.ts +0 -11
  33. package/dist/api/rest/C6.d.ts +0 -1000
  34. package/dist/api/rest/Cache.d.ts +0 -37
  35. package/dist/api/rest/Cache.test.d.ts +0 -12
  36. package/dist/api/rest/Cities.d.ts +0 -37
  37. package/dist/api/rest/Cities.test.d.ts +0 -17
  38. package/dist/api/rest/Counties.d.ts +0 -37
  39. package/dist/api/rest/Counties.test.d.ts +0 -18
  40. package/dist/api/rest/Countries.d.ts +0 -37
  41. package/dist/api/rest/Countries.test.d.ts +0 -24
  42. package/dist/api/rest/Geometries.d.ts +0 -37
  43. package/dist/api/rest/Geometries.test.d.ts +0 -16
  44. package/dist/api/rest/Images.d.ts +0 -37
  45. package/dist/api/rest/Images.test.d.ts +0 -16
  46. package/dist/api/rest/Land_Section_Info.d.ts +0 -37
  47. package/dist/api/rest/Land_Section_Info.test.d.ts +0 -15
  48. package/dist/api/rest/Neighborhoods.d.ts +0 -37
  49. package/dist/api/rest/Neighborhoods.test.d.ts +0 -12
  50. package/dist/api/rest/Parcel_Building_Details.d.ts +0 -37
  51. package/dist/api/rest/Parcel_Building_Details.test.d.ts +0 -40
  52. package/dist/api/rest/Parcel_Neighborhoods.d.ts +0 -37
  53. package/dist/api/rest/Parcel_Neighborhoods.test.d.ts +0 -15
  54. package/dist/api/rest/Parcel_Owners.d.ts +0 -37
  55. package/dist/api/rest/Parcel_Owners.test.d.ts +0 -23
  56. package/dist/api/rest/Parcel_Sales.d.ts +0 -37
  57. package/dist/api/rest/Parcel_Sales.test.d.ts +0 -19
  58. package/dist/api/rest/Parcel_Tax_History.d.ts +0 -37
  59. package/dist/api/rest/Parcel_Tax_History.test.d.ts +0 -24
  60. package/dist/api/rest/Parcels.d.ts +0 -37
  61. package/dist/api/rest/Parcels.test.d.ts +0 -42
  62. package/dist/api/rest/Payment_Charge_Logs.d.ts +0 -37
  63. package/dist/api/rest/Payment_Charge_Logs.test.d.ts +0 -17
  64. package/dist/api/rest/Payment_Subscriptions.d.ts +0 -37
  65. package/dist/api/rest/Payment_Subscriptions.test.d.ts +0 -20
  66. package/dist/api/rest/Property_Units.d.ts +0 -37
  67. package/dist/api/rest/Property_Units.test.d.ts +0 -55
  68. package/dist/api/rest/Sources.d.ts +0 -37
  69. package/dist/api/rest/Sources.test.d.ts +0 -17
  70. package/dist/api/rest/States.d.ts +0 -37
  71. package/dist/api/rest/States.test.d.ts +0 -20
  72. package/dist/api/rest/Tax_Districts.d.ts +0 -37
  73. package/dist/api/rest/Tax_Districts.test.d.ts +0 -12
  74. package/dist/api/rest/Users.d.ts +0 -37
  75. package/dist/api/rest/Users.test.d.ts +0 -14
  76. package/dist/api/rest/Valuation_Reports.d.ts +0 -37
  77. package/dist/api/rest/Valuation_Reports.test.d.ts +0 -36
  78. package/dist/api/rest/Zip_Codes.d.ts +0 -37
  79. package/dist/api/rest/Zip_Codes.test.d.ts +0 -15
package/dist/index.cjs.js CHANGED
@@ -2,12 +2,13 @@
2
2
 
3
3
  var axios = require('axios');
4
4
  var Qs = require('qs');
5
+ var tslib = require('tslib');
5
6
  var reactToastify = require('react-toastify');
6
7
  var namedPlaceholders = require('named-placeholders');
7
8
  var buffer = require('buffer');
8
9
 
9
10
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
10
- const C6Constants = {
11
+ var C6Constants = {
11
12
  // try to 1=1 match the Rest abstract class
12
13
  ADDDATE: 'ADDDATE',
13
14
  ADDTIME: 'ADDTIME',
@@ -165,7 +166,7 @@ const C6Constants = {
165
166
  FINISH: 'FINISH',
166
167
  VALIDATE_C6_ENTITY_ID_REGEX: '#^([a-fA-F0-9]{20,35})$#',
167
168
  };
168
- const C6C = C6Constants;
169
+ var C6C = C6Constants;
169
170
 
170
171
  // @link https://www.npmjs.com/package/axios-cache-adapter
171
172
  // updating these values
@@ -270,20 +271,22 @@ var axiosInstance = (axios.create({
270
271
  */
271
272
  }));
272
273
 
273
- function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler = alert) {
274
- const payload = {};
275
- const tableNames = Array.isArray(tableName) ? tableName : [tableName];
276
- const tableDefinitions = tableNames.map((name) => {
277
- const tableDefinition = Object.values(C6.TABLES).find((t) => t.TABLE_NAME === name);
274
+ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler) {
275
+ if (regexErrorHandler === void 0) { regexErrorHandler = alert; }
276
+ var payload = {};
277
+ var tableNames = Array.isArray(tableName) ? tableName : [tableName];
278
+ var tableDefinitions = tableNames.map(function (name) {
279
+ var tableDefinition = Object.values(C6.TABLES).find(function (t) { return t.TABLE_NAME === name; });
278
280
  if (!tableDefinition) {
279
- console.error(`Table name (${name}) is not found in the C6.TABLES object.`, C6.TABLES);
280
- throw new Error(`Table name (${name}) is not found in the C6.TABLES object.`);
281
+ console.error("Table name (".concat(name, ") is not found in the C6.TABLES object."), C6.TABLES);
282
+ throw new Error("Table name (".concat(name, ") is not found in the C6.TABLES object."));
281
283
  }
282
284
  return tableDefinition;
283
285
  });
284
- for (const tableDefinition of tableDefinitions) {
285
- for (const value of Object.keys(restfulObject)) {
286
- const shortReference = value.toUpperCase();
286
+ for (var _i = 0, tableDefinitions_1 = tableDefinitions; _i < tableDefinitions_1.length; _i++) {
287
+ var tableDefinition = tableDefinitions_1[_i];
288
+ var _loop_1 = function (value) {
289
+ var shortReference = value.toUpperCase();
287
290
  if ([
288
291
  C6Constants.GET,
289
292
  C6Constants.POST,
@@ -294,33 +297,36 @@ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler
294
297
  C6Constants.JOIN,
295
298
  C6Constants.PAGINATION
296
299
  ].includes(value)) {
297
- const val = restfulObject[value];
298
- if (Array.isArray(val)) {
299
- payload[value] = val.sort();
300
+ var val_1 = restfulObject[value];
301
+ if (Array.isArray(val_1)) {
302
+ payload[value] = val_1.sort();
300
303
  }
301
- else if (typeof val === 'object' && val !== null) {
302
- payload[value] = Object.keys(val)
304
+ else if (typeof val_1 === 'object' && val_1 !== null) {
305
+ payload[value] = Object.keys(val_1)
303
306
  .sort()
304
- .reduce((acc, key) => ({ ...acc, [key]: val[key] }), {});
307
+ .reduce(function (acc, key) {
308
+ var _a;
309
+ return (tslib.__assign(tslib.__assign({}, acc), (_a = {}, _a[key] = val_1[key], _a)));
310
+ }, {});
305
311
  }
306
- continue;
312
+ return "continue";
307
313
  }
308
314
  if (shortReference in tableDefinition) {
309
- const longName = tableDefinition[shortReference];
310
- const columnValue = restfulObject[value];
315
+ var longName = tableDefinition[shortReference];
316
+ var columnValue = restfulObject[value];
311
317
  payload[longName] = columnValue;
312
- const regexValidations = tableDefinition.REGEX_VALIDATION[longName];
318
+ var regexValidations = tableDefinition.REGEX_VALIDATION[longName];
313
319
  if (regexValidations instanceof RegExp) {
314
320
  if (!regexValidations.test(columnValue)) {
315
- regexErrorHandler(`Failed to match regex (${regexValidations}) for column (${longName})`);
316
- throw new Error(`Failed to match regex (${regexValidations}) for column (${longName})`);
321
+ regexErrorHandler("Failed to match regex (".concat(regexValidations, ") for column (").concat(longName, ")"));
322
+ throw new Error("Failed to match regex (".concat(regexValidations, ") for column (").concat(longName, ")"));
317
323
  }
318
324
  }
319
325
  else if (typeof regexValidations === 'object' && regexValidations !== null) {
320
- for (const errorMessage in regexValidations) {
321
- const regex = regexValidations[errorMessage];
326
+ for (var errorMessage in regexValidations) {
327
+ var regex = regexValidations[errorMessage];
322
328
  if (!regex.test(columnValue)) {
323
- const devErrorMessage = `Failed to match regex (${regex}) for column (${longName})`;
329
+ var devErrorMessage = "Failed to match regex (".concat(regex, ") for column (").concat(longName, ")");
324
330
  regexErrorHandler(errorMessage || devErrorMessage);
325
331
  throw new Error(devErrorMessage);
326
332
  }
@@ -329,37 +335,45 @@ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler
329
335
  }
330
336
  else if (Object.values(tableDefinition.COLUMNS).includes(value)) {
331
337
  // Already a fully qualified column name
332
- const columnValue = restfulObject[value];
338
+ var columnValue = restfulObject[value];
333
339
  payload[value] = columnValue;
334
- const regexValidations = tableDefinition.REGEX_VALIDATION[value];
340
+ var regexValidations = tableDefinition.REGEX_VALIDATION[value];
335
341
  if (regexValidations instanceof RegExp) {
336
342
  if (!regexValidations.test(columnValue)) {
337
- regexErrorHandler(`Failed to match regex (${regexValidations}) for column (${value})`);
338
- throw new Error(`Failed to match regex (${regexValidations}) for column (${value})`);
343
+ regexErrorHandler("Failed to match regex (".concat(regexValidations, ") for column (").concat(value, ")"));
344
+ throw new Error("Failed to match regex (".concat(regexValidations, ") for column (").concat(value, ")"));
339
345
  }
340
346
  }
341
347
  else if (typeof regexValidations === 'object' && regexValidations !== null) {
342
- for (const errorMessage in regexValidations) {
343
- const regex = regexValidations[errorMessage];
348
+ for (var errorMessage in regexValidations) {
349
+ var regex = regexValidations[errorMessage];
344
350
  if (!regex.test(columnValue)) {
345
- const devErrorMessage = `Failed to match regex (${regex}) for column (${value})`;
351
+ var devErrorMessage = "Failed to match regex (".concat(regex, ") for column (").concat(value, ")");
346
352
  regexErrorHandler(errorMessage || devErrorMessage);
347
353
  throw new Error(devErrorMessage);
348
354
  }
349
355
  }
350
356
  }
351
357
  }
358
+ };
359
+ for (var _a = 0, _b = Object.keys(restfulObject); _a < _b.length; _a++) {
360
+ var value = _b[_a];
361
+ _loop_1(value);
352
362
  }
353
363
  }
354
364
  return Object.keys(payload)
355
365
  .sort()
356
- .reduce((acc, key) => ({ ...acc, [key]: payload[key] }), {});
366
+ .reduce(function (acc, key) {
367
+ var _a;
368
+ return (tslib.__assign(tslib.__assign({}, acc), (_a = {}, _a[key] = payload[key], _a)));
369
+ }, {});
357
370
  }
358
371
 
359
- const isNode = () => {
372
+ var isNode = function () {
373
+ var _a;
360
374
  console.log('Checking if running in Node.js environment...');
361
- const isNodeEnv = typeof process !== 'undefined' && !!process.versions?.node;
362
- console.log(`Is Node.js environment: ${isNodeEnv}`);
375
+ var isNodeEnv = typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
376
+ console.log("Is Node.js environment: ".concat(isNodeEnv));
363
377
  return isNodeEnv;
364
378
  };
365
379
 
@@ -367,94 +381,112 @@ const isNode = () => {
367
381
  * Facade: routes API calls to SQL or HTTP executors based on runtime context.
368
382
  */
369
383
  function restRequest(configX) {
370
- return async (request) => {
371
- const config = typeof configX === "function" ? configX() : configX;
372
- config.verbose ??= true; // Default to verbose logging if not set
373
- // SQL path if on Node with a provided pool
374
- if (isNode() && config.mysqlPool) {
375
- const { SqlExecutor } = await Promise.resolve().then(function () { return SqlExecutor$1; });
376
- const executor = new SqlExecutor(config, request);
377
- return executor.execute();
378
- }
379
- // HTTP path fallback
380
- const { HttpExecutor } = await Promise.resolve().then(function () { return HttpExecutor$1; });
381
- const http = new HttpExecutor(config, request);
382
- return http.execute();
383
- };
384
+ var _this = this;
385
+ return function (request) { return tslib.__awaiter(_this, void 0, void 0, function () {
386
+ var config, SqlExecutor, executor, HttpExecutor, http;
387
+ var _a;
388
+ return tslib.__generator(this, function (_b) {
389
+ switch (_b.label) {
390
+ case 0:
391
+ config = typeof configX === "function" ? configX() : configX;
392
+ (_a = config.verbose) !== null && _a !== void 0 ? _a : (config.verbose = true); // Default to verbose logging if not set
393
+ if (!(isNode() && config.mysqlPool)) return [3 /*break*/, 2];
394
+ return [4 /*yield*/, Promise.resolve().then(function () { return SqlExecutor$1; })];
395
+ case 1:
396
+ SqlExecutor = (_b.sent()).SqlExecutor;
397
+ executor = new SqlExecutor(config, request);
398
+ return [2 /*return*/, executor.execute()];
399
+ case 2: return [4 /*yield*/, Promise.resolve().then(function () { return HttpExecutor$1; })];
400
+ case 3:
401
+ HttpExecutor = (_b.sent()).HttpExecutor;
402
+ http = new HttpExecutor(config, request);
403
+ return [2 /*return*/, http.execute()];
404
+ }
405
+ });
406
+ }); };
384
407
  }
385
408
 
386
409
  function restOrm(configFn) {
387
410
  return {
388
- Get: restRequest(() => ({
389
- ...configFn(),
390
- requestMethod: "GET"
391
- })),
392
- Put: restRequest(() => ({
393
- ...configFn(),
394
- requestMethod: "PUT"
395
- })),
396
- Post: restRequest(() => ({
397
- ...configFn(),
398
- requestMethod: "POST"
399
- })),
400
- Delete: restRequest(() => ({
401
- ...configFn(),
402
- requestMethod: "DELETE"
403
- }))
411
+ Get: restRequest(function () { return (tslib.__assign(tslib.__assign({}, configFn()), { requestMethod: "GET" })); }),
412
+ Put: restRequest(function () { return (tslib.__assign(tslib.__assign({}, configFn()), { requestMethod: "PUT" })); }),
413
+ Post: restRequest(function () { return (tslib.__assign(tslib.__assign({}, configFn()), { requestMethod: "POST" })); }),
414
+ Delete: restRequest(function () { return (tslib.__assign(tslib.__assign({}, configFn()), { requestMethod: "DELETE" })); })
404
415
  };
405
416
  }
406
417
 
407
- function timeout(shouldContinueAfterTimeout, cb, timeoutMs = 3000) {
408
- const timer = () => setTimeout(() => {
418
+ function timeout(shouldContinueAfterTimeout, cb, timeoutMs) {
419
+ if (timeoutMs === void 0) { timeoutMs = 3000; }
420
+ var timer = function () { return setTimeout(function () {
409
421
  if (false === shouldContinueAfterTimeout()) {
410
422
  return;
411
423
  }
412
424
  cb();
413
- }, timeoutMs);
414
- const timerId = timer();
415
- return () => {
425
+ }, timeoutMs); };
426
+ var timerId = timer();
427
+ return function () {
416
428
  clearTimeout(timerId);
417
429
  };
418
430
  }
419
431
 
420
- class Executor {
421
- config;
422
- request;
423
- useNamedParams;
424
- constructor(config, request, useNamedParams = false) {
432
+ var Executor = /** @class */ (function () {
433
+ function Executor(config, request, useNamedParams) {
434
+ if (useNamedParams === void 0) { useNamedParams = false; }
425
435
  this.config = config;
426
436
  this.request = request;
427
437
  this.useNamedParams = useNamedParams;
428
438
  }
429
- async runLifecycleHooks(phase, args) {
430
- const lifecycleGroup = this.config.restModel.LIFECYCLE_HOOKS[this.config.requestMethod]?.[phase];
431
- if (!lifecycleGroup)
432
- return;
433
- for (const [key, fn] of Object.entries(lifecycleGroup)) {
434
- if (typeof fn === "function") {
435
- if (this.config.verbose || args.request.debug) {
436
- console.groupCollapsed(`[LIFECYCLE] ${this.config.requestMethod}.${String(phase)}:${key}`);
437
- console.log("config:", args.config);
438
- console.log("request:", args.request);
439
- if ("response" in args) {
440
- console.log("response:", args.response);
441
- }
442
- console.groupEnd();
443
- }
444
- try {
445
- // todo - this
446
- await fn(args);
447
- }
448
- catch (err) {
449
- console.error(`[LIFECYCLE ERROR] ${this.config.requestMethod}.${String(phase)}:${key}`, err);
450
- throw err;
439
+ Executor.prototype.runLifecycleHooks = function (phase, args) {
440
+ return tslib.__awaiter(this, void 0, void 0, function () {
441
+ var lifecycleGroup, _i, _a, _b, key, fn, err_1;
442
+ var _c;
443
+ return tslib.__generator(this, function (_d) {
444
+ switch (_d.label) {
445
+ case 0:
446
+ lifecycleGroup = (_c = this.config.restModel.LIFECYCLE_HOOKS[this.config.requestMethod]) === null || _c === void 0 ? void 0 : _c[phase];
447
+ if (!lifecycleGroup)
448
+ return [2 /*return*/];
449
+ _i = 0, _a = Object.entries(lifecycleGroup);
450
+ _d.label = 1;
451
+ case 1:
452
+ if (!(_i < _a.length)) return [3 /*break*/, 6];
453
+ _b = _a[_i], key = _b[0], fn = _b[1];
454
+ if (!(typeof fn === "function")) return [3 /*break*/, 5];
455
+ if (this.config.verbose || args.request.debug) {
456
+ console.groupCollapsed("[LIFECYCLE] ".concat(this.config.requestMethod, ".").concat(String(phase), ":").concat(key));
457
+ console.log("config:", args.config);
458
+ console.log("request:", args.request);
459
+ if ("response" in args) {
460
+ console.log("response:", args.response);
461
+ }
462
+ console.groupEnd();
463
+ }
464
+ _d.label = 2;
465
+ case 2:
466
+ _d.trys.push([2, 4, , 5]);
467
+ // todo - this
468
+ return [4 /*yield*/, fn(args)];
469
+ case 3:
470
+ // todo - this
471
+ _d.sent();
472
+ return [3 /*break*/, 5];
473
+ case 4:
474
+ err_1 = _d.sent();
475
+ console.error("[LIFECYCLE ERROR] ".concat(this.config.requestMethod, ".").concat(String(phase), ":").concat(key), err_1);
476
+ throw err_1;
477
+ case 5:
478
+ _i++;
479
+ return [3 /*break*/, 1];
480
+ case 6: return [2 /*return*/];
451
481
  }
452
- }
453
- }
454
- }
455
- }
482
+ });
483
+ });
484
+ };
485
+ return Executor;
486
+ }());
456
487
 
457
- function getEnvVar(key, fallback = '') {
488
+ function getEnvVar(key, fallback) {
489
+ if (fallback === void 0) { fallback = ''; }
458
490
  // Vite-style injection
459
491
  // @ts-ignore
460
492
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) }) !== 'undefined' && undefined && key in undefined) {
@@ -491,12 +523,12 @@ exports.eFetchDependencies = void 0;
491
523
  })(exports.eFetchDependencies || (exports.eFetchDependencies = {}));
492
524
 
493
525
  // Refined TypeScript types for CarbonORM
494
- const POST = 'POST';
495
- const PUT = 'PUT';
496
- const GET = 'GET';
497
- const DELETE = 'DELETE';
526
+ var POST = 'POST';
527
+ var PUT = 'PUT';
528
+ var GET = 'GET';
529
+ var DELETE = 'DELETE';
498
530
 
499
- const toastOptions = {
531
+ var toastOptions = {
500
532
  position: "bottom-left",
501
533
  autoClose: 10000,
502
534
  hideProgressBar: false,
@@ -505,7 +537,7 @@ const toastOptions = {
505
537
  draggable: true,
506
538
  theme: "dark",
507
539
  };
508
- const toastOptionsDevs = {
540
+ var toastOptionsDevs = {
509
541
  position: "bottom-right",
510
542
  autoClose: 3000,
511
543
  hideProgressBar: false,
@@ -517,19 +549,20 @@ const toastOptionsDevs = {
517
549
 
518
550
  // When we capture DropExceptions and display them as a custom page, this will change.
519
551
  function TestRestfulResponse(response, success, error) {
520
- if (undefined === response.data?.['ERROR TYPE']
521
- && (undefined !== response?.data?.rest
522
- || undefined !== response.data?.created
523
- || undefined !== response.data?.updated
524
- || undefined !== response.data?.deleted)) {
525
- let successReturn = 'function' === typeof success ? success?.(response) : success;
552
+ var _a, _b, _c, _d, _e, _f, _g, _h;
553
+ if (undefined === ((_a = response.data) === null || _a === void 0 ? void 0 : _a['ERROR TYPE'])
554
+ && (undefined !== ((_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.rest)
555
+ || undefined !== ((_c = response.data) === null || _c === void 0 ? void 0 : _c.created)
556
+ || undefined !== ((_d = response.data) === null || _d === void 0 ? void 0 : _d.updated)
557
+ || undefined !== ((_e = response.data) === null || _e === void 0 ? void 0 : _e.deleted))) {
558
+ var successReturn = 'function' === typeof success ? success === null || success === void 0 ? void 0 : success(response) : success;
526
559
  if (typeof successReturn === 'string') {
527
560
  reactToastify.toast.success(successReturn, toastOptions);
528
561
  }
529
562
  // this could end up with bad results for deleting id's === 0
530
- return response.data.created ?? response.data.updated ?? response.data.deleted ?? true;
563
+ return (_h = (_g = (_f = response.data.created) !== null && _f !== void 0 ? _f : response.data.updated) !== null && _g !== void 0 ? _g : response.data.deleted) !== null && _h !== void 0 ? _h : true;
531
564
  }
532
- let errorReturn = 'function' === typeof error ? error?.(response) : error;
565
+ var errorReturn = 'function' === typeof error ? error === null || error === void 0 ? void 0 : error(response) : error;
533
566
  if (typeof errorReturn === 'string') {
534
567
  reactToastify.toast.error(errorReturn, toastOptions);
535
568
  }
@@ -542,15 +575,15 @@ function removePrefixIfExists(tableName, prefix) {
542
575
  return tableName;
543
576
  }
544
577
  function removeInvalidKeys(request, c6Tables) {
545
- let intersection = {};
546
- let restfulObjectKeys = [];
547
- const tableList = Object.values(c6Tables);
548
- tableList.forEach(table => Object.values(table.COLUMNS).forEach(column => {
578
+ var intersection = {};
579
+ var restfulObjectKeys = [];
580
+ var tableList = Object.values(c6Tables);
581
+ tableList.forEach(function (table) { return Object.values(table.COLUMNS).forEach(function (column) {
549
582
  if (false === restfulObjectKeys.includes(column)) {
550
583
  restfulObjectKeys.push(column);
551
584
  }
552
- }));
553
- Object.keys(request).forEach(key => {
585
+ }); });
586
+ Object.keys(request).forEach(function (key) {
554
587
  if (restfulObjectKeys.includes(key)) {
555
588
  intersection[key] = request[key];
556
589
  }
@@ -564,10 +597,10 @@ function removeInvalidKeys(request, c6Tables) {
564
597
  exports.apiRequestCache = [];
565
598
  exports.userCustomClearCache = [];
566
599
  function clearCache(props) {
567
- if (false === props?.ignoreWarning) {
600
+ if (false === (props === null || props === void 0 ? void 0 : props.ignoreWarning)) {
568
601
  console.warn('The rest api clearCache should only be used with extreme care! Avoid using this in favor of using `cacheResults : boolean`.');
569
602
  }
570
- exports.userCustomClearCache.map((f) => 'function' === typeof f && f());
603
+ exports.userCustomClearCache.map(function (f) { return 'function' === typeof f && f(); });
571
604
  exports.userCustomClearCache = exports.apiRequestCache = [];
572
605
  }
573
606
  function checkCache(cacheResult, requestMethod, tableName, request) {
@@ -582,551 +615,601 @@ function checkCache(cacheResult, requestMethod, tableName, request) {
582
615
  }
583
616
 
584
617
  function sortAndSerializeQueryObject(tables, query) {
585
- const orderedQuery = Object.keys(query).sort().reduce((obj, key) => {
618
+ var orderedQuery = Object.keys(query).sort().reduce(function (obj, key) {
586
619
  obj[key] = query[key];
587
620
  return obj;
588
621
  }, {});
589
622
  return tables + ' ' + JSON.stringify(orderedQuery);
590
623
  }
591
624
 
592
- class HttpExecutor extends Executor {
593
- putState(response, request, callback) {
594
- this.config.reactBootstrap?.updateRestfulObjectArrays({
595
- callback,
625
+ var HttpExecutor = /** @class */ (function (_super) {
626
+ tslib.__extends(HttpExecutor, _super);
627
+ function HttpExecutor() {
628
+ return _super !== null && _super.apply(this, arguments) || this;
629
+ }
630
+ HttpExecutor.prototype.putState = function (response, request, callback) {
631
+ var _a, _b;
632
+ (_a = this.config.reactBootstrap) === null || _a === void 0 ? void 0 : _a.updateRestfulObjectArrays({
633
+ callback: callback,
596
634
  dataOrCallback: [
597
- removeInvalidKeys({
598
- ...request,
599
- ...response?.data?.rest,
600
- }, this.config.C6.TABLES)
635
+ removeInvalidKeys(tslib.__assign(tslib.__assign({}, request), (_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.rest), this.config.C6.TABLES)
601
636
  ],
602
637
  stateKey: this.config.restModel.TABLE_NAME,
603
638
  uniqueObjectId: this.config.restModel.PRIMARY_SHORT
604
639
  });
605
- }
606
- postState(response, request, callback) {
640
+ };
641
+ HttpExecutor.prototype.postState = function (response, request, callback) {
642
+ var _this = this;
643
+ var _a, _b, _c;
607
644
  if (1 !== this.config.restModel.PRIMARY_SHORT.length) {
608
645
  console.error("C6 received unexpected result's given the primary key length");
609
646
  }
610
647
  else {
611
- const pk = this.config.restModel.PRIMARY_SHORT[0];
648
+ var pk = this.config.restModel.PRIMARY_SHORT[0];
612
649
  // TODO - should overrides be handled differently? Why override: (react/php), driver missmatches, aux data..
613
650
  // @ts-ignore - this is technically a correct error, but we allow it anyway...
614
- request[pk] = response.data?.created;
651
+ request[pk] = (_a = response.data) === null || _a === void 0 ? void 0 : _a.created;
615
652
  }
616
- this.config.reactBootstrap?.updateRestfulObjectArrays({
617
- callback,
653
+ (_b = this.config.reactBootstrap) === null || _b === void 0 ? void 0 : _b.updateRestfulObjectArrays({
654
+ callback: callback,
618
655
  dataOrCallback: undefined !== request.dataInsertMultipleRows
619
- ? request.dataInsertMultipleRows.map((request, index) => {
620
- return removeInvalidKeys({
621
- ...request,
622
- ...(index === 0 ? response?.data?.rest : {}),
623
- }, this.config.C6.TABLES);
656
+ ? request.dataInsertMultipleRows.map(function (request, index) {
657
+ var _a;
658
+ return removeInvalidKeys(tslib.__assign(tslib.__assign({}, request), (index === 0 ? (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.rest : {})), _this.config.C6.TABLES);
624
659
  })
625
660
  : [
626
- removeInvalidKeys({
627
- ...request,
628
- ...response?.data?.rest,
629
- }, this.config.C6.TABLES)
661
+ removeInvalidKeys(tslib.__assign(tslib.__assign({}, request), (_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.rest), this.config.C6.TABLES)
630
662
  ],
631
663
  stateKey: this.config.restModel.TABLE_NAME,
632
664
  uniqueObjectId: this.config.restModel.PRIMARY_SHORT
633
665
  });
634
- }
635
- deleteState(_response, request, callback) {
636
- this.config.reactBootstrap?.deleteRestfulObjectArrays({
637
- callback,
666
+ };
667
+ HttpExecutor.prototype.deleteState = function (_response, request, callback) {
668
+ var _a;
669
+ (_a = this.config.reactBootstrap) === null || _a === void 0 ? void 0 : _a.deleteRestfulObjectArrays({
670
+ callback: callback,
638
671
  dataOrCallback: [
639
672
  request,
640
673
  ],
641
674
  stateKey: this.config.restModel.TABLE_NAME,
642
675
  uniqueObjectId: this.config.restModel.PRIMARY_SHORT
643
676
  });
644
- }
645
- async execute() {
646
- const { C6, axios, restURL, withCredentials, restModel, reactBootstrap, requestMethod, skipPrimaryCheck, clearCache, } = this.config;
647
- console.log('this.config', this.config);
648
- await this.runLifecycleHooks("beforeProcessing", {
649
- config: this.config,
650
- request: this.request,
651
- });
652
- const tableName = restModel.TABLE_NAME;
653
- const fullTableList = Array.isArray(tableName) ? tableName : [tableName];
654
- const operatingTableFullName = fullTableList[0];
655
- const operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
656
- const tables = fullTableList.join(',');
657
- switch (requestMethod) {
658
- case GET:
659
- case POST:
660
- case PUT:
661
- case DELETE:
662
- break;
663
- default:
664
- throw Error('Bad request method passed to getApi');
665
- }
666
- if (null !== clearCache || undefined !== clearCache) {
667
- exports.userCustomClearCache[tables + requestMethod] = clearCache;
668
- }
669
- console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0');
670
- console.log('request', this.request);
671
- console.groupEnd();
672
- // an undefined query would indicate queryCallback returned undefined,
673
- // thus the request shouldn't fire as is in custom cache
674
- if (undefined === this.request || null === this.request) {
675
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + tableName + ') undefined, returning null (will not fire)!', 'color: #c00');
676
- console.log('request', this.request);
677
- console.log('%c Returning (undefined|null) for a query would indicate a custom cache hit (outside API.tsx), thus the request should not fire.', 'color: #c00');
678
- console.trace();
679
- console.groupEnd();
680
- return null;
681
- }
682
- let query = this.request;
683
- if (C6.GET === requestMethod) {
684
- if (undefined === query[C6.PAGINATION]) {
685
- query[C6.PAGINATION] = {};
686
- }
687
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
688
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
689
- }
690
- // this is parameterless and could return itself with a new page number, or undefined if the end is reached
691
- const apiRequest = async () => {
692
- const { debug, cacheResults = (C6.GET === requestMethod), dataInsertMultipleRows, success, fetchDependencies = exports.eFetchDependencies.NONE, error = "An unexpected API error occurred!" } = this.request;
693
- if (C6.GET === requestMethod
694
- && undefined !== query?.[C6.PAGINATION]?.[C6.PAGE]
695
- && 1 !== query[C6.PAGINATION][C6.PAGE]) {
696
- console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
697
- console.log('Request Data (note you may see the success and/or error prompt):', this.request);
698
- console.trace();
699
- console.groupEnd();
700
- }
701
- // The problem with creating cache keys with a stringified object is the order of keys matters and it's possible for the same query to be stringified differently.
702
- // Here we ensure the key order will be identical between two of the same requests. https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key
703
- // literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
704
- let querySerialized = sortAndSerializeQueryObject(tables, query ?? {});
705
- let cacheResult = exports.apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
706
- let cachingConfirmed = false;
707
- // determine if we need to paginate.
708
- if (requestMethod === C6.GET) {
709
- if (undefined === query?.[C6.PAGINATION]) {
710
- if (undefined === query || null === query) {
711
- query = {};
712
- }
713
- query[C6.PAGINATION] = {};
714
- }
715
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
716
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
717
- // this will evaluate true most the time
718
- if (true === cacheResults) {
719
- // just find the next, non-fetched, page and return a function to request it
720
- if (undefined !== cacheResult) { // we will return in this loop
721
- do {
722
- const cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
723
- if (false !== cacheCheck) {
724
- return (await cacheCheck).data;
725
- }
726
- // this line incrementing page is why we return recursively
727
- ++query[C6.PAGINATION][C6.PAGE];
728
- // this json stringify is to capture the new page number
729
- querySerialized = sortAndSerializeQueryObject(tables, query ?? {});
730
- cacheResult = exports.apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
731
- } while (undefined !== cacheResult);
732
- if (debug && isLocal()) {
733
- reactToastify.toast.warning("DEVS: Request in cache. (" + exports.apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
734
- }
735
- // @ts-ignore - this is an incorrect warning on TS, it's well typed
736
- return apiRequest;
737
- }
738
- cachingConfirmed = true;
739
- }
740
- else {
741
- if (debug && isLocal()) {
742
- reactToastify.toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
743
- }
744
- }
745
- if (debug && isLocal()) {
746
- reactToastify.toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
747
- }
748
- }
749
- else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
750
- if (cacheResult) {
751
- const cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
752
- if (false !== cacheCheck) {
753
- return (await cacheCheck).data;
754
- }
755
- }
756
- cachingConfirmed = true;
757
- // push to cache so we do not repeat the request
758
- }
759
- let addBackPK;
760
- let apiResponse;
761
- let returnGetNextPageFunction = false;
762
- let restRequestUri = restURL + operatingTable + '/';
763
- const needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
764
- && false === skipPrimaryCheck;
765
- const TABLES = C6.TABLES;
766
- // todo - aggregate primary key check with condition check
767
- // check if PK exists in query, clone so pop does not affect the real data
768
- const primaryKey = structuredClone(TABLES[operatingTable]?.PRIMARY)?.pop()?.split('.')?.pop();
769
- if (needsConditionOrPrimaryCheck) {
770
- if (undefined === primaryKey) {
771
- if (null === query
772
- || undefined === query
773
- || undefined === query?.[C6.WHERE]
774
- || (true === Array.isArray(query[C6.WHERE])
775
- || query[C6.WHERE].length === 0)
776
- || (Object.keys(query?.[C6.WHERE]).length === 0)) {
777
- console.error(query);
778
- throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify(TABLES[operatingTable]?.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
779
- }
780
- }
781
- else {
782
- if (undefined === query
783
- || null === query
784
- || false === primaryKey in query) {
785
- if (true === debug && isLocal()) {
786
- reactToastify.toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
787
- }
788
- throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
789
- }
790
- if (undefined === query?.[primaryKey]
791
- || null === query?.[primaryKey]) {
792
- reactToastify.toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
793
- throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
794
- }
795
- }
796
- }
797
- // A part of me exists that wants to remove this, but it's a good feature
798
- // this allows developers the ability to cache requests based on primary key
799
- // for tables like `photos` this can be a huge performance boost
800
- if (undefined !== query
801
- && null !== query
802
- && undefined !== primaryKey
803
- && primaryKey in query) {
804
- restRequestUri += query[primaryKey] + '/';
805
- const removedPkValue = query[primaryKey];
806
- addBackPK = () => {
807
- query ??= {};
808
- query[primaryKey] = removedPkValue;
809
- };
810
- delete query[primaryKey];
811
- console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue);
812
- }
813
- else {
814
- console.log('query', query);
815
- }
816
- try {
817
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
818
- console.log(this.request);
819
- console.log('%c If this is the first request for this datatype; thus the value being set is currently undefined, please remember to update the state to null.', 'color: #A020F0');
820
- console.log('%c Remember undefined indicated the request has not fired, null indicates the request is firing, an empty array would signal no data was returned for the sql stmt.', 'color: #A020F0');
821
- console.trace();
822
- console.groupEnd();
823
- this.runLifecycleHooks("beforeExecution", {
824
- config: this.config,
825
- request: this.request
826
- });
827
- const axiosActiveRequest = axios[requestMethod.toLowerCase()](restRequestUri, ...(() => {
828
- const convert = (data) => convertForRequestBody(data, fullTableList, C6, (message) => reactToastify.toast.error(message, toastOptions));
829
- const baseConfig = {
830
- withCredentials: withCredentials,
831
- };
832
- switch (requestMethod) {
833
- case GET:
834
- return [{
835
- ...baseConfig,
836
- params: query
837
- }];
838
- case POST:
839
- if (dataInsertMultipleRows !== undefined) {
840
- return [
841
- dataInsertMultipleRows.map(convert),
842
- baseConfig
843
- ];
844
- }
845
- return [convert(query), baseConfig];
846
- case PUT:
847
- return [convert(query), baseConfig];
848
- case DELETE:
849
- return [{
850
- ...baseConfig,
851
- data: convert(query)
852
- }];
853
- default:
854
- throw new Error(`The request method (${requestMethod}) was not recognized.`);
855
- }
856
- })());
857
- if (cachingConfirmed) {
858
- // push to cache so we do not repeat the request
859
- exports.apiRequestCache.push({
860
- requestArgumentsSerialized: querySerialized,
861
- request: axiosActiveRequest
862
- });
863
- }
864
- // todo - wip verify this works
865
- // we had removed the value from the request to add to the URI.
866
- addBackPK?.(); // adding back so post-processing methods work
867
- // returning the promise with this then is important for tests. todo - we could make that optional.
868
- // https://rapidapi.com/guides/axios-async-await
869
- return axiosActiveRequest.then(async (response) => {
870
- // noinspection SuspiciousTypeOfGuard
871
- if (typeof response.data === 'string') {
872
- if (isTest()) {
873
- console.trace();
874
- throw new Error('The response data was a string this typically indicated html was sent. Make sure all cookies (' + JSON.stringify(response.config.headers) + ') needed are present! (' + response.data + ')');
875
- }
876
- return Promise.reject(response);
877
- }
878
- if (cachingConfirmed) {
879
- const cacheIndex = exports.apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized);
880
- // TODO - currently nonthing is setting this correctly
881
- exports.apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
882
- // only cache get method requests
883
- exports.apiRequestCache[cacheIndex].response = response;
884
- }
885
- this.runLifecycleHooks("afterExecution", {
886
- config: this.config,
887
- request: this.request,
888
- response
889
- });
890
- // todo - this feels dumb now, but i digress
891
- apiResponse = TestRestfulResponse(response, success, error);
892
- if (false === apiResponse) {
893
- if (debug && isLocal()) {
894
- reactToastify.toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
895
- }
896
- return response;
897
- }
898
- const callback = () => this.runLifecycleHooks("afterCommit", {
899
- config: this.config,
900
- request: this.request,
901
- response
902
- });
903
- if (undefined !== reactBootstrap && response) {
677
+ };
678
+ HttpExecutor.prototype.execute = function () {
679
+ return tslib.__awaiter(this, void 0, void 0, function () {
680
+ var _a, C6, axios, restURL, withCredentials, restModel, reactBootstrap, requestMethod, skipPrimaryCheck, clearCache, tableName, fullTableList, operatingTableFullName, operatingTable, tables, query, apiRequest;
681
+ var _this = this;
682
+ return tslib.__generator(this, function (_b) {
683
+ switch (_b.label) {
684
+ case 0:
685
+ _a = this.config, C6 = _a.C6, axios = _a.axios, restURL = _a.restURL, withCredentials = _a.withCredentials, restModel = _a.restModel, reactBootstrap = _a.reactBootstrap, requestMethod = _a.requestMethod, skipPrimaryCheck = _a.skipPrimaryCheck, clearCache = _a.clearCache;
686
+ console.log('this.config', this.config);
687
+ return [4 /*yield*/, this.runLifecycleHooks("beforeProcessing", {
688
+ config: this.config,
689
+ request: this.request,
690
+ })];
691
+ case 1:
692
+ _b.sent();
693
+ tableName = restModel.TABLE_NAME;
694
+ fullTableList = Array.isArray(tableName) ? tableName : [tableName];
695
+ operatingTableFullName = fullTableList[0];
696
+ operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
697
+ tables = fullTableList.join(',');
904
698
  switch (requestMethod) {
905
699
  case GET:
906
- response.data && reactBootstrap.updateRestfulObjectArrays({
907
- dataOrCallback: Array.isArray(response.data.rest) ? response.data.rest : [response.data.rest],
908
- stateKey: this.config.restModel.TABLE_NAME,
909
- uniqueObjectId: this.config.restModel.PRIMARY_SHORT,
910
- callback
911
- });
912
- break;
913
700
  case POST:
914
- this.postState(response, this.request, callback);
915
- break;
916
701
  case PUT:
917
- this.putState(response, this.request, callback);
918
- break;
919
702
  case DELETE:
920
- this.deleteState(response, this.request, callback);
921
703
  break;
704
+ default:
705
+ throw Error('Bad request method passed to getApi');
922
706
  }
923
- }
924
- else {
925
- callback();
926
- }
927
- if (C6.GET === requestMethod) {
928
- const responseData = response.data;
929
- returnGetNextPageFunction = 1 !== query?.[C6.PAGINATION]?.[C6.LIMIT] &&
930
- query?.[C6.PAGINATION]?.[C6.LIMIT] === responseData.rest.length;
931
- if (false === isTest() || this.config.verbose) {
932
- console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + responseData.rest?.length + ') of possible (' + query?.[C6.PAGINATION]?.[C6.LIMIT] + ') limit!', 'color: #0c0');
933
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
934
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
935
- console.log('%c Response Data:', 'color: #0c0', responseData.rest);
936
- console.log('%c Will return get next page function:' + (returnGetNextPageFunction ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
707
+ if (null !== clearCache || undefined !== clearCache) {
708
+ exports.userCustomClearCache[tables + requestMethod] = clearCache;
709
+ }
710
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0');
711
+ console.log('request', this.request);
712
+ console.groupEnd();
713
+ // an undefined query would indicate queryCallback returned undefined,
714
+ // thus the request shouldn't fire as is in custom cache
715
+ if (undefined === this.request || null === this.request) {
716
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + tableName + ') undefined, returning null (will not fire)!', 'color: #c00');
717
+ console.log('request', this.request);
718
+ console.log('%c Returning (undefined|null) for a query would indicate a custom cache hit (outside API.tsx), thus the request should not fire.', 'color: #c00');
937
719
  console.trace();
938
720
  console.groupEnd();
721
+ return [2 /*return*/, null];
939
722
  }
940
- if (false === returnGetNextPageFunction) {
941
- responseData.next = apiRequest;
942
- }
943
- else {
944
- responseData.next = undefined;
945
- if (true === debug
946
- && isLocal()) {
947
- reactToastify.toast.success("DEVS: Response returned length (" + responseData.rest?.length + ") less than limit (" + query?.[C6.PAGINATION]?.[C6.LIMIT] + ").", toastOptionsDevs);
723
+ query = this.request;
724
+ if (C6.GET === requestMethod) {
725
+ if (undefined === query[C6.PAGINATION]) {
726
+ query[C6.PAGINATION] = {};
948
727
  }
728
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
729
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
949
730
  }
950
- if (fetchDependencies
951
- && 'number' === typeof fetchDependencies
952
- && responseData.rest.length > 0) {
953
- console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
954
- + (fetchDependencies & exports.eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
955
- + (fetchDependencies & exports.eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
956
- + (fetchDependencies & exports.eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
957
- + (fetchDependencies & exports.eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
958
- console.groupCollapsed('Collapsed JS Trace');
959
- console.trace(); // hidden in collapsed group
960
- console.groupEnd();
961
- // noinspection JSBitwiseOperatorUsage
962
- let dependencies = {};
963
- // Remember this is a binary bitwise operation, so we can check for multiple dependencies at once
964
- if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
965
- dependencies = operatingTable.endsWith("carbon_carbons")
966
- ? {
967
- // the context of the entity system is a bit different
968
- ...fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
969
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
970
- : {},
971
- ...fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
972
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
973
- : {}
974
- } : {
975
- // the context of the entity system is a bit different
976
- ...fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
977
- ? {
978
- ...Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce((accumulator, columnName) => {
979
- if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
980
- accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
731
+ apiRequest = function () { return tslib.__awaiter(_this, void 0, void 0, function () {
732
+ var _a, debug, _b, cacheResults, dataInsertMultipleRows, success, _c, fetchDependencies, _d, error, querySerialized, cacheResult, cachingConfirmed, cacheCheck, cacheCheck, addBackPK, apiResponse, returnGetNextPageFunction, restRequestUri, needsConditionOrPrimaryCheck, TABLES, primaryKey, removedPkValue_1, axiosActiveRequest;
733
+ var _e;
734
+ var _this = this;
735
+ var _f, _g, _h, _j, _k, _l;
736
+ return tslib.__generator(this, function (_m) {
737
+ switch (_m.label) {
738
+ case 0:
739
+ _a = this.request, debug = _a.debug, _b = _a.cacheResults, cacheResults = _b === void 0 ? (C6.GET === requestMethod) : _b, dataInsertMultipleRows = _a.dataInsertMultipleRows, success = _a.success, _c = _a.fetchDependencies, fetchDependencies = _c === void 0 ? exports.eFetchDependencies.NONE : _c, _d = _a.error, error = _d === void 0 ? "An unexpected API error occurred!" : _d;
740
+ if (C6.GET === requestMethod
741
+ && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
742
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
743
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
744
+ console.log('Request Data (note you may see the success and/or error prompt):', this.request);
745
+ console.trace();
746
+ console.groupEnd();
747
+ }
748
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
749
+ cacheResult = exports.apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
750
+ cachingConfirmed = false;
751
+ if (!(requestMethod === C6.GET)) return [3 /*break*/, 9];
752
+ if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
753
+ if (undefined === query || null === query) {
754
+ query = {};
755
+ }
756
+ query[C6.PAGINATION] = {};
757
+ }
758
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
759
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
760
+ if (!(true === cacheResults)) return [3 /*break*/, 7];
761
+ if (!(undefined !== cacheResult)) return [3 /*break*/, 6];
762
+ _m.label = 1;
763
+ case 1:
764
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
765
+ if (!(false !== cacheCheck)) return [3 /*break*/, 3];
766
+ return [4 /*yield*/, cacheCheck];
767
+ case 2: return [2 /*return*/, (_m.sent()).data];
768
+ case 3:
769
+ // this line incrementing page is why we return recursively
770
+ ++query[C6.PAGINATION][C6.PAGE];
771
+ // this json stringify is to capture the new page number
772
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
773
+ cacheResult = exports.apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
774
+ _m.label = 4;
775
+ case 4:
776
+ if (undefined !== cacheResult) return [3 /*break*/, 1];
777
+ _m.label = 5;
778
+ case 5:
779
+ if (debug && isLocal()) {
780
+ reactToastify.toast.warning("DEVS: Request in cache. (" + exports.apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; }) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
781
+ }
782
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
783
+ return [2 /*return*/, apiRequest];
784
+ case 6:
785
+ cachingConfirmed = true;
786
+ return [3 /*break*/, 8];
787
+ case 7:
788
+ if (debug && isLocal()) {
789
+ reactToastify.toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
790
+ }
791
+ _m.label = 8;
792
+ case 8:
793
+ if (debug && isLocal()) {
794
+ reactToastify.toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
795
+ }
796
+ return [3 /*break*/, 12];
797
+ case 9:
798
+ if (!cacheResults) return [3 /*break*/, 12];
799
+ if (!cacheResult) return [3 /*break*/, 11];
800
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
801
+ if (!(false !== cacheCheck)) return [3 /*break*/, 11];
802
+ return [4 /*yield*/, cacheCheck];
803
+ case 10: return [2 /*return*/, (_m.sent()).data];
804
+ case 11:
805
+ cachingConfirmed = true;
806
+ _m.label = 12;
807
+ case 12:
808
+ returnGetNextPageFunction = false;
809
+ restRequestUri = restURL + operatingTable + '/';
810
+ needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
811
+ && false === skipPrimaryCheck;
812
+ TABLES = C6.TABLES;
813
+ primaryKey = (_k = (_j = (_h = structuredClone((_g = TABLES[operatingTable]) === null || _g === void 0 ? void 0 : _g.PRIMARY)) === null || _h === void 0 ? void 0 : _h.pop()) === null || _j === void 0 ? void 0 : _j.split('.')) === null || _k === void 0 ? void 0 : _k.pop();
814
+ if (needsConditionOrPrimaryCheck) {
815
+ if (undefined === primaryKey) {
816
+ if (null === query
817
+ || undefined === query
818
+ || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
819
+ || (true === Array.isArray(query[C6.WHERE])
820
+ || query[C6.WHERE].length === 0)
821
+ || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
822
+ console.error(query);
823
+ throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify((_l = TABLES[operatingTable]) === null || _l === void 0 ? void 0 : _l.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
824
+ }
825
+ }
826
+ else {
827
+ if (undefined === query
828
+ || null === query
829
+ || false === primaryKey in query) {
830
+ if (true === debug && isLocal()) {
831
+ reactToastify.toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
832
+ }
833
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
834
+ }
835
+ if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
836
+ || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
837
+ reactToastify.toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
838
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
981
839
  }
982
- return accumulator;
983
- }, {}),
984
- ...C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
840
+ }
841
+ }
842
+ // A part of me exists that wants to remove this, but it's a good feature
843
+ // this allows developers the ability to cache requests based on primary key
844
+ // for tables like `photos` this can be a huge performance boost
845
+ if (undefined !== query
846
+ && null !== query
847
+ && undefined !== primaryKey
848
+ && primaryKey in query) {
849
+ restRequestUri += query[primaryKey] + '/';
850
+ removedPkValue_1 = query[primaryKey];
851
+ addBackPK = function () {
852
+ query !== null && query !== void 0 ? query : (query = {});
853
+ query[primaryKey] = removedPkValue_1;
854
+ };
855
+ delete query[primaryKey];
856
+ console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
985
857
  }
986
- : {},
987
- ...fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
988
- ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce((accumulator, primaryKey) => {
989
- if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
990
- accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
858
+ else {
859
+ console.log('query', query);
860
+ }
861
+ try {
862
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
863
+ console.log(this.request);
864
+ console.log('%c If this is the first request for this datatype; thus the value being set is currently undefined, please remember to update the state to null.', 'color: #A020F0');
865
+ console.log('%c Remember undefined indicated the request has not fired, null indicates the request is firing, an empty array would signal no data was returned for the sql stmt.', 'color: #A020F0');
866
+ console.trace();
867
+ console.groupEnd();
868
+ this.runLifecycleHooks("beforeExecution", {
869
+ config: this.config,
870
+ request: this.request
871
+ });
872
+ axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, tslib.__spreadArray([restRequestUri], (function () {
873
+ var convert = function (data) {
874
+ return convertForRequestBody(data, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); });
875
+ };
876
+ var baseConfig = {
877
+ withCredentials: withCredentials,
878
+ };
879
+ switch (requestMethod) {
880
+ case GET:
881
+ return [tslib.__assign(tslib.__assign({}, baseConfig), { params: query })];
882
+ case POST:
883
+ if (dataInsertMultipleRows !== undefined) {
884
+ return [
885
+ dataInsertMultipleRows.map(convert),
886
+ baseConfig
887
+ ];
888
+ }
889
+ return [convert(query), baseConfig];
890
+ case PUT:
891
+ return [convert(query), baseConfig];
892
+ case DELETE:
893
+ return [tslib.__assign(tslib.__assign({}, baseConfig), { data: convert(query) })];
894
+ default:
895
+ throw new Error("The request method (".concat(requestMethod, ") was not recognized."));
896
+ }
897
+ })(), false));
898
+ if (cachingConfirmed) {
899
+ // push to cache so we do not repeat the request
900
+ exports.apiRequestCache.push({
901
+ requestArgumentsSerialized: querySerialized,
902
+ request: axiosActiveRequest
903
+ });
991
904
  }
992
- return accumulator;
993
- }, {})
994
- : {}
995
- };
996
- }
997
- else {
998
- // this is the natural mysql context
999
- dependencies = {
1000
- ...fetchDependencies & exports.eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1001
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1002
- : {},
1003
- ...fetchDependencies & exports.eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1004
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
1005
- : {}
1006
- };
1007
- }
1008
- let fetchReferences = {};
1009
- let apiRequestPromises = [];
1010
- console.log('%c Dependencies', 'color: #005555', dependencies);
1011
- Object.keys(dependencies)
1012
- .forEach(column => dependencies[column]
1013
- .forEach((constraint) => {
1014
- const columnValues = responseData.rest[column] ?? responseData.rest.map((row) => {
1015
- if (operatingTable.endsWith("carbons")
1016
- && 'entity_tag' in row
1017
- && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1018
- return false; // map
1019
- }
1020
- if (!(column in row)) {
1021
- return false;
1022
- }
1023
- // todo - row[column] is a FK value, we should optionally remove values that are already in state
1024
- // this could be any column in the table constraint.TABLE, not just the primary key
1025
- return row[column];
1026
- }).filter(n => n) ?? [];
1027
- if (columnValues.length === 0) {
1028
- return; // forEach
1029
- }
1030
- fetchReferences[constraint.TABLE] ??= {};
1031
- fetchReferences[constraint.TABLE][constraint.COLUMN] ??= [];
1032
- fetchReferences[constraint.TABLE][constraint.COLUMN].push(columnValues);
1033
- }));
1034
- console.log('fetchReferences', fetchReferences);
1035
- for (const tableToFetch in fetchReferences) {
1036
- if (fetchDependencies & exports.eFetchDependencies.C6ENTITY
1037
- && 'string' === typeof tableName
1038
- && tableName.endsWith("carbon_carbons")) {
1039
- // todo - rethink the table ref entity system - when tables are renamed? no hooks exist in mysql
1040
- // since were already filtering on column, we can assume the first row constraint is the same as the rest
1041
- const referencesTables = responseData.rest.reduce((accumulator, row) => {
1042
- if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1043
- accumulator.push(row['entity_tag']);
905
+ // todo - wip verify this works
906
+ // we had removed the value from the request to add to the URI.
907
+ addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
908
+ // returning the promise with this then is important for tests. todo - we could make that optional.
909
+ // https://rapidapi.com/guides/axios-async-await
910
+ return [2 /*return*/, axiosActiveRequest.then(function (response) { return tslib.__awaiter(_this, void 0, void 0, function () {
911
+ var cacheIndex, callback, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
912
+ var _this = this;
913
+ var _d, _e, _f, _g, _h, _j;
914
+ return tslib.__generator(this, function (_k) {
915
+ switch (_k.label) {
916
+ case 0:
917
+ // noinspection SuspiciousTypeOfGuard
918
+ if (typeof response.data === 'string') {
919
+ if (isTest()) {
920
+ console.trace();
921
+ throw new Error('The response data was a string this typically indicated html was sent. Make sure all cookies (' + JSON.stringify(response.config.headers) + ') needed are present! (' + response.data + ')');
922
+ }
923
+ return [2 /*return*/, Promise.reject(response)];
924
+ }
925
+ if (cachingConfirmed) {
926
+ cacheIndex = exports.apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
927
+ // TODO - currently nonthing is setting this correctly
928
+ exports.apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
929
+ // only cache get method requests
930
+ exports.apiRequestCache[cacheIndex].response = response;
931
+ }
932
+ this.runLifecycleHooks("afterExecution", {
933
+ config: this.config,
934
+ request: this.request,
935
+ response: response
936
+ });
937
+ // todo - this feels dumb now, but i digress
938
+ apiResponse = TestRestfulResponse(response, success, error);
939
+ if (false === apiResponse) {
940
+ if (debug && isLocal()) {
941
+ reactToastify.toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
942
+ }
943
+ return [2 /*return*/, response];
944
+ }
945
+ callback = function () { return _this.runLifecycleHooks("afterCommit", {
946
+ config: _this.config,
947
+ request: _this.request,
948
+ response: response
949
+ }); };
950
+ if (undefined !== reactBootstrap && response) {
951
+ switch (requestMethod) {
952
+ case GET:
953
+ response.data && reactBootstrap.updateRestfulObjectArrays({
954
+ dataOrCallback: Array.isArray(response.data.rest) ? response.data.rest : [response.data.rest],
955
+ stateKey: this.config.restModel.TABLE_NAME,
956
+ uniqueObjectId: this.config.restModel.PRIMARY_SHORT,
957
+ callback: callback
958
+ });
959
+ break;
960
+ case POST:
961
+ this.postState(response, this.request, callback);
962
+ break;
963
+ case PUT:
964
+ this.putState(response, this.request, callback);
965
+ break;
966
+ case DELETE:
967
+ this.deleteState(response, this.request, callback);
968
+ break;
969
+ }
970
+ }
971
+ else {
972
+ callback();
973
+ }
974
+ if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
975
+ responseData_1 = response.data;
976
+ returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
977
+ ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
978
+ if (false === isTest() || this.config.verbose) {
979
+ console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + ((_f = responseData_1.rest) === null || _f === void 0 ? void 0 : _f.length) + ') of possible (' + ((_g = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _g === void 0 ? void 0 : _g[C6.LIMIT]) + ') limit!', 'color: #0c0');
980
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
981
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
982
+ console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
983
+ console.log('%c Will return get next page function:' + (returnGetNextPageFunction ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
984
+ console.trace();
985
+ console.groupEnd();
986
+ }
987
+ if (false === returnGetNextPageFunction) {
988
+ responseData_1.next = apiRequest;
989
+ }
990
+ else {
991
+ responseData_1.next = undefined;
992
+ if (true === debug
993
+ && isLocal()) {
994
+ reactToastify.toast.success("DEVS: Response returned length (" + ((_h = responseData_1.rest) === null || _h === void 0 ? void 0 : _h.length) + ") less than limit (" + ((_j = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _j === void 0 ? void 0 : _j[C6.LIMIT]) + ").", toastOptionsDevs);
995
+ }
996
+ }
997
+ if (!(fetchDependencies
998
+ && 'number' === typeof fetchDependencies
999
+ && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
1000
+ console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
1001
+ + (fetchDependencies & exports.eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
1002
+ + (fetchDependencies & exports.eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
1003
+ + (fetchDependencies & exports.eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
1004
+ + (fetchDependencies & exports.eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
1005
+ console.groupCollapsed('Collapsed JS Trace');
1006
+ console.trace(); // hidden in collapsed group
1007
+ console.groupEnd();
1008
+ dependencies_1 = {};
1009
+ // Remember this is a binary bitwise operation, so we can check for multiple dependencies at once
1010
+ if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
1011
+ dependencies_1 = operatingTable.endsWith("carbon_carbons")
1012
+ ? tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1013
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1014
+ : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
1015
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1016
+ : {}) : tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1017
+ ? tslib.__assign(tslib.__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
1018
+ if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
1019
+ accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
1020
+ }
1021
+ return accumulator;
1022
+ }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1023
+ ) : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
1024
+ ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1025
+ if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1026
+ accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1027
+ }
1028
+ return accumulator;
1029
+ }, {})
1030
+ : {});
1031
+ }
1032
+ else {
1033
+ // this is the natural mysql context
1034
+ dependencies_1 = tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1035
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1036
+ : {}), fetchDependencies & exports.eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1037
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1038
+ : {});
1039
+ }
1040
+ fetchReferences_1 = {};
1041
+ apiRequestPromises = [];
1042
+ console.log('%c Dependencies', 'color: #005555', dependencies_1);
1043
+ Object.keys(dependencies_1)
1044
+ .forEach(function (column) { return dependencies_1[column]
1045
+ .forEach(function (constraint) {
1046
+ var _a, _b, _c, _d;
1047
+ var _e, _f, _g;
1048
+ var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1049
+ if (operatingTable.endsWith("carbons")
1050
+ && 'entity_tag' in row
1051
+ && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1052
+ return false; // map
1053
+ }
1054
+ if (!(column in row)) {
1055
+ return false;
1056
+ }
1057
+ // todo - row[column] is a FK value, we should optionally remove values that are already in state
1058
+ // this could be any column in the table constraint.TABLE, not just the primary key
1059
+ return row[column];
1060
+ }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1061
+ if (columnValues.length === 0) {
1062
+ return; // forEach
1063
+ }
1064
+ (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1065
+ (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1066
+ fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1067
+ }); });
1068
+ console.log('fetchReferences', fetchReferences_1);
1069
+ _loop_1 = function (tableToFetch) {
1070
+ var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1071
+ var _l;
1072
+ return tslib.__generator(this, function (_m) {
1073
+ switch (_m.label) {
1074
+ case 0:
1075
+ if (fetchDependencies & exports.eFetchDependencies.C6ENTITY
1076
+ && 'string' === typeof tableName
1077
+ && tableName.endsWith("carbon_carbons")) {
1078
+ referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1079
+ if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1080
+ accumulator.push(row['entity_tag']);
1081
+ }
1082
+ return accumulator;
1083
+ }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1084
+ shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1085
+ if (!shouldContinue) {
1086
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1087
+ return [2 /*return*/, "continue"];
1088
+ }
1089
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1090
+ }
1091
+ return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1092
+ case 1:
1093
+ fetchTable = _m.sent();
1094
+ RestApi = fetchTable.default;
1095
+ console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1096
+ nextFetchDependencies = exports.eFetchDependencies.NONE;
1097
+ if (fetchDependencies & exports.eFetchDependencies.RECURSIVE) {
1098
+ if (fetchDependencies & exports.eFetchDependencies.ALL) {
1099
+ throw Error('Recursive fetch dependencies with both PARENT and CHILD reference will result in an infin1ite loop. As there is not real ending condition, this is not supported.');
1100
+ }
1101
+ nextFetchDependencies = fetchDependencies;
1102
+ }
1103
+ else if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
1104
+ if (tableToFetch === "carbon_carbons") {
1105
+ nextFetchDependencies = fetchDependencies;
1106
+ }
1107
+ else {
1108
+ nextFetchDependencies = fetchDependencies ^ exports.eFetchDependencies.C6ENTITY;
1109
+ }
1110
+ }
1111
+ console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1112
+ // todo - filter out ids that exist in state?!? note - remember that this does not necessarily mean the pk, but only known is its an FK to somewhere
1113
+ // it not certain that they are using carbons' entities either
1114
+ // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1115
+ // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1116
+ apiRequestPromises.push(RestApi.Get((_l = {},
1117
+ _l[C6.WHERE] = {
1118
+ 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1119
+ fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1120
+ if (0 === fetchReferences_1[tableToFetch][column].length) {
1121
+ console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1122
+ return false;
1123
+ }
1124
+ sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1125
+ ? fetchReferences_1[tableToFetch][column][0]
1126
+ : [
1127
+ C6.IN, fetchReferences_1[tableToFetch][column]
1128
+ ];
1129
+ return sum;
1130
+ }, {})
1131
+ },
1132
+ _l.fetchDependencies = nextFetchDependencies,
1133
+ _l)));
1134
+ return [2 /*return*/];
1135
+ }
1136
+ });
1137
+ };
1138
+ _a = fetchReferences_1;
1139
+ _b = [];
1140
+ for (_c in _a)
1141
+ _b.push(_c);
1142
+ _i = 0;
1143
+ _k.label = 1;
1144
+ case 1:
1145
+ if (!(_i < _b.length)) return [3 /*break*/, 4];
1146
+ _c = _b[_i];
1147
+ if (!(_c in _a)) return [3 /*break*/, 3];
1148
+ tableToFetch = _c;
1149
+ return [5 /*yield**/, _loop_1(tableToFetch)];
1150
+ case 2:
1151
+ _k.sent();
1152
+ _k.label = 3;
1153
+ case 3:
1154
+ _i++;
1155
+ return [3 /*break*/, 1];
1156
+ case 4:
1157
+ console.groupEnd();
1158
+ return [4 /*yield*/, Promise.all(apiRequestPromises)];
1159
+ case 5:
1160
+ _k.sent();
1161
+ apiRequestPromises.map(function (promise) { return tslib.__awaiter(_this, void 0, void 0, function () {
1162
+ var _a, _b;
1163
+ return tslib.__generator(this, function (_c) {
1164
+ switch (_c.label) {
1165
+ case 0:
1166
+ if (!Array.isArray(this.request.fetchDependencies)) {
1167
+ // to reassign value we must ref the root
1168
+ this.request.fetchDependencies = [];
1169
+ }
1170
+ _b = (_a = this.request.fetchDependencies).push;
1171
+ return [4 /*yield*/, promise];
1172
+ case 1:
1173
+ _b.apply(_a, [_c.sent()]);
1174
+ return [2 /*return*/];
1175
+ }
1176
+ });
1177
+ }); });
1178
+ _k.label = 6;
1179
+ case 6:
1180
+ if (debug && isLocal()) {
1181
+ reactToastify.toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1182
+ }
1183
+ // this is the literal axios return
1184
+ return [2 /*return*/, response];
1185
+ }
1186
+ });
1187
+ }); }).then(function (response) { return response.data; })]; // this escapes from axios context
1044
1188
  }
1045
- return accumulator;
1046
- }, []).map((entityTag) => entityTag.split('\\').pop().toLowerCase());
1047
- const shouldContinue = referencesTables.find((referencesTable) => tableToFetch.endsWith(referencesTable));
1048
- if (!shouldContinue) {
1049
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1050
- continue;
1051
- }
1052
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1053
- }
1054
- const fetchTable = await C6.IMPORT(tableToFetch);
1055
- const RestApi = fetchTable.default;
1056
- console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1057
- let nextFetchDependencies = exports.eFetchDependencies.NONE;
1058
- if (fetchDependencies & exports.eFetchDependencies.RECURSIVE) {
1059
- if (fetchDependencies & exports.eFetchDependencies.ALL) {
1060
- throw Error('Recursive fetch dependencies with both PARENT and CHILD reference will result in an infin1ite loop. As there is not real ending condition, this is not supported.');
1061
- }
1062
- nextFetchDependencies = fetchDependencies;
1063
- }
1064
- else if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
1065
- if (tableToFetch === "carbon_carbons") {
1066
- nextFetchDependencies = fetchDependencies;
1067
- }
1068
- else {
1069
- nextFetchDependencies = fetchDependencies ^ exports.eFetchDependencies.C6ENTITY;
1070
- }
1071
- }
1072
- console.log('fetchReferences', fetchReferences[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1073
- // todo - filter out ids that exist in state?!? note - remember that this does not necessarily mean the pk, but only known is its an FK to somewhere
1074
- // it not certain that they are using carbons' entities either
1075
- // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1076
- // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1077
- apiRequestPromises.push(RestApi.Get({
1078
- [C6.WHERE]: {
1079
- 0: Object.keys(fetchReferences[tableToFetch]).reduce((sum, column) => {
1080
- fetchReferences[tableToFetch][column] = fetchReferences[tableToFetch][column].flat(Infinity);
1081
- if (0 === fetchReferences[tableToFetch][column].length) {
1082
- console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData);
1083
- return false;
1189
+ catch (throwableError) {
1190
+ if (isTest()) {
1191
+ throw new Error(JSON.stringify(throwableError));
1084
1192
  }
1085
- sum[column] = fetchReferences[tableToFetch][column].length === 1
1086
- ? fetchReferences[tableToFetch][column][0]
1087
- : [
1088
- C6.IN, fetchReferences[tableToFetch][column]
1089
- ];
1090
- return sum;
1091
- }, {})
1092
- },
1093
- fetchDependencies: nextFetchDependencies
1094
- }));
1095
- }
1096
- console.groupEnd();
1097
- await Promise.all(apiRequestPromises);
1098
- apiRequestPromises.map(async (promise) => {
1099
- if (!Array.isArray(this.request.fetchDependencies)) {
1100
- // to reassign value we must ref the root
1101
- this.request.fetchDependencies = [];
1193
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1194
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1195
+ console.warn(throwableError);
1196
+ console.trace();
1197
+ console.groupEnd();
1198
+ TestRestfulResponse(throwableError, success, error);
1199
+ return [2 /*return*/, null];
1200
+ }
1201
+ return [2 /*return*/];
1102
1202
  }
1103
- this.request.fetchDependencies.push(await promise);
1104
1203
  });
1105
- }
1106
- }
1107
- if (debug && isLocal()) {
1108
- reactToastify.toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1109
- }
1110
- // this is the literal axios return
1111
- return response;
1112
- }).then(response => response.data); // this escapes from axios context
1113
- }
1114
- catch (throwableError) {
1115
- if (isTest()) {
1116
- throw new Error(JSON.stringify(throwableError));
1204
+ }); };
1205
+ return [4 /*yield*/, apiRequest()];
1206
+ case 2: return [2 /*return*/, _b.sent()];
1117
1207
  }
1118
- console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1119
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1120
- console.warn(throwableError);
1121
- console.trace();
1122
- console.groupEnd();
1123
- TestRestfulResponse(throwableError, success, error);
1124
- return null;
1125
- }
1126
- };
1127
- return await apiRequest();
1128
- }
1129
- }
1208
+ });
1209
+ });
1210
+ };
1211
+ return HttpExecutor;
1212
+ }(Executor));
1130
1213
 
1131
1214
  var HttpExecutor$1 = /*#__PURE__*/Object.freeze({
1132
1215
  __proto__: null,
@@ -1143,188 +1226,221 @@ function convertHexIfBinary(_col, val, columnDef) {
1143
1226
  return val;
1144
1227
  }
1145
1228
 
1146
- class AggregateBuilder extends Executor {
1147
- buildAggregateField(field) {
1229
+ var AggregateBuilder = /** @class */ (function (_super) {
1230
+ tslib.__extends(AggregateBuilder, _super);
1231
+ function AggregateBuilder() {
1232
+ return _super !== null && _super.apply(this, arguments) || this;
1233
+ }
1234
+ AggregateBuilder.prototype.buildAggregateField = function (field) {
1235
+ var _this = this;
1148
1236
  if (typeof field === 'string') {
1149
1237
  return field;
1150
1238
  }
1151
1239
  if (!Array.isArray(field) || field.length === 0) {
1152
1240
  throw new Error('Invalid SELECT field entry');
1153
1241
  }
1154
- let [fn, ...args] = field;
1155
- let alias;
1242
+ var fn = field[0], args = field.slice(1);
1243
+ var alias;
1156
1244
  if (args.length >= 2 && String(args[args.length - 2]).toUpperCase() === 'AS') {
1157
1245
  alias = String(args.pop());
1158
1246
  args.pop();
1159
1247
  }
1160
- const F = String(fn).toUpperCase();
1161
- const argList = args.map(arg => Array.isArray(arg) ? this.buildAggregateField(arg) : arg).join(', ');
1162
- let expr = `${F}(${argList})`;
1248
+ var F = String(fn).toUpperCase();
1249
+ var argList = args.map(function (arg) {
1250
+ return Array.isArray(arg) ? _this.buildAggregateField(arg) : arg;
1251
+ }).join(', ');
1252
+ var expr = "".concat(F, "(").concat(argList, ")");
1163
1253
  if (alias) {
1164
- expr += ` AS ${alias}`;
1254
+ expr += " AS ".concat(alias);
1165
1255
  }
1166
- this.config.verbose && console.log(`[SELECT] ${expr}`);
1256
+ this.config.verbose && console.log("[SELECT] ".concat(expr));
1167
1257
  return expr;
1168
- }
1169
- }
1258
+ };
1259
+ return AggregateBuilder;
1260
+ }(Executor));
1170
1261
 
1171
- class ConditionBuilder extends AggregateBuilder {
1172
- aliasMap = {};
1173
- initAlias(baseTable, joins) {
1174
- this.aliasMap = { [baseTable]: baseTable };
1262
+ var ConditionBuilder = /** @class */ (function (_super) {
1263
+ tslib.__extends(ConditionBuilder, _super);
1264
+ function ConditionBuilder() {
1265
+ var _this = _super !== null && _super.apply(this, arguments) || this;
1266
+ _this.aliasMap = {};
1267
+ _this.OPERATORS = new Set([
1268
+ C6C.EQUAL, C6C.NOT_EQUAL, C6C.LESS_THAN, C6C.LESS_THAN_OR_EQUAL_TO,
1269
+ C6C.GREATER_THAN, C6C.GREATER_THAN_OR_EQUAL_TO,
1270
+ C6C.LIKE, C6C.NOT_LIKE,
1271
+ C6C.IN, C6C.NOT_IN, 'NOT IN',
1272
+ C6C.IS, C6C.IS_NOT,
1273
+ C6C.BETWEEN, 'NOT BETWEEN',
1274
+ C6C.MATCH_AGAINST,
1275
+ C6C.ST_DISTANCE_SPHERE
1276
+ ]);
1277
+ return _this;
1278
+ }
1279
+ ConditionBuilder.prototype.initAlias = function (baseTable, joins) {
1280
+ var _a;
1281
+ this.aliasMap = (_a = {}, _a[baseTable] = baseTable, _a);
1175
1282
  if (!joins)
1176
1283
  return;
1177
- for (const joinType in joins) {
1178
- for (const raw in joins[joinType]) {
1179
- const [table, alias] = raw.split(' ');
1284
+ for (var joinType in joins) {
1285
+ for (var raw in joins[joinType]) {
1286
+ var _b = raw.split(' '), table = _b[0], alias = _b[1];
1180
1287
  this.aliasMap[alias || table] = table;
1181
1288
  }
1182
1289
  }
1183
- }
1184
- isColumnRef(ref) {
1290
+ };
1291
+ ConditionBuilder.prototype.isColumnRef = function (ref) {
1292
+ var _a, _b;
1185
1293
  if (typeof ref !== 'string' || !ref.includes('.'))
1186
1294
  return false;
1187
- const [prefix, column] = ref.split('.', 2);
1188
- const tableName = this.aliasMap[prefix] || prefix;
1189
- const table = this.config.C6?.TABLES?.[tableName];
1295
+ var _c = ref.split('.', 2), prefix = _c[0], column = _c[1];
1296
+ var tableName = this.aliasMap[prefix] || prefix;
1297
+ var table = (_b = (_a = this.config.C6) === null || _a === void 0 ? void 0 : _a.TABLES) === null || _b === void 0 ? void 0 : _b[tableName];
1190
1298
  if (!table)
1191
1299
  return false;
1192
- const fullKey = `${tableName}.${column}`;
1300
+ var fullKey = "".concat(tableName, ".").concat(column);
1193
1301
  if (table.COLUMNS && (fullKey in table.COLUMNS))
1194
1302
  return true;
1195
- if (table.COLUMNS && Object.values(table.COLUMNS).includes(ref))
1303
+ if (table.COLUMNS && Object.values(table.COLUMNS).includes(column))
1196
1304
  return true;
1197
- this.config.verbose && console.log(`[COLUMN REF] ${ref} is not a valid column reference`);
1198
1305
  return false;
1199
- }
1200
- execute() {
1306
+ };
1307
+ ConditionBuilder.prototype.execute = function () {
1201
1308
  throw new Error("Method not implemented.");
1202
- }
1203
- OPERATORS = new Set([
1204
- C6C.EQUAL, C6C.NOT_EQUAL, C6C.LESS_THAN, C6C.LESS_THAN_OR_EQUAL_TO,
1205
- C6C.GREATER_THAN, C6C.GREATER_THAN_OR_EQUAL_TO,
1206
- C6C.LIKE, C6C.NOT_LIKE,
1207
- C6C.IN, C6C.NOT_IN, 'NOT IN',
1208
- C6C.IS, C6C.IS_NOT,
1209
- C6C.BETWEEN, 'NOT BETWEEN',
1210
- C6C.MATCH_AGAINST,
1211
- C6C.ST_DISTANCE_SPHERE
1212
- ]);
1213
- validateOperator(op) {
1309
+ };
1310
+ ConditionBuilder.prototype.isTableReference = function (val) {
1311
+ var _a, _b;
1312
+ if (typeof val !== 'string' || !val.includes('.'))
1313
+ return false;
1314
+ var _c = val.split('.'), prefix = _c[0], column = _c[1];
1315
+ var tableName = (_a = this.aliasMap[prefix]) !== null && _a !== void 0 ? _a : prefix;
1316
+ return (typeof ((_b = this.config.C6) === null || _b === void 0 ? void 0 : _b.TABLES[tableName]) === 'object' &&
1317
+ val in this.config.C6.TABLES[tableName].COLUMNS &&
1318
+ this.config.C6.TABLES[tableName].COLUMNS[val] === column);
1319
+ };
1320
+ ConditionBuilder.prototype.validateOperator = function (op) {
1214
1321
  if (!this.OPERATORS.has(op)) {
1215
- throw new Error(`Invalid or unsupported SQL operator detected: '${op}'`);
1322
+ throw new Error("Invalid or unsupported SQL operator detected: '".concat(op, "'"));
1216
1323
  }
1217
- }
1218
- addParam(params, column, value) {
1219
- const columnDef = this.config.C6[column.split('.')[0]]?.TYPE_VALIDATION?.[column];
1220
- const val = convertHexIfBinary(column, value, columnDef);
1324
+ };
1325
+ ConditionBuilder.prototype.addParam = function (params, column, value) {
1326
+ var _a, _b;
1327
+ var columnDef = (_b = (_a = this.config.C6[column.split('.')[0]]) === null || _a === void 0 ? void 0 : _a.TYPE_VALIDATION) === null || _b === void 0 ? void 0 : _b[column];
1328
+ var val = convertHexIfBinary(column, value, columnDef);
1221
1329
  if (this.useNamedParams) {
1222
- const key = `param${Object.keys(params).length}`;
1330
+ var key = "param".concat(Object.keys(params).length);
1223
1331
  params[key] = val;
1224
- return `:${key}`;
1332
+ return ":".concat(key);
1225
1333
  }
1226
1334
  else {
1227
1335
  params.push(val);
1228
1336
  return '?';
1229
1337
  }
1230
- }
1231
- buildBooleanJoinedConditions(set, andMode = true, params = []) {
1232
- const booleanOperator = andMode ? 'AND' : 'OR';
1233
- const addCondition = (column, op, value) => {
1338
+ };
1339
+ ConditionBuilder.prototype.buildBooleanJoinedConditions = function (set, andMode, params) {
1340
+ var _this = this;
1341
+ if (andMode === void 0) { andMode = true; }
1342
+ if (params === void 0) { params = []; }
1343
+ var booleanOperator = andMode ? 'AND' : 'OR';
1344
+ var addCondition = function (column, op, value) {
1234
1345
  // Support function-based expressions like [C6C.ST_DISTANCE_SPHERE, col1, col2]
1235
1346
  if (typeof column === 'string' &&
1236
- this.OPERATORS.has(column) &&
1347
+ _this.OPERATORS.has(column) &&
1237
1348
  Array.isArray(op)) {
1238
1349
  if (column === C6C.ST_DISTANCE_SPHERE) {
1239
- const [col1, col2] = op;
1240
- const threshold = Array.isArray(value) ? value[0] : value;
1241
- return `ST_Distance_Sphere(${col1}, ${col2}) < ${this.addParam(params, '', threshold)}`;
1350
+ var col1 = op[0], col2 = op[1];
1351
+ var threshold = Array.isArray(value) ? value[0] : value;
1352
+ return "ST_Distance_Sphere(".concat(col1, ", ").concat(col2, ") < ").concat(_this.addParam(params, '', threshold));
1242
1353
  }
1243
1354
  }
1244
- const leftIsCol = this.isColumnRef(column);
1245
- const rightIsCol = typeof value === 'string' && this.isColumnRef(value);
1355
+ var leftIsCol = _this.isColumnRef(column);
1356
+ var leftIsRef = _this.isTableReference(column);
1357
+ var rightIsCol = typeof value === 'string' && _this.isColumnRef(value);
1246
1358
  if (!leftIsCol && !rightIsCol) {
1247
- throw new Error(`Potential SQL injection detected: '${column} ${op} ${value}'`);
1359
+ throw new Error("Potential SQL injection detected: '".concat(column, " ").concat(op, " ").concat(value, "'"));
1248
1360
  }
1249
- this.validateOperator(op);
1361
+ _this.validateOperator(op);
1250
1362
  if (op === C6C.MATCH_AGAINST && Array.isArray(value)) {
1251
- const [search, mode] = value;
1252
- const paramName = this.useNamedParams ? `param${Object.keys(params).length}` : null;
1253
- if (this.useNamedParams) {
1363
+ var search = value[0], mode = value[1];
1364
+ var paramName = _this.useNamedParams ? "param".concat(Object.keys(params).length) : null;
1365
+ if (_this.useNamedParams) {
1254
1366
  params[paramName] = search;
1255
1367
  }
1256
1368
  else {
1257
1369
  params.push(search);
1258
1370
  }
1259
- let againstClause;
1371
+ var againstClause = void 0;
1260
1372
  switch ((mode || '').toUpperCase()) {
1261
1373
  case 'BOOLEAN':
1262
- againstClause = this.useNamedParams ? `AGAINST(:${paramName} IN BOOLEAN MODE)` : `AGAINST(? IN BOOLEAN MODE)`;
1374
+ againstClause = _this.useNamedParams ? "AGAINST(:".concat(paramName, " IN BOOLEAN MODE)") : "AGAINST(? IN BOOLEAN MODE)";
1263
1375
  break;
1264
1376
  case 'WITH QUERY EXPANSION':
1265
- againstClause = this.useNamedParams ? `AGAINST(:${paramName} WITH QUERY EXPANSION)` : `AGAINST(? WITH QUERY EXPANSION)`;
1377
+ againstClause = _this.useNamedParams ? "AGAINST(:".concat(paramName, " WITH QUERY EXPANSION)") : "AGAINST(? WITH QUERY EXPANSION)";
1266
1378
  break;
1267
1379
  default: // NATURAL or undefined
1268
- againstClause = this.useNamedParams ? `AGAINST(:${paramName})` : `AGAINST(?)`;
1380
+ againstClause = _this.useNamedParams ? "AGAINST(:".concat(paramName, ")") : "AGAINST(?)";
1269
1381
  break;
1270
1382
  }
1271
1383
  if (!leftIsCol) {
1272
- throw new Error(`MATCH_AGAINST requires a table reference as the left operand. Column '${column}' is not a valid table reference.`);
1384
+ throw new Error("MATCH_AGAINST requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1273
1385
  }
1274
- const matchClause = `(MATCH(${column}) ${againstClause})`;
1275
- this.config.verbose && console.log(`[MATCH_AGAINST] ${matchClause}`);
1386
+ var matchClause = "(MATCH(".concat(column, ") ").concat(againstClause, ")");
1387
+ _this.config.verbose && console.log("[MATCH_AGAINST] ".concat(matchClause));
1276
1388
  return matchClause;
1277
1389
  }
1278
1390
  if ((op === C6C.IN || op === C6C.NOT_IN) && Array.isArray(value)) {
1279
- const placeholders = value.map(v => this.isColumnRef(v) ? v : this.addParam(params, column, v)).join(', ');
1280
- const normalized = op.replace('_', ' ');
1281
- if (!leftIsCol) {
1282
- throw new Error(`IN operator requires a table reference as the left operand. Column '${column}' is not a valid table reference.`);
1391
+ var placeholders = value.map(function (v) {
1392
+ return _this.isColumnRef(v) ? v : _this.addParam(params, column, v);
1393
+ }).join(', ');
1394
+ var normalized = op.replace('_', ' ');
1395
+ if (!leftIsRef) {
1396
+ throw new Error("IN operator requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1283
1397
  }
1284
- return `( ${column} ${normalized} (${placeholders}) )`;
1398
+ return "( ".concat(column, " ").concat(normalized, " (").concat(placeholders, ") )");
1285
1399
  }
1286
1400
  if (op === C6C.BETWEEN || op === 'NOT BETWEEN') {
1287
1401
  if (!Array.isArray(value) || value.length !== 2) {
1288
- throw new Error(`BETWEEN operator requires an array of two values. Received: ${JSON.stringify(value)}`);
1402
+ throw new Error("BETWEEN operator requires an array of two values");
1289
1403
  }
1290
- const [start, end] = value;
1291
- if (!leftIsCol) {
1292
- throw new Error(`BETWEEN operator requires a table reference as the left operand. Column '${column}' is not a valid table reference.`);
1404
+ var start = value[0], end = value[1];
1405
+ if (!leftIsRef) {
1406
+ throw new Error("BETWEEN operator requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1293
1407
  }
1294
- return `(${column}) ${op.replace('_', ' ')} ${this.addParam(params, column, start)} AND ${this.addParam(params, column, end)}`;
1408
+ return "(".concat(column, ") ").concat(op.replace('_', ' '), " ").concat(_this.addParam(params, column, start), " AND ").concat(_this.addParam(params, column, end));
1295
1409
  }
1296
- if (leftIsCol && rightIsCol) {
1297
- return `(${column}) ${op} ${value}`;
1410
+ var rightIsRef = _this.isTableReference(value);
1411
+ if (leftIsRef && rightIsRef) {
1412
+ return "(".concat(column, ") ").concat(op, " ").concat(value);
1298
1413
  }
1299
- if (leftIsCol && !rightIsCol) {
1300
- return `(${column}) ${op} ${this.addParam(params, column, value)}`;
1414
+ if (leftIsRef && !rightIsRef) {
1415
+ return "(".concat(column, ") ").concat(op, " ").concat(_this.addParam(params, column, value));
1301
1416
  }
1302
- if (rightIsCol) {
1303
- return `(${this.addParam(params, column, column)}) ${op} ${value}`;
1417
+ if (rightIsRef) {
1418
+ return "(".concat(_this.addParam(params, column, column), ") ").concat(op, " ").concat(value);
1304
1419
  }
1305
- throw new Error(`Neither operand appears to be a table reference`);
1420
+ throw new Error("Neither operand appears to be a table reference");
1306
1421
  };
1307
- const parts = [];
1308
- const buildFromObject = (obj, mode) => {
1309
- const subParts = [];
1310
- for (const [k, v] of Object.entries(obj)) {
1422
+ var parts = [];
1423
+ var buildFromObject = function (obj, mode) {
1424
+ var subParts = [];
1425
+ for (var _i = 0, _a = Object.entries(obj); _i < _a.length; _i++) {
1426
+ var _b = _a[_i], k = _b[0], v = _b[1];
1311
1427
  // numeric keys represent nested OR groups
1312
1428
  if (!isNaN(Number(k))) {
1313
- const sub = this.buildBooleanJoinedConditions(v, false, params);
1429
+ var sub = _this.buildBooleanJoinedConditions(v, false, params);
1314
1430
  if (sub)
1315
1431
  subParts.push(sub);
1316
1432
  continue;
1317
1433
  }
1318
1434
  if (typeof v === 'object' && v !== null && Object.keys(v).length === 1) {
1319
- const [op, val] = Object.entries(v)[0];
1435
+ var _c = Object.entries(v)[0], op = _c[0], val = _c[1];
1320
1436
  subParts.push(addCondition(k, op, val));
1321
1437
  }
1322
1438
  else if (Array.isArray(v) && v.length >= 2 && typeof v[0] === 'string') {
1323
- const [op, val] = v;
1439
+ var _d = v, op = _d[0], val = _d[1];
1324
1440
  subParts.push(addCondition(k, op, val));
1325
1441
  }
1326
1442
  else if (typeof v === 'object' && v !== null) {
1327
- const sub = this.buildBooleanJoinedConditions(v, mode, params);
1443
+ var sub = _this.buildBooleanJoinedConditions(v, mode, params);
1328
1444
  if (sub)
1329
1445
  subParts.push(sub);
1330
1446
  }
@@ -1332,105 +1448,126 @@ class ConditionBuilder extends AggregateBuilder {
1332
1448
  subParts.push(addCondition(k, '=', v));
1333
1449
  }
1334
1450
  }
1335
- return subParts.join(` ${mode ? 'AND' : 'OR'} `);
1451
+ return subParts.join(" ".concat(mode ? 'AND' : 'OR', " "));
1336
1452
  };
1337
1453
  if (Array.isArray(set)) {
1338
- for (const item of set) {
1339
- const sub = this.buildBooleanJoinedConditions(item, false, params);
1454
+ for (var _i = 0, set_1 = set; _i < set_1.length; _i++) {
1455
+ var item = set_1[_i];
1456
+ var sub = this.buildBooleanJoinedConditions(item, false, params);
1340
1457
  if (sub)
1341
1458
  parts.push(sub);
1342
1459
  }
1343
1460
  }
1344
1461
  else if (typeof set === 'object' && set !== null) {
1345
- const sub = buildFromObject(set, andMode);
1462
+ var sub = buildFromObject(set, andMode);
1346
1463
  if (sub)
1347
1464
  parts.push(sub);
1348
1465
  }
1349
- const clause = parts.join(` ${booleanOperator} `);
1350
- return clause ? `(${clause})` : '';
1351
- }
1352
- buildWhereClause(whereArg, params) {
1353
- const clause = this.buildBooleanJoinedConditions(whereArg, true, params);
1466
+ var clause = parts.join(" ".concat(booleanOperator, " "));
1467
+ return clause ? "(".concat(clause, ")") : '';
1468
+ };
1469
+ ConditionBuilder.prototype.buildWhereClause = function (whereArg, params) {
1470
+ var clause = this.buildBooleanJoinedConditions(whereArg, true, params);
1354
1471
  if (!clause)
1355
1472
  return '';
1356
- const trimmed = clause.replace(/^\((.*)\)$/, '$1');
1357
- this.config.verbose && console.log(`[WHERE] ${trimmed}`);
1358
- return ` WHERE ${trimmed}`;
1359
- }
1360
- }
1473
+ var trimmed = clause.replace(/^\((.*)\)$/, '$1');
1474
+ this.config.verbose && console.log("[WHERE] ".concat(trimmed));
1475
+ return " WHERE ".concat(trimmed);
1476
+ };
1477
+ return ConditionBuilder;
1478
+ }(AggregateBuilder));
1361
1479
 
1362
- class JoinBuilder extends ConditionBuilder {
1363
- buildJoinClauses(joinArgs, params) {
1364
- let sql = '';
1365
- for (const joinType in joinArgs) {
1366
- const joinKind = joinType.replace('_', ' ').toUpperCase();
1367
- for (const raw in joinArgs[joinType]) {
1368
- const [table, alias] = raw.split(' ');
1480
+ var JoinBuilder = /** @class */ (function (_super) {
1481
+ tslib.__extends(JoinBuilder, _super);
1482
+ function JoinBuilder() {
1483
+ return _super !== null && _super.apply(this, arguments) || this;
1484
+ }
1485
+ JoinBuilder.prototype.buildJoinClauses = function (joinArgs, params) {
1486
+ var sql = '';
1487
+ for (var joinType in joinArgs) {
1488
+ var joinKind = joinType.replace('_', ' ').toUpperCase();
1489
+ for (var raw in joinArgs[joinType]) {
1490
+ var _a = raw.split(' '), table = _a[0], alias = _a[1];
1369
1491
  this.aliasMap[alias || table] = table;
1370
- const onClause = this.buildBooleanJoinedConditions(joinArgs[joinType][raw], true, params);
1371
- const joinSql = alias ? `\`${table}\` AS \`${alias}\`` : `\`${table}\``;
1372
- sql += ` ${joinKind} JOIN ${joinSql} ON ${onClause}`;
1492
+ var onClause = this.buildBooleanJoinedConditions(joinArgs[joinType][raw], true, params);
1493
+ var joinSql = alias ? "`".concat(table, "` AS `").concat(alias, "`") : "`".concat(table, "`");
1494
+ sql += " ".concat(joinKind, " JOIN ").concat(joinSql, " ON ").concat(onClause);
1373
1495
  }
1374
1496
  }
1375
- this.config.verbose && console.log(`[JOIN] ${sql.trim()}`);
1497
+ this.config.verbose && console.log("[JOIN] ".concat(sql.trim()));
1376
1498
  return sql;
1377
- }
1378
- }
1499
+ };
1500
+ return JoinBuilder;
1501
+ }(ConditionBuilder));
1379
1502
 
1380
- class DeleteQueryBuilder extends JoinBuilder {
1381
- build(table) {
1382
- const params = this.useNamedParams ? {} : [];
1503
+ var DeleteQueryBuilder = /** @class */ (function (_super) {
1504
+ tslib.__extends(DeleteQueryBuilder, _super);
1505
+ function DeleteQueryBuilder() {
1506
+ return _super !== null && _super.apply(this, arguments) || this;
1507
+ }
1508
+ DeleteQueryBuilder.prototype.build = function (table) {
1509
+ this.aliasMap = {};
1510
+ var params = this.useNamedParams ? {} : [];
1383
1511
  this.initAlias(table, this.request.JOIN);
1384
- let sql = `DELETE \`${table}\` FROM \`${table}\``;
1512
+ var sql = "DELETE `".concat(table, "` FROM `").concat(table, "`");
1385
1513
  if (this.request.JOIN) {
1386
1514
  sql += this.buildJoinClauses(this.request.JOIN, params);
1387
1515
  }
1388
1516
  if (this.request.WHERE) {
1389
1517
  sql += this.buildWhereClause(this.request.WHERE, params);
1390
1518
  }
1391
- return { sql, params };
1392
- }
1393
- }
1519
+ return { sql: sql, params: params };
1520
+ };
1521
+ return DeleteQueryBuilder;
1522
+ }(JoinBuilder));
1394
1523
 
1395
- class PostQueryBuilder extends ConditionBuilder {
1396
- trimTablePrefix(table, column) {
1524
+ var PostQueryBuilder = /** @class */ (function (_super) {
1525
+ tslib.__extends(PostQueryBuilder, _super);
1526
+ function PostQueryBuilder() {
1527
+ return _super !== null && _super.apply(this, arguments) || this;
1528
+ }
1529
+ PostQueryBuilder.prototype.trimTablePrefix = function (table, column) {
1397
1530
  if (!column.includes('.'))
1398
1531
  return column;
1399
- const [prefix, col] = column.split('.', 2);
1532
+ var _a = column.split('.', 2), prefix = _a[0], col = _a[1];
1400
1533
  if (prefix !== table) {
1401
- throw new Error(`Invalid prefixed column: '${column}'. Expected prefix '${table}.'`);
1534
+ throw new Error("Invalid prefixed column: '".concat(column, "'. Expected prefix '").concat(table, ".'"));
1402
1535
  }
1403
1536
  return col;
1404
- }
1405
- build(table) {
1406
- const verb = C6C.REPLACE in this.request ? C6C.REPLACE : C6C.INSERT;
1407
- const body = verb in this.request ? this.request[verb] : this.request;
1408
- const keys = Object.keys(body);
1409
- const params = [];
1410
- const placeholders = [];
1411
- for (const key of keys) {
1412
- const value = body[key];
1413
- const placeholder = this.addParam(params, key, value);
1537
+ };
1538
+ PostQueryBuilder.prototype.build = function (table) {
1539
+ var _this = this;
1540
+ this.aliasMap = {};
1541
+ var verb = C6C.REPLACE in this.request ? C6C.REPLACE : C6C.INSERT;
1542
+ var body = verb in this.request ? this.request[verb] : this.request;
1543
+ var keys = Object.keys(body);
1544
+ var params = [];
1545
+ var placeholders = [];
1546
+ for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
1547
+ var key = keys_1[_i];
1548
+ var value = body[key];
1549
+ var placeholder = this.addParam(params, key, value);
1414
1550
  placeholders.push(placeholder);
1415
1551
  }
1416
- let sql = `${verb} INTO \`${table}\` (
1417
- ${keys.map(k => `\`${this.trimTablePrefix(table, k)}\``).join(', ')}
1418
- ) VALUES (
1419
- ${placeholders.join(', ')}
1420
- )`;
1552
+ var sql = "".concat(verb, " INTO `").concat(table, "` (\n ").concat(keys.map(function (k) { return "`".concat(_this.trimTablePrefix(table, k), "`"); }).join(', '), "\n ) VALUES (\n ").concat(placeholders.join(', '), "\n )");
1421
1553
  if (C6C.UPDATE in this.request) {
1422
- const updateData = this.request[C6C.UPDATE];
1554
+ var updateData = this.request[C6C.UPDATE];
1423
1555
  if (!Array.isArray(updateData)) {
1424
- throw new Error(`Update data must be an array of keys to update, got: ${JSON.stringify(updateData)}`);
1556
+ throw new Error("Update data must be an array of keys to update, got: ".concat(JSON.stringify(updateData)));
1425
1557
  }
1426
- const updateClause = updateData.map(k => `\`${k}\` = VALUES(\`${k}\`)`).join(', ');
1427
- sql += ` ON DUPLICATE KEY UPDATE ${updateClause}`;
1558
+ var updateClause = updateData.map(function (k) { return "`".concat(k, "` = VALUES(`").concat(k, "`)"); }).join(', ');
1559
+ sql += " ON DUPLICATE KEY UPDATE ".concat(updateClause);
1428
1560
  }
1429
- return { sql, params };
1430
- }
1431
- }
1561
+ return { sql: sql, params: params };
1562
+ };
1563
+ return PostQueryBuilder;
1564
+ }(ConditionBuilder));
1432
1565
 
1433
- class PaginationBuilder extends JoinBuilder {
1566
+ var PaginationBuilder = /** @class */ (function (_super) {
1567
+ tslib.__extends(PaginationBuilder, _super);
1568
+ function PaginationBuilder() {
1569
+ return _super !== null && _super.apply(this, arguments) || this;
1570
+ }
1434
1571
  /**
1435
1572
  * MySQL ORDER/LIMIT/OFFSET generator.
1436
1573
  *
@@ -1444,49 +1581,61 @@ class PaginationBuilder extends JoinBuilder {
1444
1581
  * }
1445
1582
  * ```
1446
1583
  */
1447
- buildPaginationClause(pagination) {
1448
- let sql = "";
1584
+ PaginationBuilder.prototype.buildPaginationClause = function (pagination) {
1585
+ var _this = this;
1586
+ var _a;
1587
+ var sql = "";
1449
1588
  /* -------- ORDER BY -------- */
1450
- if (pagination?.[C6Constants.ORDER]) {
1451
- const orderParts = [];
1452
- for (const [key, val] of Object.entries(pagination[C6Constants.ORDER])) {
1589
+ if (pagination === null || pagination === void 0 ? void 0 : pagination[C6Constants.ORDER]) {
1590
+ var orderParts = [];
1591
+ for (var _i = 0, _b = Object.entries(pagination[C6Constants.ORDER]); _i < _b.length; _i++) {
1592
+ var _c = _b[_i], key = _c[0], val = _c[1];
1453
1593
  // FUNCTION CALL: val is an array of args
1454
1594
  if (Array.isArray(val)) {
1455
- const args = val
1456
- .map((arg) => Array.isArray(arg) ? this.buildAggregateField(arg) : String(arg))
1595
+ var args = val
1596
+ .map(function (arg) { return Array.isArray(arg) ? _this.buildAggregateField(arg) : String(arg); })
1457
1597
  .join(", ");
1458
- orderParts.push(`${key}(${args})`);
1598
+ orderParts.push("".concat(key, "(").concat(args, ")"));
1459
1599
  }
1460
1600
  // SIMPLE COLUMN + DIR (ASC/DESC)
1461
1601
  else {
1462
- orderParts.push(`${key} ${String(val).toUpperCase()}`);
1602
+ orderParts.push("".concat(key, " ").concat(String(val).toUpperCase()));
1463
1603
  }
1464
1604
  }
1465
1605
  if (orderParts.length)
1466
- sql += ` ORDER BY ${orderParts.join(", ")}`;
1606
+ sql += " ORDER BY ".concat(orderParts.join(", "));
1467
1607
  }
1468
1608
  /* -------- LIMIT / OFFSET -------- */
1469
- if (pagination?.[C6Constants.LIMIT] != null) {
1470
- const lim = parseInt(pagination[C6Constants.LIMIT], 10);
1471
- const page = parseInt(pagination[C6Constants.PAGE] ?? 1, 10);
1472
- const offset = (page - 1) * lim;
1473
- sql += ` LIMIT ${offset}, ${lim}`;
1609
+ if ((pagination === null || pagination === void 0 ? void 0 : pagination[C6Constants.LIMIT]) != null) {
1610
+ var lim = parseInt(pagination[C6Constants.LIMIT], 10);
1611
+ var page = parseInt((_a = pagination[C6Constants.PAGE]) !== null && _a !== void 0 ? _a : 1, 10);
1612
+ var offset = (page - 1) * lim;
1613
+ sql += " LIMIT ".concat(offset, ", ").concat(lim);
1474
1614
  }
1475
- this.config.verbose && console.log(`[PAGINATION] ${sql.trim()}`);
1615
+ this.config.verbose && console.log("[PAGINATION] ".concat(sql.trim()));
1476
1616
  return sql;
1477
- }
1478
- }
1617
+ };
1618
+ return PaginationBuilder;
1619
+ }(JoinBuilder));
1479
1620
 
1480
- class SelectQueryBuilder extends PaginationBuilder {
1481
- build(table, isSubSelect = false) {
1482
- const args = this.request;
1621
+ var SelectQueryBuilder = /** @class */ (function (_super) {
1622
+ tslib.__extends(SelectQueryBuilder, _super);
1623
+ function SelectQueryBuilder() {
1624
+ return _super !== null && _super.apply(this, arguments) || this;
1625
+ }
1626
+ SelectQueryBuilder.prototype.build = function (table, isSubSelect) {
1627
+ var _this = this;
1628
+ var _a;
1629
+ if (isSubSelect === void 0) { isSubSelect = false; }
1630
+ this.aliasMap = {};
1631
+ var args = this.request;
1483
1632
  this.initAlias(table, args.JOIN);
1484
- const params = this.useNamedParams ? {} : [];
1485
- const selectList = args.SELECT ?? ['*'];
1486
- const selectFields = selectList
1487
- .map((f) => this.buildAggregateField(f))
1633
+ var params = this.useNamedParams ? {} : [];
1634
+ var selectList = (_a = args.SELECT) !== null && _a !== void 0 ? _a : ['*'];
1635
+ var selectFields = selectList
1636
+ .map(function (f) { return _this.buildAggregateField(f); })
1488
1637
  .join(', ');
1489
- let sql = `SELECT ${selectFields} FROM \`${table}\``;
1638
+ var sql = "SELECT ".concat(selectFields, " FROM `").concat(table, "`");
1490
1639
  if (args.JOIN) {
1491
1640
  sql += this.buildJoinClauses(args.JOIN, params);
1492
1641
  }
@@ -1494,165 +1643,229 @@ class SelectQueryBuilder extends PaginationBuilder {
1494
1643
  sql += this.buildWhereClause(args.WHERE, params);
1495
1644
  }
1496
1645
  if (args.GROUP_BY) {
1497
- const groupBy = Array.isArray(args.GROUP_BY)
1646
+ var groupBy = Array.isArray(args.GROUP_BY)
1498
1647
  ? args.GROUP_BY.join(', ')
1499
1648
  : args.GROUP_BY;
1500
- sql += ` GROUP BY ${groupBy}`;
1649
+ sql += " GROUP BY ".concat(groupBy);
1501
1650
  }
1502
1651
  if (args.HAVING) {
1503
- sql += ` HAVING ${this.buildBooleanJoinedConditions(args.HAVING, true, params)}`;
1652
+ sql += " HAVING ".concat(this.buildBooleanJoinedConditions(args.HAVING, true, params));
1504
1653
  }
1505
1654
  if (args.PAGINATION) {
1506
1655
  sql += this.buildPaginationClause(args.PAGINATION);
1507
1656
  }
1508
1657
  else if (!isSubSelect) {
1509
- sql += ` LIMIT 100`;
1658
+ sql += " LIMIT 100";
1510
1659
  }
1511
- console.log(`[SELECT] ${sql.trim()}`);
1512
- return { sql, params };
1513
- }
1514
- }
1660
+ console.log("[SELECT] ".concat(sql.trim()));
1661
+ return { sql: sql, params: params };
1662
+ };
1663
+ return SelectQueryBuilder;
1664
+ }(PaginationBuilder));
1515
1665
 
1516
- class UpdateQueryBuilder extends PaginationBuilder {
1517
- build(table) {
1518
- const args = this.request;
1519
- const params = this.useNamedParams ? {} : [];
1666
+ var UpdateQueryBuilder = /** @class */ (function (_super) {
1667
+ tslib.__extends(UpdateQueryBuilder, _super);
1668
+ function UpdateQueryBuilder() {
1669
+ return _super !== null && _super.apply(this, arguments) || this;
1670
+ }
1671
+ UpdateQueryBuilder.prototype.build = function (table) {
1672
+ var _this = this;
1673
+ this.aliasMap = {};
1674
+ var args = this.request;
1675
+ var params = this.useNamedParams ? {} : [];
1520
1676
  this.initAlias(table, args.JOIN);
1521
- let sql = `UPDATE \`${table}\``;
1677
+ var sql = "UPDATE `".concat(table, "`");
1522
1678
  if (args.JOIN) {
1523
1679
  sql += this.buildJoinClauses(args.JOIN, params);
1524
1680
  }
1525
1681
  if (!(C6C.UPDATE in this.request)) {
1526
1682
  throw new Error("No update data provided in the request.");
1527
1683
  }
1528
- const setClauses = Object.entries(this.request[C6C.UPDATE]).map(([col, val]) => this.addParam(params, col, val));
1529
- sql += ` SET ${setClauses.join(', ')}`;
1684
+ var setClauses = Object.entries(this.request[C6C.UPDATE]).map(function (_a) {
1685
+ var col = _a[0], val = _a[1];
1686
+ return _this.addParam(params, col, val);
1687
+ });
1688
+ sql += " SET ".concat(setClauses.join(', '));
1530
1689
  if (args.WHERE) {
1531
1690
  sql += this.buildWhereClause(args.WHERE, params);
1532
1691
  }
1533
1692
  if (args.PAGINATION) {
1534
1693
  sql += this.buildPaginationClause(args.PAGINATION);
1535
1694
  }
1536
- return { sql, params };
1537
- }
1538
- }
1695
+ return { sql: sql, params: params };
1696
+ };
1697
+ return UpdateQueryBuilder;
1698
+ }(PaginationBuilder));
1539
1699
 
1540
- class SqlExecutor extends Executor {
1541
- async execute() {
1542
- const { TABLE_NAME } = this.config.restModel;
1543
- const method = this.config.requestMethod;
1544
- this.config.verbose && console.log(`[SQL EXECUTOR] ▶️ Executing ${method} on table "${TABLE_NAME}"`);
1545
- this.config.verbose && console.log(`[SQL EXECUTOR] 🧩 Request:`, JSON.stringify(this.request, undefined, 2));
1546
- switch (method) {
1547
- case 'GET': {
1548
- const rest = await this.runQuery();
1549
- return rest;
1550
- }
1551
- case 'POST': {
1552
- const result = await this.runQuery();
1553
- return result;
1554
- }
1555
- case 'PUT': {
1556
- const result = await this.runQuery();
1557
- return result;
1558
- }
1559
- case 'DELETE': {
1560
- const result = await this.runQuery();
1561
- return result;
1562
- }
1563
- default:
1564
- throw new Error(`Unsupported request method: ${method}`);
1565
- }
1566
- }
1567
- async withConnection(cb) {
1568
- console.log(`[SQL EXECUTOR] 📡 Getting DB connection`);
1569
- const conn = await this.config.mysqlPool.getConnection();
1570
- try {
1571
- this.config.verbose && console.log(`[SQL EXECUTOR] ✅ Connection acquired`);
1572
- return await cb(conn);
1573
- }
1574
- finally {
1575
- this.config.verbose && console.log(`[SQL EXECUTOR] 🔌 Releasing DB connection`);
1576
- conn.release();
1577
- }
1700
+ var SqlExecutor = /** @class */ (function (_super) {
1701
+ tslib.__extends(SqlExecutor, _super);
1702
+ function SqlExecutor() {
1703
+ var _this = _super !== null && _super.apply(this, arguments) || this;
1704
+ _this.serialize = function (row) { return Object.fromEntries(Object.entries(row).map(function (_a) {
1705
+ var k = _a[0], v = _a[1];
1706
+ return [k, buffer.Buffer.isBuffer(v) ? v.toString('hex').toUpperCase() : v];
1707
+ })); };
1708
+ return _this;
1578
1709
  }
1579
- serialize = (row) => Object.fromEntries(Object.entries(row).map(([k, v]) => [k, buffer.Buffer.isBuffer(v) ? v.toString('hex').toUpperCase() : v]));
1580
- formatSQLWithParams(sql, params) {
1710
+ SqlExecutor.prototype.execute = function () {
1711
+ return tslib.__awaiter(this, void 0, void 0, function () {
1712
+ var TABLE_NAME, method, _a, rest, result, result, result;
1713
+ return tslib.__generator(this, function (_b) {
1714
+ switch (_b.label) {
1715
+ case 0:
1716
+ TABLE_NAME = this.config.restModel.TABLE_NAME;
1717
+ method = this.config.requestMethod;
1718
+ this.config.verbose && console.log("[SQL EXECUTOR] \u25B6\uFE0F Executing ".concat(method, " on table \"").concat(TABLE_NAME, "\""));
1719
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83E\uDDE9 Request body:", this.request.body);
1720
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83E\uDDE9 Request query:", this.request.query);
1721
+ _a = method;
1722
+ switch (_a) {
1723
+ case 'GET': return [3 /*break*/, 1];
1724
+ case 'POST': return [3 /*break*/, 3];
1725
+ case 'PUT': return [3 /*break*/, 5];
1726
+ case 'DELETE': return [3 /*break*/, 7];
1727
+ }
1728
+ return [3 /*break*/, 9];
1729
+ case 1: return [4 /*yield*/, this.runQuery()];
1730
+ case 2:
1731
+ rest = _b.sent();
1732
+ return [2 /*return*/, rest];
1733
+ case 3: return [4 /*yield*/, this.runQuery()];
1734
+ case 4:
1735
+ result = _b.sent();
1736
+ return [2 /*return*/, result];
1737
+ case 5: return [4 /*yield*/, this.runQuery()];
1738
+ case 6:
1739
+ result = _b.sent();
1740
+ return [2 /*return*/, result];
1741
+ case 7: return [4 /*yield*/, this.runQuery()];
1742
+ case 8:
1743
+ result = _b.sent();
1744
+ return [2 /*return*/, result];
1745
+ case 9: throw new Error("Unsupported request method: ".concat(method));
1746
+ }
1747
+ });
1748
+ });
1749
+ };
1750
+ SqlExecutor.prototype.withConnection = function (cb) {
1751
+ return tslib.__awaiter(this, void 0, void 0, function () {
1752
+ var conn;
1753
+ return tslib.__generator(this, function (_a) {
1754
+ switch (_a.label) {
1755
+ case 0:
1756
+ console.log("[SQL EXECUTOR] \uD83D\uDCE1 Getting DB connection");
1757
+ return [4 /*yield*/, this.config.mysqlPool.getConnection()];
1758
+ case 1:
1759
+ conn = _a.sent();
1760
+ _a.label = 2;
1761
+ case 2:
1762
+ _a.trys.push([2, , 4, 5]);
1763
+ this.config.verbose && console.log("[SQL EXECUTOR] \u2705 Connection acquired");
1764
+ return [4 /*yield*/, cb(conn)];
1765
+ case 3: return [2 /*return*/, _a.sent()];
1766
+ case 4:
1767
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83D\uDD0C Releasing DB connection");
1768
+ conn.release();
1769
+ return [7 /*endfinally*/];
1770
+ case 5: return [2 /*return*/];
1771
+ }
1772
+ });
1773
+ });
1774
+ };
1775
+ SqlExecutor.prototype.formatSQLWithParams = function (sql, params) {
1776
+ var _this = this;
1581
1777
  if (Array.isArray(params)) {
1582
- let index = 0;
1583
- return sql.replace(/\?/g, () => {
1584
- if (index >= params.length)
1778
+ var index_1 = 0;
1779
+ return sql.replace(/\?/g, function () {
1780
+ if (index_1 >= params.length)
1585
1781
  return '?';
1586
- const val = params[index++];
1587
- return this.formatValue(val);
1782
+ var val = params[index_1++];
1783
+ return _this.formatValue(val);
1588
1784
  });
1589
1785
  }
1590
1786
  else {
1591
- return sql.replace(/:([a-zA-Z0-9_]+)/g, (_, key) => {
1592
- const val = params[key];
1593
- return this.formatValue(val);
1787
+ return sql.replace(/:([a-zA-Z0-9_]+)/g, function (_, key) {
1788
+ var val = params[key];
1789
+ return _this.formatValue(val);
1594
1790
  });
1595
1791
  }
1596
- }
1597
- formatValue(val) {
1792
+ };
1793
+ SqlExecutor.prototype.formatValue = function (val) {
1598
1794
  if (val === null || val === undefined)
1599
1795
  return 'NULL';
1600
1796
  if (buffer.Buffer.isBuffer(val))
1601
- return `UNHEX('${val.toString('hex')}')`;
1797
+ return "UNHEX('".concat(val.toString('hex'), "')");
1602
1798
  if (typeof val === 'string')
1603
- return `'${val.replace(/'/g, "''")}'`;
1799
+ return "'".concat(val.replace(/'/g, "''"), "'");
1604
1800
  if (typeof val === 'number')
1605
1801
  return val.toString();
1606
1802
  if (val instanceof Date)
1607
- return `'${val.toISOString().slice(0, 19).replace('T', ' ')}'`;
1608
- return `'${JSON.stringify(val)}'`;
1609
- }
1610
- async runQuery() {
1611
- const { TABLE_NAME } = this.config.restModel;
1612
- const method = this.config.requestMethod;
1613
- let builder;
1614
- switch (method) {
1615
- case 'GET':
1616
- builder = new SelectQueryBuilder(this.config, this.request);
1617
- break;
1618
- case 'PUT':
1619
- builder = new UpdateQueryBuilder(this.config, this.request);
1620
- break;
1621
- case 'DELETE':
1622
- builder = new DeleteQueryBuilder(this.config, this.request);
1623
- break;
1624
- case 'POST':
1625
- builder = new PostQueryBuilder(this.config, this.request);
1626
- break;
1627
- default:
1628
- throw new Error(`Unsupported query method: ${method}`);
1629
- }
1630
- const QueryResult = builder.build(TABLE_NAME);
1631
- this.config.verbose && console.log(`[SQL EXECUTOR] 🧠 Generated ${method.toUpperCase()} SQL:`, QueryResult);
1632
- const formatted = this.formatSQLWithParams(QueryResult.sql, QueryResult.params);
1633
- this.config.verbose && console.log(`[SQL EXECUTOR] 🧠 Formatted ${method.toUpperCase()} SQL:`, formatted);
1634
- const toUnnamed = namedPlaceholders();
1635
- const [sql, values] = toUnnamed(QueryResult.sql, QueryResult.params);
1636
- return await this.withConnection(async (conn) => {
1637
- const [result] = await conn.query(sql, values);
1638
- if (method === 'GET') {
1639
- this.config.verbose && console.log(`[SQL EXECUTOR] 📦 Rows fetched:`, result);
1640
- return {
1641
- rest: result.map(this.serialize),
1642
- sql: { sql, values }
1643
- };
1644
- }
1645
- else {
1646
- this.config.verbose && console.log(`[SQL EXECUTOR] ✏️ Rows affected:`, result.affectedRows);
1647
- return {
1648
- affected: result.affectedRows,
1649
- rest: [],
1650
- sql: { sql, values }
1651
- };
1652
- }
1803
+ return "'".concat(val.toISOString().slice(0, 19).replace('T', ' '), "'");
1804
+ return "'".concat(JSON.stringify(val), "'");
1805
+ };
1806
+ SqlExecutor.prototype.runQuery = function () {
1807
+ return tslib.__awaiter(this, void 0, void 0, function () {
1808
+ var TABLE_NAME, method, builder, QueryResult, formatted, toUnnamed, _a, sql, values;
1809
+ var _this = this;
1810
+ return tslib.__generator(this, function (_b) {
1811
+ switch (_b.label) {
1812
+ case 0:
1813
+ TABLE_NAME = this.config.restModel.TABLE_NAME;
1814
+ method = this.config.requestMethod;
1815
+ switch (method) {
1816
+ case 'GET':
1817
+ builder = new SelectQueryBuilder(this.config, this.request);
1818
+ break;
1819
+ case 'PUT':
1820
+ builder = new UpdateQueryBuilder(this.config, this.request);
1821
+ break;
1822
+ case 'DELETE':
1823
+ builder = new DeleteQueryBuilder(this.config, this.request);
1824
+ break;
1825
+ case 'POST':
1826
+ builder = new PostQueryBuilder(this.config, this.request);
1827
+ break;
1828
+ default:
1829
+ throw new Error("Unsupported query method: ".concat(method));
1830
+ }
1831
+ QueryResult = builder.build(TABLE_NAME);
1832
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83E\uDDE0 Generated ".concat(method.toUpperCase(), " SQL:"), QueryResult);
1833
+ formatted = this.formatSQLWithParams(QueryResult.sql, QueryResult.params);
1834
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83E\uDDE0 Formatted ".concat(method.toUpperCase(), " SQL:"), formatted);
1835
+ toUnnamed = namedPlaceholders();
1836
+ _a = toUnnamed(QueryResult.sql, QueryResult.params), sql = _a[0], values = _a[1];
1837
+ return [4 /*yield*/, this.withConnection(function (conn) { return tslib.__awaiter(_this, void 0, void 0, function () {
1838
+ var result;
1839
+ return tslib.__generator(this, function (_a) {
1840
+ switch (_a.label) {
1841
+ case 0: return [4 /*yield*/, conn.query(sql, values)];
1842
+ case 1:
1843
+ result = (_a.sent())[0];
1844
+ if (method === 'GET') {
1845
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83D\uDCE6 Rows fetched:", result);
1846
+ return [2 /*return*/, {
1847
+ rest: result.map(this.serialize),
1848
+ sql: { sql: sql, values: values }
1849
+ }];
1850
+ }
1851
+ else {
1852
+ this.config.verbose && console.log("[SQL EXECUTOR] \u270F\uFE0F Rows affected:", result.affectedRows);
1853
+ return [2 /*return*/, {
1854
+ affected: result.affectedRows,
1855
+ rest: [],
1856
+ sql: { sql: sql, values: values }
1857
+ }];
1858
+ }
1859
+ }
1860
+ });
1861
+ }); })];
1862
+ case 1: return [2 /*return*/, _b.sent()];
1863
+ }
1864
+ });
1653
1865
  });
1654
- }
1655
- }
1866
+ };
1867
+ return SqlExecutor;
1868
+ }(Executor));
1656
1869
 
1657
1870
  var SqlExecutor$1 = /*#__PURE__*/Object.freeze({
1658
1871
  __proto__: null,
@@ -1661,80 +1874,101 @@ var SqlExecutor$1 = /*#__PURE__*/Object.freeze({
1661
1874
 
1662
1875
  // TODO - WE MUST make this a generic - optional, but helpful
1663
1876
  // note sure how it would help anyone actually...
1664
- function ExpressHandler({ C6, mysqlPool }) {
1665
- return async (req, res, next) => {
1666
- try {
1667
- const method = req.method.toUpperCase();
1668
- const table = req.params.table;
1669
- const primary = req.params.primary;
1670
- const payload = method === 'GET' ? req.query : req.body;
1671
- if (!(table in C6.TABLES)) {
1672
- res.status(400).json({ error: `Invalid table: ${table}` });
1673
- return;
1674
- }
1675
- const primaryKeys = C6.TABLES[table].PRIMARY;
1676
- if (primary && primaryKeys.length !== 1) {
1677
- if (primaryKeys.length > 1) {
1678
- res.status(400).json({ error: `Table ${table} has multiple primary keys. Cannot implicitly determine key.` });
1679
- return;
1680
- }
1681
- res.status(400).json({
1682
- error: `Table ${table} has no primary keys. Please specify one.`
1683
- });
1684
- return;
1685
- }
1686
- const primaryKeyName = primaryKeys[0];
1687
- // 👇 Call restRequest for the resolved method
1688
- // TODO - add primary conditionally based on method signature
1689
- switch (method) {
1690
- case 'GET':
1691
- if (primary) {
1692
- payload[C6C.WHERE][primaryKeyName] = primary;
1877
+ function ExpressHandler(_a) {
1878
+ var _this = this;
1879
+ var C6 = _a.C6, mysqlPool = _a.mysqlPool;
1880
+ return function (req, res, next) { return tslib.__awaiter(_this, void 0, void 0, function () {
1881
+ var method, table, primary, payload, primaryKeys, primaryKeyName, response, err_1;
1882
+ return tslib.__generator(this, function (_a) {
1883
+ switch (_a.label) {
1884
+ case 0:
1885
+ _a.trys.push([0, 2, , 3]);
1886
+ method = req.method.toUpperCase();
1887
+ table = req.params.table;
1888
+ primary = req.params.primary;
1889
+ payload = method === 'GET' ? req.query : req.body;
1890
+ if (!(table in C6.TABLES)) {
1891
+ res.status(400).json({ error: "Invalid table: ".concat(table) });
1892
+ return [2 /*return*/];
1693
1893
  }
1694
- break;
1695
- case 'PUT':
1696
- case 'DELETE':
1697
- if (primary) {
1698
- payload[C6C.WHERE][primaryKeyName] = primary;
1894
+ primaryKeys = C6.TABLES[table].PRIMARY;
1895
+ if (primary && primaryKeys.length !== 1) {
1896
+ if (primaryKeys.length > 1) {
1897
+ res.status(400).json({ error: "Table ".concat(table, " has multiple primary keys. Cannot implicitly determine key.") });
1898
+ return [2 /*return*/];
1899
+ }
1900
+ res.status(400).json({
1901
+ error: "Table ".concat(table, " has no primary keys. Please specify one.")
1902
+ });
1903
+ return [2 /*return*/];
1699
1904
  }
1700
- else {
1701
- res.status(400).json({ error: `Invalid request: ${method} requires a primary key.` });
1905
+ primaryKeyName = primaryKeys[0];
1906
+ // 👇 Call restRequest for the resolved method
1907
+ // TODO - add primary conditionally based on method signature
1908
+ switch (method) {
1909
+ case 'GET':
1910
+ if (primary) {
1911
+ payload[C6C.WHERE][primaryKeyName] = primary;
1912
+ }
1913
+ break;
1914
+ case 'PUT':
1915
+ case 'DELETE':
1916
+ if (primary) {
1917
+ payload[C6C.WHERE][primaryKeyName] = primary;
1918
+ }
1919
+ else {
1920
+ res.status(400).json({ error: "Invalid request: ".concat(method, " requires a primary key.") });
1921
+ }
1922
+ break;
1923
+ case 'POST':
1924
+ break;
1925
+ default:
1926
+ res.status(405).json({ error: "Method ".concat(method, " not allowed") });
1927
+ return [2 /*return*/];
1702
1928
  }
1703
- break;
1704
- case 'POST':
1705
- break;
1706
- default:
1707
- res.status(405).json({ error: `Method ${method} not allowed` });
1708
- return;
1929
+ return [4 /*yield*/, restRequest({
1930
+ C6: C6,
1931
+ mysqlPool: mysqlPool,
1932
+ requestMethod: method,
1933
+ restModel: C6.TABLES[table]
1934
+ })(payload)];
1935
+ case 1:
1936
+ response = _a.sent();
1937
+ res.status(200).json(tslib.__assign({ success: true }, response));
1938
+ return [3 /*break*/, 3];
1939
+ case 2:
1940
+ err_1 = _a.sent();
1941
+ res.status(500).json({ success: false, error: err_1 });
1942
+ next(err_1);
1943
+ return [3 /*break*/, 3];
1944
+ case 3: return [2 /*return*/];
1709
1945
  }
1710
- const response = await restRequest({
1711
- C6,
1712
- mysqlPool,
1713
- requestMethod: method,
1714
- restModel: C6.TABLES[table]
1715
- })(payload);
1716
- res.status(200).json({ success: true, ...response });
1717
- }
1718
- catch (err) {
1719
- res.status(500).json({ success: false, error: err });
1720
- next(err);
1721
- }
1722
- };
1946
+ });
1947
+ }); };
1723
1948
  }
1724
1949
 
1725
1950
  // Alias a table name with a given alias
1726
- const A = (tableName, alias) => `${tableName} ${alias}`;
1951
+ var A = function (tableName, alias) {
1952
+ return "".concat(tableName, " ").concat(alias);
1953
+ };
1727
1954
  // Qualify a column constant (e.g. 'property_units.parcel_id') to an alias
1728
- const F = (qualifiedCol, alias) => `${alias}.${qualifiedCol.split('.').pop()}`;
1955
+ var F = function (qualifiedCol, alias) {
1956
+ return "".concat(alias, ".").concat(qualifiedCol.split('.').pop());
1957
+ };
1729
1958
  // Equal join condition using full-qualified column constants
1730
- const fieldEq = (leftCol, rightCol, leftAlias, rightAlias) => ({
1731
- [F(leftCol, leftAlias)]: F(rightCol, rightAlias)
1732
- });
1959
+ var fieldEq = function (leftCol, rightCol, leftAlias, rightAlias) {
1960
+ var _a;
1961
+ return (_a = {},
1962
+ _a[F(leftCol, leftAlias)] = F(rightCol, rightAlias),
1963
+ _a);
1964
+ };
1733
1965
  // ST_Distance_Sphere for aliased fields
1734
- const distSphere = (fromCol, toCol, fromAlias, toAlias) => [C6C.ST_DISTANCE_SPHERE, F(fromCol, fromAlias), F(toCol, toAlias)];
1966
+ var distSphere = function (fromCol, toCol, fromAlias, toAlias) {
1967
+ return [C6C.ST_DISTANCE_SPHERE, F(fromCol, fromAlias), F(toCol, toAlias)];
1968
+ };
1735
1969
 
1736
1970
  function determineRuntimeJsType(mysqlType) {
1737
- const base = mysqlType.toLowerCase().split('(')[0];
1971
+ var base = mysqlType.toLowerCase().split('(')[0];
1738
1972
  if ([
1739
1973
  'binary', 'varbinary', 'blob', 'tinyblob', 'mediumblob', 'longblob'
1740
1974
  ].includes(base))
@@ -1755,15 +1989,23 @@ function determineRuntimeJsType(mysqlType) {
1755
1989
  return 'string';
1756
1990
  }
1757
1991
  function getPrimaryKeyTypes(table) {
1758
- const result = {};
1759
- for (const key of table.PRIMARY_SHORT) {
1760
- const fullKey = Object.entries(table.COLUMNS).find(([_, short]) => short === key)?.[0];
1992
+ var _a;
1993
+ var result = {};
1994
+ var _loop_1 = function (key) {
1995
+ var fullKey = (_a = Object.entries(table.COLUMNS).find(function (_a) {
1996
+ _a[0]; var short = _a[1];
1997
+ return short === key;
1998
+ })) === null || _a === void 0 ? void 0 : _a[0];
1761
1999
  if (typeof fullKey === 'string') {
1762
- const validation = table.TYPE_VALIDATION[fullKey];
2000
+ var validation = table.TYPE_VALIDATION[fullKey];
1763
2001
  if (!validation)
1764
- continue;
2002
+ return "continue";
1765
2003
  result[key] = determineRuntimeJsType(validation.MYSQL_TYPE);
1766
2004
  }
2005
+ };
2006
+ for (var _i = 0, _b = table.PRIMARY_SHORT; _i < _b.length; _i++) {
2007
+ var key = _b[_i];
2008
+ _loop_1(key);
1767
2009
  }
1768
2010
  return result;
1769
2011
  }
@@ -1772,30 +2014,42 @@ function getPrimaryKeyTypes(table) {
1772
2014
  * Conditionally group a log if verbose.
1773
2015
  */
1774
2016
  function group(title, data) {
1775
- console.groupCollapsed(`%c${title}`, "color: #007acc");
2017
+ console.groupCollapsed("%c".concat(title), "color: #007acc");
1776
2018
  if (data !== undefined)
1777
2019
  console.log(data);
1778
2020
  console.groupEnd();
1779
2021
  }
1780
- function info(message, ...optional) {
1781
- console.info(`%cINFO: ${message}`, "color: #0a0", ...optional);
2022
+ function info(message) {
2023
+ var optional = [];
2024
+ for (var _i = 1; _i < arguments.length; _i++) {
2025
+ optional[_i - 1] = arguments[_i];
2026
+ }
2027
+ console.info.apply(console, tslib.__spreadArray(["%cINFO: ".concat(message), "color: #0a0"], optional, false));
1782
2028
  }
1783
- function warn(message, ...optional) {
1784
- console.warn(`%cWARN: ${message}`, "color: #e90", ...optional);
2029
+ function warn(message) {
2030
+ var optional = [];
2031
+ for (var _i = 1; _i < arguments.length; _i++) {
2032
+ optional[_i - 1] = arguments[_i];
2033
+ }
2034
+ console.warn.apply(console, tslib.__spreadArray(["%cWARN: ".concat(message), "color: #e90"], optional, false));
1785
2035
  }
1786
- function error(message, ...optional) {
1787
- console.error(`%cERROR: ${message}`, "color: #c00", ...optional);
2036
+ function error(message) {
2037
+ var optional = [];
2038
+ for (var _i = 1; _i < arguments.length; _i++) {
2039
+ optional[_i - 1] = arguments[_i];
2040
+ }
2041
+ console.error.apply(console, tslib.__spreadArray(["%cERROR: ".concat(message), "color: #c00"], optional, false));
1788
2042
  }
1789
2043
 
1790
2044
  function checkAllRequestsComplete() {
1791
- const stillRunning = exports.apiRequestCache.filter((cache) => undefined === cache.response);
2045
+ var stillRunning = exports.apiRequestCache.filter(function (cache) { return undefined === cache.response; });
1792
2046
  if (stillRunning.length !== 0) {
1793
2047
  if (document === null || document === undefined) {
1794
2048
  throw new Error('document is undefined while waiting for API requests to complete (' + JSON.stringify(exports.apiRequestCache) + ')');
1795
2049
  }
1796
2050
  // when requests return emtpy sets in full renders, it may not be possible to track their progress.
1797
2051
  console.warn('stillRunning...', stillRunning);
1798
- return stillRunning.map((cache) => cache.requestArgumentsSerialized);
2052
+ return stillRunning.map(function (cache) { return cache.requestArgumentsSerialized; });
1799
2053
  }
1800
2054
  return true;
1801
2055
  }
@@ -1808,7 +2062,7 @@ function onError(message) {
1808
2062
  }
1809
2063
 
1810
2064
  function isVerbose () {
1811
- const envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
2065
+ var envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
1812
2066
  return ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
1813
2067
  }
1814
2068