@carbonorm/carbonnode 3.5.9 → 3.6.1

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