prostgles-server 4.2.178 → 4.2.180

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/.vscode/settings.json +10 -1
  2. package/dist/DboBuilder/TableHandler/DataValidator.d.ts +1 -1
  3. package/dist/DboBuilder/TableHandler/DataValidator.d.ts.map +1 -1
  4. package/dist/DboBuilder/TableHandler/DataValidator.js +4 -4
  5. package/dist/DboBuilder/TableHandler/DataValidator.js.map +1 -1
  6. package/dist/DboBuilder/TableHandler/TableHandler.d.ts +1 -1
  7. package/dist/DboBuilder/TableHandler/TableHandler.d.ts.map +1 -1
  8. package/dist/DboBuilder/TableHandler/insert.js +3 -3
  9. package/dist/DboBuilder/TableHandler/insert.js.map +1 -1
  10. package/dist/DboBuilder/TableHandler/update.d.ts.map +1 -1
  11. package/dist/DboBuilder/TableHandler/update.js +45 -19
  12. package/dist/DboBuilder/TableHandler/update.js.map +1 -1
  13. package/dist/DboBuilder/ViewHandler/ViewHandler.d.ts +1 -1
  14. package/dist/DboBuilder/ViewHandler/ViewHandler.d.ts.map +1 -1
  15. package/dist/DboBuilder/ViewHandler/ViewHandler.js +2 -2
  16. package/dist/DboBuilder/ViewHandler/ViewHandler.js.map +1 -1
  17. package/dist/DboBuilder/parseUpdateRules.js +1 -1
  18. package/dist/DboBuilder/parseUpdateRules.js.map +1 -1
  19. package/dist/Logging.d.ts +10 -3
  20. package/dist/Logging.d.ts.map +1 -1
  21. package/dist/Prostgles.d.ts +2 -2
  22. package/dist/Prostgles.d.ts.map +1 -1
  23. package/dist/Prostgles.js +118 -53
  24. package/dist/Prostgles.js.map +1 -1
  25. package/dist/ProstglesTypes.d.ts +77 -23
  26. package/dist/ProstglesTypes.d.ts.map +1 -1
  27. package/dist/ProstglesTypes.js.map +1 -1
  28. package/dist/SyncReplication.js +2 -2
  29. package/dist/SyncReplication.js.map +1 -1
  30. package/dist/initProstgles.d.ts +9 -2
  31. package/dist/initProstgles.d.ts.map +1 -1
  32. package/dist/initProstgles.js +65 -57
  33. package/dist/initProstgles.js.map +1 -1
  34. package/dist/utils.d.ts.map +1 -1
  35. package/dist/utils.js.map +1 -1
  36. package/documentation/CLIENT.md +542 -0
  37. package/documentation/SERVER.md +104 -0
  38. package/documentation/utils/clientTypes.ts +8436 -0
  39. package/documentation/utils/dist/clientTypes.d.ts +7705 -0
  40. package/documentation/utils/dist/clientTypes.d.ts.map +1 -0
  41. package/documentation/utils/dist/clientTypes.js +8438 -0
  42. package/documentation/utils/dist/definitions.d.ts +7705 -0
  43. package/documentation/utils/dist/definitions.d.ts.map +1 -0
  44. package/documentation/utils/dist/definitions.js +8438 -0
  45. package/documentation/utils/dist/generateClientDocs.d.ts +3 -0
  46. package/documentation/utils/dist/generateClientDocs.d.ts.map +1 -0
  47. package/documentation/utils/dist/generateClientDocs.js +115 -0
  48. package/documentation/utils/dist/generateDocs.d.ts +2 -0
  49. package/documentation/utils/dist/generateDocs.d.ts.map +1 -0
  50. package/documentation/utils/dist/generateDocs.js +6 -0
  51. package/documentation/utils/dist/generateMarkdown.d.ts +2 -0
  52. package/documentation/utils/dist/generateMarkdown.d.ts.map +1 -0
  53. package/documentation/utils/dist/generateMarkdown.js +68 -0
  54. package/documentation/utils/dist/generateServerDocs.d.ts +2 -0
  55. package/documentation/utils/dist/generateServerDocs.d.ts.map +1 -0
  56. package/documentation/utils/dist/generateServerDocs.js +80 -0
  57. package/documentation/utils/dist/getResolvedTypes.d.ts +15 -0
  58. package/documentation/utils/dist/getResolvedTypes.d.ts.map +1 -0
  59. package/documentation/utils/dist/getResolvedTypes.js +29 -0
  60. package/documentation/utils/dist/getSerializableType.d.ts +69 -0
  61. package/documentation/utils/dist/getSerializableType.d.ts.map +1 -0
  62. package/documentation/utils/dist/getSerializableType.js +273 -0
  63. package/documentation/utils/dist/getSymbolComments.d.ts +11 -0
  64. package/documentation/utils/dist/getSymbolComments.d.ts.map +1 -0
  65. package/documentation/utils/dist/getSymbolComments.js +60 -0
  66. package/documentation/utils/dist/loadTsFile.d.ts +7 -0
  67. package/documentation/utils/dist/loadTsFile.d.ts.map +1 -0
  68. package/documentation/utils/dist/loadTsFile.js +33 -0
  69. package/documentation/utils/dist/moduleResolver.d.ts +9 -0
  70. package/documentation/utils/dist/moduleResolver.d.ts.map +1 -0
  71. package/documentation/utils/dist/moduleResolver.js +27 -0
  72. package/documentation/utils/dist/serverTypes.d.ts +307 -0
  73. package/documentation/utils/dist/serverTypes.d.ts.map +1 -0
  74. package/documentation/utils/dist/serverTypes.js +347 -0
  75. package/documentation/utils/generateClientDocs.ts +142 -0
  76. package/documentation/utils/generateDocs.ts +4 -0
  77. package/documentation/utils/generateServerDocs.ts +82 -0
  78. package/documentation/utils/getResolvedTypes.ts +45 -0
  79. package/documentation/utils/getSerializableType.ts +479 -0
  80. package/documentation/utils/loadTsFile.ts +45 -0
  81. package/documentation/utils/moduleResolver.ts +31 -0
  82. package/documentation/utils/node_modules/.package-lock.json +67 -0
  83. package/documentation/utils/node_modules/@types/node/LICENSE +21 -0
  84. package/documentation/utils/node_modules/@types/node/README.md +15 -0
  85. package/documentation/utils/node_modules/@types/node/assert/strict.d.ts +8 -0
  86. package/documentation/utils/node_modules/@types/node/assert.d.ts +1040 -0
  87. package/documentation/utils/node_modules/@types/node/async_hooks.d.ts +541 -0
  88. package/documentation/utils/node_modules/@types/node/buffer.buffer.d.ts +385 -0
  89. package/documentation/utils/node_modules/@types/node/buffer.d.ts +1934 -0
  90. package/documentation/utils/node_modules/@types/node/child_process.d.ts +1548 -0
  91. package/documentation/utils/node_modules/@types/node/cluster.d.ts +578 -0
  92. package/documentation/utils/node_modules/@types/node/compatibility/disposable.d.ts +16 -0
  93. package/documentation/utils/node_modules/@types/node/compatibility/index.d.ts +9 -0
  94. package/documentation/utils/node_modules/@types/node/compatibility/indexable.d.ts +20 -0
  95. package/documentation/utils/node_modules/@types/node/compatibility/iterators.d.ts +21 -0
  96. package/documentation/utils/node_modules/@types/node/console.d.ts +452 -0
  97. package/documentation/utils/node_modules/@types/node/constants.d.ts +19 -0
  98. package/documentation/utils/node_modules/@types/node/crypto.d.ts +4519 -0
  99. package/documentation/utils/node_modules/@types/node/dgram.d.ts +596 -0
  100. package/documentation/utils/node_modules/@types/node/diagnostics_channel.d.ts +554 -0
  101. package/documentation/utils/node_modules/@types/node/dns/promises.d.ts +477 -0
  102. package/documentation/utils/node_modules/@types/node/dns.d.ts +864 -0
  103. package/documentation/utils/node_modules/@types/node/dom-events.d.ts +124 -0
  104. package/documentation/utils/node_modules/@types/node/domain.d.ts +170 -0
  105. package/documentation/utils/node_modules/@types/node/events.d.ts +931 -0
  106. package/documentation/utils/node_modules/@types/node/fs/promises.d.ts +1245 -0
  107. package/documentation/utils/node_modules/@types/node/fs.d.ts +4317 -0
  108. package/documentation/utils/node_modules/@types/node/globals.d.ts +468 -0
  109. package/documentation/utils/node_modules/@types/node/globals.typedarray.d.ts +21 -0
  110. package/documentation/utils/node_modules/@types/node/http.d.ts +1944 -0
  111. package/documentation/utils/node_modules/@types/node/http2.d.ts +2555 -0
  112. package/documentation/utils/node_modules/@types/node/https.d.ts +544 -0
  113. package/documentation/utils/node_modules/@types/node/index.d.ts +91 -0
  114. package/documentation/utils/node_modules/@types/node/inspector.d.ts +3696 -0
  115. package/documentation/utils/node_modules/@types/node/module.d.ts +315 -0
  116. package/documentation/utils/node_modules/@types/node/net.d.ts +1005 -0
  117. package/documentation/utils/node_modules/@types/node/os.d.ts +495 -0
  118. package/documentation/utils/node_modules/@types/node/package.json +220 -0
  119. package/documentation/utils/node_modules/@types/node/path.d.ts +200 -0
  120. package/documentation/utils/node_modules/@types/node/perf_hooks.d.ts +934 -0
  121. package/documentation/utils/node_modules/@types/node/process.d.ts +1879 -0
  122. package/documentation/utils/node_modules/@types/node/punycode.d.ts +117 -0
  123. package/documentation/utils/node_modules/@types/node/querystring.d.ts +153 -0
  124. package/documentation/utils/node_modules/@types/node/readline/promises.d.ts +162 -0
  125. package/documentation/utils/node_modules/@types/node/readline.d.ts +589 -0
  126. package/documentation/utils/node_modules/@types/node/repl.d.ts +430 -0
  127. package/documentation/utils/node_modules/@types/node/sea.d.ts +153 -0
  128. package/documentation/utils/node_modules/@types/node/stream/consumers.d.ts +12 -0
  129. package/documentation/utils/node_modules/@types/node/stream/promises.d.ts +90 -0
  130. package/documentation/utils/node_modules/@types/node/stream/web.d.ts +524 -0
  131. package/documentation/utils/node_modules/@types/node/stream.d.ts +1726 -0
  132. package/documentation/utils/node_modules/@types/node/string_decoder.d.ts +67 -0
  133. package/documentation/utils/node_modules/@types/node/test.d.ts +1938 -0
  134. package/documentation/utils/node_modules/@types/node/timers/promises.d.ts +97 -0
  135. package/documentation/utils/node_modules/@types/node/timers.d.ts +240 -0
  136. package/documentation/utils/node_modules/@types/node/tls.d.ts +1217 -0
  137. package/documentation/utils/node_modules/@types/node/trace_events.d.ts +197 -0
  138. package/documentation/utils/node_modules/@types/node/ts5.6/buffer.buffer.d.ts +385 -0
  139. package/documentation/utils/node_modules/@types/node/ts5.6/globals.typedarray.d.ts +19 -0
  140. package/documentation/utils/node_modules/@types/node/ts5.6/index.d.ts +91 -0
  141. package/documentation/utils/node_modules/@types/node/tty.d.ts +208 -0
  142. package/documentation/utils/node_modules/@types/node/url.d.ts +955 -0
  143. package/documentation/utils/node_modules/@types/node/util.d.ts +2306 -0
  144. package/documentation/utils/node_modules/@types/node/v8.d.ts +808 -0
  145. package/documentation/utils/node_modules/@types/node/vm.d.ts +922 -0
  146. package/documentation/utils/node_modules/@types/node/wasi.d.ts +181 -0
  147. package/documentation/utils/node_modules/@types/node/worker_threads.d.ts +694 -0
  148. package/documentation/utils/node_modules/@types/node/zlib.d.ts +539 -0
  149. package/documentation/utils/node_modules/undici-types/LICENSE +21 -0
  150. package/documentation/utils/node_modules/undici-types/README.md +6 -0
  151. package/documentation/utils/node_modules/undici-types/agent.d.ts +31 -0
  152. package/documentation/utils/node_modules/undici-types/api.d.ts +43 -0
  153. package/documentation/utils/node_modules/undici-types/balanced-pool.d.ts +29 -0
  154. package/documentation/utils/node_modules/undici-types/cache.d.ts +36 -0
  155. package/documentation/utils/node_modules/undici-types/client.d.ts +108 -0
  156. package/documentation/utils/node_modules/undici-types/connector.d.ts +34 -0
  157. package/documentation/utils/node_modules/undici-types/content-type.d.ts +21 -0
  158. package/documentation/utils/node_modules/undici-types/cookies.d.ts +28 -0
  159. package/documentation/utils/node_modules/undici-types/diagnostics-channel.d.ts +66 -0
  160. package/documentation/utils/node_modules/undici-types/dispatcher.d.ts +255 -0
  161. package/documentation/utils/node_modules/undici-types/env-http-proxy-agent.d.ts +21 -0
  162. package/documentation/utils/node_modules/undici-types/errors.d.ts +149 -0
  163. package/documentation/utils/node_modules/undici-types/eventsource.d.ts +63 -0
  164. package/documentation/utils/node_modules/undici-types/fetch.d.ts +209 -0
  165. package/documentation/utils/node_modules/undici-types/file.d.ts +39 -0
  166. package/documentation/utils/node_modules/undici-types/filereader.d.ts +54 -0
  167. package/documentation/utils/node_modules/undici-types/formdata.d.ts +108 -0
  168. package/documentation/utils/node_modules/undici-types/global-dispatcher.d.ts +9 -0
  169. package/documentation/utils/node_modules/undici-types/global-origin.d.ts +7 -0
  170. package/documentation/utils/node_modules/undici-types/handlers.d.ts +15 -0
  171. package/documentation/utils/node_modules/undici-types/header.d.ts +4 -0
  172. package/documentation/utils/node_modules/undici-types/index.d.ts +71 -0
  173. package/documentation/utils/node_modules/undici-types/interceptors.d.ts +15 -0
  174. package/documentation/utils/node_modules/undici-types/mock-agent.d.ts +50 -0
  175. package/documentation/utils/node_modules/undici-types/mock-client.d.ts +25 -0
  176. package/documentation/utils/node_modules/undici-types/mock-errors.d.ts +12 -0
  177. package/documentation/utils/node_modules/undici-types/mock-interceptor.d.ts +93 -0
  178. package/documentation/utils/node_modules/undici-types/mock-pool.d.ts +25 -0
  179. package/documentation/utils/node_modules/undici-types/package.json +55 -0
  180. package/documentation/utils/node_modules/undici-types/patch.d.ts +71 -0
  181. package/documentation/utils/node_modules/undici-types/pool-stats.d.ts +19 -0
  182. package/documentation/utils/node_modules/undici-types/pool.d.ts +39 -0
  183. package/documentation/utils/node_modules/undici-types/proxy-agent.d.ts +28 -0
  184. package/documentation/utils/node_modules/undici-types/readable.d.ts +60 -0
  185. package/documentation/utils/node_modules/undici-types/retry-agent.d.ts +8 -0
  186. package/documentation/utils/node_modules/undici-types/retry-handler.d.ts +116 -0
  187. package/documentation/utils/node_modules/undici-types/util.d.ts +18 -0
  188. package/documentation/utils/node_modules/undici-types/webidl.d.ts +222 -0
  189. package/documentation/utils/node_modules/undici-types/websocket.d.ts +152 -0
  190. package/documentation/utils/package-lock.json +75 -0
  191. package/documentation/utils/package.json +14 -0
  192. package/documentation/utils/serverTypes.ts +345 -0
  193. package/documentation/utils/tsconfig.json +28 -0
  194. package/examples/full-example-typescript/DBoGenerated.d.ts +2 -2
  195. package/examples/full-example-typescript/DBoGenerated.ts +2 -2
  196. package/examples/full-example-typescript/index.ts +39 -45
  197. package/examples/full-example-vanilla/index.js +51 -53
  198. package/examples/server/typescript/index.ts +24 -30
  199. package/lib/DboBuilder/TableHandler/DataValidator.ts +5 -5
  200. package/lib/DboBuilder/TableHandler/TableHandler.ts +1 -1
  201. package/lib/DboBuilder/TableHandler/insert.ts +3 -3
  202. package/lib/DboBuilder/TableHandler/update.ts +106 -48
  203. package/lib/DboBuilder/ViewHandler/ViewHandler.ts +2 -2
  204. package/lib/DboBuilder/parseUpdateRules.ts +1 -1
  205. package/lib/Logging.ts +7 -3
  206. package/lib/Prostgles.ts +209 -142
  207. package/lib/ProstglesTypes.ts +130 -51
  208. package/lib/SyncReplication.ts +2 -2
  209. package/lib/initProstgles.ts +145 -111
  210. package/lib/utils.ts +4 -5
  211. package/package.json +3 -2
  212. package/examples/server/typescript/index.d.ts +0 -2
  213. package/examples/server/typescript/index.d.ts.map +0 -1
  214. package/examples/server/typescript/index.js +0 -54
  215. package/examples/server/typescript/index.js.map +0 -1
package/lib/Prostgles.ts CHANGED
@@ -3,37 +3,37 @@
3
3
  * Licensed under the MIT License. See LICENSE in the project root for license information.
4
4
  *--------------------------------------------------------------------------------------------*/
5
5
 
6
- import * as pgPromise from 'pg-promise';
6
+ import * as pgPromise from "pg-promise";
7
7
  import { AuthHandler } from "./Auth/AuthHandler";
8
8
  import { FileManager } from "./FileManager/FileManager";
9
9
  import { SchemaWatch } from "./SchemaWatch/SchemaWatch";
10
10
  import { OnInitReason, initProstgles } from "./initProstgles";
11
11
  import { makeSocketError, onSocketConnected } from "./onSocketConnected";
12
12
  import { clientCanRunSqlRequest, runClientSqlRequest } from "./runClientRequest";
13
- import pg = require('pg-promise/typescript/pg-subset');
14
- const { version } = require('../package.json');
13
+ import pg = require("pg-promise/typescript/pg-subset");
14
+ const { version } = require("../package.json");
15
15
 
16
16
  import type { ProstglesInitOptions } from "./ProstglesTypes";
17
17
  import { RestApi } from "./RestApi";
18
18
  import TableConfigurator from "./TableConfig/TableConfig";
19
-
20
- import { DBHandlerServer, DboBuilder, LocalParams, PRGLIOSocket, getErrorAsObject } from "./DboBuilder/DboBuilder";
19
+
20
+ import {
21
+ DBHandlerServer,
22
+ DboBuilder,
23
+ LocalParams,
24
+ PRGLIOSocket,
25
+ getErrorAsObject,
26
+ } from "./DboBuilder/DboBuilder";
21
27
  export { DBHandlerServer };
22
28
  export type PGP = pgPromise.IMain<{}, pg.IClient>;
23
29
 
24
- import {
25
- CHANNELS,
26
- ClientSchema,
27
- SQLRequest,
28
- isObject, omitKeys, tryCatch
29
- } from "prostgles-types";
30
+ import { CHANNELS, ClientSchema, SQLRequest, isObject, omitKeys, tryCatch } from "prostgles-types";
30
31
  import { DBEventsManager } from "./DBEventsManager";
31
32
  import { PublishParser } from "./PublishParser/PublishParser";
32
33
  export { getOrSetTransporter, sendEmail, verifySMTPConfig } from "./Auth/sendEmail";
33
34
 
34
35
  export type DB = pgPromise.IDatabase<{}, pg.IClient>;
35
- export type DBorTx = DB | pgPromise.ITask<{}>
36
-
36
+ export type DBorTx = DB | pgPromise.ITask<{}>;
37
37
 
38
38
  export const TABLE_METHODS = ["update", "find", "findOne", "insert", "delete", "upsert"] as const;
39
39
 
@@ -48,17 +48,17 @@ export const TABLE_METHODS = ["update", "find", "findOne", "insert", "delete", "
48
48
  export type OnReady = {
49
49
  dbo: DBHandlerServer;
50
50
  db: DB;
51
- }
51
+ };
52
52
 
53
53
  const DEFAULT_KEYWORDS = {
54
54
  $filter: "$filter",
55
55
  $and: "$and",
56
56
  $or: "$or",
57
- $not: "$not"
57
+ $not: "$not",
58
58
  };
59
59
 
60
60
  import { randomUUID } from "crypto";
61
- import * as fs from 'fs';
61
+ import * as fs from "fs";
62
62
 
63
63
  export class Prostgles {
64
64
  /**
@@ -70,22 +70,22 @@ export class Prostgles {
70
70
  dbConnection: {
71
71
  host: "localhost",
72
72
  port: 5432,
73
- application_name: "prostgles_app"
73
+ application_name: "prostgles_app",
74
74
  },
75
- onReady: () => {
76
- //empty
75
+ onReady: () => {
76
+ //empty
77
77
  },
78
78
  watchSchema: false,
79
79
  watchSchemaType: "DDL_trigger",
80
80
  };
81
-
81
+
82
82
  db?: DB;
83
83
  pgp?: PGP;
84
84
  dbo?: DBHandlerServer;
85
85
  _dboBuilder?: DboBuilder;
86
86
  get dboBuilder(): DboBuilder {
87
87
  if (!this._dboBuilder) {
88
- console.trace(1)
88
+ console.trace(1);
89
89
  throw "get dboBuilder: it's undefined";
90
90
  }
91
91
  return this._dboBuilder;
@@ -118,14 +118,39 @@ export class Prostgles {
118
118
  if (!params) throw "ProstglesInitOptions missing";
119
119
 
120
120
  const config: Record<keyof ProstglesInitOptions, 1> = {
121
- transactions: 1, joins: 1, tsGeneratedTypesDir: 1, disableRealtime: 1,
122
- onReady: 1, dbConnection: 1, dbOptions: 1, publishMethods: 1,
123
- io: 1, publish: 1, schema: 1, publishRawSQL: 1, wsChannelNamePrefix: 1,
124
- onSocketConnect: 1, onSocketDisconnect: 1, sqlFilePath: 1, auth: 1,
125
- DEBUG_MODE: 1, watchSchema: 1, watchSchemaType: 1, fileTable: 1, onQuery: 1,
126
- tableConfig: 1, tableConfigMigrations: 1, keywords: 1, onNotice: 1, onLog: 1, restApi: 1, testRulesOnConnect: 1
121
+ transactions: 1,
122
+ joins: 1,
123
+ tsGeneratedTypesDir: 1,
124
+ disableRealtime: 1,
125
+ onReady: 1,
126
+ dbConnection: 1,
127
+ dbOptions: 1,
128
+ publishMethods: 1,
129
+ io: 1,
130
+ publish: 1,
131
+ schema: 1,
132
+ publishRawSQL: 1,
133
+ wsChannelNamePrefix: 1,
134
+ onSocketConnect: 1,
135
+ onSocketDisconnect: 1,
136
+ sqlFilePath: 1,
137
+ auth: 1,
138
+ DEBUG_MODE: 1,
139
+ watchSchema: 1,
140
+ watchSchemaType: 1,
141
+ fileTable: 1,
142
+ onQuery: 1,
143
+ tableConfig: 1,
144
+ tableConfigMigrations: 1,
145
+ keywords: 1,
146
+ onNotice: 1,
147
+ onLog: 1,
148
+ restApi: 1,
149
+ testRulesOnConnect: 1,
127
150
  };
128
- const unknownParams = Object.keys(params).filter((key: string) => !Object.keys(config).includes(key))
151
+ const unknownParams = Object.keys(params).filter(
152
+ (key: string) => !Object.keys(config).includes(key)
153
+ );
129
154
  if (unknownParams.length) {
130
155
  console.error(`Unrecognised ProstglesInitOptions params: ${unknownParams.join()}`);
131
156
  }
@@ -136,12 +161,12 @@ export class Prostgles {
136
161
  if (this.opts?.fileTable) {
137
162
  this.opts.fileTable.tableName ??= "media";
138
163
  }
139
- this.opts.schema ??= { "public": 1 };
164
+ this.opts.schema ??= { public: 1 };
140
165
 
141
166
  this.keywords = {
142
167
  ...DEFAULT_KEYWORDS,
143
168
  ...params.keywords,
144
- }
169
+ };
145
170
  }
146
171
 
147
172
  destroyed = false;
@@ -151,45 +176,45 @@ export class Prostgles {
151
176
  }
152
177
 
153
178
  getTSFileName() {
154
- const fileName = "DBoGenerated.d.ts" //`dbo_${this.schema}_types.ts`;
155
- const _dir = (this.opts.tsGeneratedTypesDir || "");
156
- const dir = _dir.endsWith("/")? _dir : `${_dir}/`;
179
+ const fileName = "DBSchemaGenerated.d.ts"; //`dbo_${this.schema}_types.ts`;
180
+ const _dir = this.opts.tsGeneratedTypesDir || "";
181
+ const dir = _dir.endsWith("/") ? _dir : `${_dir}/`;
157
182
  const fullPath = dir + fileName;
158
- return { fileName, fullPath }
183
+ return { fileName, fullPath };
159
184
  }
160
185
 
161
186
  private getFileText(fullPath: string, _format = "utf8"): Promise<string> {
162
187
  return new Promise((resolve, reject) => {
163
- fs.readFile(fullPath, 'utf8', function (err, data) {
188
+ fs.readFile(fullPath, "utf8", function (err, data) {
164
189
  if (err) reject(err);
165
190
  else resolve(data);
166
191
  });
167
- })
192
+ });
168
193
  }
169
194
 
170
195
  getTSFileContent = () => {
171
- const header = `/* This file was generated by Prostgles \n` +
172
- // `* ${(new Date).toUTCString()} \n`
173
- `*/ \n\n `;
196
+ const header =
197
+ `/* This file was generated by Prostgles \n` +
198
+ // `* ${(new Date).toUTCString()} \n`
199
+ `*/ \n\n `;
174
200
  return header + this.dboBuilder.tsTypesDefinition;
175
- }
201
+ };
176
202
 
177
203
  /**
178
204
  * Will write the Schema Typescript definitions to file (tsGeneratedTypesDir)
179
205
  */
180
206
  writeDBSchema(force = false) {
181
-
182
207
  if (this.opts.tsGeneratedTypesDir) {
183
208
  const { fullPath, fileName } = this.getTSFileName();
184
209
  const fileContent = this.getTSFileContent();
185
- fs.readFile(fullPath, 'utf8', function (err, data) {
186
- if (err || (force || data !== fileContent)) {
210
+ fs.readFile(fullPath, "utf8", function (err, data) {
211
+ if (err || force || data !== fileContent) {
187
212
  fs.writeFileSync(fullPath, fileContent);
188
- console.log("Prostgles: Created typescript schema definition file: \n " + fileName)
213
+ console.log("Prostgles: Created typescript schema definition file: \n " + fileName);
189
214
  }
190
215
  });
191
216
  } else if (force) {
192
- console.error("Schema changed. tsGeneratedTypesDir needs to be set to reload server")
217
+ console.error("Schema changed. tsGeneratedTypesDir needs to be set to reload server");
193
218
  }
194
219
  }
195
220
 
@@ -197,11 +222,11 @@ export class Prostgles {
197
222
  * Will re-create the dbo object
198
223
  */
199
224
  refreshDBO = async () => {
200
- await this.opts.onLog?.({
201
- type: "debug",
202
- command: "refreshDBO.start",
203
- duration: -1,
204
- data: { }
225
+ await this.opts.onLog?.({
226
+ type: "debug",
227
+ command: "refreshDBO.start",
228
+ duration: -1,
229
+ data: {},
205
230
  });
206
231
  const start = Date.now();
207
232
  if (this._dboBuilder) {
@@ -211,9 +236,13 @@ export class Prostgles {
211
236
  }
212
237
  if (!this.dboBuilder) throw "this.dboBuilder";
213
238
  this.dbo = this.dboBuilder.dbo;
214
- await this.opts.onLog?.({ type: "debug", command: "refreshDBO.end", duration: Date.now() - start })
239
+ await this.opts.onLog?.({
240
+ type: "debug",
241
+ command: "refreshDBO.end",
242
+ duration: Date.now() - start,
243
+ });
215
244
  return this.dbo;
216
- }
245
+ };
217
246
 
218
247
  initRestApi = async () => {
219
248
  if (this.opts.restApi) {
@@ -222,29 +251,36 @@ export class Prostgles {
222
251
  this.restApi?.destroy();
223
252
  this.restApi = undefined;
224
253
  }
225
- }
254
+ };
226
255
 
227
256
  initAuthHandler = async () => {
228
257
  this.authHandler?.destroy();
229
258
  this.authHandler = new AuthHandler(this as any);
230
259
  await this.authHandler.init();
231
- }
260
+ };
232
261
 
233
262
  initTableConfig = async (reason: OnInitReason) => {
234
263
  const res = await tryCatch(async () => {
235
-
236
- if(this.tableConfigurator?.initialising){
264
+ if (this.tableConfigurator?.initialising) {
237
265
  console.error("TableConfigurator WILL deadlock", { reason });
238
266
  }
239
267
  await this.tableConfigurator?.destroy();
240
268
  this.tableConfigurator = new TableConfigurator(this);
241
269
  try {
242
270
  const now = Date.now();
243
- await this.opts.onLog?.({ type: "debug", command: "tableConfigurator.init.start", duration: -1 });
271
+ await this.opts.onLog?.({
272
+ type: "debug",
273
+ command: "tableConfigurator.init.start",
274
+ duration: -1,
275
+ });
244
276
  await this.tableConfigurator.init();
245
- await this.opts.onLog?.({ type: "debug", command: "tableConfigurator.init.end", duration: Date.now() - now });
277
+ await this.opts.onLog?.({
278
+ type: "debug",
279
+ command: "tableConfigurator.init.end",
280
+ duration: Date.now() - now,
281
+ });
246
282
  } catch (e) {
247
- if(this.opts.tableConfigMigrations?.silentFail === false){
283
+ if (this.opts.tableConfigMigrations?.silentFail === false) {
248
284
  console.error("TableConfigurator silentFail: ", e);
249
285
  } else {
250
286
  throw e;
@@ -252,21 +288,21 @@ export class Prostgles {
252
288
  }
253
289
  });
254
290
  await this.opts.onLog?.({ type: "debug", command: "initTableConfig", ...res });
255
- if(res.hasError) throw res.error;
291
+ if (res.hasError) throw res.error;
256
292
  return res.data;
257
- }
293
+ };
258
294
 
259
295
  /* Create media table if required */
260
296
  initFileTable = async () => {
261
297
  const res = await tryCatch(async () => {
262
-
263
298
  if (this.opts.fileTable) {
264
299
  const { cloudClient, localConfig, imageOptions } = this.opts.fileTable;
265
300
  await this.refreshDBO();
266
- if (!cloudClient && !localConfig) throw "fileTable missing param: Must provide awsS3Config OR localConfig";
267
-
301
+ if (!cloudClient && !localConfig)
302
+ throw "fileTable missing param: Must provide awsS3Config OR localConfig";
303
+
268
304
  this.fileManager = new FileManager(cloudClient || localConfig!, imageOptions);
269
-
305
+
270
306
  try {
271
307
  await this.fileManager.init(this);
272
308
  } catch (e) {
@@ -278,55 +314,61 @@ export class Prostgles {
278
314
  this.fileManager = undefined;
279
315
  }
280
316
  await this.refreshDBO();
281
- return { data: {} }
317
+ return { data: {} };
282
318
  });
283
- await this.opts.onLog?.({
284
- type: "debug",
285
- command: "initFileTable",
319
+ await this.opts.onLog?.({
320
+ type: "debug",
321
+ command: "initFileTable",
286
322
  ...res,
287
323
  });
288
- if(res.error !== undefined) throw res.error;
324
+ if (res.error !== undefined) throw res.error;
289
325
  return res.data;
290
- }
326
+ };
291
327
 
292
328
  isSuperUser = false;
293
329
 
294
330
  init = initProstgles.bind(this);
295
331
 
296
332
  async runSQLFile(filePath: string) {
297
-
298
333
  const res = await tryCatch(async () => {
299
- const fileContent = await this.getFileText(filePath);//.then(console.log);
300
-
301
- const result = await this.db?.multi(fileContent)
334
+ const fileContent = await this.getFileText(filePath); //.then(console.log);
335
+
336
+ const result = await this.db
337
+ ?.multi(fileContent)
302
338
  .then((data) => {
303
339
  console.log("Prostgles: SQL file executed successfuly \n -> " + filePath);
304
340
  return data;
305
- }).catch((err) => {
341
+ })
342
+ .catch((err) => {
306
343
  const { position, length } = err,
307
344
  lines = fileContent.split("\n");
308
345
  let errMsg = filePath + " error: ";
309
-
346
+
310
347
  if (position && length && fileContent) {
311
- const startLine = Math.max(0, fileContent.substring(0, position).split("\n").length - 2),
348
+ const startLine = Math.max(
349
+ 0,
350
+ fileContent.substring(0, position).split("\n").length - 2
351
+ ),
312
352
  endLine = startLine + 3;
313
-
353
+
314
354
  errMsg += "\n\n";
315
- errMsg += lines.slice(startLine, endLine).map((txt, i) => `${startLine + i + 1} ${i === 1 ? "->" : " "} ${txt}`).join("\n");
355
+ errMsg += lines
356
+ .slice(startLine, endLine)
357
+ .map((txt, i) => `${startLine + i + 1} ${i === 1 ? "->" : " "} ${txt}`)
358
+ .join("\n");
316
359
  errMsg += "\n\n";
317
360
  }
318
361
  console.error(errMsg, err);
319
362
  return Promise.reject(err);
320
363
  });
321
- return { success: result?.length }
364
+ return { success: result?.length };
322
365
  });
323
366
 
324
367
  await this.opts.onLog?.({ type: "debug", command: "runSQLFile", ...res });
325
- if(res.error !== undefined) throw res.error;
368
+ if (res.error !== undefined) throw res.error;
326
369
  return res.success;
327
370
  }
328
371
 
329
-
330
372
  connectedSockets: PRGLIOSocket[] = [];
331
373
  async setSocketEvents() {
332
374
  this.checkDb();
@@ -334,11 +376,11 @@ export class Prostgles {
334
376
  if (!this.dbo) throw "dbo missing";
335
377
 
336
378
  const publishParser = new PublishParser(
337
- this.opts.publish,
338
- this.opts.publishMethods,
339
- this.opts.publishRawSQL,
340
- this.dbo,
341
- this.db!,
379
+ this.opts.publish,
380
+ this.opts.publishMethods,
381
+ this.opts.publishRawSQL,
382
+ this.dbo,
383
+ this.db!,
342
384
  this
343
385
  );
344
386
  this.publishParser = publishParser;
@@ -347,7 +389,7 @@ export class Prostgles {
347
389
 
348
390
  /* Already initialised. Only reconnect sockets */
349
391
  if (this.connectedSockets.length) {
350
- this.connectedSockets.forEach(s => {
392
+ this.connectedSockets.forEach((s) => {
351
393
  s.emit(CHANNELS.SCHEMA_CHANGED);
352
394
  this.pushSocketSchema(s);
353
395
  });
@@ -355,22 +397,23 @@ export class Prostgles {
355
397
  }
356
398
 
357
399
  /* Initialise */
358
- this.opts.io.removeAllListeners('connection');
359
- this.opts.io.on('connection', this.onSocketConnected);
400
+ this.opts.io.removeAllListeners("connection");
401
+ this.opts.io.on("connection", this.onSocketConnected);
360
402
  /** In some cases io will re-init with already connected sockets */
361
- this.opts.io?.sockets.sockets.forEach(socket => this.onSocketConnected(socket))
403
+ this.opts.io?.sockets.sockets.forEach((socket) => this.onSocketConnected(socket));
362
404
  }
363
405
 
364
406
  onSocketConnected = onSocketConnected.bind(this);
365
407
 
366
408
  getClientSchema = async (clientReq: Pick<LocalParams, "socket" | "httpReq">) => {
367
-
368
409
  const result = await tryCatch(async () => {
369
-
370
- const clientInfo = clientReq.socket? { type: "socket" as const, socket: clientReq.socket } : clientReq.httpReq? { type: "http" as const, httpReq: clientReq.httpReq } : undefined;
371
- if(!clientInfo) throw "Invalid client";
372
- if(!this.authHandler) throw "this.authHandler missing";
373
- const userData = await this.authHandler.getClientInfo(clientInfo);
410
+ const clientInfo =
411
+ clientReq.socket ? { type: "socket" as const, socket: clientReq.socket }
412
+ : clientReq.httpReq ? { type: "http" as const, httpReq: clientReq.httpReq }
413
+ : undefined;
414
+ if (!clientInfo) throw "Invalid client";
415
+ if (!this.authHandler) throw "this.authHandler missing";
416
+ const userData = await this.authHandler.getClientInfo(clientInfo);
374
417
  const { publishParser } = this;
375
418
  let fullSchema: Awaited<ReturnType<PublishParser["getSchemaFromPublish"]>> | undefined;
376
419
  let publishValidationError;
@@ -388,15 +431,19 @@ export class Prostgles {
388
431
  rawSQL = allowed;
389
432
  }
390
433
 
391
- const { schema, tables, tableSchemaErrors } = fullSchema ?? { schema: {}, tables: [], tableSchemaErrors: {} };
434
+ const { schema, tables, tableSchemaErrors } = fullSchema ?? {
435
+ schema: {},
436
+ tables: [],
437
+ tableSchemaErrors: {},
438
+ };
392
439
  const joinTables2: string[][] = [];
393
440
  if (this.opts.joins) {
394
- const _joinTables2 = this.dboBuilder.getAllJoinPaths()
395
- .filter(jp =>
396
- ![jp.t1, jp.t2].find(t => !schema[t] || !schema[t]?.findOne)
397
- ).map(jp => [jp.t1, jp.t2].sort());
398
- _joinTables2.map(jt => {
399
- if (!joinTables2.find(_jt => _jt.join() === jt.join())) {
441
+ const _joinTables2 = this.dboBuilder
442
+ .getAllJoinPaths()
443
+ .filter((jp) => ![jp.t1, jp.t2].find((t) => !schema[t] || !schema[t]?.findOne))
444
+ .map((jp) => [jp.t1, jp.t2].sort());
445
+ _joinTables2.map((jt) => {
446
+ if (!joinTables2.find((_jt) => _jt.join() === jt.join())) {
400
447
  joinTables2.push(jt);
401
448
  }
402
449
  });
@@ -404,77 +451,97 @@ export class Prostgles {
404
451
 
405
452
  const methods = await publishParser?.getAllowedMethods(clientInfo, userData);
406
453
 
407
- const methodSchema: ClientSchema["methods"] = !methods? [] : Object.entries(methods).map(([methodName, method]) => {
408
- if(isObject(method) && "run" in method){
409
- return {
410
- name: methodName,
411
- ...omitKeys(method, ["run"]),
412
- }
413
- }
414
- return methodName;
415
- }).sort((a, b) => {
416
- const aName = isObject(a)? a.name : a;
417
- const bName = isObject(b)? b.name : b;
418
- return aName.localeCompare(bName);
419
- });
454
+ const methodSchema: ClientSchema["methods"] =
455
+ !methods ?
456
+ []
457
+ : Object.entries(methods)
458
+ .map(([methodName, method]) => {
459
+ if (isObject(method) && "run" in method) {
460
+ return {
461
+ name: methodName,
462
+ ...omitKeys(method, ["run"]),
463
+ };
464
+ }
465
+ return methodName;
466
+ })
467
+ .sort((a, b) => {
468
+ const aName = isObject(a) ? a.name : a;
469
+ const bName = isObject(b) ? b.name : b;
470
+ return aName.localeCompare(bName);
471
+ });
420
472
 
421
473
  const { auth } = await this.authHandler.getClientAuth(clientReq);
422
-
474
+
423
475
  const clientSchema: ClientSchema = {
424
476
  schema,
425
- methods: methodSchema,
477
+ methods: methodSchema,
426
478
  tableSchema: tables,
427
479
  rawSQL,
428
480
  joinTables: joinTables2,
429
481
  tableSchemaErrors,
430
482
  auth,
431
483
  version,
432
- err: publishValidationError? "Server Error: User publish validation failed." : undefined
484
+ err: publishValidationError ? "Server Error: User publish validation failed." : undefined,
433
485
  };
434
-
486
+
435
487
  return {
436
488
  publishValidationError,
437
489
  clientSchema,
438
- userData
439
- }
490
+ userData,
491
+ };
440
492
  });
441
493
  const sid = result.userData?.sid ?? this.authHandler?.getSIDNoError(clientReq);
442
- await this.opts.onLog?.({
494
+ await this.opts.onLog?.({
443
495
  type: "connect.getClientSchema",
444
496
  duration: result.duration,
445
497
  sid,
446
498
  socketId: clientReq.socket?.id,
447
499
  error: result.error || result.publishValidationError,
448
500
  });
449
- if(result.hasError) throw result.error;
501
+ if (result.hasError) throw result.error;
450
502
  return result.clientSchema;
451
- }
503
+ };
452
504
 
453
505
  pushSocketSchema = async (socket: PRGLIOSocket) => {
454
-
455
506
  try {
456
507
  const clientSchema = await this.getClientSchema({ socket });
457
508
  socket.prostgles = clientSchema;
458
509
  if (clientSchema.rawSQL) {
459
- socket.removeAllListeners(CHANNELS.SQL)
460
- socket.on(CHANNELS.SQL, async ({ query, params, options }: SQLRequest, cb = (..._callback: any) => { /* Empty */ }) => {
461
-
462
- runClientSqlRequest.bind(this)({ type: "socket", socket, query, args: params, options }).then(res => {
463
- cb(null, res);
464
- }).catch(err => {
465
- makeSocketError(cb, err);
466
- });
467
- });
510
+ socket.removeAllListeners(CHANNELS.SQL);
511
+ socket.on(
512
+ CHANNELS.SQL,
513
+ async (
514
+ { query, params, options }: SQLRequest,
515
+ cb = (..._callback: any) => {
516
+ /* Empty */
517
+ }
518
+ ) => {
519
+ runClientSqlRequest
520
+ .bind(this)({ type: "socket", socket, query, args: params, options })
521
+ .then((res) => {
522
+ cb(null, res);
523
+ })
524
+ .catch((err) => {
525
+ makeSocketError(cb, err);
526
+ });
527
+ }
528
+ );
468
529
  }
530
+ await this.dboBuilder.prostgles.opts.onLog?.({
531
+ type: "debug",
532
+ command: "pushSocketSchema",
533
+ duration: -1,
534
+ data: { socketId: socket.id, clientSchema },
535
+ });
469
536
  socket.emit(CHANNELS.SCHEMA, clientSchema);
470
-
471
537
  } catch (err) {
472
538
  socket.emit(CHANNELS.SCHEMA, { err: getErrorAsObject(err) });
473
539
  }
474
- }
540
+ };
475
541
  }
476
542
 
477
-
478
543
  export async function getIsSuperUser(db: DB): Promise<boolean> {
479
- return db.oneOrNone("select usesuper from pg_user where usename = CURRENT_USER;").then(r => r.usesuper);
480
- }
544
+ return db
545
+ .oneOrNone("select usesuper from pg_user where usename = CURRENT_USER;")
546
+ .then((r) => r.usesuper);
547
+ }