@restura/core 0.1.0-alpha.1 → 0.1.0-alpha.11

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