@carbonorm/carbonnode 3.5.8 → 3.6.0

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