@restura/core 0.1.0-alpha.6 → 0.1.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,39 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
3
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
7
  var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
5
10
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __objRest = (source, exclude) => {
26
+ var target = {};
27
+ for (var prop in source)
28
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
+ target[prop] = source[prop];
30
+ if (source != null && __getOwnPropSymbols)
31
+ for (var prop of __getOwnPropSymbols(source)) {
32
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
+ target[prop] = source[prop];
34
+ }
35
+ return target;
36
+ };
6
37
  var __export = (target, all) => {
7
38
  for (var name in all)
8
39
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -15,6 +46,14 @@ var __copyProps = (to, from, except, desc) => {
15
46
  }
16
47
  return to;
17
48
  };
49
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
+ // If the importer is in node compatibility mode or this is not an ESM
51
+ // file that has been converted to a CommonJS file using a Babel-
52
+ // compatible transform (i.e. "__esModule" has not been set), then set
53
+ // "default" to the CommonJS "module.exports" for node compatibility.
54
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
+ mod
56
+ ));
18
57
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
58
  var __decorateClass = (decorators, target, key, kind) => {
20
59
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
@@ -28,10 +67,68 @@ var __decorateClass = (decorators, target, key, kind) => {
28
67
  // src/index.ts
29
68
  var src_exports = {};
30
69
  __export(src_exports, {
70
+ PsqlPool: () => PsqlPool,
71
+ logger: () => logger,
31
72
  restura: () => restura
32
73
  });
33
74
  module.exports = __toCommonJS(src_exports);
34
75
 
76
+ // src/logger/logger.ts
77
+ var import_internal = require("@restura/internal");
78
+ var import_winston = __toESM(require("winston"));
79
+ var import_logform = require("logform");
80
+
81
+ // src/config.schema.ts
82
+ var import_zod = require("zod");
83
+ var loggerConfigSchema = import_zod.z.object({
84
+ level: import_zod.z.enum(["info", "warn", "error", "debug"]).default("info")
85
+ });
86
+ var resturaConfigSchema = import_zod.z.object({
87
+ authToken: import_zod.z.string().min(1, "Missing Restura Auth Token"),
88
+ sendErrorStackTrace: import_zod.z.boolean().default(false),
89
+ schemaFilePath: import_zod.z.string().default(process.cwd() + "/restura.schema.json"),
90
+ generatedTypesPath: import_zod.z.string().default(process.cwd() + "/src/@types")
91
+ });
92
+
93
+ // src/logger/logger.ts
94
+ var loggerConfig = import_internal.config.validate("logger", loggerConfigSchema);
95
+ var consoleFormat = import_logform.format.combine(
96
+ import_logform.format.timestamp({
97
+ format: "YYYY-MM-DD HH:mm:ss.sss"
98
+ }),
99
+ import_logform.format.errors({ stack: true }),
100
+ import_logform.format.padLevels(),
101
+ import_logform.format.colorize({ all: true }),
102
+ import_logform.format.printf((info) => {
103
+ return `[${info.timestamp}] ${info.level} ${info.message}`;
104
+ })
105
+ );
106
+ var logger = import_winston.default.createLogger({
107
+ level: loggerConfig.level,
108
+ format: import_logform.format.combine(
109
+ import_logform.format.timestamp({
110
+ format: "YYYY-MM-DD HH:mm:ss.sss"
111
+ }),
112
+ import_logform.format.errors({ stack: true }),
113
+ import_logform.format.json()
114
+ ),
115
+ //defaultMeta: { service: 'user-service' },
116
+ transports: [
117
+ //
118
+ // - Write to all logs with level `info` and below to `combined.log`
119
+ // - Write all logs error (and below) to `error.log`.
120
+ // - Write all logs to standard out.
121
+ //
122
+ // new winston.transports.File({ filename: 'error.log', level: 'error' }),
123
+ // new winston.transports.File({ filename: 'combined.log' }),
124
+ new import_winston.default.transports.Console({ format: consoleFormat })
125
+ ]
126
+ });
127
+
128
+ // src/restura/restura.ts
129
+ var import_core_utils6 = require("@redskytech/core-utils");
130
+ var import_internal2 = require("@restura/internal");
131
+
35
132
  // ../../node_modules/.pnpm/autobind-decorator@2.4.0/node_modules/autobind-decorator/lib/esm/index.js
36
133
  function _typeof(obj) {
37
134
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
@@ -78,22 +175,1853 @@ function boundMethod(target, key, descriptor) {
78
175
  };
79
176
  }
80
177
 
178
+ // src/restura/restura.ts
179
+ var import_body_parser = __toESM(require("body-parser"));
180
+ var import_compression = __toESM(require("compression"));
181
+ var import_cookie_parser = __toESM(require("cookie-parser"));
182
+ var import_crypto = require("crypto");
183
+ var express = __toESM(require("express"));
184
+ var import_fs2 = __toESM(require("fs"));
185
+ var import_path2 = __toESM(require("path"));
186
+ var prettier3 = __toESM(require("prettier"));
187
+
188
+ // src/restura/errors.ts
189
+ var RsError = class _RsError {
190
+ constructor(errCode, message) {
191
+ this.err = errCode;
192
+ this.msg = message || "";
193
+ this.status = _RsError.htmlStatus(errCode);
194
+ this.stack = new Error().stack || "";
195
+ }
196
+ static htmlStatus(code) {
197
+ return htmlStatusMap[code];
198
+ }
199
+ };
200
+ var htmlStatusMap = {
201
+ UNKNOWN_ERROR: 500 /* SERVER_ERROR */,
202
+ NOT_FOUND: 404 /* NOT_FOUND */,
203
+ EMAIL_TAKEN: 409 /* CONFLICT */,
204
+ FORBIDDEN: 403 /* FORBIDDEN */,
205
+ CONFLICT: 409 /* CONFLICT */,
206
+ UNAUTHORIZED: 401 /* UNAUTHORIZED */,
207
+ UPDATE_FORBIDDEN: 403 /* FORBIDDEN */,
208
+ CREATE_FORBIDDEN: 403 /* FORBIDDEN */,
209
+ DELETE_FORBIDDEN: 403 /* FORBIDDEN */,
210
+ DELETE_FAILURE: 500 /* SERVER_ERROR */,
211
+ BAD_REQUEST: 400 /* BAD_REQUEST */,
212
+ INVALID_TOKEN: 401 /* UNAUTHORIZED */,
213
+ INCORRECT_EMAIL_OR_PASSWORD: 401 /* UNAUTHORIZED */,
214
+ DUPLICATE_TOKEN: 409 /* CONFLICT */,
215
+ DUPLICATE_USERNAME: 409 /* CONFLICT */,
216
+ DUPLICATE_EMAIL: 409 /* CONFLICT */,
217
+ DUPLICATE: 409 /* CONFLICT */,
218
+ EMAIL_NOT_VERIFIED: 400 /* BAD_REQUEST */,
219
+ UPDATE_WITHOUT_ID: 400 /* BAD_REQUEST */,
220
+ CONNECTION_ERROR: 599 /* NETWORK_CONNECT_TIMEOUT */,
221
+ INVALID_PAYMENT: 403 /* FORBIDDEN */,
222
+ DECLINED_PAYMENT: 403 /* FORBIDDEN */,
223
+ INTEGRATION_ERROR: 500 /* SERVER_ERROR */,
224
+ CANNOT_RESERVE: 403 /* FORBIDDEN */,
225
+ REFUND_FAILURE: 403 /* FORBIDDEN */,
226
+ INVALID_INVOICE: 403 /* FORBIDDEN */,
227
+ INVALID_COUPON: 403 /* FORBIDDEN */,
228
+ SERVICE_UNAVAILABLE: 503 /* SERVICE_UNAVAILABLE */,
229
+ METHOD_UNALLOWED: 405 /* METHOD_NOT_ALLOWED */,
230
+ LOGIN_EXPIRED: 401 /* UNAUTHORIZED */,
231
+ THIRD_PARTY_ERROR: 400 /* BAD_REQUEST */,
232
+ ACCESS_DENIED: 403 /* FORBIDDEN */,
233
+ DATABASE_ERROR: 500 /* SERVER_ERROR */,
234
+ SCHEMA_ERROR: 500 /* SERVER_ERROR */
235
+ };
236
+
237
+ // src/restura/sql/SqlUtils.ts
238
+ var SqlUtils = class _SqlUtils {
239
+ static convertDatabaseTypeToTypescript(type, value) {
240
+ type = type.toLocaleLowerCase();
241
+ if (type.startsWith("tinyint") || type.startsWith("boolean")) return "boolean";
242
+ if (type.indexOf("int") > -1 || type.startsWith("decimal") || type.startsWith("double") || type.startsWith("float"))
243
+ return "number";
244
+ if (type === "json") {
245
+ if (!value) return "object";
246
+ return value.split(",").map((val) => {
247
+ return val.replace(/['"]/g, "");
248
+ }).join(" | ");
249
+ }
250
+ if (type.startsWith("varchar") || type.indexOf("text") > -1 || type.startsWith("char") || type.indexOf("blob") > -1 || type.startsWith("binary"))
251
+ return "string";
252
+ if (type.startsWith("date") || type.startsWith("time")) return "string";
253
+ if (type.startsWith("enum")) return _SqlUtils.convertDatabaseEnumToStringUnion(value || type);
254
+ return "any";
255
+ }
256
+ static convertDatabaseEnumToStringUnion(type) {
257
+ return type.replace(/^enum\(|\)/g, "").split(",").map((value) => {
258
+ return `'${value.replace(/'/g, "")}'`;
259
+ }).join(" | ");
260
+ }
261
+ };
262
+
263
+ // src/restura/ResponseValidator.ts
264
+ var ResponseValidator = class _ResponseValidator {
265
+ constructor(schema) {
266
+ this.database = schema.database;
267
+ this.rootMap = {};
268
+ for (const endpoint of schema.endpoints) {
269
+ const endpointMap = {};
270
+ for (const route of endpoint.routes) {
271
+ if (_ResponseValidator.isCustomRoute(route)) {
272
+ endpointMap[`${route.method}:${route.path}`] = { validator: "any" };
273
+ continue;
274
+ }
275
+ endpointMap[`${route.method}:${route.path}`] = this.getRouteResponseType(route);
276
+ }
277
+ const endpointUrl = endpoint.baseUrl.endsWith("/") ? endpoint.baseUrl.slice(0, -1) : endpoint.baseUrl;
278
+ this.rootMap[endpointUrl] = { validator: endpointMap };
279
+ }
280
+ }
281
+ validateResponseParams(data, endpointUrl, routeData) {
282
+ if (!this.rootMap) {
283
+ throw new RsError("BAD_REQUEST", "Cannot validate response without type maps");
284
+ }
285
+ const routeMap = this.rootMap[endpointUrl].validator[`${routeData.method}:${routeData.path}`];
286
+ data = this.validateAndCoerceMap("_base", data, routeMap);
287
+ }
288
+ getRouteResponseType(route) {
289
+ const map = {};
290
+ for (const field of route.response) {
291
+ map[field.name] = this.getFieldResponseType(field, route.table);
292
+ }
293
+ if (route.type === "PAGED") {
294
+ return {
295
+ validator: {
296
+ data: { validator: map, isArray: true },
297
+ total: { validator: "number" }
298
+ }
299
+ };
300
+ }
301
+ if (route.method === "DELETE") {
302
+ return {
303
+ validator: "boolean"
304
+ };
305
+ }
306
+ return { validator: map, isArray: route.type === "ARRAY" };
307
+ }
308
+ getFieldResponseType(field, tableName) {
309
+ if (field.selector) {
310
+ return this.getTypeFromTable(field.selector, tableName);
311
+ } else if (field.subquery) {
312
+ const table = this.database.find((t) => t.name == tableName);
313
+ if (!table) return { isArray: true, validator: "any" };
314
+ const isOptional = table.roles.length > 0;
315
+ const validator = {};
316
+ for (const prop of field.subquery.properties) {
317
+ validator[prop.name] = this.getFieldResponseType(prop, field.subquery.table);
318
+ }
319
+ return {
320
+ isArray: true,
321
+ isOptional,
322
+ validator
323
+ };
324
+ }
325
+ return { validator: "any" };
326
+ }
327
+ getTypeFromTable(selector, name) {
328
+ const path3 = selector.split(".");
329
+ if (path3.length === 0 || path3.length > 2 || path3[0] === "") return { validator: "any", isOptional: false };
330
+ const tableName = path3.length == 2 ? path3[0] : name, columnName = path3.length == 2 ? path3[1] : path3[0];
331
+ const table = this.database.find((t) => t.name == tableName);
332
+ const column = table == null ? void 0 : table.columns.find((c) => c.name == columnName);
333
+ if (!table || !column) return { validator: "any", isOptional: false };
334
+ let validator = SqlUtils.convertDatabaseTypeToTypescript(
335
+ column.type,
336
+ column.value
337
+ );
338
+ if (!_ResponseValidator.validatorIsValidString(validator)) validator = this.parseValidationEnum(validator);
339
+ return {
340
+ validator,
341
+ isOptional: column.roles.length > 0 || column.isNullable
342
+ };
343
+ }
344
+ parseValidationEnum(validator) {
345
+ let terms = validator.split("|");
346
+ terms = terms.map((v) => v.replace(/'/g, "").trim());
347
+ return terms;
348
+ }
349
+ validateAndCoerceMap(name, value, { isOptional, isArray, validator }) {
350
+ if (validator === "any") return value;
351
+ const valueType = typeof value;
352
+ if (value == null) {
353
+ if (isOptional) return value;
354
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is required`);
355
+ }
356
+ if (isArray) {
357
+ if (!Array.isArray(value)) {
358
+ throw new RsError(
359
+ "DATABASE_ERROR",
360
+ `Response param (${name}) is a/an ${valueType} instead of an array`
361
+ );
362
+ }
363
+ value.forEach((v, i) => this.validateAndCoerceMap(`${name}[${i}]`, v, { validator }));
364
+ return value;
365
+ }
366
+ if (typeof validator === "string") {
367
+ if (validator === "boolean" && valueType === "number") {
368
+ if (value !== 0 && value !== 1)
369
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is of the wrong type (${valueType})`);
370
+ return value === 1;
371
+ } else if (validator === "string" && valueType === "string") {
372
+ if (typeof value === "string" && value.match(
373
+ /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.?\d*$|\d{2}:\d{2}:\d{2}.?\d*$|^\d{4}-\d{2}-\d{2}$/
374
+ )) {
375
+ const date = new Date(value);
376
+ if (date.toISOString() === "1970-01-01T00:00:00.000Z") return null;
377
+ const timezoneOffset = date.getTimezoneOffset() * 6e4;
378
+ return new Date(date.getTime() - timezoneOffset * 2).toISOString();
379
+ }
380
+ return value;
381
+ } else if (valueType === validator) {
382
+ return value;
383
+ } else if (valueType === "object") {
384
+ return value;
385
+ }
386
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is of the wrong type (${valueType})`);
387
+ }
388
+ if (Array.isArray(validator) && typeof value === "string") {
389
+ if (validator.includes(value)) return value;
390
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is not one of the enum options (${value})`);
391
+ }
392
+ if (valueType !== "object") {
393
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is of the wrong type (${valueType})`);
394
+ }
395
+ for (const prop in value) {
396
+ if (!validator[prop])
397
+ throw new RsError("DATABASE_ERROR", `Response param (${name}.${prop}) is not allowed`);
398
+ }
399
+ for (const prop in validator) {
400
+ value[prop] = this.validateAndCoerceMap(`${name}.${prop}`, value[prop], validator[prop]);
401
+ }
402
+ return value;
403
+ }
404
+ static isCustomRoute(route) {
405
+ return route.type === "CUSTOM_ONE" || route.type === "CUSTOM_ARRAY" || route.type === "CUSTOM_PAGED";
406
+ }
407
+ static validatorIsValidString(validator) {
408
+ return !validator.includes("|");
409
+ }
410
+ };
411
+
412
+ // src/restura/apiGenerator.ts
413
+ var import_core_utils = require("@redskytech/core-utils");
414
+ var import_prettier = __toESM(require("prettier"));
415
+ var ApiTree = class _ApiTree {
416
+ constructor(namespace, database) {
417
+ this.database = database;
418
+ this.data = [];
419
+ this.namespace = namespace;
420
+ this.children = /* @__PURE__ */ new Map();
421
+ }
422
+ static createRootNode(database) {
423
+ return new _ApiTree(null, database);
424
+ }
425
+ static isRouteData(data) {
426
+ return data.method !== void 0;
427
+ }
428
+ static isEndpointData(data) {
429
+ return data.routes !== void 0;
430
+ }
431
+ addData(namespaces, route) {
432
+ if (import_core_utils.ObjectUtils.isEmpty(namespaces)) {
433
+ this.data.push(route);
434
+ return;
435
+ }
436
+ const childName = namespaces[0];
437
+ this.children.set(childName, this.children.get(childName) || new _ApiTree(childName, this.database));
438
+ this.children.get(childName).addData(namespaces.slice(1), route);
439
+ }
440
+ createApiModels() {
441
+ let result = "";
442
+ for (const child of this.children.values()) {
443
+ result += child.createApiModelImpl(true);
444
+ }
445
+ return result;
446
+ }
447
+ createApiModelImpl(isBase) {
448
+ let result = ``;
449
+ for (const data of this.data) {
450
+ if (_ApiTree.isEndpointData(data)) {
451
+ result += _ApiTree.generateEndpointComments(data);
452
+ }
453
+ }
454
+ result += isBase ? `
455
+ declare namespace ${this.namespace} {` : `
456
+ export namespace ${this.namespace} {`;
457
+ for (const data of this.data) {
458
+ if (_ApiTree.isRouteData(data)) {
459
+ result += this.generateRouteModels(data);
460
+ }
461
+ }
462
+ for (const child of this.children.values()) {
463
+ result += child.createApiModelImpl(false);
464
+ }
465
+ result += "}";
466
+ return result;
467
+ }
468
+ static generateEndpointComments(endpoint) {
469
+ return `
470
+ // ${endpoint.name}
471
+ // ${endpoint.description}`;
472
+ }
473
+ generateRouteModels(route) {
474
+ let modelString = ``;
475
+ modelString += `
476
+ // ${route.name}
477
+ // ${route.description}
478
+ export namespace ${import_core_utils.StringUtils.capitalizeFirst(route.method.toLowerCase())} {
479
+ ${this.generateRequestParameters(route)}
480
+ ${this.generateResponseParameters(route)}
481
+ }`;
482
+ return modelString;
483
+ }
484
+ generateRequestParameters(route) {
485
+ let modelString = ``;
486
+ if (ResponseValidator.isCustomRoute(route) && route.requestType) {
487
+ modelString += `
488
+ export type Req = CustomTypes.${route.requestType}`;
489
+ return modelString;
490
+ }
491
+ if (!route.request) return modelString;
492
+ modelString += `
493
+ export interface Req{
494
+ ${route.request.map((p) => {
495
+ let requestType = "any";
496
+ const oneOfValidator = p.validator.find((v) => v.type === "ONE_OF");
497
+ const typeCheckValidator = p.validator.find((v) => v.type === "TYPE_CHECK");
498
+ if (oneOfValidator && import_core_utils.ObjectUtils.isArrayWithData(oneOfValidator.value)) {
499
+ requestType = oneOfValidator.value.map((v) => `'${v}'`).join(" | ");
500
+ } else if (typeCheckValidator) {
501
+ switch (typeCheckValidator.value) {
502
+ case "string":
503
+ case "number":
504
+ case "boolean":
505
+ case "string[]":
506
+ case "number[]":
507
+ case "any[]":
508
+ requestType = typeCheckValidator.value;
509
+ break;
510
+ }
511
+ }
512
+ return `'${p.name}'${p.required ? "" : "?"}:${requestType}`;
513
+ }).join(";\n")}${import_core_utils.ObjectUtils.isArrayWithData(route.request) ? ";" : ""}
514
+ `;
515
+ modelString += `}`;
516
+ return modelString;
517
+ }
518
+ generateResponseParameters(route) {
519
+ if (ResponseValidator.isCustomRoute(route)) {
520
+ if (["number", "string", "boolean"].includes(route.responseType))
521
+ return `export type Res = ${route.responseType}`;
522
+ else if (["CUSTOM_ARRAY", "CUSTOM_PAGED"].includes(route.type))
523
+ return `export type Res = CustomTypes.${route.responseType}[]`;
524
+ else return `export type Res = CustomTypes.${route.responseType}`;
525
+ }
526
+ return `export interface Res ${this.getFields(route.response)}`;
527
+ }
528
+ getFields(fields) {
529
+ const nameFields = fields.map((f) => this.getNameAndType(f));
530
+ const nested = `{
531
+ ${nameFields.join(";\n ")}${import_core_utils.ObjectUtils.isArrayWithData(nameFields) ? ";" : ""}
532
+ }`;
533
+ return nested;
534
+ }
535
+ getNameAndType(p) {
536
+ let responseType = "any", optional = false, array = false;
537
+ if (p.selector) {
538
+ ({ responseType, optional } = this.getTypeFromTable(p.selector, p.name));
539
+ } else if (p.subquery) {
540
+ responseType = this.getFields(p.subquery.properties);
541
+ array = true;
542
+ }
543
+ return `${p.name}${optional ? "?" : ""}:${responseType}${array ? "[]" : ""}`;
544
+ }
545
+ getTypeFromTable(selector, name) {
546
+ const path3 = selector.split(".");
547
+ if (path3.length === 0 || path3.length > 2 || path3[0] === "") return { responseType: "any", optional: false };
548
+ let tableName = path3.length == 2 ? path3[0] : name;
549
+ const columnName = path3.length == 2 ? path3[1] : path3[0];
550
+ let table = this.database.find((t) => t.name == tableName);
551
+ if (!table && tableName.includes("_")) {
552
+ const tableAliasSplit = tableName.split("_");
553
+ tableName = tableAliasSplit[1];
554
+ table = this.database.find((t) => t.name == tableName);
555
+ }
556
+ const column = table == null ? void 0 : table.columns.find((c) => c.name == columnName);
557
+ if (!table || !column) return { responseType: "any", optional: false };
558
+ return {
559
+ responseType: SqlUtils.convertDatabaseTypeToTypescript(column.type, column.value),
560
+ optional: column.roles.length > 0 || column.isNullable
561
+ };
562
+ }
563
+ };
564
+ function pathToNamespaces(path3) {
565
+ return path3.split("/").map((e) => import_core_utils.StringUtils.toPascalCasing(e)).filter((e) => e);
566
+ }
567
+ function apiGenerator(schema, schemaHash) {
568
+ let apiString = `/** Auto generated file from Schema Hash (${schemaHash}). DO NOT MODIFY **/`;
569
+ const rootNamespace = ApiTree.createRootNode(schema.database);
570
+ for (const endpoint of schema.endpoints) {
571
+ const endpointNamespaces = pathToNamespaces(endpoint.baseUrl);
572
+ rootNamespace.addData(endpointNamespaces, endpoint);
573
+ for (const route of endpoint.routes) {
574
+ const fullNamespace = [...endpointNamespaces, ...pathToNamespaces(route.path)];
575
+ rootNamespace.addData(fullNamespace, route);
576
+ }
577
+ }
578
+ apiString += rootNamespace.createApiModels();
579
+ if (schema.customTypes.length > 0) {
580
+ apiString += `
581
+
582
+ declare namespace CustomTypes {
583
+ ${schema.customTypes}
584
+ }`;
585
+ }
586
+ return import_prettier.default.format(apiString, __spreadValues({
587
+ parser: "typescript"
588
+ }, {
589
+ trailingComma: "none",
590
+ tabWidth: 4,
591
+ useTabs: true,
592
+ endOfLine: "lf",
593
+ printWidth: 120,
594
+ singleQuote: true
595
+ }));
596
+ }
597
+
598
+ // src/restura/middleware/addApiResponseFunctions.ts
599
+ function addApiResponseFunctions(req, res, next) {
600
+ res.sendData = function(data, statusCode = 200) {
601
+ res.status(statusCode).send({ data });
602
+ };
603
+ res.sendNoWrap = function(dataNoWrap, statusCode = 200) {
604
+ res.status(statusCode).send(dataNoWrap);
605
+ };
606
+ res.sendPaginated = function(pagedData, statusCode = 200) {
607
+ res.status(statusCode).send({ data: pagedData.data, total: pagedData.total });
608
+ };
609
+ res.sendError = function(shortError, msg, htmlStatusCode, stack) {
610
+ if (htmlStatusCode === void 0) {
611
+ if (RsError.htmlStatus(shortError) !== void 0) {
612
+ htmlStatusCode = RsError.htmlStatus(shortError);
613
+ } else {
614
+ htmlStatusCode = 500;
615
+ }
616
+ }
617
+ const errorData = __spreadValues({
618
+ err: shortError,
619
+ msg
620
+ }, restura.resturaConfig.sendErrorStackTrace && stack ? { stack } : {});
621
+ res.status(htmlStatusCode).send(errorData);
622
+ };
623
+ next();
624
+ }
625
+
626
+ // src/restura/validateRequestParams.ts
627
+ var import_core_utils2 = require("@redskytech/core-utils");
628
+ var import_jsonschema = __toESM(require("jsonschema"));
629
+ var import_zod3 = require("zod");
630
+
631
+ // src/restura/types/validation.types.ts
632
+ var import_zod2 = require("zod");
633
+ var validatorDataSchemeValue = import_zod2.z.union([import_zod2.z.string(), import_zod2.z.array(import_zod2.z.string()), import_zod2.z.number(), import_zod2.z.array(import_zod2.z.number())]);
634
+ var validatorDataSchema = import_zod2.z.object({
635
+ type: import_zod2.z.enum(["TYPE_CHECK", "MIN", "MAX", "ONE_OF"]),
636
+ value: validatorDataSchemeValue
637
+ }).strict();
638
+
639
+ // src/restura/utils/addQuotesToStrings.ts
640
+ function addQuotesToStrings(variable) {
641
+ if (typeof variable === "string") {
642
+ return `'${variable}'`;
643
+ } else if (Array.isArray(variable)) {
644
+ const arrayWithQuotes = variable.map(addQuotesToStrings);
645
+ return arrayWithQuotes;
646
+ } else {
647
+ return variable;
648
+ }
649
+ }
650
+
651
+ // src/restura/validateRequestParams.ts
652
+ function validateRequestParams(req, routeData, validationSchema) {
653
+ const requestData = getRequestData(req);
654
+ req.data = requestData;
655
+ if (routeData.request === void 0) {
656
+ if (routeData.type !== "CUSTOM_ONE" && routeData.type !== "CUSTOM_ARRAY" && routeData.type !== "CUSTOM_PAGED")
657
+ throw new RsError("BAD_REQUEST", `No request parameters provided for standard request.`);
658
+ if (!routeData.responseType) throw new RsError("BAD_REQUEST", `No response type defined for custom request.`);
659
+ if (!routeData.requestType) throw new RsError("BAD_REQUEST", `No request type defined for custom request.`);
660
+ const currentInterface = validationSchema[routeData.requestType];
661
+ const validator = new import_jsonschema.default.Validator();
662
+ const executeValidation = validator.validate(req.data, currentInterface);
663
+ if (!executeValidation.valid) {
664
+ throw new RsError(
665
+ "BAD_REQUEST",
666
+ `Request custom setup has failed the following check: (${executeValidation.errors})`
667
+ );
668
+ }
669
+ return;
670
+ }
671
+ Object.keys(req.data).forEach((requestParamName) => {
672
+ const requestParam = routeData.request.find((param) => param.name === requestParamName);
673
+ if (!requestParam) {
674
+ throw new RsError("BAD_REQUEST", `Request param (${requestParamName}) is not allowed`);
675
+ }
676
+ });
677
+ routeData.request.forEach((requestParam) => {
678
+ const requestValue = requestData[requestParam.name];
679
+ if (requestParam.required && requestValue === void 0)
680
+ throw new RsError("BAD_REQUEST", `Request param (${requestParam.name}) is required but missing`);
681
+ else if (!requestParam.required && requestValue === void 0) return;
682
+ validateRequestSingleParam(requestValue, requestParam);
683
+ });
684
+ }
685
+ function validateRequestSingleParam(requestValue, requestParam) {
686
+ requestParam.validator.forEach((validator) => {
687
+ switch (validator.type) {
688
+ case "TYPE_CHECK":
689
+ performTypeCheck(requestValue, validator, requestParam.name);
690
+ break;
691
+ case "MIN":
692
+ performMinCheck(requestValue, validator, requestParam.name);
693
+ break;
694
+ case "MAX":
695
+ performMaxCheck(requestValue, validator, requestParam.name);
696
+ break;
697
+ case "ONE_OF":
698
+ performOneOfCheck(requestValue, validator, requestParam.name);
699
+ break;
700
+ }
701
+ });
702
+ }
703
+ function isValidType(type, requestValue) {
704
+ try {
705
+ expectValidType(type, requestValue);
706
+ return true;
707
+ } catch (e) {
708
+ return false;
709
+ }
710
+ }
711
+ function expectValidType(type, requestValue) {
712
+ if (type === "number") {
713
+ return import_zod3.z.number().parse(requestValue);
714
+ }
715
+ if (type === "string") {
716
+ return import_zod3.z.string().parse(requestValue);
717
+ }
718
+ if (type === "boolean") {
719
+ return import_zod3.z.boolean().parse(requestValue);
720
+ }
721
+ if (type === "string[]") {
722
+ return import_zod3.z.array(import_zod3.z.string()).parse(requestValue);
723
+ }
724
+ if (type === "number[]") {
725
+ return import_zod3.z.array(import_zod3.z.number()).parse(requestValue);
726
+ }
727
+ if (type === "any[]") {
728
+ return import_zod3.z.array(import_zod3.z.any()).parse(requestValue);
729
+ }
730
+ if (type === "object") {
731
+ return import_zod3.z.object({}).strict().parse(requestValue);
732
+ }
733
+ }
734
+ function performTypeCheck(requestValue, validator, requestParamName) {
735
+ if (!isValidType(validator.value, requestValue)) {
736
+ throw new RsError(
737
+ "BAD_REQUEST",
738
+ `Request param (${requestParamName}) with value (${addQuotesToStrings(requestValue)}) is not of type (${validator.value})`
739
+ );
740
+ }
741
+ try {
742
+ validatorDataSchemeValue.parse(validator.value);
743
+ } catch (e) {
744
+ throw new RsError("SCHEMA_ERROR", `Schema validator value (${validator.value}) is not a valid type`);
745
+ }
746
+ }
747
+ function expectOnlyNumbers(requestValue, validator, requestParamName) {
748
+ if (!isValueNumber(requestValue))
749
+ throw new RsError(
750
+ "BAD_REQUEST",
751
+ `Request param (${requestParamName}) with value (${requestValue}) is not of type number`
752
+ );
753
+ if (!isValueNumber(validator.value))
754
+ throw new RsError("SCHEMA_ERROR", `Schema validator value (${validator.value} is not of type number`);
755
+ }
756
+ function performMinCheck(requestValue, validator, requestParamName) {
757
+ expectOnlyNumbers(requestValue, validator, requestParamName);
758
+ if (requestValue < validator.value)
759
+ throw new RsError(
760
+ "BAD_REQUEST",
761
+ `Request param (${requestParamName}) with value (${requestValue}) is less than (${validator.value})`
762
+ );
763
+ }
764
+ function performMaxCheck(requestValue, validator, requestParamName) {
765
+ expectOnlyNumbers(requestValue, validator, requestParamName);
766
+ if (requestValue > validator.value)
767
+ throw new RsError(
768
+ "BAD_REQUEST",
769
+ `Request param (${requestParamName}) with value (${requestValue}) is more than (${validator.value})`
770
+ );
771
+ }
772
+ function performOneOfCheck(requestValue, validator, requestParamName) {
773
+ if (!import_core_utils2.ObjectUtils.isArrayWithData(validator.value))
774
+ throw new RsError("SCHEMA_ERROR", `Schema validator value (${validator.value}) is not of type array`);
775
+ if (typeof requestValue === "object")
776
+ throw new RsError("BAD_REQUEST", `Request param (${requestParamName}) is not of type string or number`);
777
+ if (!validator.value.includes(requestValue))
778
+ throw new RsError(
779
+ "BAD_REQUEST",
780
+ `Request param (${requestParamName}) with value (${requestValue}) is not one of (${validator.value.join(", ")})`
781
+ );
782
+ }
783
+ function isValueNumber(value) {
784
+ return !isNaN(Number(value));
785
+ }
786
+ function getRequestData(req) {
787
+ let body = "";
788
+ if (req.method === "GET" || req.method === "DELETE") {
789
+ body = "query";
790
+ } else {
791
+ body = "body";
792
+ }
793
+ const bodyData = req[body];
794
+ if (bodyData) {
795
+ for (const attr in bodyData) {
796
+ if (attr === "token") {
797
+ delete bodyData[attr];
798
+ continue;
799
+ }
800
+ if (bodyData[attr] instanceof Array) {
801
+ const attrList = [];
802
+ for (const value of bodyData[attr]) {
803
+ if (isNaN(Number(value))) continue;
804
+ attrList.push(Number(value));
805
+ }
806
+ if (import_core_utils2.ObjectUtils.isArrayWithData(attrList)) {
807
+ bodyData[attr] = attrList;
808
+ }
809
+ } else {
810
+ bodyData[attr] = import_core_utils2.ObjectUtils.safeParse(bodyData[attr]);
811
+ if (isNaN(Number(bodyData[attr]))) continue;
812
+ bodyData[attr] = Number(bodyData[attr]);
813
+ }
814
+ }
815
+ }
816
+ return bodyData;
817
+ }
818
+
819
+ // src/restura/restura.schema.ts
820
+ var import_zod4 = require("zod");
821
+ var orderBySchema = import_zod4.z.object({
822
+ columnName: import_zod4.z.string(),
823
+ order: import_zod4.z.enum(["ASC", "DESC"]),
824
+ tableName: import_zod4.z.string()
825
+ }).strict();
826
+ var groupBySchema = import_zod4.z.object({
827
+ columnName: import_zod4.z.string(),
828
+ tableName: import_zod4.z.string()
829
+ }).strict();
830
+ var whereDataSchema = import_zod4.z.object({
831
+ tableName: import_zod4.z.string().optional(),
832
+ columnName: import_zod4.z.string().optional(),
833
+ operator: import_zod4.z.enum(["=", "<", ">", "<=", ">=", "!=", "LIKE", "IN", "NOT IN", "STARTS WITH", "ENDS WITH"]).optional(),
834
+ value: import_zod4.z.string().or(import_zod4.z.number()).optional(),
835
+ custom: import_zod4.z.string().optional(),
836
+ conjunction: import_zod4.z.enum(["AND", "OR"]).optional()
837
+ }).strict();
838
+ var assignmentDataSchema = import_zod4.z.object({
839
+ name: import_zod4.z.string(),
840
+ value: import_zod4.z.string()
841
+ }).strict();
842
+ var joinDataSchema = import_zod4.z.object({
843
+ table: import_zod4.z.string(),
844
+ localColumnName: import_zod4.z.string().optional(),
845
+ foreignColumnName: import_zod4.z.string().optional(),
846
+ custom: import_zod4.z.string().optional(),
847
+ type: import_zod4.z.enum(["LEFT", "INNER"]),
848
+ alias: import_zod4.z.string().optional()
849
+ }).strict();
850
+ var requestDataSchema = import_zod4.z.object({
851
+ name: import_zod4.z.string(),
852
+ required: import_zod4.z.boolean(),
853
+ validator: import_zod4.z.array(validatorDataSchema)
854
+ }).strict();
855
+ var responseDataSchema = import_zod4.z.object({
856
+ name: import_zod4.z.string(),
857
+ selector: import_zod4.z.string().optional(),
858
+ subquery: import_zod4.z.object({
859
+ table: import_zod4.z.string(),
860
+ joins: import_zod4.z.array(joinDataSchema),
861
+ where: import_zod4.z.array(whereDataSchema),
862
+ properties: import_zod4.z.array(import_zod4.z.lazy(() => responseDataSchema)),
863
+ // Explicit type for the lazy schema
864
+ groupBy: groupBySchema.optional(),
865
+ orderBy: orderBySchema.optional()
866
+ }).optional()
867
+ }).strict();
868
+ var routeDataBaseSchema = import_zod4.z.object({
869
+ method: import_zod4.z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
870
+ name: import_zod4.z.string(),
871
+ description: import_zod4.z.string(),
872
+ path: import_zod4.z.string(),
873
+ roles: import_zod4.z.array(import_zod4.z.string())
874
+ }).strict();
875
+ var standardRouteSchema = routeDataBaseSchema.extend({
876
+ type: import_zod4.z.enum(["ONE", "ARRAY", "PAGED"]),
877
+ table: import_zod4.z.string(),
878
+ joins: import_zod4.z.array(joinDataSchema),
879
+ assignments: import_zod4.z.array(assignmentDataSchema),
880
+ where: import_zod4.z.array(whereDataSchema),
881
+ request: import_zod4.z.array(requestDataSchema),
882
+ response: import_zod4.z.array(responseDataSchema),
883
+ groupBy: groupBySchema.optional(),
884
+ orderBy: orderBySchema.optional()
885
+ }).strict();
886
+ var customRouteSchema = routeDataBaseSchema.extend({
887
+ type: import_zod4.z.enum(["CUSTOM_ONE", "CUSTOM_ARRAY", "CUSTOM_PAGED"]),
888
+ responseType: import_zod4.z.union([import_zod4.z.string(), import_zod4.z.enum(["string", "number", "boolean"])]),
889
+ requestType: import_zod4.z.string().optional(),
890
+ request: import_zod4.z.array(requestDataSchema).optional(),
891
+ table: import_zod4.z.undefined(),
892
+ joins: import_zod4.z.undefined(),
893
+ assignments: import_zod4.z.undefined(),
894
+ fileUploadType: import_zod4.z.enum(["SINGLE", "MULTIPLE"]).optional()
895
+ }).strict();
896
+ var postgresColumnNumericTypesSchema = import_zod4.z.enum([
897
+ "SMALLINT",
898
+ // 2 bytes, -32,768 to 32,767
899
+ "INTEGER",
900
+ // 4 bytes, -2,147,483,648 to 2,147,483,647
901
+ "BIGINT",
902
+ // 8 bytes, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
903
+ "DECIMAL",
904
+ // user-specified precision, exact numeric
905
+ "NUMERIC",
906
+ // same as DECIMAL
907
+ "REAL",
908
+ // 4 bytes, 6 decimal digits precision (single precision)
909
+ "DOUBLE PRECISION",
910
+ // 8 bytes, 15 decimal digits precision (double precision)
911
+ "SERIAL",
912
+ // auto-incrementing integer
913
+ "BIGSERIAL"
914
+ // auto-incrementing big integer
915
+ ]);
916
+ var postgresColumnStringTypesSchema = import_zod4.z.enum([
917
+ "CHAR",
918
+ // fixed-length, blank-padded
919
+ "VARCHAR",
920
+ // variable-length with limit
921
+ "TEXT",
922
+ // variable-length without limit
923
+ "BYTEA"
924
+ // binary data
925
+ ]);
926
+ var postgresColumnDateTypesSchema = import_zod4.z.enum([
927
+ "DATE",
928
+ // calendar date (year, month, day)
929
+ "TIMESTAMP",
930
+ // both date and time (without time zone)
931
+ "TIMESTAMPTZ",
932
+ // both date and time (with time zone)
933
+ "TIME",
934
+ // time of day (without time zone)
935
+ "INTERVAL"
936
+ // time span
937
+ ]);
938
+ var mariaDbColumnNumericTypesSchema = import_zod4.z.enum([
939
+ "BOOLEAN",
940
+ // 1-byte A synonym for "TINYINT(1)". Supported from version 1.2.0 onwards.
941
+ "TINYINT",
942
+ // 1-byte A very small integer. Numeric value with scale 0. Signed: -126 to +127. Unsigned: 0 to 253.
943
+ "SMALLINT",
944
+ // 2-bytes A small integer. Signed: -32,766 to 32,767. Unsigned: 0 to 65,533.
945
+ "MEDIUMINT",
946
+ // 3-bytes A medium integer. Signed: -8388608 to 8388607. Unsigned: 0 to 16777215. Supported starting with MariaDB ColumnStore 1.4.2.
947
+ "INTEGER",
948
+ // 4-bytes A normal-size integer. Numeric value with scale 0. Signed: -2,147,483,646 to 2,147,483,647. Unsigned: 0 to 4,294,967,293
949
+ "BIGINT",
950
+ // 8-bytes A large integer. Numeric value with scale 0. Signed: -9,223,372,036,854,775,806 to +9,223,372,036,854,775,807 Unsigned: 0 to +18,446,744,073,709,551,613
951
+ "DECIMAL",
952
+ // 2, 4, or 8 bytes A packed fixed-point number that can have a specific total number of digits and with a set number of digits after a decimal. The maximum precision (total number of digits) that can be specified is 18.
953
+ "FLOAT",
954
+ // 4 bytes Stored in 32-bit IEEE-754 floating point format. As such, the number of significant digits is about 6, and the range of values is approximately +/- 1e38.
955
+ "DOUBLE"
956
+ // 8 bytes Stored in 64-bit IEEE-754 floating point format. As such, the number of significant digits is about 15 and the range of values is approximately +/-1e308.
957
+ ]);
958
+ var mariaDbColumnStringTypesSchema = import_zod4.z.enum([
959
+ "CHAR",
960
+ // 1, 2, 4, or 8 bytes Holds letters and special characters of fixed length. Max length is 255. Default and minimum size is 1 byte.
961
+ "VARCHAR",
962
+ // 1, 2, 4, or 8 bytes or 8-byte token Holds letters, numbers, and special characters of variable length. Max length = 8000 bytes or characters and minimum length = 1 byte or character.
963
+ "TINYTEXT",
964
+ // 255 bytes Holds a small amount of letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
965
+ "TINYBLOB",
966
+ // 255 bytes Holds a small amount of binary data of variable length. Supported from version 1.1.0 onwards.
967
+ "TEXT",
968
+ // 64 KB Holds letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
969
+ "BLOB",
970
+ // 64 KB Holds binary data of variable length. Supported from version 1.1.0 onwards.
971
+ "MEDIUMTEXT",
972
+ // 16 MB Holds a medium amount of letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
973
+ "MEDIUMBLOB",
974
+ // 16 MB Holds a medium amount of binary data of variable length. Supported from version 1.1.0 onwards.
975
+ "LONGTEXT",
976
+ // 1.96 GB Holds a large amount of letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
977
+ "JSON",
978
+ // Alias for LONGTEXT, creates a CONSTRAINT for JSON_VALID, holds a JSON-formatted string of plain text.
979
+ "LONGBLOB",
980
+ // 1.96 GB Holds a large amount of binary data of variable length. Supported from version 1.1.0 onwards.
981
+ "ENUM"
982
+ // Enum type
983
+ ]);
984
+ var mariaDbColumnDateTypesSchema = import_zod4.z.enum([
985
+ "DATE",
986
+ // 4-bytes Date has year, month, and day.
987
+ "DATETIME",
988
+ // 8-bytes A date and time combination. Supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59. From version 1.2.0 microseconds are also supported.
989
+ "TIME",
990
+ // 8-bytes Holds hour, minute, second and optionally microseconds for time.
991
+ "TIMESTAMP"
992
+ // 4-bytes Values are stored as the number of seconds since 1970-01-01 00:00:00 UTC, and optionally microseconds.
993
+ ]);
994
+ var columnDataSchema = import_zod4.z.object({
995
+ name: import_zod4.z.string(),
996
+ type: import_zod4.z.union([
997
+ postgresColumnNumericTypesSchema,
998
+ postgresColumnStringTypesSchema,
999
+ postgresColumnDateTypesSchema,
1000
+ mariaDbColumnNumericTypesSchema,
1001
+ mariaDbColumnStringTypesSchema,
1002
+ mariaDbColumnDateTypesSchema
1003
+ ]),
1004
+ isNullable: import_zod4.z.boolean(),
1005
+ roles: import_zod4.z.array(import_zod4.z.string()),
1006
+ comment: import_zod4.z.string().optional(),
1007
+ default: import_zod4.z.string().optional(),
1008
+ value: import_zod4.z.string().optional(),
1009
+ isPrimary: import_zod4.z.boolean().optional(),
1010
+ isUnique: import_zod4.z.boolean().optional(),
1011
+ hasAutoIncrement: import_zod4.z.boolean().optional(),
1012
+ length: import_zod4.z.number().optional()
1013
+ }).strict();
1014
+ var indexDataSchema = import_zod4.z.object({
1015
+ name: import_zod4.z.string(),
1016
+ columns: import_zod4.z.array(import_zod4.z.string()),
1017
+ isUnique: import_zod4.z.boolean(),
1018
+ isPrimaryKey: import_zod4.z.boolean(),
1019
+ order: import_zod4.z.enum(["ASC", "DESC"])
1020
+ }).strict();
1021
+ var foreignKeyActionsSchema = import_zod4.z.enum([
1022
+ "CASCADE",
1023
+ // CASCADE action for foreign keys
1024
+ "SET NULL",
1025
+ // SET NULL action for foreign keys
1026
+ "RESTRICT",
1027
+ // RESTRICT action for foreign keys
1028
+ "NO ACTION",
1029
+ // NO ACTION for foreign keys
1030
+ "SET DEFAULT"
1031
+ // SET DEFAULT action for foreign keys
1032
+ ]);
1033
+ var foreignKeyDataSchema = import_zod4.z.object({
1034
+ name: import_zod4.z.string(),
1035
+ column: import_zod4.z.string(),
1036
+ refTable: import_zod4.z.string(),
1037
+ refColumn: import_zod4.z.string(),
1038
+ onDelete: foreignKeyActionsSchema,
1039
+ onUpdate: foreignKeyActionsSchema
1040
+ }).strict();
1041
+ var checkConstraintDataSchema = import_zod4.z.object({
1042
+ name: import_zod4.z.string(),
1043
+ check: import_zod4.z.string()
1044
+ }).strict();
1045
+ var tableDataSchema = import_zod4.z.object({
1046
+ name: import_zod4.z.string(),
1047
+ columns: import_zod4.z.array(columnDataSchema),
1048
+ indexes: import_zod4.z.array(indexDataSchema),
1049
+ foreignKeys: import_zod4.z.array(foreignKeyDataSchema),
1050
+ checkConstraints: import_zod4.z.array(checkConstraintDataSchema),
1051
+ roles: import_zod4.z.array(import_zod4.z.string())
1052
+ }).strict();
1053
+ var endpointDataSchema = import_zod4.z.object({
1054
+ name: import_zod4.z.string(),
1055
+ description: import_zod4.z.string(),
1056
+ baseUrl: import_zod4.z.string(),
1057
+ routes: import_zod4.z.array(import_zod4.z.union([standardRouteSchema, customRouteSchema]))
1058
+ }).strict();
1059
+ var resturaZodSchema = import_zod4.z.object({
1060
+ database: import_zod4.z.array(tableDataSchema),
1061
+ endpoints: import_zod4.z.array(endpointDataSchema),
1062
+ globalParams: import_zod4.z.array(import_zod4.z.string()),
1063
+ roles: import_zod4.z.array(import_zod4.z.string()),
1064
+ customTypes: import_zod4.z.string()
1065
+ }).strict();
1066
+ async function isSchemaValid(schemaToCheck) {
1067
+ try {
1068
+ resturaZodSchema.parse(schemaToCheck);
1069
+ return true;
1070
+ } catch (error) {
1071
+ logger.error(error);
1072
+ return false;
1073
+ }
1074
+ }
1075
+
1076
+ // src/restura/middleware/schemaValidation.ts
1077
+ async function schemaValidation(req, res, next) {
1078
+ req.data = getRequestData(req);
1079
+ try {
1080
+ resturaZodSchema.parse(req.data);
1081
+ next();
1082
+ } catch (error) {
1083
+ logger.error(error);
1084
+ res.sendError("BAD_REQUEST", error, 400 /* BAD_REQUEST */);
1085
+ }
1086
+ }
1087
+
1088
+ // src/restura/modelGenerator.ts
1089
+ var import_core_utils3 = require("@redskytech/core-utils");
1090
+ var import_prettier2 = __toESM(require("prettier"));
1091
+ function modelGenerator(schema, schemaHash) {
1092
+ let modelString = `/** Auto generated file from Schema Hash (${schemaHash}). DO NOT MODIFY **/
1093
+ `;
1094
+ modelString += `declare namespace Model {
1095
+ `;
1096
+ for (const table of schema.database) {
1097
+ modelString += convertTable(table);
1098
+ }
1099
+ modelString += `}`;
1100
+ return import_prettier2.default.format(modelString, __spreadValues({
1101
+ parser: "typescript"
1102
+ }, {
1103
+ trailingComma: "none",
1104
+ tabWidth: 4,
1105
+ useTabs: true,
1106
+ endOfLine: "lf",
1107
+ printWidth: 120,
1108
+ singleQuote: true
1109
+ }));
1110
+ }
1111
+ function convertTable(table) {
1112
+ let modelString = ` export interface ${import_core_utils3.StringUtils.capitalizeFirst(table.name)} {
1113
+ `;
1114
+ for (const column of table.columns) {
1115
+ modelString += ` ${column.name}${column.isNullable ? "?" : ""}: ${SqlUtils.convertDatabaseTypeToTypescript(column.type, column.value)};
1116
+ `;
1117
+ }
1118
+ modelString += ` }
1119
+ `;
1120
+ return modelString;
1121
+ }
1122
+
1123
+ // src/restura/middleware/authenticateUser.ts
1124
+ function authenticateUser(applicationAuthenticateHandler) {
1125
+ return (req, res, next) => {
1126
+ applicationAuthenticateHandler(
1127
+ req,
1128
+ (userDetails) => {
1129
+ req.requesterDetails = __spreadValues(__spreadValues({}, req.requesterDetails), userDetails);
1130
+ next();
1131
+ },
1132
+ (errorMessage) => {
1133
+ res.sendError("UNAUTHORIZED", errorMessage);
1134
+ }
1135
+ );
1136
+ };
1137
+ }
1138
+
1139
+ // src/restura/customTypeValidationGenerator.ts
1140
+ var import_fs = __toESM(require("fs"));
1141
+ var TJS = __toESM(require("typescript-json-schema"));
1142
+ var import_path = __toESM(require("path"));
1143
+ var import_tmp = __toESM(require("tmp"));
1144
+ var process2 = __toESM(require("process"));
1145
+ function customTypeValidationGenerator(currentSchema) {
1146
+ const schemaObject = {};
1147
+ const customInterfaceNames = currentSchema.customTypes.match(new RegExp("(?<=interface\\s)(\\w+)|(?<=type\\s)(\\w+)", "g"));
1148
+ if (!customInterfaceNames) return {};
1149
+ const temporaryFile = import_tmp.default.fileSync({ mode: 420, prefix: "prefix-", postfix: ".ts" });
1150
+ import_fs.default.writeFileSync(temporaryFile.name, currentSchema.customTypes);
1151
+ const compilerOptions = {
1152
+ strictNullChecks: true,
1153
+ skipLibCheck: true
1154
+ };
1155
+ const program = TJS.getProgramFromFiles(
1156
+ [
1157
+ (0, import_path.resolve)(temporaryFile.name),
1158
+ // find a way to remove
1159
+ import_path.default.join(process2.cwd(), "src/@types/models.d.ts"),
1160
+ import_path.default.join(process2.cwd(), "src/@types/api.d.ts")
1161
+ ],
1162
+ compilerOptions
1163
+ );
1164
+ customInterfaceNames.forEach((item) => {
1165
+ const ddlSchema = TJS.generateSchema(program, item, {
1166
+ required: true
1167
+ });
1168
+ schemaObject[item] = ddlSchema || {};
1169
+ });
1170
+ temporaryFile.removeCallback();
1171
+ return schemaObject;
1172
+ }
1173
+
1174
+ // src/restura/sql/SqlEngine.ts
1175
+ var import_core_utils4 = require("@redskytech/core-utils");
1176
+ var SqlEngine = class {
1177
+ async runQueryForRoute(req, routeData, schema) {
1178
+ if (!this.doesRoleHavePermissionToTable(req.requesterDetails.role, schema, routeData.table))
1179
+ throw new RsError("UNAUTHORIZED", "You do not have permission to access this table");
1180
+ switch (routeData.method) {
1181
+ case "POST":
1182
+ return this.executeCreateRequest(req, routeData, schema);
1183
+ case "GET":
1184
+ return this.executeGetRequest(req, routeData, schema);
1185
+ case "PUT":
1186
+ case "PATCH":
1187
+ return this.executeUpdateRequest(req, routeData, schema);
1188
+ case "DELETE":
1189
+ return this.executeDeleteRequest(req, routeData, schema);
1190
+ }
1191
+ }
1192
+ getTableSchema(schema, tableName) {
1193
+ const tableSchema = schema.database.find((item) => item.name === tableName);
1194
+ if (!tableSchema) throw new RsError("SCHEMA_ERROR", `Table ${tableName} not found in schema`);
1195
+ return tableSchema;
1196
+ }
1197
+ doesRoleHavePermissionToColumn(role, schema, item, joins) {
1198
+ if (item.selector) {
1199
+ let tableName = item.selector.split(".")[0];
1200
+ const columnName = item.selector.split(".")[1];
1201
+ let tableSchema = schema.database.find((item2) => item2.name === tableName);
1202
+ if (!tableSchema) {
1203
+ const join = joins.find((join2) => join2.alias === tableName);
1204
+ if (!join) throw new RsError("SCHEMA_ERROR", `Table ${tableName} not found in schema`);
1205
+ tableName = join.table;
1206
+ tableSchema = schema.database.find((item2) => item2.name === tableName);
1207
+ }
1208
+ if (!tableSchema) throw new RsError("SCHEMA_ERROR", `Table ${tableName} not found in schema`);
1209
+ const columnSchema = tableSchema.columns.find((item2) => item2.name === columnName);
1210
+ if (!columnSchema)
1211
+ throw new RsError("SCHEMA_ERROR", `Column ${columnName} not found in table ${tableName}`);
1212
+ const doesColumnHaveRoles = import_core_utils4.ObjectUtils.isArrayWithData(columnSchema.roles);
1213
+ if (!doesColumnHaveRoles) return true;
1214
+ if (!role) return false;
1215
+ return columnSchema.roles.includes(role);
1216
+ }
1217
+ if (item.subquery) {
1218
+ return import_core_utils4.ObjectUtils.isArrayWithData(
1219
+ item.subquery.properties.filter((nestedItem) => {
1220
+ return this.doesRoleHavePermissionToColumn(role, schema, nestedItem, joins);
1221
+ })
1222
+ );
1223
+ }
1224
+ return false;
1225
+ }
1226
+ doesRoleHavePermissionToTable(userRole, schema, tableName) {
1227
+ const tableSchema = this.getTableSchema(schema, tableName);
1228
+ const doesTableHaveRoles = import_core_utils4.ObjectUtils.isArrayWithData(tableSchema.roles);
1229
+ if (!doesTableHaveRoles) return true;
1230
+ if (!userRole) return false;
1231
+ return tableSchema.roles.includes(userRole);
1232
+ }
1233
+ replaceParamKeywords(value, routeData, req, sqlParams) {
1234
+ let returnValue = value;
1235
+ returnValue = this.replaceLocalParamKeywords(returnValue, routeData, req, sqlParams);
1236
+ returnValue = this.replaceGlobalParamKeywords(returnValue, routeData, req, sqlParams);
1237
+ return returnValue;
1238
+ }
1239
+ replaceLocalParamKeywords(value, routeData, req, sqlParams) {
1240
+ var _a;
1241
+ if (!routeData.request) return value;
1242
+ const data = req.data;
1243
+ if (typeof value === "string") {
1244
+ (_a = value.match(/\$[a-zA-Z][a-zA-Z0-9_]+/g)) == null ? void 0 : _a.forEach((param) => {
1245
+ const requestParam = routeData.request.find((item) => {
1246
+ return item.name === param.replace("$", "");
1247
+ });
1248
+ if (!requestParam)
1249
+ throw new RsError("SCHEMA_ERROR", `Invalid route keyword in route ${routeData.name}`);
1250
+ sqlParams.push(data[requestParam.name]);
1251
+ });
1252
+ return value.replace(new RegExp(/\$[a-zA-Z][a-zA-Z0-9_]+/g), "?");
1253
+ }
1254
+ return value;
1255
+ }
1256
+ replaceGlobalParamKeywords(value, routeData, req, sqlParams) {
1257
+ var _a;
1258
+ if (typeof value === "string") {
1259
+ (_a = value.match(/#[a-zA-Z][a-zA-Z0-9_]+/g)) == null ? void 0 : _a.forEach((param) => {
1260
+ param = param.replace("#", "");
1261
+ const globalParamValue = req.requesterDetails[param];
1262
+ if (!globalParamValue)
1263
+ throw new RsError("SCHEMA_ERROR", `Invalid global keyword clause in route ${routeData.name}`);
1264
+ sqlParams.push(globalParamValue);
1265
+ });
1266
+ return value.replace(new RegExp(/#[a-zA-Z][a-zA-Z0-9_]+/g), "?");
1267
+ }
1268
+ return value;
1269
+ }
1270
+ };
1271
+
1272
+ // src/restura/sql/filterSqlParser.ts
1273
+ var import_pegjs = __toESM(require("pegjs"));
1274
+ var filterSqlGrammar = `
1275
+ start = expressionList
1276
+
1277
+ expressionList =
1278
+ leftExpression:expression operator:operator rightExpression:expressionList
1279
+ { return \`\${leftExpression} \${operator} \${rightExpression}\`;}
1280
+ / expression
1281
+
1282
+ expression =
1283
+ negate:negate?"(" "column:" column:column ","? value:value? ","? type:type? ")"
1284
+ {return \`\${negate? "!" : ""}(\${type? type(column, value) : \`\${column} = \${mysql.escape(value)}\`})\`;}
1285
+ /
1286
+ negate:negate?"("expression:expressionList")" { return \`\${negate? "!" : ""}(\${expression})\`; }
1287
+
1288
+ negate = "!"
1289
+
1290
+ operator = "and"i / "or"i
1291
+
1292
+ column = left:text "." right:text { return \`\${mysql.escapeId(left)}.\${mysql.escapeId(right)}\`; }
1293
+ /
1294
+ text:text { return mysql.escapeId(text); }
1295
+
1296
+
1297
+ text = text:[ a-z0-9-_:.@]i+ { return text.join("");}
1298
+
1299
+ type = "type:" type:typeString { return type; }
1300
+ typeString = text:"startsWith" { return function(column, value) { return \`\${column} LIKE '\${mysql.escape(value).slice(1,-1)}%'\`; } } /
1301
+ text:"endsWith" { return function(column, value) { return \`\${column} LIKE '%\${mysql.escape(value).slice(1,-1)}'\`; } } /
1302
+ text:"contains" { return function(column, value) { return \`\${column} LIKE '%\${mysql.escape(value).slice(1,-1)}%'\`; } } /
1303
+ text:"exact" { return function(column, value) { return \`\${column} = '\${mysql.escape(value).slice(1,-1)}'\`; } } /
1304
+ text:"greaterThanEqual" { return function(column, value) { return \`\${column} >= '\${mysql.escape(value).slice(1,-1)}'\`; } } /
1305
+ text:"greaterThan" { return function(column, value) { return \`\${column} > '\${mysql.escape(value).slice(1,-1)}'\`; } } /
1306
+ text:"lessThanEqual" { return function(column, value) { return \`\${column} <= '\${mysql.escape(value).slice(1,-1)}'\`; } } /
1307
+ text:"lessThan" { return function(column, value) { return \`\${column} < '\${mysql.escape(value).slice(1,-1)}'\`; } } /
1308
+ text:"isNull" { return function(column, value) { return \`isNull(\${column})\`; } }
1309
+
1310
+ value = "value:" value:text { return value; }
1311
+
1312
+ `;
1313
+ var filterSqlParser = import_pegjs.default.generate(filterSqlGrammar, {
1314
+ format: "commonjs"
1315
+ // dependencies: { mysql: 'mysql' } // todo: figure out a better way to escape values depending on the database type
1316
+ });
1317
+ var filterSqlParser_default = filterSqlParser;
1318
+
1319
+ // src/restura/sql/PsqlEngine.ts
1320
+ var import_core_utils5 = require("@redskytech/core-utils");
1321
+
1322
+ // src/restura/sql/PsqlUtils.ts
1323
+ var import_pg_format = __toESM(require("pg-format"));
1324
+ function escapeColumnName(columnName) {
1325
+ if (columnName === void 0) return "";
1326
+ return `"${columnName.replace(/"/g, "")}"`.replace(".", '"."');
1327
+ }
1328
+ function questionMarksToOrderedParams(query) {
1329
+ let count = 1;
1330
+ return query.replace(/'\?'/g, () => `$${count++}`);
1331
+ }
1332
+ function insertObjectQuery(table, obj) {
1333
+ const keys = Object.keys(obj);
1334
+ const params = Object.values(obj);
1335
+ const columns = keys.map((column) => escapeColumnName(column)).join(", ");
1336
+ const values = params.map((value) => SQL`${value}`).join(", ");
1337
+ const query = `INSERT INTO "${table}" (${columns})
1338
+ VALUES (${values})
1339
+ RETURNING *`;
1340
+ return query;
1341
+ }
1342
+ function updateObjectQuery(table, obj, whereStatement) {
1343
+ const setArray = [];
1344
+ for (const i in obj) {
1345
+ setArray.push(`${escapeColumnName(i)} = ` + SQL`${obj[i]}`);
1346
+ }
1347
+ return `UPDATE ${escapeColumnName(table)}
1348
+ SET ${setArray.join(", ")} ${whereStatement}
1349
+ RETURNING *`;
1350
+ }
1351
+ function isValueNumber2(value) {
1352
+ return !isNaN(Number(value));
1353
+ }
1354
+ function SQL(strings, ...values) {
1355
+ let query = strings[0];
1356
+ values.forEach((value, index) => {
1357
+ if (isValueNumber2(value)) {
1358
+ query += value;
1359
+ } else {
1360
+ query += import_pg_format.default.literal(value);
1361
+ }
1362
+ query += strings[index + 1];
1363
+ });
1364
+ return query;
1365
+ }
1366
+
1367
+ // src/restura/sql/PsqlEngine.ts
1368
+ var PsqlEngine = class extends SqlEngine {
1369
+ constructor(psqlConnectionPool) {
1370
+ super();
1371
+ this.psqlConnectionPool = psqlConnectionPool;
1372
+ }
1373
+ async diffDatabaseToSchema(schema) {
1374
+ console.log(schema);
1375
+ return Promise.resolve("");
1376
+ }
1377
+ generateDatabaseSchemaFromSchema(schema) {
1378
+ console.log(schema);
1379
+ return "";
1380
+ }
1381
+ createNestedSelect(req, schema, item, routeData, userRole, sqlParams) {
1382
+ console.log(req, schema, item, routeData, userRole, sqlParams);
1383
+ return "";
1384
+ }
1385
+ async executeCreateRequest(req, routeData, schema) {
1386
+ const sqlParams = [];
1387
+ const parameterObj = {};
1388
+ (routeData.assignments || []).forEach((assignment) => {
1389
+ parameterObj[assignment.name] = this.replaceParamKeywords(assignment.value, routeData, req, sqlParams);
1390
+ });
1391
+ const query = insertObjectQuery(routeData.table, __spreadValues(__spreadValues({}, req.data), parameterObj));
1392
+ const createdItem = await this.psqlConnectionPool.queryOne(query, sqlParams);
1393
+ const insertId = createdItem == null ? void 0 : createdItem.id;
1394
+ const whereData = [
1395
+ {
1396
+ tableName: routeData.table,
1397
+ value: insertId,
1398
+ columnName: "id",
1399
+ operator: "="
1400
+ }
1401
+ ];
1402
+ req.data = { id: insertId };
1403
+ return this.executeGetRequest(req, __spreadProps(__spreadValues({}, routeData), { where: whereData }), schema);
1404
+ }
1405
+ async executeGetRequest(req, routeData, schema) {
1406
+ const DEFAULT_PAGED_PAGE_NUMBER = 0;
1407
+ const DEFAULT_PAGED_PER_PAGE_NUMBER = 25;
1408
+ const sqlParams = [];
1409
+ const userRole = req.requesterDetails.role;
1410
+ let sqlStatement = "";
1411
+ const selectColumns = [];
1412
+ routeData.response.forEach((item) => {
1413
+ if (item.subquery || this.doesRoleHavePermissionToColumn(userRole, schema, item, routeData.joins))
1414
+ selectColumns.push(item);
1415
+ });
1416
+ if (!selectColumns.length) throw new RsError("UNAUTHORIZED", `You do not have permission to access this data.`);
1417
+ let selectStatement = "SELECT \n";
1418
+ selectStatement += ` ${selectColumns.map((item) => {
1419
+ if (item.subquery) {
1420
+ return `${this.createNestedSelect(req, schema, item, routeData, userRole, sqlParams)} AS ${item.name}`;
1421
+ }
1422
+ return `${escapeColumnName(item.selector)} AS ${escapeColumnName(item.name)}`;
1423
+ }).join(",\n ")}
1424
+ `;
1425
+ sqlStatement += `FROM "${routeData.table}"
1426
+ `;
1427
+ sqlStatement += this.generateJoinStatements(
1428
+ req,
1429
+ routeData.joins,
1430
+ routeData.table,
1431
+ routeData,
1432
+ schema,
1433
+ userRole,
1434
+ sqlParams
1435
+ );
1436
+ sqlStatement += this.generateWhereClause(req, routeData.where, routeData, sqlParams);
1437
+ let groupByOrderByStatement = this.generateGroupBy(routeData);
1438
+ groupByOrderByStatement += this.generateOrderBy(req, routeData);
1439
+ if (routeData.type === "ONE") {
1440
+ return this.psqlConnectionPool.queryOne(
1441
+ `${selectStatement}${sqlStatement}${groupByOrderByStatement};`,
1442
+ sqlParams
1443
+ );
1444
+ } else if (routeData.type === "ARRAY") {
1445
+ return this.psqlConnectionPool.runQuery(
1446
+ `${selectStatement}${sqlStatement}${groupByOrderByStatement};`,
1447
+ sqlParams
1448
+ );
1449
+ } else if (routeData.type === "PAGED") {
1450
+ const data = req.data;
1451
+ const pageResults = await this.psqlConnectionPool.runQuery(
1452
+ `${selectStatement}${sqlStatement}${groupByOrderByStatement} LIMIT ? OFFSET ?;SELECT COUNT(${routeData.groupBy ? `DISTINCT ${routeData.groupBy.tableName}.${routeData.groupBy.columnName}` : "*"}) AS total
1453
+ ${sqlStatement};`,
1454
+ [
1455
+ ...sqlParams,
1456
+ data.perPage || DEFAULT_PAGED_PER_PAGE_NUMBER,
1457
+ (data.page - 1) * data.perPage || DEFAULT_PAGED_PAGE_NUMBER,
1458
+ ...sqlParams
1459
+ ]
1460
+ );
1461
+ let total = 0;
1462
+ if (import_core_utils5.ObjectUtils.isArrayWithData(pageResults)) {
1463
+ total = pageResults[1][0].total;
1464
+ }
1465
+ return { data: pageResults[0], total };
1466
+ } else {
1467
+ throw new RsError("UNKNOWN_ERROR", "Unknown route type.");
1468
+ }
1469
+ }
1470
+ async executeUpdateRequest(req, routeData, schema) {
1471
+ const sqlParams = [];
1472
+ const _a = req.body, { id } = _a, bodyNoId = __objRest(_a, ["id"]);
1473
+ const table = schema.database.find((item) => {
1474
+ return item.name === routeData.table;
1475
+ });
1476
+ if (!table) throw new RsError("UNKNOWN_ERROR", "Unknown table.");
1477
+ if (table.columns.find((column) => column.name === "modifiedOn")) {
1478
+ bodyNoId.modifiedOn = (/* @__PURE__ */ new Date()).toISOString();
1479
+ }
1480
+ for (const assignment of routeData.assignments) {
1481
+ const column = table.columns.find((column2) => column2.name === assignment.name);
1482
+ if (!column) continue;
1483
+ const assignmentWithPrefix = escapeColumnName(`${routeData.table}.${assignment.name}`);
1484
+ if (SqlUtils.convertDatabaseTypeToTypescript(column.type) === "number")
1485
+ bodyNoId[assignmentWithPrefix] = Number(assignment.value);
1486
+ else bodyNoId[assignmentWithPrefix] = assignment.value;
1487
+ }
1488
+ const whereClause = this.generateWhereClause(req, routeData.where, routeData, sqlParams);
1489
+ const query = updateObjectQuery(routeData.table, bodyNoId, whereClause);
1490
+ await this.psqlConnectionPool.queryOne(query, [...sqlParams]);
1491
+ return this.executeGetRequest(req, routeData, schema);
1492
+ }
1493
+ async executeDeleteRequest(req, routeData, schema) {
1494
+ const sqlParams = [];
1495
+ const joinStatement = this.generateJoinStatements(
1496
+ req,
1497
+ routeData.joins,
1498
+ routeData.table,
1499
+ routeData,
1500
+ schema,
1501
+ req.requesterDetails.role,
1502
+ sqlParams
1503
+ );
1504
+ let deleteStatement = `DELETE
1505
+ FROM "${routeData.table}" ${joinStatement}`;
1506
+ deleteStatement += this.generateWhereClause(req, routeData.where, routeData, sqlParams);
1507
+ deleteStatement += ";";
1508
+ await this.psqlConnectionPool.runQuery(deleteStatement, sqlParams);
1509
+ return true;
1510
+ }
1511
+ generateJoinStatements(req, joins, baseTable, routeData, schema, userRole, sqlParams) {
1512
+ console.log(req, joins, baseTable, routeData, schema, userRole, sqlParams);
1513
+ return "";
1514
+ }
1515
+ getTableSchema(schema, tableName) {
1516
+ console.log(schema, tableName);
1517
+ return {};
1518
+ }
1519
+ generateGroupBy(routeData) {
1520
+ let groupBy = "";
1521
+ if (routeData.groupBy) {
1522
+ groupBy = `GROUP BY ${escapeColumnName(routeData.groupBy.tableName)}.${escapeColumnName(routeData.groupBy.columnName)}
1523
+ `;
1524
+ }
1525
+ return groupBy;
1526
+ }
1527
+ generateOrderBy(req, routeData) {
1528
+ let orderBy = "";
1529
+ const orderOptions = {
1530
+ ASC: "ASC",
1531
+ DESC: "DESC"
1532
+ };
1533
+ const data = req.data;
1534
+ if (routeData.type === "PAGED" && "sortBy" in data) {
1535
+ const sortOrder = orderOptions[data.sortOrder] || "ASC";
1536
+ orderBy = `ORDER BY ${escapeColumnName(data.sortBy)} ${sortOrder}
1537
+ `;
1538
+ } else if (routeData.orderBy) {
1539
+ const sortOrder = orderOptions[routeData.orderBy.order] || "ASC";
1540
+ orderBy = `ORDER BY ${escapeColumnName(routeData.orderBy.tableName)}.${escapeColumnName(routeData.orderBy.columnName)} ${sortOrder}
1541
+ `;
1542
+ }
1543
+ return orderBy;
1544
+ }
1545
+ generateWhereClause(req, where, routeData, sqlParams) {
1546
+ let whereClause = "";
1547
+ where.forEach((item, index) => {
1548
+ if (index === 0) whereClause = "WHERE ";
1549
+ if (item.custom) {
1550
+ whereClause += this.replaceParamKeywords(item.custom, routeData, req, sqlParams);
1551
+ return;
1552
+ }
1553
+ if (item.operator === void 0 || item.value === void 0 || item.columnName === void 0 || item.tableName === void 0)
1554
+ throw new RsError(
1555
+ "SCHEMA_ERROR",
1556
+ `Invalid where clause in route ${routeData.name}, missing required fields if not custom`
1557
+ );
1558
+ let operator = item.operator;
1559
+ if (operator === "LIKE") {
1560
+ sqlParams[sqlParams.length - 1] = `%${sqlParams[sqlParams.length - 1]}%`;
1561
+ } else if (operator === "STARTS WITH") {
1562
+ operator = "LIKE";
1563
+ sqlParams[sqlParams.length - 1] = `${sqlParams[sqlParams.length - 1]}%`;
1564
+ } else if (operator === "ENDS WITH") {
1565
+ operator = "LIKE";
1566
+ sqlParams[sqlParams.length - 1] = `%${sqlParams[sqlParams.length - 1]}`;
1567
+ }
1568
+ const replacedValue = this.replaceParamKeywords(item.value, routeData, req, sqlParams);
1569
+ const escapedValue = SQL`${replacedValue}`;
1570
+ whereClause += ` ${item.conjunction || ""} "${item.tableName}"."${item.columnName}" ${operator} ${["IN", "NOT IN"].includes(operator) ? `(${escapedValue})` : escapedValue}
1571
+ `;
1572
+ });
1573
+ const data = req.data;
1574
+ if (routeData.type === "PAGED" && !!(data == null ? void 0 : data.filter)) {
1575
+ let statement = data.filter.replace(/\$[a-zA-Z][a-zA-Z0-9_]+/g, (value) => {
1576
+ const requestParam = routeData.request.find((item) => {
1577
+ return item.name === value.replace("$", "");
1578
+ });
1579
+ if (!requestParam)
1580
+ throw new RsError("SCHEMA_ERROR", `Invalid route keyword in route ${routeData.name}`);
1581
+ return data[requestParam.name];
1582
+ });
1583
+ statement = statement.replace(/#[a-zA-Z][a-zA-Z0-9_]+/g, (value) => {
1584
+ const requestParam = routeData.request.find((item) => {
1585
+ return item.name === value.replace("#", "");
1586
+ });
1587
+ if (!requestParam)
1588
+ throw new RsError("SCHEMA_ERROR", `Invalid route keyword in route ${routeData.name}`);
1589
+ return data[requestParam.name];
1590
+ });
1591
+ statement = filterSqlParser_default.parse(statement);
1592
+ if (whereClause.startsWith("WHERE")) {
1593
+ whereClause += ` AND (${statement})
1594
+ `;
1595
+ } else {
1596
+ whereClause += `WHERE ${statement}
1597
+ `;
1598
+ }
1599
+ }
1600
+ return whereClause;
1601
+ }
1602
+ };
1603
+
1604
+ // src/restura/restura.ts
1605
+ var import_pg2 = require("pg");
1606
+
1607
+ // src/restura/sql/PsqlPool.ts
1608
+ var import_pg = require("pg");
1609
+ var PsqlPool = class {
1610
+ constructor(poolConfig) {
1611
+ this.poolConfig = poolConfig;
1612
+ this.pool = new import_pg.Pool(poolConfig);
1613
+ }
1614
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1615
+ async queryOne(query, options) {
1616
+ const formattedQuery = questionMarksToOrderedParams(query);
1617
+ try {
1618
+ const response = await this.pool.query(formattedQuery, options);
1619
+ return response.rows[0];
1620
+ } catch (error) {
1621
+ console.error(error, query, options);
1622
+ if ((error == null ? void 0 : error.routine) === "_bt_check_unique") {
1623
+ throw new RsError("DUPLICATE", error.message);
1624
+ }
1625
+ throw new RsError("DATABASE_ERROR", `${error.message}`);
1626
+ }
1627
+ }
1628
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1629
+ async runQuery(query, options) {
1630
+ const formattedQuery = questionMarksToOrderedParams(query);
1631
+ const queryUpdated = query.replace(/[\t\n]/g, " ");
1632
+ console.log(queryUpdated, options);
1633
+ try {
1634
+ const response = await this.pool.query(formattedQuery, options);
1635
+ return response.rows;
1636
+ } catch (error) {
1637
+ console.error(error, query, options);
1638
+ if ((error == null ? void 0 : error.routine) === "_bt_check_unique") {
1639
+ throw new RsError("DUPLICATE", error.message);
1640
+ }
1641
+ throw new RsError("DATABASE_ERROR", `${error.message}`);
1642
+ }
1643
+ }
1644
+ };
1645
+
81
1646
  // src/restura/restura.ts
82
1647
  var ResturaEngine = class {
83
- init(app) {
1648
+ constructor() {
1649
+ this.publicEndpoints = {
1650
+ GET: [],
1651
+ POST: [],
1652
+ PUT: [],
1653
+ PATCH: [],
1654
+ DELETE: []
1655
+ };
1656
+ }
1657
+ /**
1658
+ * Initializes the Restura engine with the provided Express application.
1659
+ *
1660
+ * @param app - The Express application instance to initialize with Restura.
1661
+ * @returns A promise that resolves when the initialization is complete.
1662
+ */
1663
+ async init(app, authenticationHandler, psqlConnectionPool) {
1664
+ this.psqlConnectionPool = psqlConnectionPool;
1665
+ this.psqlEngine = new PsqlEngine(this.psqlConnectionPool);
1666
+ setupPgReturnTypes();
1667
+ this.resturaConfig = import_internal2.config.validate("restura", resturaConfigSchema);
1668
+ this.authenticationHandler = authenticationHandler;
1669
+ app.use((0, import_compression.default)());
1670
+ app.use(import_body_parser.default.json({ limit: "32mb" }));
1671
+ app.use(import_body_parser.default.urlencoded({ limit: "32mb", extended: false }));
1672
+ app.use((0, import_cookie_parser.default)());
1673
+ app.disable("x-powered-by");
1674
+ app.use("/", addApiResponseFunctions);
1675
+ app.use("/api/", authenticateUser(this.authenticationHandler));
84
1676
  app.use("/restura", this.resturaAuthentication);
85
- console.log("Restura Engine Initialized");
1677
+ app.put(
1678
+ "/restura/v1/schema",
1679
+ schemaValidation,
1680
+ this.updateSchema
1681
+ );
1682
+ app.post(
1683
+ "/restura/v1/schema/preview",
1684
+ schemaValidation,
1685
+ this.previewCreateSchema
1686
+ );
1687
+ app.get("/restura/v1/schema", this.getSchema);
1688
+ app.get("/restura/v1/schema/types", this.getSchemaAndTypes);
1689
+ this.expressApp = app;
1690
+ await this.reloadEndpoints();
1691
+ await this.validateGeneratedTypesFolder();
1692
+ logger.info("Restura Engine Initialized");
1693
+ }
1694
+ /**
1695
+ * Determines if a given endpoint is public based on the HTTP method and full URL. This
1696
+ * is determined on whether the endpoint in the schema has no roles assigned to it.
1697
+ *
1698
+ * @param method - The HTTP method (e.g., 'GET', 'POST', 'PUT', 'PATCH', 'DELETE').
1699
+ * @param fullUrl - The full URL of the endpoint.
1700
+ * @returns A boolean indicating whether the endpoint is public.
1701
+ */
1702
+ isEndpointPublic(method, fullUrl) {
1703
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) return false;
1704
+ return this.publicEndpoints[method].includes(fullUrl);
1705
+ }
1706
+ /**
1707
+ * Checks if an endpoint exists for a given HTTP method and full URL.
1708
+ *
1709
+ * @param method - The HTTP method to check (e.g., 'GET', 'POST', 'PUT', 'PATCH', 'DELETE').
1710
+ * @param fullUrl - The full URL of the endpoint to check.
1711
+ * @returns `true` if the endpoint exists, otherwise `false`.
1712
+ */
1713
+ doesEndpointExist(method, fullUrl) {
1714
+ return this.schema.endpoints.some((endpoint) => {
1715
+ if (!fullUrl.startsWith(endpoint.baseUrl)) return false;
1716
+ const pathWithoutBaseUrl = fullUrl.replace(endpoint.baseUrl, "");
1717
+ return endpoint.routes.some((route) => {
1718
+ return route.method === method && route.path === pathWithoutBaseUrl;
1719
+ });
1720
+ });
1721
+ }
1722
+ /**
1723
+ * Generates an API from the provided schema and writes it to the specified output file.
1724
+ *
1725
+ * @param outputFile - The path to the file where the generated API will be written.
1726
+ * @param providedSchema - The schema from which the API will be generated.
1727
+ * @returns A promise that resolves when the API has been successfully generated and written to the output file.
1728
+ */
1729
+ async generateApiFromSchema(outputFile, providedSchema) {
1730
+ import_fs2.default.writeFileSync(
1731
+ outputFile,
1732
+ await apiGenerator(providedSchema, await this.generateHashForSchema(providedSchema))
1733
+ );
1734
+ }
1735
+ /**
1736
+ * Generates a model from the provided schema and writes it to the specified output file.
1737
+ *
1738
+ * @param outputFile - The path to the file where the generated model will be written.
1739
+ * @param providedSchema - The schema from which the model will be generated.
1740
+ * @returns A promise that resolves when the model has been successfully written to the output file.
1741
+ */
1742
+ async generateModelFromSchema(outputFile, providedSchema) {
1743
+ import_fs2.default.writeFileSync(
1744
+ outputFile,
1745
+ await modelGenerator(providedSchema, await this.generateHashForSchema(providedSchema))
1746
+ );
1747
+ }
1748
+ /**
1749
+ * Retrieves the latest file system schema for Restura.
1750
+ *
1751
+ * @returns {Promise<ResturaSchema>} A promise that resolves to the latest Restura schema.
1752
+ * @throws {Error} If the schema file is missing or the schema is not valid.
1753
+ */
1754
+ async getLatestFileSystemSchema() {
1755
+ if (!import_fs2.default.existsSync(this.resturaConfig.schemaFilePath)) {
1756
+ logger.error(`Missing restura schema file, expected path: ${this.resturaConfig.schemaFilePath}`);
1757
+ throw new Error("Missing restura schema file");
1758
+ }
1759
+ const schemaFileData = import_fs2.default.readFileSync(this.resturaConfig.schemaFilePath, { encoding: "utf8" });
1760
+ const schema = import_core_utils6.ObjectUtils.safeParse(schemaFileData);
1761
+ const isValid = await isSchemaValid(schema);
1762
+ if (!isValid) {
1763
+ logger.error("Schema is not valid");
1764
+ throw new Error("Schema is not valid");
1765
+ }
1766
+ return schema;
1767
+ }
1768
+ /**
1769
+ * Asynchronously generates and retrieves hashes for the provided schema and related generated files.
1770
+ *
1771
+ * @param providedSchema - The schema for which hashes need to be generated.
1772
+ * @returns A promise that resolves to an object containing:
1773
+ * - `schemaHash`: The hash of the provided schema.
1774
+ * - `apiCreatedSchemaHash`: The hash extracted from the generated `api.d.ts` file.
1775
+ * - `modelCreatedSchemaHash`: The hash extracted from the generated `models.d.ts` file.
1776
+ */
1777
+ async getHashes(providedSchema) {
1778
+ var _a, _b, _c, _d;
1779
+ const schemaHash = await this.generateHashForSchema(providedSchema);
1780
+ const apiFile = import_fs2.default.readFileSync(import_path2.default.join(this.resturaConfig.generatedTypesPath, "api.d.ts"));
1781
+ const apiCreatedSchemaHash = (_b = (_a = apiFile.toString().match(/\((.*)\)/)) == null ? void 0 : _a[1]) != null ? _b : "";
1782
+ const modelFile = import_fs2.default.readFileSync(import_path2.default.join(this.resturaConfig.generatedTypesPath, "models.d.ts"));
1783
+ const modelCreatedSchemaHash = (_d = (_c = modelFile.toString().match(/\((.*)\)/)) == null ? void 0 : _c[1]) != null ? _d : "";
1784
+ return {
1785
+ schemaHash,
1786
+ apiCreatedSchemaHash,
1787
+ modelCreatedSchemaHash
1788
+ };
1789
+ }
1790
+ async reloadEndpoints() {
1791
+ this.schema = await this.getLatestFileSystemSchema();
1792
+ this.customTypeValidation = customTypeValidationGenerator(this.schema);
1793
+ this.resturaRouter = express.Router();
1794
+ this.resetPublicEndpoints();
1795
+ let routeCount = 0;
1796
+ for (const endpoint of this.schema.endpoints) {
1797
+ const baseUrl = endpoint.baseUrl.endsWith("/") ? endpoint.baseUrl.slice(0, -1) : endpoint.baseUrl;
1798
+ this.expressApp.use(baseUrl, (req, res, next) => {
1799
+ this.resturaRouter(req, res, next);
1800
+ });
1801
+ for (const route of endpoint.routes) {
1802
+ route.path = route.path.startsWith("/") ? route.path : `/${route.path}`;
1803
+ route.path = route.path.endsWith("/") ? route.path.slice(0, -1) : route.path;
1804
+ const fullUrl = `${baseUrl}${route.path}`;
1805
+ if (route.roles.length === 0) this.publicEndpoints[route.method].push(fullUrl);
1806
+ this.resturaRouter[route.method.toLowerCase()](
1807
+ route.path,
1808
+ // <-- Notice we only use path here since the baseUrl is already added to the router.
1809
+ this.executeRouteLogic
1810
+ );
1811
+ routeCount++;
1812
+ }
1813
+ }
1814
+ this.responseValidator = new ResponseValidator(this.schema);
1815
+ logger.info(`Restura loaded (${routeCount}) endpoint${routeCount > 1 ? "s" : ""}`);
1816
+ }
1817
+ async validateGeneratedTypesFolder() {
1818
+ if (!import_fs2.default.existsSync(this.resturaConfig.generatedTypesPath)) {
1819
+ import_fs2.default.mkdirSync(this.resturaConfig.generatedTypesPath, { recursive: true });
1820
+ }
1821
+ const hasApiFile = import_fs2.default.existsSync(import_path2.default.join(this.resturaConfig.generatedTypesPath, "api.d.ts"));
1822
+ const hasModelsFile = import_fs2.default.existsSync(import_path2.default.join(this.resturaConfig.generatedTypesPath, "models.d.ts"));
1823
+ if (!hasApiFile) {
1824
+ await this.generateApiFromSchema(import_path2.default.join(this.resturaConfig.generatedTypesPath, "api.d.ts"), this.schema);
1825
+ }
1826
+ if (!hasModelsFile) {
1827
+ await this.generateModelFromSchema(
1828
+ import_path2.default.join(this.resturaConfig.generatedTypesPath, "models.d.ts"),
1829
+ this.schema
1830
+ );
1831
+ }
1832
+ const hashes = await this.getHashes(this.schema);
1833
+ if (hashes.schemaHash !== hashes.apiCreatedSchemaHash) {
1834
+ await this.generateApiFromSchema(import_path2.default.join(this.resturaConfig.generatedTypesPath, "api.d.ts"), this.schema);
1835
+ }
1836
+ if (hashes.schemaHash !== hashes.modelCreatedSchemaHash) {
1837
+ await this.generateModelFromSchema(
1838
+ import_path2.default.join(this.resturaConfig.generatedTypesPath, "models.d.ts"),
1839
+ this.schema
1840
+ );
1841
+ }
86
1842
  }
87
1843
  resturaAuthentication(req, res, next) {
88
- next();
1844
+ if (req.headers["x-auth-token"] !== this.resturaConfig.authToken) res.status(401).send("Unauthorized");
1845
+ else next();
1846
+ }
1847
+ async previewCreateSchema(req, res) {
1848
+ try {
1849
+ const schemaDiff = { commands: "", endPoints: [], globalParams: [], roles: [], customTypes: false };
1850
+ res.send({ data: schemaDiff });
1851
+ } catch (err) {
1852
+ res.status(400).send(err);
1853
+ }
1854
+ }
1855
+ async updateSchema(req, res) {
1856
+ try {
1857
+ this.schema = req.data;
1858
+ await this.storeFileSystemSchema();
1859
+ await this.reloadEndpoints();
1860
+ await this.updateTypes();
1861
+ res.send({ data: "success" });
1862
+ } catch (err) {
1863
+ if (err instanceof Error) res.status(400).send(err.message);
1864
+ else res.status(400).send("Unknown error");
1865
+ }
1866
+ }
1867
+ async updateTypes() {
1868
+ await this.generateApiFromSchema(import_path2.default.join(this.resturaConfig.generatedTypesPath, "api.d.ts"), this.schema);
1869
+ await this.generateModelFromSchema(
1870
+ import_path2.default.join(this.resturaConfig.generatedTypesPath, "models.d.ts"),
1871
+ this.schema
1872
+ );
1873
+ }
1874
+ async getSchema(req, res) {
1875
+ res.send({ data: this.schema });
1876
+ }
1877
+ async getSchemaAndTypes(req, res) {
1878
+ try {
1879
+ const schema = await this.getLatestFileSystemSchema();
1880
+ const schemaHash = await this.generateHashForSchema(schema);
1881
+ const apiText = await apiGenerator(schema, schemaHash);
1882
+ const modelsText = await modelGenerator(schema, schemaHash);
1883
+ res.send({ schema, api: apiText, models: modelsText });
1884
+ } catch (err) {
1885
+ res.status(400).send({ error: err });
1886
+ }
1887
+ }
1888
+ async executeRouteLogic(req, res, next) {
1889
+ try {
1890
+ const routeData = this.getRouteData(req.method, req.baseUrl, req.path);
1891
+ this.validateAuthorization(req, routeData);
1892
+ validateRequestParams(req, routeData, this.customTypeValidation);
1893
+ const data = await this.psqlEngine.runQueryForRoute(
1894
+ req,
1895
+ routeData,
1896
+ this.schema
1897
+ );
1898
+ if (routeData.type === "PAGED") res.sendNoWrap(data);
1899
+ else res.sendData(data);
1900
+ } catch (e) {
1901
+ next(e);
1902
+ }
1903
+ }
1904
+ isCustomRoute(route) {
1905
+ return route.type === "CUSTOM_ONE" || route.type === "CUSTOM_ARRAY" || route.type === "CUSTOM_PAGED";
1906
+ }
1907
+ // @boundMethod
1908
+ // private async runCustomRouteLogic<T>(req: RsRequest<T>, res: RsResponse<T>, routeData: RouteData) {
1909
+ // const version = req.baseUrl.split('/')[2];
1910
+ // let domain = routeData.path.split('/')[1];
1911
+ // domain = domain.split('-').reduce((acc, value, index) => {
1912
+ // if (index === 0) acc = value;
1913
+ // else acc += StringUtils.capitalizeFirst(value);
1914
+ // return acc;
1915
+ // }, '');
1916
+ // const customApiName = `${StringUtils.capitalizeFirst(domain)}Api${StringUtils.capitalizeFirst(version)}`;
1917
+ // const customApi = apiFactory.getCustomApi(customApiName);
1918
+ // if (!customApi) throw new RsError('NOT_FOUND', `API domain ${domain}-${version} not found`);
1919
+ // const functionName = `${routeData.method.toLowerCase()}${routeData.path
1920
+ // .replace(new RegExp('-', 'g'), '/')
1921
+ // .split('/')
1922
+ // .reduce((acc, cur) => {
1923
+ // if (cur === '') return acc;
1924
+ // return acc + StringUtils.capitalizeFirst(cur);
1925
+ // }, '')}`;
1926
+ // // @ts-expect-error - Here we are dynamically calling the function from a custom class, not sure how to typescript this
1927
+ // const customFunction = customApi[functionName] as (
1928
+ // req: RsRequest<T>,
1929
+ // res: RsResponse<T>,
1930
+ // routeData: RouteData
1931
+ // ) => Promise<void>;
1932
+ // if (!customFunction) throw new RsError('NOT_FOUND', `API path ${routeData.path} not implemented`);
1933
+ // await customFunction(req, res, routeData);
1934
+ // }
1935
+ async generateHashForSchema(providedSchema) {
1936
+ const schemaPrettyStr = await prettier3.format(JSON.stringify(providedSchema), __spreadValues({
1937
+ parser: "json"
1938
+ }, {
1939
+ trailingComma: "none",
1940
+ tabWidth: 4,
1941
+ useTabs: true,
1942
+ endOfLine: "lf",
1943
+ printWidth: 120,
1944
+ singleQuote: true
1945
+ }));
1946
+ return (0, import_crypto.createHash)("sha256").update(schemaPrettyStr).digest("hex");
1947
+ }
1948
+ async storeFileSystemSchema() {
1949
+ const schemaPrettyStr = await prettier3.format(JSON.stringify(this.schema), __spreadValues({
1950
+ parser: "json"
1951
+ }, {
1952
+ trailingComma: "none",
1953
+ tabWidth: 4,
1954
+ useTabs: true,
1955
+ endOfLine: "lf",
1956
+ printWidth: 120,
1957
+ singleQuote: true
1958
+ }));
1959
+ import_fs2.default.writeFileSync(this.resturaConfig.schemaFilePath, schemaPrettyStr);
1960
+ }
1961
+ resetPublicEndpoints() {
1962
+ this.publicEndpoints = {
1963
+ GET: [],
1964
+ POST: [],
1965
+ PUT: [],
1966
+ PATCH: [],
1967
+ DELETE: []
1968
+ };
1969
+ }
1970
+ validateAuthorization(req, routeData) {
1971
+ const role = req.requesterDetails.role;
1972
+ if (routeData.roles.length === 0 || !role) return;
1973
+ if (!routeData.roles.includes(role))
1974
+ throw new RsError("UNAUTHORIZED", "Not authorized to access this endpoint");
1975
+ }
1976
+ getRouteData(method, baseUrl, path3) {
1977
+ const endpoint = this.schema.endpoints.find((item) => {
1978
+ return item.baseUrl === baseUrl;
1979
+ });
1980
+ if (!endpoint) throw new RsError("NOT_FOUND", "Route not found");
1981
+ const route = endpoint.routes.find((item) => {
1982
+ return item.method === method && item.path === path3;
1983
+ });
1984
+ if (!route) throw new RsError("NOT_FOUND", "Route not found");
1985
+ return route;
89
1986
  }
90
1987
  };
91
1988
  __decorateClass([
92
1989
  boundMethod
93
1990
  ], ResturaEngine.prototype, "resturaAuthentication", 1);
1991
+ __decorateClass([
1992
+ boundMethod
1993
+ ], ResturaEngine.prototype, "previewCreateSchema", 1);
1994
+ __decorateClass([
1995
+ boundMethod
1996
+ ], ResturaEngine.prototype, "updateSchema", 1);
1997
+ __decorateClass([
1998
+ boundMethod
1999
+ ], ResturaEngine.prototype, "getSchema", 1);
2000
+ __decorateClass([
2001
+ boundMethod
2002
+ ], ResturaEngine.prototype, "getSchemaAndTypes", 1);
2003
+ __decorateClass([
2004
+ boundMethod
2005
+ ], ResturaEngine.prototype, "executeRouteLogic", 1);
2006
+ __decorateClass([
2007
+ boundMethod
2008
+ ], ResturaEngine.prototype, "isCustomRoute", 1);
2009
+ var setupPgReturnTypes = () => {
2010
+ const TIMESTAMPTZ_OID = 1184;
2011
+ import_pg2.types.setTypeParser(TIMESTAMPTZ_OID, (val) => {
2012
+ return val === null ? null : new Date(val).toISOString();
2013
+ });
2014
+ const BIGINT_OID = 20;
2015
+ import_pg2.types.setTypeParser(BIGINT_OID, (val) => {
2016
+ return val === null ? null : Number(val);
2017
+ });
2018
+ };
2019
+ setupPgReturnTypes();
94
2020
  var restura = new ResturaEngine();
95
2021
  // Annotate the CommonJS export names for ESM import in node:
96
2022
  0 && (module.exports = {
2023
+ PsqlPool,
2024
+ logger,
97
2025
  restura
98
2026
  });
99
2027
  //# sourceMappingURL=index.js.map