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