prostgles-server 4.0.57 → 4.0.59

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 (221) hide show
  1. package/dist/DboBuilder/getColumns.d.ts.map +1 -1
  2. package/dist/DboBuilder/getColumns.js +1 -13
  3. package/dist/DboBuilder/getColumns.js.map +1 -1
  4. package/dist/DboBuilder/runSQL.js +2 -2
  5. package/dist/DboBuilder/runSQL.js.map +1 -1
  6. package/dist/Prostgles.d.ts.map +1 -1
  7. package/dist/PubSubManager/PubSubManager.d.ts +1 -1
  8. package/dist/PubSubManager/PubSubManager.d.ts.map +1 -1
  9. package/dist/PubSubManager/PubSubManager.js +14 -1
  10. package/dist/PubSubManager/PubSubManager.js.map +1 -1
  11. package/lib/DboBuilder/getColumns.ts +1 -18
  12. package/lib/DboBuilder/runSQL.ts +2 -2
  13. package/lib/Prostgles.ts +3 -3
  14. package/lib/PubSubManager/PubSubManager.ts +14 -1
  15. package/package.json +2 -2
  16. package/tests/client/PID.txt +1 -1
  17. package/tests/client/package.json +2 -2
  18. package/tests/client/tsconfig.json +2 -1
  19. package/tests/isomorphic_queries.ts +11 -9
  20. package/tests/server/DBoGenerated.d.ts +1 -1
  21. package/tests/server/dboTypeCheck.ts +3 -3
  22. package/tests/server/index.ts +7 -6
  23. package/tests/server/package-lock.json +1 -1
  24. package/tests/server/package.json +3 -3
  25. package/tests/server/publishTypeCheck.ts +1 -1
  26. package/tests/server/tsconfig.json +3 -2
  27. package/tests/test.sh +2 -0
  28. package/dist/FileManager.d.ts +0 -143
  29. package/dist/FileManager.d.ts.map +0 -1
  30. package/dist/FileManager.js +0 -646
  31. package/dist/FileManager.js.map +0 -1
  32. package/dist/TableConfig.d.ts +0 -267
  33. package/dist/TableConfig.d.ts.map +0 -1
  34. package/dist/TableConfig.js +0 -463
  35. package/dist/TableConfig.js.map +0 -1
  36. package/dist/validation.d.ts +0 -126
  37. package/dist/validation.d.ts.map +0 -1
  38. package/dist/validation.js +0 -405
  39. package/dist/validation.js.map +0 -1
  40. package/lib/AuthHandler.d.ts +0 -187
  41. package/lib/AuthHandler.d.ts.map +0 -1
  42. package/lib/AuthHandler.js +0 -478
  43. package/lib/DBEventsManager.d.ts +0 -38
  44. package/lib/DBEventsManager.d.ts.map +0 -1
  45. package/lib/DBEventsManager.js +0 -140
  46. package/lib/DBSchemaBuilder.d.ts +0 -13
  47. package/lib/DBSchemaBuilder.d.ts.map +0 -1
  48. package/lib/DBSchemaBuilder.js +0 -145
  49. package/lib/DboBuilder/QueryBuilder/Functions.d.ts +0 -64
  50. package/lib/DboBuilder/QueryBuilder/Functions.d.ts.map +0 -1
  51. package/lib/DboBuilder/QueryBuilder/Functions.js +0 -984
  52. package/lib/DboBuilder/QueryBuilder/QueryBuilder.d.ts +0 -73
  53. package/lib/DboBuilder/QueryBuilder/QueryBuilder.d.ts.map +0 -1
  54. package/lib/DboBuilder/QueryBuilder/QueryBuilder.js +0 -335
  55. package/lib/DboBuilder/QueryBuilder/makeSelectQuery.d.ts +0 -8
  56. package/lib/DboBuilder/QueryBuilder/makeSelectQuery.d.ts.map +0 -1
  57. package/lib/DboBuilder/QueryBuilder/makeSelectQuery.js +0 -227
  58. package/lib/DboBuilder/TableHandler.d.ts +0 -37
  59. package/lib/DboBuilder/TableHandler.d.ts.map +0 -1
  60. package/lib/DboBuilder/TableHandler.js +0 -213
  61. package/lib/DboBuilder/ViewHandler.d.ts +0 -119
  62. package/lib/DboBuilder/ViewHandler.d.ts.map +0 -1
  63. package/lib/DboBuilder/ViewHandler.js +0 -1023
  64. package/lib/DboBuilder/delete.d.ts +0 -6
  65. package/lib/DboBuilder/delete.d.ts.map +0 -1
  66. package/lib/DboBuilder/delete.js +0 -128
  67. package/lib/DboBuilder/find.d.ts +0 -8
  68. package/lib/DboBuilder/find.d.ts.map +0 -1
  69. package/lib/DboBuilder/find.js +0 -91
  70. package/lib/DboBuilder/getColumns.d.ts +0 -12
  71. package/lib/DboBuilder/getColumns.d.ts.map +0 -1
  72. package/lib/DboBuilder/getColumns.js +0 -92
  73. package/lib/DboBuilder/getCondition.d.ts +0 -22
  74. package/lib/DboBuilder/getCondition.d.ts.map +0 -1
  75. package/lib/DboBuilder/getCondition.js +0 -236
  76. package/lib/DboBuilder/getSubscribeRelatedTables.d.ts +0 -20
  77. package/lib/DboBuilder/getSubscribeRelatedTables.d.ts.map +0 -1
  78. package/lib/DboBuilder/getSubscribeRelatedTables.js +0 -152
  79. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.d.ts +0 -3
  80. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.d.ts.map +0 -1
  81. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.js +0 -207
  82. package/lib/DboBuilder/insert.d.ts +0 -6
  83. package/lib/DboBuilder/insert.d.ts.map +0 -1
  84. package/lib/DboBuilder/insert.js +0 -180
  85. package/lib/DboBuilder/insertDataParse.d.ts +0 -12
  86. package/lib/DboBuilder/insertDataParse.d.ts.map +0 -1
  87. package/lib/DboBuilder/insertDataParse.js +0 -253
  88. package/lib/DboBuilder/parseUpdateRules.d.ts +0 -18
  89. package/lib/DboBuilder/parseUpdateRules.d.ts.map +0 -1
  90. package/lib/DboBuilder/parseUpdateRules.js +0 -123
  91. package/lib/DboBuilder/runSQL.d.ts +0 -7
  92. package/lib/DboBuilder/runSQL.d.ts.map +0 -1
  93. package/lib/DboBuilder/runSQL.js +0 -135
  94. package/lib/DboBuilder/subscribe.d.ts +0 -20
  95. package/lib/DboBuilder/subscribe.d.ts.map +0 -1
  96. package/lib/DboBuilder/subscribe.js +0 -90
  97. package/lib/DboBuilder/update.d.ts +0 -6
  98. package/lib/DboBuilder/update.d.ts.map +0 -1
  99. package/lib/DboBuilder/update.js +0 -151
  100. package/lib/DboBuilder/uploadFile.d.ts +0 -7
  101. package/lib/DboBuilder/uploadFile.d.ts.map +0 -1
  102. package/lib/DboBuilder/uploadFile.js +0 -53
  103. package/lib/DboBuilder.d.ts +0 -306
  104. package/lib/DboBuilder.d.ts.map +0 -1
  105. package/lib/DboBuilder.js +0 -745
  106. package/lib/Event_Trigger_Tags.d.ts +0 -4
  107. package/lib/Event_Trigger_Tags.d.ts.map +0 -1
  108. package/lib/Event_Trigger_Tags.js +0 -116
  109. package/lib/FileManager/FileManager.d.ts +0 -135
  110. package/lib/FileManager/FileManager.d.ts.map +0 -1
  111. package/lib/FileManager/FileManager.js +0 -303
  112. package/lib/FileManager/initFileManager.d.ts +0 -4
  113. package/lib/FileManager/initFileManager.d.ts.map +0 -1
  114. package/lib/FileManager/initFileManager.js +0 -231
  115. package/lib/FileManager/parseFile.d.ts +0 -15
  116. package/lib/FileManager/parseFile.d.ts.map +0 -1
  117. package/lib/FileManager/parseFile.js +0 -58
  118. package/lib/FileManager/upload.d.ts +0 -6
  119. package/lib/FileManager/upload.d.ts.map +0 -1
  120. package/lib/FileManager/upload.js +0 -98
  121. package/lib/FileManager/uploadStream.d.ts +0 -5
  122. package/lib/FileManager/uploadStream.d.ts.map +0 -1
  123. package/lib/FileManager/uploadStream.js +0 -92
  124. package/lib/Filtering.d.ts +0 -15
  125. package/lib/Filtering.d.ts.map +0 -1
  126. package/lib/Filtering.js +0 -336
  127. package/lib/JSONBValidation/validate_jsonb_schema_sql.d.ts +0 -4
  128. package/lib/JSONBValidation/validate_jsonb_schema_sql.d.ts.map +0 -1
  129. package/lib/JSONBValidation/validate_jsonb_schema_sql.js +0 -500
  130. package/lib/JSONBValidation/validation.d.ts +0 -9
  131. package/lib/JSONBValidation/validation.d.ts.map +0 -1
  132. package/lib/JSONBValidation/validation.js +0 -131
  133. package/lib/PostgresNotifListenManager.d.ts +0 -28
  134. package/lib/PostgresNotifListenManager.d.ts.map +0 -1
  135. package/lib/PostgresNotifListenManager.js +0 -134
  136. package/lib/Prostgles.d.ts +0 -289
  137. package/lib/Prostgles.d.ts.map +0 -1
  138. package/lib/Prostgles.js +0 -685
  139. package/lib/PubSubManager/PubSubManager.d.ts +0 -175
  140. package/lib/PubSubManager/PubSubManager.d.ts.map +0 -1
  141. package/lib/PubSubManager/PubSubManager.js +0 -452
  142. package/lib/PubSubManager/addSub.d.ts +0 -8
  143. package/lib/PubSubManager/addSub.d.ts.map +0 -1
  144. package/lib/PubSubManager/addSub.js +0 -166
  145. package/lib/PubSubManager/addSync.d.ts +0 -8
  146. package/lib/PubSubManager/addSync.d.ts.map +0 -1
  147. package/lib/PubSubManager/addSync.js +0 -109
  148. package/lib/PubSubManager/getInitQuery.d.ts +0 -9
  149. package/lib/PubSubManager/getInitQuery.d.ts.map +0 -1
  150. package/lib/PubSubManager/getInitQuery.js +0 -552
  151. package/lib/PubSubManager/initPubSubManager.d.ts +0 -3
  152. package/lib/PubSubManager/initPubSubManager.d.ts.map +0 -1
  153. package/lib/PubSubManager/initPubSubManager.js +0 -116
  154. package/lib/PubSubManager/notifListener.d.ts +0 -5
  155. package/lib/PubSubManager/notifListener.d.ts.map +0 -1
  156. package/lib/PubSubManager/notifListener.js +0 -100
  157. package/lib/PubSubManager/pushSubData.d.ts +0 -3
  158. package/lib/PubSubManager/pushSubData.d.ts.map +0 -1
  159. package/lib/PubSubManager/pushSubData.js +0 -51
  160. package/lib/PublishParser.d.ts +0 -284
  161. package/lib/PublishParser.d.ts.map +0 -1
  162. package/lib/PublishParser.js +0 -421
  163. package/lib/SchemaWatch.d.ts +0 -13
  164. package/lib/SchemaWatch.d.ts.map +0 -1
  165. package/lib/SchemaWatch.js +0 -35
  166. package/lib/SyncReplication.d.ts +0 -34
  167. package/lib/SyncReplication.d.ts.map +0 -1
  168. package/lib/SyncReplication.js +0 -412
  169. package/lib/TableConfig/TableConfig.d.ts +0 -284
  170. package/lib/TableConfig/TableConfig.d.ts.map +0 -1
  171. package/lib/TableConfig/TableConfig.js +0 -437
  172. package/lib/TableConfig/getColumnDefinitionQuery.d.ts +0 -27
  173. package/lib/TableConfig/getColumnDefinitionQuery.d.ts.map +0 -1
  174. package/lib/TableConfig/getColumnDefinitionQuery.js +0 -87
  175. package/lib/TableConfig/getConstraintDefinitionQueries.d.ts +0 -34
  176. package/lib/TableConfig/getConstraintDefinitionQueries.d.ts.map +0 -1
  177. package/lib/TableConfig/getConstraintDefinitionQueries.js +0 -65
  178. package/lib/TableConfig/getFutureTableSchema.d.ts +0 -15
  179. package/lib/TableConfig/getFutureTableSchema.d.ts.map +0 -1
  180. package/lib/TableConfig/getFutureTableSchema.js +0 -43
  181. package/lib/TableConfig/getTableColumnQueries.d.ts +0 -16
  182. package/lib/TableConfig/getTableColumnQueries.d.ts.map +0 -1
  183. package/lib/TableConfig/getTableColumnQueries.js +0 -107
  184. package/lib/index.d.ts +0 -5
  185. package/lib/index.d.ts.map +0 -1
  186. package/lib/index.js +0 -7
  187. package/lib/shortestPath.d.ts +0 -10
  188. package/lib/shortestPath.d.ts.map +0 -1
  189. package/lib/shortestPath.js +0 -111
  190. package/lib/utils.d.ts +0 -3
  191. package/lib/utils.d.ts.map +0 -1
  192. package/lib/utils.js +0 -12
  193. package/tests/client/index.d.ts +0 -2
  194. package/tests/client/index.d.ts.map +0 -1
  195. package/tests/client/index.js +0 -80
  196. package/tests/client/index.js.map +0 -1
  197. package/tests/client_only_queries.d.ts +0 -4
  198. package/tests/client_only_queries.d.ts.map +0 -1
  199. package/tests/client_only_queries.js +0 -282
  200. package/tests/config_test/DBoGenerated.d.ts +0 -388
  201. package/tests/config_test/index.js +0 -174
  202. package/tests/config_test/index.js.map +0 -1
  203. package/tests/isomorphic_queries.d.ts +0 -9
  204. package/tests/isomorphic_queries.d.ts.map +0 -1
  205. package/tests/isomorphic_queries.js +0 -773
  206. package/tests/manual_test/DBoGenerated.d.ts +0 -398
  207. package/tests/manual_test/index.d.ts +0 -2
  208. package/tests/manual_test/index.d.ts.map +0 -1
  209. package/tests/manual_test/index.js +0 -65
  210. package/tests/server/dboTypeCheck.d.ts +0 -2
  211. package/tests/server/dboTypeCheck.d.ts.map +0 -1
  212. package/tests/server/dboTypeCheck.js +0 -27
  213. package/tests/server/index.d.ts +0 -2
  214. package/tests/server/index.d.ts.map +0 -1
  215. package/tests/server/index.js +0 -507
  216. package/tests/server/publishTypeCheck.d.ts +0 -2
  217. package/tests/server/publishTypeCheck.d.ts.map +0 -1
  218. package/tests/server/publishTypeCheck.js +0 -130
  219. package/tests/server_only_queries.d.ts +0 -2
  220. package/tests/server_only_queries.d.ts.map +0 -1
  221. package/tests/server_only_queries.js +0 -19
package/lib/Prostgles.js DELETED
@@ -1,685 +0,0 @@
1
- "use strict";
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Stefan L. All rights reserved.
4
- * Licensed under the MIT License. See LICENSE in the project root for license information.
5
- *--------------------------------------------------------------------------------------------*/
6
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
- if (k2 === undefined) k2 = k;
8
- var desc = Object.getOwnPropertyDescriptor(m, k);
9
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
- desc = { enumerable: true, get: function() { return m[k]; } };
11
- }
12
- Object.defineProperty(o, k2, desc);
13
- }) : (function(o, m, k, k2) {
14
- if (k2 === undefined) k2 = k;
15
- o[k2] = m[k];
16
- }));
17
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
- Object.defineProperty(o, "default", { enumerable: true, value: v });
19
- }) : function(o, v) {
20
- o["default"] = v;
21
- });
22
- var __importStar = (this && this.__importStar) || function (mod) {
23
- if (mod && mod.__esModule) return mod;
24
- var result = {};
25
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
26
- __setModuleDefault(result, mod);
27
- return result;
28
- };
29
- var __importDefault = (this && this.__importDefault) || function (mod) {
30
- return (mod && mod.__esModule) ? mod : { "default": mod };
31
- };
32
- Object.defineProperty(exports, "__esModule", { value: true });
33
- exports.isSuperUser = exports.Prostgles = exports.JOIN_TYPES = exports.TABLE_METHODS = void 0;
34
- const promise = __importStar(require("bluebird"));
35
- const pgPromise = __importStar(require("pg-promise"));
36
- const FileManager_1 = require("./FileManager/FileManager");
37
- const { version } = require('../package.json');
38
- const AuthHandler_1 = __importDefault(require("./AuthHandler"));
39
- const TableConfig_1 = __importDefault(require("./TableConfig/TableConfig"));
40
- const utils_1 = require("./utils");
41
- const DboBuilder_1 = require("./DboBuilder");
42
- const PubSubManager_1 = require("./PubSubManager/PubSubManager");
43
- const prostgles_types_1 = require("prostgles-types");
44
- const PublishParser_1 = require("./PublishParser");
45
- const DBEventsManager_1 = require("./DBEventsManager");
46
- exports.TABLE_METHODS = ["update", "find", "findOne", "insert", "delete", "upsert"];
47
- function getDbConnection(dbConnection, options, debugQueries = false, onNotice) {
48
- const pgp = pgPromise({
49
- promiseLib: promise,
50
- ...(debugQueries ? {
51
- query: function (ctx) {
52
- console.log({
53
- ...(0, PubSubManager_1.pickKeys)(ctx, ["params", "query"]),
54
- });
55
- },
56
- error: (error, ctx) => {
57
- console.log({
58
- ...(0, PubSubManager_1.pickKeys)(ctx, ["params", "query"]),
59
- error
60
- });
61
- }
62
- } : {}),
63
- ...((onNotice || debugQueries) ? {
64
- connect: function ({ client, dc, useCount }) {
65
- const isFresh = !useCount;
66
- if (isFresh && !client.listeners('notice').length) {
67
- client.on('notice', function (msg) {
68
- if (onNotice) {
69
- onNotice(msg, (0, utils_1.get)(msg, "message"));
70
- }
71
- else {
72
- console.log("notice: %j", (0, utils_1.get)(msg, "message"));
73
- }
74
- });
75
- }
76
- if (isFresh && !client.listeners('error').length) {
77
- client.on('error', function (msg) {
78
- if (onNotice) {
79
- onNotice(msg, (0, utils_1.get)(msg, "message"));
80
- }
81
- else {
82
- console.log("error: %j", (0, utils_1.get)(msg, "message"));
83
- }
84
- });
85
- }
86
- },
87
- } : {})
88
- });
89
- pgp.pg.defaults.max = 70;
90
- // /* Casts count/sum/max to bigint. Needs rework to remove casting "+count" and other issues; */
91
- // pgp.pg.types.setTypeParser(20, BigInt);
92
- /**
93
- * Prevent timestamp casting to ensure we don't lose the microseconds.
94
- * This is needed to ensure the filters work as expected for a given row
95
- *
96
- register(1114, parseTimestamp) // timestamp without time zone
97
- register(1184, parseTimestampTz) // timestamp with time zone
98
- */
99
- // pgp.pg.types.setTypeParser(1114, v => v); // timestamp without time zone
100
- // pgp.pg.types.setTypeParser(1184, v => v); // timestamp with time zone
101
- // pgp.pg.types.setTypeParser(1182, v => v); // date
102
- pgp.pg.types.setTypeParser(pgp.pg.types.builtins.TIMESTAMP, v => v); // timestamp without time zone
103
- pgp.pg.types.setTypeParser(pgp.pg.types.builtins.TIMESTAMPTZ, v => v); // timestamp with time zone
104
- pgp.pg.types.setTypeParser(pgp.pg.types.builtins.DATE, v => v); // date
105
- if (options) {
106
- Object.assign(pgp.pg.defaults, options);
107
- }
108
- return {
109
- db: pgp(dbConnection),
110
- pgp
111
- };
112
- }
113
- exports.JOIN_TYPES = ["one-many", "many-one", "one-one", "many-many"];
114
- const DEFAULT_KEYWORDS = {
115
- $filter: "$filter",
116
- $and: "$and",
117
- $or: "$or",
118
- $not: "$not"
119
- };
120
- const fs = __importStar(require("fs"));
121
- const ViewHandler_1 = require("./DboBuilder/ViewHandler");
122
- class Prostgles {
123
- opts = {
124
- DEBUG_MODE: false,
125
- dbConnection: {
126
- host: "localhost",
127
- port: 5432,
128
- application_name: "prostgles_app"
129
- },
130
- onReady: () => {
131
- //empty
132
- },
133
- schema: "public",
134
- watchSchema: false,
135
- watchSchemaType: "DDL_trigger",
136
- };
137
- db;
138
- pgp;
139
- dbo;
140
- _dboBuilder;
141
- get dboBuilder() {
142
- if (!this._dboBuilder)
143
- throw "get dboBuilder: it's undefined";
144
- return this._dboBuilder;
145
- }
146
- set dboBuilder(d) {
147
- this._dboBuilder = d;
148
- }
149
- publishParser;
150
- authHandler;
151
- schemaWatch;
152
- keywords = DEFAULT_KEYWORDS;
153
- loaded = false;
154
- dbEventsManager;
155
- fileManager;
156
- tableConfigurator;
157
- isMedia(tableName) {
158
- return this.opts?.fileTable?.tableName === tableName;
159
- }
160
- constructor(params) {
161
- if (!params)
162
- throw "ProstglesInitOptions missing";
163
- if (!params.io)
164
- console.warn("io missing. WebSockets will not be set up");
165
- const config = {
166
- transactions: 1, joins: 1, tsGeneratedTypesDir: 1,
167
- onReady: 1, dbConnection: 1, dbOptions: 1, publishMethods: 1,
168
- io: 1, publish: 1, schema: 1, publishRawSQL: 1, wsChannelNamePrefix: 1,
169
- onSocketConnect: 1, onSocketDisconnect: 1, sqlFilePath: 1, auth: 1,
170
- DEBUG_MODE: 1, watchSchema: 1, watchSchemaType: 1, fileTable: 1,
171
- tableConfig: 1, tableConfigMigrations: 1, keywords: 1, onNotice: 1
172
- };
173
- const unknownParams = Object.keys(params).filter((key) => !Object.keys(config).includes(key));
174
- if (unknownParams.length) {
175
- console.error(`Unrecognised ProstglesInitOptions params: ${unknownParams.join()}`);
176
- }
177
- Object.assign(this.opts, params);
178
- /* set defaults */
179
- if (this.opts?.fileTable) {
180
- this.opts.fileTable.tableName = this.opts?.fileTable?.tableName || "media";
181
- }
182
- this.opts.schema = this.opts.schema || "public";
183
- this.keywords = {
184
- ...DEFAULT_KEYWORDS,
185
- ...params.keywords,
186
- };
187
- }
188
- destroyed = false;
189
- async onSchemaChange(event) {
190
- const { watchSchema, watchSchemaType, onReady, tsGeneratedTypesDir } = this.opts;
191
- if (watchSchema && this.loaded) {
192
- (0, PubSubManager_1.log)("Schema changed");
193
- const { query } = event;
194
- if (typeof query === "string" && query.includes(PubSubManager_1.PubSubManager.EXCLUDE_QUERY_FROM_SCHEMA_WATCH_ID)) {
195
- (0, PubSubManager_1.log)("Schema change event excluded from triggers due to EXCLUDE_QUERY_FROM_SCHEMA_WATCH_ID");
196
- return;
197
- }
198
- if (typeof watchSchema === "function") {
199
- /* Only call the provided func */
200
- watchSchema(event);
201
- }
202
- else if (watchSchema === "hotReloadMode") {
203
- if (tsGeneratedTypesDir) {
204
- /* Hot reload integration. Will only touch tsGeneratedTypesDir */
205
- console.log("watchSchema: Re-writing TS schema");
206
- await this.refreshDBO();
207
- this.writeDBSchema(true);
208
- }
209
- }
210
- else if (watchSchema || (0, prostgles_types_1.isObject)(watchSchemaType) && "checkIntervalMillis" in watchSchemaType) {
211
- /* Full re-init. Sockets must reconnect */
212
- console.log("watchSchema: Full re-initialisation", { query });
213
- this.init(onReady, query);
214
- }
215
- }
216
- }
217
- checkDb() {
218
- if (!this.db || !this.db.connect)
219
- throw "something went wrong getting a db connection";
220
- }
221
- getTSFileName() {
222
- const fileName = "DBoGenerated.d.ts"; //`dbo_${this.schema}_types.ts`;
223
- const fullPath = (this.opts.tsGeneratedTypesDir || "") + fileName;
224
- return { fileName, fullPath };
225
- }
226
- getFileText(fullPath, format = "utf8") {
227
- return new Promise((resolve, reject) => {
228
- fs.readFile(fullPath, 'utf8', function (err, data) {
229
- if (err)
230
- reject(err);
231
- else
232
- resolve(data);
233
- });
234
- });
235
- }
236
- getTSFileContent = () => {
237
- const header = `/* This file was generated by Prostgles \n` +
238
- // `* ${(new Date).toUTCString()} \n`
239
- `*/ \n\n `;
240
- return header + this.dboBuilder.tsTypesDefinition;
241
- };
242
- /**
243
- * Will write the Schema Typescript definitions to file (tsGeneratedTypesDir)
244
- */
245
- writeDBSchema(force = false) {
246
- if (this.opts.tsGeneratedTypesDir) {
247
- const { fullPath, fileName } = this.getTSFileName();
248
- const fileContent = this.getTSFileContent();
249
- fs.readFile(fullPath, 'utf8', function (err, data) {
250
- if (err || (force || data !== fileContent)) {
251
- fs.writeFileSync(fullPath, fileContent);
252
- console.log("Prostgles: Created typescript schema definition file: \n " + fileName);
253
- }
254
- });
255
- }
256
- else if (force) {
257
- console.error("Schema changed. tsGeneratedTypesDir needs to be set to reload server");
258
- }
259
- }
260
- /**
261
- * Will re-create the dbo object
262
- */
263
- refreshDBO = async () => {
264
- if (this._dboBuilder) {
265
- await this._dboBuilder.build();
266
- // this._dboBuilder.destroy();
267
- }
268
- else {
269
- this.dboBuilder = await DboBuilder_1.DboBuilder.create(this);
270
- }
271
- if (!this.dboBuilder)
272
- throw "this.dboBuilder";
273
- this.dbo = this.dboBuilder.dbo;
274
- return this.dbo;
275
- };
276
- initWatchSchema = (onReady) => {
277
- if (this.opts.watchSchema === "hotReloadMode" && !this.opts.tsGeneratedTypesDir) {
278
- throw "tsGeneratedTypesDir option is needed for watchSchema: hotReloadMode to work ";
279
- }
280
- else if (this.opts.watchSchema &&
281
- typeof this.opts.watchSchemaType === "object" &&
282
- "checkIntervalMillis" in this.opts.watchSchemaType &&
283
- typeof this.opts.watchSchemaType.checkIntervalMillis === "number") {
284
- if (this.schema_checkIntervalMillis) {
285
- clearInterval(this.schema_checkIntervalMillis);
286
- }
287
- this.schema_checkIntervalMillis = setInterval(async () => {
288
- if (!this.loaded)
289
- return;
290
- const dbuilder = await DboBuilder_1.DboBuilder.create(this);
291
- if (dbuilder.tsTypesDefinition !== this.dboBuilder.tsTypesDefinition) {
292
- await this.refreshDBO();
293
- this.init(onReady, "schema_checkIntervalMillis tsTypesDefinition changed");
294
- }
295
- }, this.opts.watchSchemaType.checkIntervalMillis);
296
- }
297
- };
298
- /* Create media table if required */
299
- initFileTable = async () => {
300
- if (this.opts.fileTable) {
301
- const { awsS3Config, localConfig, imageOptions } = this.opts.fileTable;
302
- await this.refreshDBO();
303
- if (!awsS3Config && !localConfig)
304
- throw "fileTable missing param: Must provide awsS3Config OR localConfig";
305
- this.fileManager = new FileManager_1.FileManager(awsS3Config || localConfig, imageOptions);
306
- try {
307
- await this.fileManager.init(this);
308
- }
309
- catch (e) {
310
- console.error("FileManager: ", e);
311
- throw e;
312
- }
313
- }
314
- await this.refreshDBO();
315
- };
316
- isSuperUser = false;
317
- schema_checkIntervalMillis;
318
- async init(onReady, reason) {
319
- this.loaded = false;
320
- this.initWatchSchema(onReady);
321
- /* 1. Connect to db */
322
- if (!this.db) {
323
- const { db, pgp } = getDbConnection(this.opts.dbConnection, this.opts.dbOptions, this.opts.DEBUG_MODE, notice => {
324
- if (this.opts.onNotice)
325
- this.opts.onNotice(notice);
326
- if (this.dbEventsManager) {
327
- this.dbEventsManager.onNotice(notice);
328
- }
329
- });
330
- this.db = db;
331
- this.pgp = pgp;
332
- this.isSuperUser = await isSuperUser(db);
333
- }
334
- this.checkDb();
335
- const db = this.db;
336
- const pgp = this.pgp;
337
- /* 2. Execute any SQL file if provided */
338
- if (this.opts.sqlFilePath) {
339
- await this.runSQLFile(this.opts.sqlFilePath);
340
- }
341
- try {
342
- await this.refreshDBO();
343
- if (this.opts.tableConfig) {
344
- if (this.tableConfigurator?.initialising) {
345
- console.error("TableConfigurator WILL deadlock", { reason });
346
- }
347
- this.tableConfigurator = new TableConfig_1.default(this);
348
- try {
349
- await this.tableConfigurator.init();
350
- }
351
- catch (e) {
352
- if (this.opts.tableConfigMigrations?.silentFail === false) {
353
- console.error("TableConfigurator silentFail: ", e);
354
- }
355
- else {
356
- throw e;
357
- }
358
- }
359
- }
360
- /* 3. Make DBO object from all tables and views */
361
- // await this.refreshDBO();
362
- /* Create media table if required */
363
- await this.initFileTable();
364
- if (this.opts.publish) {
365
- if (!this.opts.io)
366
- console.warn("IO missing. Publish has no effect without io");
367
- /* 3.9 Check auth config */
368
- this.authHandler = new AuthHandler_1.default(this);
369
- await this.authHandler.init();
370
- this.publishParser = new PublishParser_1.PublishParser(this.opts.publish, this.opts.publishMethods, this.opts.publishRawSQL, this.dbo, this.db, this);
371
- this.dboBuilder.publishParser = this.publishParser;
372
- /* 4. Set publish and auth listeners */
373
- await this.setSocketEvents();
374
- }
375
- else if (this.opts.auth) {
376
- throw "Auth config does not work without publish";
377
- }
378
- this.dbEventsManager = new DBEventsManager_1.DBEventsManager(db, pgp);
379
- this.writeDBSchema();
380
- /* 5. Finish init and provide DBO object */
381
- try {
382
- if (this.destroyed) {
383
- console.trace(1);
384
- }
385
- onReady(this.dbo, this.db);
386
- }
387
- catch (err) {
388
- console.error("Prostgles: Error within onReady: \n", err);
389
- }
390
- this.loaded = true;
391
- return {
392
- db: this.dbo,
393
- _db: db,
394
- pgp,
395
- io: this.opts.io,
396
- getTSSchema: this.getTSFileContent,
397
- update: async (newOpts) => {
398
- this.opts.fileTable = newOpts.fileTable;
399
- await this.initFileTable();
400
- await this.init(onReady, "prgl.update");
401
- },
402
- restart: () => this.init(onReady, "prgl.restart"),
403
- destroy: async () => {
404
- console.log("destroying prgl instance");
405
- this.destroyed = true;
406
- if (this.opts.io) {
407
- this.opts.io.on("connection", () => {
408
- console.log("Socket connected to destroyed instance");
409
- });
410
- /** Try to close IO without stopping http server */
411
- if (this.opts.io.sockets.constructor.name === "Namespace") {
412
- for (const socket of this.opts.io.sockets.sockets.values()) {
413
- socket._onclose("server shutting down");
414
- }
415
- }
416
- if (this.opts.io.engine.constructor.name === 'Server') {
417
- this.opts.io.engine.close();
418
- }
419
- // if (typeof this.opts.io.close === "function") {
420
- // this.opts.io.close();
421
- // console.log("this.io.close")
422
- // }
423
- }
424
- this.fileManager?.destroy();
425
- this.dboBuilder?.destroy();
426
- this.authHandler?.destroy();
427
- this.dbo = undefined;
428
- this.db = undefined;
429
- await db.$pool.end();
430
- await sleep(1000);
431
- return true;
432
- }
433
- };
434
- }
435
- catch (e) {
436
- console.trace(e);
437
- throw "init issues: " + e.toString();
438
- }
439
- }
440
- async runSQLFile(filePath) {
441
- const fileContent = await this.getFileText(filePath); //.then(console.log);
442
- return this.db?.multi(fileContent).then((data) => {
443
- console.log("Prostgles: SQL file executed successfuly \n -> " + filePath);
444
- return data;
445
- }).catch((err) => {
446
- const { position, length } = err, lines = fileContent.split("\n");
447
- let errMsg = filePath + " error: ";
448
- if (position && length && fileContent) {
449
- const startLine = Math.max(0, fileContent.substring(0, position).split("\n").length - 2), endLine = startLine + 3;
450
- errMsg += "\n\n";
451
- errMsg += lines.slice(startLine, endLine).map((txt, i) => `${startLine + i + 1} ${i === 1 ? "->" : " "} ${txt}`).join("\n");
452
- errMsg += "\n\n";
453
- }
454
- console.error(errMsg, err);
455
- throw err;
456
- });
457
- }
458
- connectedSockets = [];
459
- async setSocketEvents() {
460
- this.checkDb();
461
- if (!this.dbo)
462
- throw "dbo missing";
463
- const publishParser = new PublishParser_1.PublishParser(this.opts.publish, this.opts.publishMethods, this.opts.publishRawSQL, this.dbo, this.db, this);
464
- this.publishParser = publishParser;
465
- if (!this.opts.io)
466
- return;
467
- /* Already initialised. Only reconnect sockets */
468
- if (this.connectedSockets.length) {
469
- this.connectedSockets.forEach((s) => {
470
- s.emit(prostgles_types_1.CHANNELS.SCHEMA_CHANGED);
471
- this.pushSocketSchema(s);
472
- });
473
- return;
474
- }
475
- /* Initialise */
476
- this.opts.io.on('connection', async (socket) => {
477
- if (this.destroyed) {
478
- console.log("Socket connected to destroyed instance");
479
- socket.disconnect();
480
- return;
481
- }
482
- this.connectedSockets.push(socket);
483
- if (!this.db || !this.dbo)
484
- throw new Error("db/dbo missing");
485
- const { dbo, db } = this;
486
- try {
487
- if (this.opts.onSocketConnect) {
488
- try {
489
- const getUser = async () => { return await this.authHandler?.getClientInfo({ socket }); };
490
- await this.opts.onSocketConnect({ socket, dbo: dbo, db, getUser });
491
- }
492
- catch (error) {
493
- const connectionError = error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error);
494
- socket.emit(prostgles_types_1.CHANNELS.CONNECTION, { connectionError });
495
- socket.disconnect();
496
- return;
497
- }
498
- }
499
- /* RUN Client request from Publish.
500
- Checks request against publish and if OK run it with relevant publish functions. Local (server) requests do not check the policy
501
- */
502
- socket.removeAllListeners(prostgles_types_1.CHANNELS.DEFAULT);
503
- socket.on(prostgles_types_1.CHANNELS.DEFAULT, async ({ tableName, command, param1, param2, param3 }, cb = (..._callback) => { }) => {
504
- try { /* Channel name will only include client-sent params so we ignore table_rules enforced params */
505
- if (!socket || !this.authHandler || !this.publishParser || !this.dbo) {
506
- console.error("socket or authhandler missing??!!");
507
- throw "socket or authhandler missing??!!";
508
- }
509
- const clientInfo = await this.authHandler.getClientInfo({ socket });
510
- const valid_table_command_rules = await this.publishParser.getValidatedRequestRule({ tableName, command, localParams: { socket } }, clientInfo);
511
- if (valid_table_command_rules) {
512
- const sessionUser = !clientInfo?.user ? undefined : {
513
- ...ViewHandler_1.ViewHandler._parseFieldFilter(clientInfo.sessionFields ?? [], false, (0, prostgles_types_1.getKeys)(clientInfo.user)),
514
- ...(0, PubSubManager_1.pickKeys)(clientInfo.user, ["id", "type"]),
515
- };
516
- const res = await this.dbo[tableName][command](param1, param2, param3, valid_table_command_rules, { socket, isRemoteRequest: { user: sessionUser } });
517
- cb(null, res);
518
- }
519
- else
520
- throw `Invalid OR disallowed request: ${tableName}.${command} `;
521
- }
522
- catch (err) {
523
- // const _err_msg = err.toString();
524
- // cb({ msg: _err_msg, err });
525
- console.trace(err);
526
- cb(err);
527
- // console.warn("runPublishedRequest ERROR: ", err, socket._user);
528
- }
529
- });
530
- socket.on("disconnect", () => {
531
- this.dbEventsManager?.removeNotice(socket);
532
- this.dbEventsManager?.removeNotify(undefined, socket);
533
- this.connectedSockets = this.connectedSockets.filter(s => s.id !== socket.id);
534
- // subscriptions = subscriptions.filter(sub => sub.socket.id !== socket.id);
535
- if (this.opts.onSocketDisconnect) {
536
- const getUser = async () => { return await this.authHandler?.getClientInfo({ socket }); };
537
- this.opts.onSocketDisconnect({ socket, dbo: dbo, db, getUser });
538
- }
539
- });
540
- socket.removeAllListeners(prostgles_types_1.CHANNELS.METHOD);
541
- socket.on(prostgles_types_1.CHANNELS.METHOD, async ({ method, params }, cb = (..._callback) => { }) => {
542
- try {
543
- const methods = await this.publishParser?.getAllowedMethods(socket);
544
- if (!methods || !methods[method]) {
545
- cb("Disallowed/missing method " + JSON.stringify(method));
546
- }
547
- else {
548
- try {
549
- const methodDef = methods[method];
550
- const onRun = (typeof methodDef === "function" || typeof methodDef.then === "function") ? methodDef : methodDef.run;
551
- const res = await onRun(...params);
552
- cb(null, res);
553
- }
554
- catch (err) {
555
- makeSocketError(cb, err);
556
- }
557
- }
558
- }
559
- catch (err) {
560
- makeSocketError(cb, err);
561
- console.warn("method ERROR: ", err, socket._user);
562
- }
563
- });
564
- this.pushSocketSchema(socket);
565
- }
566
- catch (e) {
567
- console.trace("setSocketEvents: ", e);
568
- }
569
- });
570
- }
571
- pushSocketSchema = async (socket) => {
572
- try {
573
- const { auth, userData } = await this.authHandler?.makeSocketAuth(socket) || {};
574
- // let needType = this.publishRawSQL && typeof this.publishRawSQL === "function";
575
- // let DATA_TYPES = !needType? [] : await this.db.any("SELECT oid, typname FROM pg_type");
576
- // let USER_TABLES = !needType? [] : await this.db.any("SELECT relid, relname FROM pg_catalog.pg_statio_user_tables");
577
- const { db, publishParser } = this;
578
- let fullSchema;
579
- let publishValidationError;
580
- let rawSQL = false;
581
- try {
582
- if (!publishParser)
583
- throw "publishParser undefined";
584
- fullSchema = await publishParser.getSchemaFromPublish(socket, userData);
585
- }
586
- catch (e) {
587
- publishValidationError = "Server Error: PUBLISH VALIDATION ERROR";
588
- console.error(`\nProstgles PUBLISH VALIDATION ERROR (after socket connected):\n ->`, e);
589
- }
590
- socket.prostgles = socket.prostgles || {};
591
- socket.prostgles.schema = fullSchema?.schema;
592
- /* RUN Raw sql from client IF PUBLISHED
593
- */
594
- if (this.opts.publishRawSQL && typeof this.opts.publishRawSQL === "function") {
595
- const canRunSQL = async () => {
596
- const publishParams = await this.publishParser?.getPublishParams({ socket });
597
- const res = await this.opts.publishRawSQL?.(publishParams);
598
- return Boolean(res && typeof res === "boolean" || res === "*");
599
- };
600
- if (await canRunSQL()) {
601
- socket.removeAllListeners(prostgles_types_1.CHANNELS.SQL);
602
- socket.on(prostgles_types_1.CHANNELS.SQL, async ({ query, params, options }, cb = (..._callback) => { }) => {
603
- if (!this.dbo?.sql)
604
- throw "Internal error: sql handler missing";
605
- this.dbo.sql(query, params, options, { socket }).then(res => {
606
- cb(null, res);
607
- }).catch(err => {
608
- makeSocketError(cb, err);
609
- });
610
- });
611
- if (db) {
612
- // let allTablesViews = await db.any(STEP2_GET_ALL_TABLES_AND_COLUMNS);
613
- // fullSchema = allTablesViews;
614
- rawSQL = true;
615
- }
616
- else
617
- console.error("db missing");
618
- }
619
- }
620
- const { schema, tables } = fullSchema ?? { schema: {}, tables: [] };
621
- const joinTables2 = [];
622
- if (this.opts.joins) {
623
- const _joinTables2 = this.dboBuilder.getJoinPaths()
624
- .filter(jp => ![jp.t1, jp.t2].find(t => !schema[t] || !schema[t]?.findOne)).map(jp => [jp.t1, jp.t2].sort());
625
- _joinTables2.map(jt => {
626
- if (!joinTables2.find(_jt => _jt.join() === jt.join())) {
627
- joinTables2.push(jt);
628
- }
629
- });
630
- }
631
- const methods = await publishParser?.getAllowedMethods(socket, userData);
632
- const methodSchema = !methods ? [] : (0, prostgles_types_1.getKeys)(methods).map(methodName => {
633
- const method = methods[methodName];
634
- if ((0, prostgles_types_1.isObject)(method) && "run" in method) {
635
- return {
636
- name: methodName,
637
- ...(0, prostgles_types_1.omitKeys)(method, ["run"])
638
- };
639
- }
640
- return methodName;
641
- });
642
- const clientSchema = {
643
- schema,
644
- methods: methodSchema,
645
- tableSchema: tables,
646
- rawSQL,
647
- joinTables: joinTables2,
648
- auth,
649
- version,
650
- err: publishValidationError
651
- };
652
- socket.emit(prostgles_types_1.CHANNELS.SCHEMA, clientSchema);
653
- }
654
- catch (err) {
655
- socket.emit(prostgles_types_1.CHANNELS.SCHEMA, { err });
656
- }
657
- };
658
- }
659
- exports.Prostgles = Prostgles;
660
- function makeSocketError(cb, err) {
661
- const err_msg = (err instanceof Error) ?
662
- err.toString() :
663
- (0, DboBuilder_1.isPlainObject)(err) ?
664
- JSON.stringify(err, null, 2) :
665
- err.toString(), e = { err_msg, err };
666
- cb(e);
667
- }
668
- // const ALL_PUBLISH_METHODS = ["update", "upsert", "delete", "insert", "find", "findOne", "subscribe", "unsubscribe", "sync", "unsync", "remove"];
669
- // const ALL_PUBLISH_METHODS = RULE_TO_METHODS.map(r => r.methods).flat();
670
- // export function flat(arr){
671
- // // let res = arr.reduce((acc, val) => [ ...acc, ...val ], []);
672
- // let res = arr.reduce(function (farr, toFlatten) {
673
- // return farr.concat(Array.isArray(toFlatten) ? flat(toFlatten) : toFlatten);
674
- // }, []);
675
- // return res;
676
- // }
677
- async function isSuperUser(db) {
678
- return db.oneOrNone("select usesuper from pg_user where usename = CURRENT_USER;").then(r => r.usesuper);
679
- }
680
- exports.isSuperUser = isSuperUser;
681
- function sleep(ms) {
682
- return new Promise((resolve) => {
683
- setTimeout(resolve, ms);
684
- });
685
- }