miqro 6.0.9 → 6.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/build/editor.bundle.js +29 -12
  2. package/build/esm/editor/common/log-socket.d.ts +3 -1
  3. package/build/esm/editor/common/log-socket.js +4 -1
  4. package/build/esm/editor/common/log-socket.js.map +1 -1
  5. package/build/esm/editor/common/templates.js +5 -5
  6. package/build/esm/editor/components/editor.js +4 -1
  7. package/build/esm/editor/components/editor.js.map +1 -1
  8. package/build/esm/editor/components/file-browser.js +28 -23
  9. package/build/esm/editor/components/file-browser.js.map +1 -1
  10. package/build/esm/editor/components/file-editor-toolbar.js +4 -4
  11. package/build/esm/editor/components/file-editor-toolbar.js.map +1 -1
  12. package/build/esm/editor/http/admin/editor/api/server/reload.api.js +2 -1
  13. package/build/esm/editor/http/admin/editor/api/server/reload.api.js.map +1 -1
  14. package/build/esm/editor/http/admin/editor/index.api.js +1 -1
  15. package/build/esm/src/cluster.js +0 -0
  16. package/build/esm/src/common/arguments.js +12 -7
  17. package/build/esm/src/common/arguments.js.map +1 -1
  18. package/build/esm/src/common/assets.d.ts +1 -0
  19. package/build/esm/src/common/assets.js +1 -1
  20. package/build/esm/src/common/assets.js.map +1 -1
  21. package/build/esm/src/common/jsx.d.ts +3 -3
  22. package/build/esm/src/common/jsx.js +36 -22
  23. package/build/esm/src/common/jsx.js.map +1 -1
  24. package/build/esm/src/common/watch.d.ts +3 -1
  25. package/build/esm/src/common/watch.js +5 -0
  26. package/build/esm/src/common/watch.js.map +1 -1
  27. package/build/esm/src/main.js +0 -0
  28. package/build/esm/src/services/app.d.ts +6 -1
  29. package/build/esm/src/services/app.js +36 -117
  30. package/build/esm/src/services/app.js.map +1 -1
  31. package/build/esm/src/services/utils/admin-interface.d.ts +3 -0
  32. package/build/esm/src/services/utils/admin-interface.js +34 -0
  33. package/build/esm/src/services/utils/admin-interface.js.map +1 -0
  34. package/build/esm/src/services/utils/cluster-cache.d.ts +2 -1
  35. package/build/esm/src/services/utils/cluster-cache.js +5 -1
  36. package/build/esm/src/services/utils/cluster-cache.js.map +1 -1
  37. package/build/esm/src/services/utils/cluster-ws.d.ts +1 -0
  38. package/build/esm/src/services/utils/cluster-ws.js +4 -0
  39. package/build/esm/src/services/utils/cluster-ws.js.map +1 -1
  40. package/build/esm/src/services/utils/db-manager.d.ts +1 -0
  41. package/build/esm/src/services/utils/db-manager.js +12 -0
  42. package/build/esm/src/services/utils/db-manager.js.map +1 -1
  43. package/build/esm/src/services/utils/log-transport.d.ts +7 -0
  44. package/build/esm/src/services/utils/log-transport.js +75 -0
  45. package/build/esm/src/services/utils/log-transport.js.map +1 -0
  46. package/build/esm/src/services/utils/websocketmanager.d.ts +1 -0
  47. package/build/esm/src/services/utils/websocketmanager.js +11 -3
  48. package/build/esm/src/services/utils/websocketmanager.js.map +1 -1
  49. package/build/esm/src/types.d.ts +2 -0
  50. package/build/lib.cjs +1268 -1195
  51. package/editor/common/log-socket.tsx +4 -1
  52. package/editor/common/templates.ts +5 -5
  53. package/editor/components/editor.tsx +4 -1
  54. package/editor/components/file-browser.tsx +48 -35
  55. package/editor/components/file-editor-toolbar.tsx +4 -0
  56. package/editor/http/admin/editor/api/server/reload.api.ts +2 -1
  57. package/editor/http/admin/editor/index.api.tsx +4 -4
  58. package/package.json +9 -7
  59. package/sea/compile.sh +8 -5
  60. package/sea/install-esbuild.sh +1 -1
  61. package/sea/install-nodejs.sh +1 -1
  62. package/sea/node.version.tag +1 -1
  63. package/sea/types.json +1 -1
  64. package/sea/version.tag.js +11 -0
  65. package/src/common/arguments.ts +11 -7
  66. package/src/common/assets.ts +1 -1
  67. package/src/common/jsx.ts +35 -23
  68. package/src/common/watch.ts +5 -0
  69. package/src/services/app.ts +37 -115
  70. package/src/services/utils/admin-interface.ts +37 -0
  71. package/src/services/utils/cluster-cache.ts +6 -1
  72. package/src/services/utils/cluster-ws.ts +6 -1
  73. package/src/services/utils/db-manager.ts +13 -0
  74. package/src/services/utils/log-transport.ts +75 -0
  75. package/src/services/utils/websocketmanager.ts +13 -3
  76. package/src/types/miqro.d.ts +2 -2
  77. package/src/types.ts +3 -0
  78. package/package.json--OLD +0 -36
package/build/lib.cjs CHANGED
@@ -4336,11 +4336,12 @@ var init_reload_api = __esm({
4336
4336
  },
4337
4337
  handler: async (req, res) => {
4338
4338
  const errors = await req?.editor?.reload();
4339
+ const parsedErrors = parseInflateErrors2(errors);
4339
4340
  return res.json({
4340
4341
  message: "OK",
4341
4342
  reloadString: req.uuid,
4342
4343
  migrations: req?.editor?.getMigrations().map((m) => m.name),
4343
- errors: parseInflateErrors2(errors)
4344
+ errors: parsedErrors ? parsedErrors : []
4344
4345
  });
4345
4346
  }
4346
4347
  };
@@ -7067,568 +7068,6 @@ function createFrame(payload) {
7067
7068
  return buffer;
7068
7069
  }
7069
7070
 
7070
- // src/services/utils/cluster-ws.ts
7071
- var ClusterWebSocketServer2MessageType = "$$$$ClusterWebSocketServer2Message$$$$$";
7072
- var ClusterWebSocketServer2 = class extends WebSocketServer {
7073
- constructor(name, options) {
7074
- super({
7075
- ...options,
7076
- validate: (req) => {
7077
- if (this.options.maxConnections !== void 0 && this.clients.size + this.remoteClients.size >= this.options.maxConnections) {
7078
- return false;
7079
- } else {
7080
- return options.validate ? options.validate(req) : true;
7081
- }
7082
- },
7083
- onError: (req, error2) => {
7084
- if (process.send) {
7085
- process.send({
7086
- type: ClusterWebSocketServer2MessageType,
7087
- action: "error",
7088
- target: this.name,
7089
- clientUUID: req.uuid,
7090
- fromPID: String(process.pid),
7091
- errorMessage: error2.message
7092
- });
7093
- }
7094
- if (options.onError) {
7095
- options.onError(req, error2);
7096
- }
7097
- },
7098
- onConnection: (req) => {
7099
- if (process.send) {
7100
- process.send({
7101
- type: ClusterWebSocketServer2MessageType,
7102
- action: "connection",
7103
- target: this.name,
7104
- fromPID: String(process.pid),
7105
- clientUUID: req.uuid
7106
- });
7107
- }
7108
- if (options.onConnection) {
7109
- options.onConnection(req);
7110
- }
7111
- },
7112
- onDisconnect: (req) => {
7113
- if (process.send) {
7114
- process.send({
7115
- type: ClusterWebSocketServer2MessageType,
7116
- action: "disconnection",
7117
- target: this.name,
7118
- fromPID: String(process.pid),
7119
- clientUUID: req.uuid
7120
- });
7121
- }
7122
- if (options.onDisconnect) {
7123
- options.onDisconnect(req);
7124
- }
7125
- }
7126
- });
7127
- this.name = name;
7128
- this.listener = async (data) => {
7129
- try {
7130
- const msg = data;
7131
- if (msg && msg.type === ClusterWebSocketServer2MessageType && msg.target === this.name && msg.action) {
7132
- switch (msg.action) {
7133
- case "sync":
7134
- if (process.send) {
7135
- for (const clientUUID of this.clients.keys()) {
7136
- process.send({
7137
- type: ClusterWebSocketServer2MessageType,
7138
- action: "connection",
7139
- target: this.name,
7140
- fromPID: String(process.pid),
7141
- clientUUID
7142
- });
7143
- }
7144
- }
7145
- break;
7146
- case "connection":
7147
- if (!msg.clientUUID) {
7148
- throw new Error(`action [${msg.action}] without clientUUID`);
7149
- }
7150
- if (!this.remoteClients.has(msg.clientUUID)) {
7151
- this.remoteClients.add(msg.clientUUID);
7152
- }
7153
- break;
7154
- case "disconnection":
7155
- if (!msg.clientUUID) {
7156
- throw new Error(`action [${msg.action}] without clientUUID`);
7157
- }
7158
- if (this.remoteClients.has(msg.clientUUID)) {
7159
- this.remoteClients.delete(msg.clientUUID);
7160
- }
7161
- break;
7162
- case "sendMessage": {
7163
- const payload = String(msg.payload);
7164
- if (!msg.clientUUID) {
7165
- await super.broadcast(payload, msg.fromUUID);
7166
- } else if (this.isConnected(msg.clientUUID)) {
7167
- await super.writeTo(msg.clientUUID, payload);
7168
- }
7169
- break;
7170
- }
7171
- default:
7172
- throw new Error(`action [${msg.action}] not supported`);
7173
- }
7174
- }
7175
- } catch (e) {
7176
- console.error(e);
7177
- }
7178
- };
7179
- if (process.send) {
7180
- process.on("message", this.listener);
7181
- process.send({
7182
- type: ClusterWebSocketServer2MessageType,
7183
- action: "sync",
7184
- fromPID: String(process.pid),
7185
- target: this.name
7186
- });
7187
- }
7188
- }
7189
- remoteClients = /* @__PURE__ */ new Set();
7190
- listener;
7191
- dispose() {
7192
- process.removeListener("message", this.listener);
7193
- }
7194
- async broadcast(payload, fromUUID) {
7195
- if (process.send) {
7196
- process.send({
7197
- type: ClusterWebSocketServer2MessageType,
7198
- action: "sendMessage",
7199
- payload,
7200
- target: this.name,
7201
- fromPID: String(process.pid),
7202
- fromUUID
7203
- });
7204
- }
7205
- return super.broadcast(payload, fromUUID);
7206
- }
7207
- async writeTo(clientUUID, payload) {
7208
- if (this.remoteClients.has(clientUUID)) {
7209
- if (process.send) {
7210
- process.send({
7211
- type: ClusterWebSocketServer2MessageType,
7212
- action: "sendMessage",
7213
- clientUUID,
7214
- target: this.name,
7215
- fromPID: String(process.pid),
7216
- payload
7217
- });
7218
- return;
7219
- }
7220
- }
7221
- if (this.clients.has(clientUUID)) {
7222
- return super.writeTo(clientUUID, payload);
7223
- }
7224
- }
7225
- isUUIDValid(uuid) {
7226
- return !this.clients.has(uuid) && !this.remoteClients.has(uuid);
7227
- }
7228
- };
7229
-
7230
- // src/services/utils/cluster-cache.ts
7231
- var ClusterCacheType = "$$$$$$$$$$$ClusterCacheType$$$$$$$$$$$";
7232
- var ClusterCache = class {
7233
- constructor(name, logger) {
7234
- this.name = name;
7235
- this.logger = logger;
7236
- this.listener = async (data) => {
7237
- try {
7238
- const msg = data;
7239
- if (msg && msg.key && msg.action && msg.type === ClusterCacheType && msg.fromPID !== process.pid, (msg.action === "set_add" || msg.action === "set" || msg.action === "unset" || msg.action === "set_delete" || msg.action === "array_push") && msg.target === this.name) {
7240
- this.logger?.debug("remote cluster cache message from [%s] [%s] [%s] [%s]", msg.fromPID, msg.target, msg.action, msg.key);
7241
- switch (msg.action) {
7242
- case "unset":
7243
- this.localCache.delete(msg.key);
7244
- break;
7245
- case "set":
7246
- this.localCache.set(msg.key, msg.value);
7247
- break;
7248
- case "set_add": {
7249
- const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
7250
- if (!(list instanceof Set)) {
7251
- throw new Error("cannot apply push on non array");
7252
- }
7253
- if (list.has(msg.value)) {
7254
- list.add(msg.value);
7255
- }
7256
- this.localCache.set(msg.key, list);
7257
- break;
7258
- }
7259
- case "set_delete": {
7260
- const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
7261
- if (!(list instanceof Set)) {
7262
- throw new Error("cannot apply push on non array");
7263
- }
7264
- if (list.has(msg.value)) {
7265
- list.delete(msg.value);
7266
- }
7267
- this.localCache.set(msg.key, list);
7268
- break;
7269
- }
7270
- case "array_push": {
7271
- const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : [];
7272
- if (!(list instanceof Array)) {
7273
- throw new Error("cannot apply push on non array");
7274
- }
7275
- list.push(msg.value);
7276
- this.localCache.set(msg.key, list);
7277
- break;
7278
- }
7279
- }
7280
- }
7281
- } catch (e) {
7282
- this.logger?.error(e);
7283
- }
7284
- };
7285
- if (process.send) {
7286
- process.on("message", this.listener);
7287
- }
7288
- }
7289
- localCache = /* @__PURE__ */ new Map();
7290
- //private logger: Logger;
7291
- listener;
7292
- dispose() {
7293
- process.removeListener("message", this.listener);
7294
- }
7295
- get(key) {
7296
- this.logger?.trace("get(%s)", key);
7297
- return this.localCache.get(key);
7298
- }
7299
- set(key, value) {
7300
- this.localCache.set(key, value);
7301
- this.logger?.trace("set(%s, ...)", key);
7302
- if (process.send) {
7303
- setTimeout(() => {
7304
- process.send({
7305
- type: ClusterCacheType,
7306
- action: "set",
7307
- target: this.name,
7308
- fromPID: process.pid,
7309
- key,
7310
- value
7311
- });
7312
- }, 10);
7313
- }
7314
- }
7315
- unset(key) {
7316
- this.logger?.trace("unset(%s)", key);
7317
- this.localCache.delete(key);
7318
- if (process.send) {
7319
- setTimeout(() => {
7320
- process.send({
7321
- type: ClusterCacheType,
7322
- target: this.name,
7323
- action: "unset",
7324
- fromPID: process.pid,
7325
- key
7326
- });
7327
- }, 10);
7328
- }
7329
- }
7330
- has(key) {
7331
- this.logger?.trace("has(%s)", key);
7332
- return this.localCache.has(key);
7333
- }
7334
- set_add(key, value) {
7335
- this.logger?.trace("push(%s)", key);
7336
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7337
- if (!(list instanceof Set)) {
7338
- throw new Error("cannot apply on non Set");
7339
- }
7340
- if (list.has(value)) {
7341
- list.add(value);
7342
- }
7343
- this.localCache.set(key, list);
7344
- if (process.send) {
7345
- setTimeout(() => {
7346
- process.send({
7347
- type: ClusterCacheType,
7348
- target: this.name,
7349
- action: "set_add",
7350
- fromPID: process.pid,
7351
- key,
7352
- value
7353
- });
7354
- }, 10);
7355
- }
7356
- }
7357
- set_delete(key, value) {
7358
- this.logger?.trace("delete(%s)", key);
7359
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7360
- if (!(list instanceof Set)) {
7361
- throw new Error("cannot apply on non Set");
7362
- }
7363
- if (list.has(value)) {
7364
- list.delete(value);
7365
- }
7366
- this.localCache.set(key, list);
7367
- if (process.send) {
7368
- setTimeout(() => {
7369
- process.send({
7370
- type: ClusterCacheType,
7371
- target: this.name,
7372
- action: "set_delete",
7373
- fromPID: process.pid,
7374
- key,
7375
- value
7376
- });
7377
- }, 10);
7378
- }
7379
- }
7380
- set_has(key, value) {
7381
- this.logger?.trace("set_has(%s)", key);
7382
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7383
- if (!(list instanceof Set)) {
7384
- throw new Error("cannot apply on non Set");
7385
- }
7386
- const ret = list.has(value);
7387
- this.localCache.set(key, list);
7388
- return ret;
7389
- }
7390
- set_clear(key) {
7391
- this.logger?.trace("set_clear(%s)", key);
7392
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7393
- if (!(list instanceof Set)) {
7394
- throw new Error("cannot apply on non Set");
7395
- }
7396
- list.clear();
7397
- this.localCache.set(key, list);
7398
- }
7399
- array_push(key, value) {
7400
- this.logger?.trace("array_push(%s)", key);
7401
- const list = this.localCache.has(key) ? this.localCache.get(key) : [];
7402
- if (!(list instanceof Array)) {
7403
- throw new Error("cannot apply on non Array");
7404
- }
7405
- list.push(value);
7406
- this.localCache.set(key, list);
7407
- if (process.send) {
7408
- setTimeout(() => {
7409
- process.send({
7410
- type: ClusterCacheType,
7411
- target: this.name,
7412
- action: "array_push",
7413
- fromPID: process.pid,
7414
- key,
7415
- value
7416
- });
7417
- }, 10);
7418
- }
7419
- }
7420
- array_clear(key) {
7421
- this.logger?.trace("array_clear(%s)", key);
7422
- if (this.localCache.has(key) && !(this.localCache.get(key) instanceof Array)) {
7423
- throw new Error("cannot apply on non Array");
7424
- }
7425
- this.localCache.set(key, []);
7426
- }
7427
- };
7428
-
7429
- // src/services/utils/cache.ts
7430
- var LocalCache = class {
7431
- constructor(name, logger) {
7432
- this.name = name;
7433
- this.logger = logger;
7434
- }
7435
- localCache = /* @__PURE__ */ new Map();
7436
- dispose() {
7437
- }
7438
- get(key) {
7439
- this.logger?.trace("get(%s)", key);
7440
- return this.localCache.get(key);
7441
- }
7442
- set(key, value) {
7443
- this.localCache.set(key, value);
7444
- this.logger?.trace("set(%s, ...)", key);
7445
- }
7446
- unset(key) {
7447
- this.logger?.trace("unset(%s)", key);
7448
- this.localCache.delete(key);
7449
- }
7450
- has(key) {
7451
- this.logger?.trace("has(%s)", key);
7452
- return this.localCache.has(key);
7453
- }
7454
- set_add(key, value) {
7455
- this.logger?.trace("set_add(%s)", key);
7456
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7457
- if (!(list instanceof Set)) {
7458
- throw new Error("cannot apply on non Set");
7459
- }
7460
- if (list.has(value)) {
7461
- list.add(value);
7462
- }
7463
- this.localCache.set(key, list);
7464
- }
7465
- set_delete(key, value) {
7466
- this.logger?.trace("set_delete(%s)", key);
7467
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7468
- if (!(list instanceof Set)) {
7469
- throw new Error("cannot apply on non Set");
7470
- }
7471
- if (list.has(value)) {
7472
- list.delete(value);
7473
- }
7474
- this.localCache.set(key, list);
7475
- }
7476
- set_has(key, value) {
7477
- this.logger?.trace("set_has(%s)", key);
7478
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7479
- if (!(list instanceof Set)) {
7480
- throw new Error("cannot apply on non Set");
7481
- }
7482
- const ret = list.has(value);
7483
- this.localCache.set(key, list);
7484
- return ret;
7485
- }
7486
- set_clear(key) {
7487
- this.logger?.trace("set_clear(%s)", key);
7488
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7489
- if (!(list instanceof Set)) {
7490
- throw new Error("cannot apply on non Set");
7491
- }
7492
- list.clear();
7493
- this.localCache.set(key, list);
7494
- }
7495
- array_push(key, value) {
7496
- this.logger?.trace("array_push(%s)", key);
7497
- const list = this.localCache.has(key) ? this.localCache.get(key) : [];
7498
- if (!(list instanceof Array)) {
7499
- throw new Error("cannot apply on non Array");
7500
- }
7501
- list.push(value);
7502
- this.localCache.set(key, list);
7503
- }
7504
- array_clear(key) {
7505
- this.logger?.trace("array_clear(%s)", key);
7506
- if (this.localCache.has(key) && !(this.localCache.get(key) instanceof Array)) {
7507
- throw new Error("cannot apply on non Array");
7508
- }
7509
- this.localCache.set(key, []);
7510
- }
7511
- };
7512
-
7513
- // src/services/utils/websocketmanager.ts
7514
- init_constants();
7515
- var WebSocketManager = class {
7516
- runningGlobalWSMap = /* @__PURE__ */ new Map();
7517
- logger = null;
7518
- name;
7519
- avoidLogSocket;
7520
- constructor(options) {
7521
- this.onUpgrade = this.onUpgrade.bind(this);
7522
- this.logger = options && options.logger ? options.logger : null;
7523
- this.name = options && options.name ? options.name : "WebSocketManager";
7524
- this.avoidLogSocket = options && options.avoidLogSocket ? options.avoidLogSocket : false;
7525
- }
7526
- deleteAllWS() {
7527
- this.runningGlobalWSMap.clear();
7528
- }
7529
- getWS(path) {
7530
- return this.runningGlobalWSMap.get(path);
7531
- }
7532
- replaceALLWS(list) {
7533
- this.deleteAllWS();
7534
- for (const wsConfig of list) {
7535
- if (!wsConfig.disabled) {
7536
- if (this.runningGlobalWSMap.has(wsConfig.path)) {
7537
- throw new Error(`ws on path ${wsConfig.path} already setup!`);
7538
- }
7539
- this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
7540
- const server2 = new ClusterWebSocketServer2(wsConfig.path, wsConfig);
7541
- this.runningGlobalWSMap.set(wsConfig.path, server2);
7542
- }
7543
- }
7544
- }
7545
- replaceALLWSBuLOGSocket(list) {
7546
- for (const path of this.runningGlobalWSMap.keys()) {
7547
- if (path !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
7548
- this.runningGlobalWSMap.delete(path);
7549
- }
7550
- }
7551
- for (const wsConfig of list) {
7552
- if (!wsConfig.disabled) {
7553
- if (wsConfig.path !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
7554
- if (this.runningGlobalWSMap.has(wsConfig.path)) {
7555
- throw new Error(`ws on path ${wsConfig.path} already setup!`);
7556
- }
7557
- this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
7558
- const server2 = new ClusterWebSocketServer2(this.name + wsConfig.path, wsConfig);
7559
- this.runningGlobalWSMap.set(wsConfig.path, server2);
7560
- }
7561
- }
7562
- }
7563
- }
7564
- /*public setupWS(path: string, server: ClusterWebSocketServer2) {
7565
- if (this.runningGlobalWSMap.has(path)) {
7566
- throw new Error(`ws on path ${path} already setup!`);
7567
- }
7568
- this.runningGlobalWSMap.set(path, server);
7569
- }*/
7570
- disconnectAllFrom(path) {
7571
- try {
7572
- this.logger?.debug("disconnect all from [%s]", path);
7573
- const ws = this.getWS(path);
7574
- if (ws) {
7575
- const clients = ws.clients.values();
7576
- if (clients) {
7577
- for (const client of clients) {
7578
- try {
7579
- client.socket.destroy();
7580
- } catch (e2) {
7581
- this.logger?.error("error disconnecting web socket client");
7582
- this.logger?.error(e2);
7583
- }
7584
- }
7585
- }
7586
- ws.dispose();
7587
- }
7588
- } catch (e) {
7589
- this.logger?.error("error disconnecting web socket clients");
7590
- this.logger?.error(e.message);
7591
- }
7592
- }
7593
- disconnectAllButLOGSocket() {
7594
- try {
7595
- for (const wsPath of this.runningGlobalWSMap.keys()) {
7596
- if (wsPath !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
7597
- this.disconnectAllFrom(wsPath);
7598
- }
7599
- }
7600
- } catch (e) {
7601
- this.logger?.error("error disconnecting web socket clients");
7602
- this.logger?.error(e.message);
7603
- }
7604
- }
7605
- disconnectAll() {
7606
- try {
7607
- for (const wsPath of this.runningGlobalWSMap.keys()) {
7608
- this.disconnectAllFrom(wsPath);
7609
- }
7610
- } catch (e) {
7611
- this.logger?.error("error disconnecting web socket clients");
7612
- this.logger?.error(e.message);
7613
- }
7614
- }
7615
- onUpgrade(req, socket, head) {
7616
- try {
7617
- const wsServer = this.getWS(req.path);
7618
- if (wsServer) {
7619
- return wsServer.onUpgrade(req, socket, head);
7620
- } else {
7621
- socket.destroy();
7622
- }
7623
- } catch (e) {
7624
- this.logger?.error(e);
7625
- }
7626
- }
7627
- };
7628
-
7629
- // src/services/utils/db-manager.ts
7630
- var import_node_cluster = __toESM(require("node:cluster"), 1);
7631
-
7632
7071
  // node_modules/@miqro/query/build/executors/sqlite3/utils.js
7633
7072
  function sqlite3ExecutorPrepare(args) {
7634
7073
  switch (args._type) {
@@ -8541,625 +7980,1200 @@ var Where = class {
8541
7980
  });
8542
7981
  return this;
8543
7982
  }
8544
- neq(column, value) {
8545
- this._filters.push({
8546
- _type: "neq",
8547
- _column: column,
8548
- _value: value
8549
- });
7983
+ neq(column, value) {
7984
+ this._filters.push({
7985
+ _type: "neq",
7986
+ _column: column,
7987
+ _value: value
7988
+ });
7989
+ return this;
7990
+ }
7991
+ literal(literal) {
7992
+ this._filters.push({
7993
+ _type: "literal",
7994
+ _literal: literal
7995
+ });
7996
+ return this;
7997
+ }
7998
+ };
7999
+
8000
+ // node_modules/@miqro/query/build/query/select.js
8001
+ var Select = class _Select extends Where {
8002
+ constructor(db) {
8003
+ super();
8004
+ this.db = db;
8005
+ this._type = "select";
8006
+ this._columns = [];
8007
+ this._selectFrom = [];
8008
+ this._groupBy = [];
8009
+ this._joins = [];
8010
+ this._orderBy = [];
8011
+ }
8012
+ prepare() {
8013
+ return getStatements(this.db.getExecutor().prepare(this));
8014
+ }
8015
+ clone() {
8016
+ const ret = new _Select(this.db);
8017
+ ret._filters = structuredClone(this._filters);
8018
+ ret._columns = structuredClone(this._columns);
8019
+ ret._groupBy = structuredClone(this._groupBy);
8020
+ ret._selectFrom = structuredClone(this._selectFrom);
8021
+ ret._orderBy = structuredClone(this._orderBy);
8022
+ ret._joins = structuredClone(this._joins);
8023
+ ret._limitBy = this._limitBy;
8024
+ ret._offsetBy = this._offsetBy;
8025
+ return ret;
8026
+ }
8027
+ async yield(logger) {
8028
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8029
+ }
8030
+ column(column) {
8031
+ if (column instanceof Array) {
8032
+ this._columns = this._columns.concat(column);
8033
+ } else {
8034
+ this._columns.push(column);
8035
+ }
8036
+ return this;
8037
+ }
8038
+ columns(column) {
8039
+ return this.column(column);
8040
+ }
8041
+ from(from) {
8042
+ if (from instanceof Array) {
8043
+ this._selectFrom = this._selectFrom.concat(from);
8044
+ } else {
8045
+ this._selectFrom.push(from);
8046
+ }
8047
+ return this;
8048
+ }
8049
+ join(table, on, verb) {
8050
+ this._joins.push({
8051
+ _table: table,
8052
+ _on: on,
8053
+ _verb: verb
8054
+ });
8055
+ return this;
8056
+ }
8057
+ left(table, on) {
8058
+ return this.join(table, on, "LEFT");
8059
+ }
8060
+ right(table, on) {
8061
+ return this.join(table, on, "RIGHT");
8062
+ }
8063
+ group(column) {
8064
+ this._groupBy.push(column);
8065
+ return this;
8066
+ }
8067
+ };
8068
+
8069
+ // node_modules/@miqro/query/build/query/count.js
8070
+ var Count = class _Count extends Where {
8071
+ constructor(db) {
8072
+ super();
8073
+ this.db = db;
8074
+ this._type = "count";
8075
+ this._selectFrom = [];
8076
+ this._groupBy = [];
8077
+ this._joins = [];
8078
+ }
8079
+ clone() {
8080
+ const ret = new _Count(this.db);
8081
+ ret._filters = structuredClone(this._filters);
8082
+ ret._groupBy = structuredClone(this._groupBy);
8083
+ ret._joins = structuredClone(this._joins);
8084
+ ret._selectFrom = structuredClone(this._selectFrom);
8085
+ ret._orderBy = structuredClone(this._orderBy);
8086
+ ret._limitBy = this._limitBy;
8087
+ ret._offsetBy = this._offsetBy;
8088
+ return ret;
8089
+ }
8090
+ from(from) {
8091
+ this._selectFrom = this._selectFrom.concat(from);
8092
+ return this;
8093
+ }
8094
+ join(table, on, verb) {
8095
+ this._joins.push({
8096
+ _table: table,
8097
+ _on: on,
8098
+ _verb: verb
8099
+ });
8100
+ return this;
8101
+ }
8102
+ left(table, on) {
8103
+ return this.join(table, on, "LEFT");
8104
+ }
8105
+ right(table, on) {
8106
+ return this.join(table, on, "RIGHT");
8107
+ }
8108
+ group(column) {
8109
+ this._groupBy.push(column);
8110
+ return this;
8111
+ }
8112
+ prepare() {
8113
+ return getStatements(this.db.getExecutor().prepare(this));
8114
+ }
8115
+ async yield(logger) {
8116
+ return parseCountResult(await runStatements(this.db, this.db.getExecutor().prepare(this), logger));
8117
+ }
8118
+ };
8119
+ async function parseCountResult(rows) {
8120
+ return {
8121
+ count: parseInt(rows[0].count, 10)
8122
+ };
8123
+ }
8124
+
8125
+ // node_modules/@miqro/query/build/query/update.js
8126
+ var Update = class _Update extends Where {
8127
+ constructor(db, _table) {
8128
+ super();
8129
+ this.db = db;
8130
+ this._table = _table;
8131
+ this._type = "update";
8132
+ this._sets = [];
8133
+ this._returning = [];
8134
+ }
8135
+ prepare() {
8136
+ return getStatements(this.db.getExecutor().prepare(this));
8137
+ }
8138
+ async yield(logger) {
8139
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8140
+ }
8141
+ clone() {
8142
+ const ret = new _Update(this.db, this._table);
8143
+ ret._filters = structuredClone(this._filters);
8144
+ ret._orderBy = structuredClone(this._orderBy);
8145
+ ret._sets = structuredClone(this._sets);
8146
+ ret._returning = structuredClone(this._returning);
8147
+ ret._limitBy = this._limitBy;
8148
+ ret._offsetBy = this._offsetBy;
8149
+ return ret;
8150
+ }
8151
+ returning(column) {
8152
+ this._returning = this._returning.concat(column);
8550
8153
  return this;
8551
8154
  }
8552
- literal(literal) {
8553
- this._filters.push({
8554
- _type: "literal",
8555
- _literal: literal
8155
+ set(column, value) {
8156
+ this._sets.push({
8157
+ column,
8158
+ value
8556
8159
  });
8557
8160
  return this;
8558
8161
  }
8559
8162
  };
8560
8163
 
8561
- // node_modules/@miqro/query/build/query/select.js
8562
- var Select = class _Select extends Where {
8563
- constructor(db) {
8164
+ // node_modules/@miqro/query/build/query/delete.js
8165
+ var Delete = class _Delete extends Where {
8166
+ constructor(db, _table) {
8564
8167
  super();
8565
8168
  this.db = db;
8566
- this._type = "select";
8567
- this._columns = [];
8568
- this._selectFrom = [];
8569
- this._groupBy = [];
8570
- this._joins = [];
8571
- this._orderBy = [];
8169
+ this._table = _table;
8170
+ this._type = "delete";
8171
+ this._returning = [];
8572
8172
  }
8573
8173
  prepare() {
8574
8174
  return getStatements(this.db.getExecutor().prepare(this));
8575
8175
  }
8176
+ async yield(logger) {
8177
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8178
+ }
8576
8179
  clone() {
8577
- const ret = new _Select(this.db);
8180
+ const ret = new _Delete(this.db, this._table);
8578
8181
  ret._filters = structuredClone(this._filters);
8579
- ret._columns = structuredClone(this._columns);
8580
- ret._groupBy = structuredClone(this._groupBy);
8581
- ret._selectFrom = structuredClone(this._selectFrom);
8582
8182
  ret._orderBy = structuredClone(this._orderBy);
8583
- ret._joins = structuredClone(this._joins);
8183
+ ret._returning = structuredClone(this._returning);
8584
8184
  ret._limitBy = this._limitBy;
8585
8185
  ret._offsetBy = this._offsetBy;
8586
8186
  return ret;
8587
8187
  }
8188
+ returning(column) {
8189
+ this._returning = this._returning.concat(column);
8190
+ return this;
8191
+ }
8192
+ };
8193
+
8194
+ // node_modules/@miqro/query/build/query/drop-database.js
8195
+ var DropDatabase = class _DropDatabase {
8196
+ constructor(db, _dbName) {
8197
+ this.db = db;
8198
+ this._dbName = _dbName;
8199
+ this._type = "drop-database";
8200
+ this._ignoreDuplicate = false;
8201
+ }
8202
+ prepare() {
8203
+ return getStatements(this.db.getExecutor().prepare(this));
8204
+ }
8205
+ ignoreDuplicates(ignore = true) {
8206
+ this._ignoreDuplicate = ignore;
8207
+ return this;
8208
+ }
8588
8209
  async yield(logger) {
8589
8210
  return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8590
8211
  }
8591
- column(column) {
8592
- if (column instanceof Array) {
8593
- this._columns = this._columns.concat(column);
8594
- } else {
8595
- this._columns.push(column);
8212
+ clone() {
8213
+ const ret = new _DropDatabase(this.db, this._dbName);
8214
+ ret._ignoreDuplicate = this._ignoreDuplicate;
8215
+ return ret;
8216
+ }
8217
+ };
8218
+
8219
+ // node_modules/@miqro/query/build/executors/sqlite3-cli/lib.js
8220
+ var import_child_process = require("child_process");
8221
+ var SQLITE_CONFIG_SCHEMA2 = {
8222
+ type: "object",
8223
+ mode: "remove_extra",
8224
+ properties: {
8225
+ storage: "string"
8226
+ }
8227
+ };
8228
+ async function sqlite3CLIExecutor(config) {
8229
+ const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA2);
8230
+ if (!databaseOptions) {
8231
+ throw new Error("config not valid");
8232
+ }
8233
+ (config.logger ? config.logger : console).error(`sqlite3-cli is affected by sql injection. do not use! only for testing!`);
8234
+ return {
8235
+ // we just use the sqlite3Executor prepare function
8236
+ prepare: sqlite3ExecutorPrepare,
8237
+ disconnect: async function sqlite3ExecutorDisconnect() {
8238
+ },
8239
+ query: async function sqlite3Executor2(sql, values) {
8240
+ return new Promise((resolve20, reject) => {
8241
+ try {
8242
+ let i = 0;
8243
+ const raw = sql.replaceAll("?", (sub) => {
8244
+ const value = values ? values[i] : void 0;
8245
+ if (value === void 0) {
8246
+ throw new Error("cannot convert query");
8247
+ }
8248
+ i++;
8249
+ return `'${value}'`;
8250
+ });
8251
+ if (values && i !== values.length) {
8252
+ throw new Error("cannot convert query");
8253
+ }
8254
+ (0, import_child_process.exec)(`sqlite3 -json "${databaseOptions.storage}" "${raw}"`, (error2, stdout, stderr) => {
8255
+ try {
8256
+ if (error2) {
8257
+ if (stderr) {
8258
+ reject(new Error(stderr));
8259
+ } else {
8260
+ reject(error2);
8261
+ }
8262
+ } else {
8263
+ if (stderr) {
8264
+ reject(new Error(stderr));
8265
+ } else {
8266
+ if (stdout) {
8267
+ resolve20(JSON.parse(stdout));
8268
+ } else {
8269
+ resolve20([]);
8270
+ }
8271
+ }
8272
+ }
8273
+ } catch (e2) {
8274
+ reject(e2);
8275
+ }
8276
+ });
8277
+ } catch (e) {
8278
+ reject(e);
8279
+ }
8280
+ });
8596
8281
  }
8597
- return this;
8282
+ };
8283
+ }
8284
+
8285
+ // node_modules/@miqro/query/build/executors/sqlite-native/lib.js
8286
+ var SQLITE_CONFIG_SCHEMA3 = {
8287
+ type: "object",
8288
+ mode: "remove_extra",
8289
+ properties: {
8290
+ storage: "string"
8598
8291
  }
8599
- columns(column) {
8600
- return this.column(column);
8292
+ };
8293
+ async function nativeSqlite(config) {
8294
+ const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA3);
8295
+ if (!databaseOptions) {
8296
+ throw new Error("config not valid");
8601
8297
  }
8602
- from(from) {
8603
- if (from instanceof Array) {
8604
- this._selectFrom = this._selectFrom.concat(from);
8605
- } else {
8606
- this._selectFrom.push(from);
8298
+ const sqliteModule = await import("node:sqlite");
8299
+ const driver = new sqliteModule.DatabaseSync(databaseOptions.storage);
8300
+ return {
8301
+ // we just use the sqlite3Executor prepare function
8302
+ prepare: sqlite3ExecutorPrepare,
8303
+ disconnect: async function sqlite3ExecutorDisconnect() {
8304
+ return driver.close();
8305
+ },
8306
+ query: async function sqlite3Executor2(sql, values) {
8307
+ return new Promise((resolve20, reject) => {
8308
+ try {
8309
+ if (values) {
8310
+ for (let i = 0; i < values.length; i++) {
8311
+ switch (typeof values[i]) {
8312
+ case "object":
8313
+ if (values[i] instanceof Date) {
8314
+ values[i] = values[i].toString();
8315
+ }
8316
+ break;
8317
+ case "boolean":
8318
+ values[i] = values[i] ? 1 : 0;
8319
+ break;
8320
+ }
8321
+ }
8322
+ }
8323
+ const stmt = driver.prepare(sql);
8324
+ stmt.setReadBigInts(true);
8325
+ if (values && values.length > 0) {
8326
+ const ret = stmt.all(...values);
8327
+ resolve20(ret);
8328
+ } else {
8329
+ const ret = stmt.all();
8330
+ resolve20(ret);
8331
+ }
8332
+ } catch (e) {
8333
+ reject(e);
8334
+ }
8335
+ });
8336
+ }
8337
+ };
8338
+ }
8339
+
8340
+ // node_modules/@miqro/query/build/db.js
8341
+ var Database = class {
8342
+ constructor(config) {
8343
+ this.config = config;
8344
+ this.status = "disconnected";
8345
+ this.executor = null;
8346
+ parser.parse(config, DATABASE_CONFIG_SCHEMA, "no_extra");
8347
+ this.executor = null;
8348
+ }
8349
+ async connect() {
8350
+ if (this.status !== "disconnected") {
8351
+ throw new Error(`cannot connect while ${this.status}`);
8352
+ }
8353
+ if (this.executor !== null) {
8354
+ throw new Error(`cannot connect executor exists!`);
8355
+ }
8356
+ this.status = "connecting";
8357
+ try {
8358
+ this.executor = await getExecutor(this.config);
8359
+ this.status = "connected";
8360
+ } catch (e) {
8361
+ this.status = "error";
8362
+ throw e;
8363
+ }
8364
+ }
8365
+ async disconnect() {
8366
+ if (this.status !== "connected") {
8367
+ throw new Error(`cannot disconnect while ${this.status}`);
8368
+ }
8369
+ this.status = "disconnecting";
8370
+ try {
8371
+ await this.getExecutor().disconnect();
8372
+ this.executor = null;
8373
+ this.status = "disconnected";
8374
+ } catch (e) {
8375
+ this.status = "error";
8376
+ throw e;
8377
+ }
8378
+ }
8379
+ getExecutor() {
8380
+ if (!this.executor) {
8381
+ throw new Error("executor not initialized!");
8382
+ }
8383
+ return this.executor;
8384
+ }
8385
+ async query(sql, values, logger) {
8386
+ const l = logger ? logger : this.config.logger ? this.config.logger : void 0;
8387
+ try {
8388
+ l?.log(sql);
8389
+ const result = await this.getExecutor().query(sql, values);
8390
+ return result;
8391
+ } catch (e) {
8392
+ l?.error(e);
8393
+ throw e;
8607
8394
  }
8608
- return this;
8609
- }
8610
- join(table, on, verb) {
8611
- this._joins.push({
8612
- _table: table,
8613
- _on: on,
8614
- _verb: verb
8615
- });
8616
- return this;
8617
8395
  }
8618
- left(table, on) {
8619
- return this.join(table, on, "LEFT");
8396
+ async transaction(transactionCB, logger) {
8397
+ try {
8398
+ await this.query("BEGIN", void 0, logger);
8399
+ const ret = await transactionCB(this, logger);
8400
+ await this.query("COMMIT", void 0, logger);
8401
+ return ret;
8402
+ } catch (e) {
8403
+ await this.query("ROLLBACK", void 0, logger);
8404
+ throw e;
8405
+ }
8620
8406
  }
8621
- right(table, on) {
8622
- return this.join(table, on, "RIGHT");
8407
+ createDatabase(dbName) {
8408
+ return new CreateDatabase(this, dbName);
8623
8409
  }
8624
- group(column) {
8625
- this._groupBy.push(column);
8626
- return this;
8410
+ createTable(table, definition) {
8411
+ return new CreateTable(this, table, definition);
8627
8412
  }
8628
- };
8629
-
8630
- // node_modules/@miqro/query/build/query/count.js
8631
- var Count = class _Count extends Where {
8632
- constructor(db) {
8633
- super();
8634
- this.db = db;
8635
- this._type = "count";
8636
- this._selectFrom = [];
8637
- this._groupBy = [];
8638
- this._joins = [];
8413
+ dropTable(table) {
8414
+ return new DropTable(this, table);
8639
8415
  }
8640
- clone() {
8641
- const ret = new _Count(this.db);
8642
- ret._filters = structuredClone(this._filters);
8643
- ret._groupBy = structuredClone(this._groupBy);
8644
- ret._joins = structuredClone(this._joins);
8645
- ret._selectFrom = structuredClone(this._selectFrom);
8646
- ret._orderBy = structuredClone(this._orderBy);
8647
- ret._limitBy = this._limitBy;
8648
- ret._offsetBy = this._offsetBy;
8649
- return ret;
8416
+ dropDatabase(dbname) {
8417
+ return new DropDatabase(this, dbname);
8650
8418
  }
8651
- from(from) {
8652
- this._selectFrom = this._selectFrom.concat(from);
8653
- return this;
8419
+ alterTable(table, inTransaction) {
8420
+ return new AlterTable(this, table, inTransaction);
8654
8421
  }
8655
- join(table, on, verb) {
8656
- this._joins.push({
8657
- _table: table,
8658
- _on: on,
8659
- _verb: verb
8660
- });
8661
- return this;
8422
+ insert(table) {
8423
+ return new Insert(this, table);
8662
8424
  }
8663
- left(table, on) {
8664
- return this.join(table, on, "LEFT");
8425
+ select() {
8426
+ return new Select(this);
8665
8427
  }
8666
- right(table, on) {
8667
- return this.join(table, on, "RIGHT");
8428
+ count() {
8429
+ return new Count(this);
8668
8430
  }
8669
- group(column) {
8670
- this._groupBy.push(column);
8671
- return this;
8431
+ update(table) {
8432
+ return new Update(this, table);
8672
8433
  }
8673
- prepare() {
8674
- return getStatements(this.db.getExecutor().prepare(this));
8434
+ delete(table) {
8435
+ return new Delete(this, table);
8675
8436
  }
8676
- async yield(logger) {
8677
- return parseCountResult(await runStatements(this.db, this.db.getExecutor().prepare(this), logger));
8437
+ where() {
8438
+ return new Where();
8678
8439
  }
8679
8440
  };
8680
- async function parseCountResult(rows) {
8681
- return {
8682
- count: parseInt(rows[0].count, 10)
8683
- };
8441
+ async function getExecutor(config) {
8442
+ switch (config.dialect) {
8443
+ case "node:sqlite":
8444
+ return await nativeSqlite(config);
8445
+ case "sqlite3-cli":
8446
+ return await sqlite3CLIExecutor(config);
8447
+ case "pg":
8448
+ return await postgresExecutor(config);
8449
+ case "sqlite3":
8450
+ return await sqlite3Executor(config);
8451
+ default:
8452
+ if (config.executor) {
8453
+ return config.executor;
8454
+ }
8455
+ throw new Error("dialect [" + config.dialect + "] not defined");
8456
+ }
8684
8457
  }
8685
8458
 
8686
- // node_modules/@miqro/query/build/query/update.js
8687
- var Update = class _Update extends Where {
8688
- constructor(db, _table) {
8689
- super();
8690
- this.db = db;
8691
- this._table = _table;
8692
- this._type = "update";
8693
- this._sets = [];
8694
- this._returning = [];
8695
- }
8696
- prepare() {
8697
- return getStatements(this.db.getExecutor().prepare(this));
8459
+ // node_modules/@miqro/query/build/migrations/lib.js
8460
+ var lib_exports = {};
8461
+ __export(lib_exports, {
8462
+ down: () => down,
8463
+ getSortedMigrations: () => getMigrationFolderSortedFiles,
8464
+ init: () => initMigrationsTable,
8465
+ up: () => up
8466
+ });
8467
+
8468
+ // node_modules/@miqro/query/build/migrations/utils.js
8469
+ var import_fs = require("fs");
8470
+ var import_path = require("path");
8471
+
8472
+ // node_modules/@miqro/query/build/migrations/constants.js
8473
+ var MIGRATIONS_TABLE_NAME = "migrations";
8474
+ var MIGRATIONS_SCHEMA = {
8475
+ name: {
8476
+ type: "string",
8477
+ primaryKey: true,
8478
+ allowNull: false
8698
8479
  }
8699
- async yield(logger) {
8700
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8480
+ };
8481
+ var NULL_LOGGER = {
8482
+ error: (...args) => {
8483
+ },
8484
+ log: (...args) => {
8701
8485
  }
8702
- clone() {
8703
- const ret = new _Update(this.db, this._table);
8704
- ret._filters = structuredClone(this._filters);
8705
- ret._orderBy = structuredClone(this._orderBy);
8706
- ret._sets = structuredClone(this._sets);
8707
- ret._returning = structuredClone(this._returning);
8708
- ret._limitBy = this._limitBy;
8709
- ret._offsetBy = this._offsetBy;
8710
- return ret;
8486
+ };
8487
+
8488
+ // node_modules/@miqro/query/build/migrations/utils.js
8489
+ async function upMigrationFolder(db, migrationsFolderPath, logger, importFN) {
8490
+ const startMS = Date.now();
8491
+ logger?.log("\n\n====== [running migrations folder] ======\n====== [%s] ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath));
8492
+ await initMigrationsTable(db, NULL_LOGGER);
8493
+ const migrations = getMigrationFolderSortedFiles(migrationsFolderPath);
8494
+ for (const migrationName of migrations) {
8495
+ const migrationPath = (0, import_path.resolve)(migrationsFolderPath, migrationName);
8496
+ await upMigration(db, migrationPath, logger, importFN);
8711
8497
  }
8712
- returning(column) {
8713
- this._returning = this._returning.concat(column);
8714
- return this;
8498
+ const took = Date.now() - startMS;
8499
+ logger?.log("\n\n====== [running migrations folder done] ======\n====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath), took);
8500
+ return migrations;
8501
+ }
8502
+ async function downMigrationFolder(db, migrationsFolderPath, logger, importFN) {
8503
+ const startMS = Date.now();
8504
+ logger?.log("\n\n====== [running migrations folder] ======\n====== [%s] ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath));
8505
+ await initMigrationsTable(db, NULL_LOGGER);
8506
+ const migrations = getMigrationFolderSortedFiles(migrationsFolderPath).reverse();
8507
+ for (const migrationName of migrations) {
8508
+ const migrationPath = (0, import_path.resolve)(migrationsFolderPath, migrationName);
8509
+ await downMigration(db, migrationPath, logger, importFN);
8715
8510
  }
8716
- set(column, value) {
8717
- this._sets.push({
8718
- column,
8719
- value
8720
- });
8721
- return this;
8511
+ const took = Date.now() - startMS;
8512
+ logger?.log("\n\n====== [running migrations folder done] ======\n====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath), took);
8513
+ return migrations;
8514
+ }
8515
+ async function upMigration(db, migrationPath, logger, importFN) {
8516
+ return runMigration(db, migrationPath, false, logger ? logger : db.config.logger, importFN);
8517
+ }
8518
+ async function upMigrationModule(db, migrationName, migrationModule, logger) {
8519
+ return runMigrationModule(db, migrationName, migrationModule, false, logger ? logger : db.config.logger);
8520
+ }
8521
+ async function downMigrationModule(db, migrationName, migrationModule, logger) {
8522
+ return runMigrationModule(db, migrationName, migrationModule, true, logger ? logger : db.config.logger);
8523
+ }
8524
+ async function downMigration(db, migrationPath, logger, importFN) {
8525
+ return runMigration(db, migrationPath, true, logger ? logger : db.config.logger, importFN);
8526
+ }
8527
+ async function initMigrationsTable(db, logger) {
8528
+ return db.createTable(MIGRATIONS_TABLE_NAME, MIGRATIONS_SCHEMA).ignoreDuplicates(true).yield(logger);
8529
+ }
8530
+ function getMigrationFolderSortedFiles(migrationsFolderPath) {
8531
+ const files = (0, import_fs.readdirSync)(migrationsFolderPath);
8532
+ return files.map((file) => {
8533
+ const ext = (0, import_path.extname)(file);
8534
+ if (ext === ".js" || ext === ".mjs" || ext === ".ts" || ext === ".tsx" || ext === ".tsx") {
8535
+ const firstDash = file.indexOf("-");
8536
+ if (firstDash !== -1) {
8537
+ const number = parseInt(file.substring(0, firstDash), 10);
8538
+ if (!isNaN(number)) {
8539
+ return {
8540
+ number,
8541
+ file
8542
+ };
8543
+ }
8544
+ }
8545
+ }
8546
+ return {
8547
+ number: 0,
8548
+ file: ""
8549
+ };
8550
+ }).filter((file) => file.file !== "").sort((a, b) => {
8551
+ return a.number - b.number;
8552
+ }).map((file) => file.file);
8553
+ }
8554
+ async function runMigrationModule(db, migrationName, migrationModule, down2 = false, logger) {
8555
+ const startMS = Date.now();
8556
+ const alreadyRun = (await db.select().from(MIGRATIONS_TABLE_NAME).column("name").limit(1).eq("name", migrationName).yield(NULL_LOGGER)).length > 0;
8557
+ if (down2) {
8558
+ if (alreadyRun) {
8559
+ logger?.log(" ====== [%s] ======", (0, import_path.relative)(process.cwd(), migrationName));
8560
+ await migrationModule.down(db, logger);
8561
+ await db.delete(MIGRATIONS_TABLE_NAME).eq("name", migrationName).yield(NULL_LOGGER);
8562
+ const took = Date.now() - startMS;
8563
+ logger?.log(" ====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
8564
+ } else {
8565
+ const took = Date.now() - startMS;
8566
+ logger?.log(" ====== skipping down [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
8567
+ }
8568
+ } else {
8569
+ if (alreadyRun) {
8570
+ const took = Date.now() - startMS;
8571
+ logger?.log(" ====== skipping up [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
8572
+ } else {
8573
+ logger?.log(" ====== [%s] ======", (0, import_path.relative)(process.cwd(), migrationName));
8574
+ await migrationModule.up(db, logger);
8575
+ await db.insert(MIGRATIONS_TABLE_NAME).column("name").value([{
8576
+ name: migrationName
8577
+ }]).ignoreDuplicates(true).yield(NULL_LOGGER);
8578
+ const took = Date.now() - startMS;
8579
+ logger?.log(" ====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
8580
+ }
8722
8581
  }
8723
- };
8582
+ }
8583
+ async function runMigration(db, migrationPath, down2 = false, logger, importFN) {
8584
+ const migrationName = (0, import_path.basename)(migrationPath).substring(0, (0, import_path.basename)(migrationPath).length - (0, import_path.extname)(migrationPath).length);
8585
+ const migrationModule = (await (importFN ? importFN(migrationPath) : import(migrationPath))).default;
8586
+ return runMigrationModule(db, migrationName, migrationModule, down2, logger);
8587
+ }
8724
8588
 
8725
- // node_modules/@miqro/query/build/query/delete.js
8726
- var Delete = class _Delete extends Where {
8727
- constructor(db, _table) {
8728
- super();
8729
- this.db = db;
8730
- this._table = _table;
8731
- this._type = "delete";
8732
- this._returning = [];
8733
- }
8734
- prepare() {
8735
- return getStatements(this.db.getExecutor().prepare(this));
8736
- }
8737
- async yield(logger) {
8738
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8739
- }
8740
- clone() {
8741
- const ret = new _Delete(this.db, this._table);
8742
- ret._filters = structuredClone(this._filters);
8743
- ret._orderBy = structuredClone(this._orderBy);
8744
- ret._returning = structuredClone(this._returning);
8745
- ret._limitBy = this._limitBy;
8746
- ret._offsetBy = this._offsetBy;
8747
- return ret;
8748
- }
8749
- returning(column) {
8750
- this._returning = this._returning.concat(column);
8751
- return this;
8752
- }
8589
+ // node_modules/@miqro/query/build/migrations/lib.js
8590
+ var up = {
8591
+ file: upMigration,
8592
+ module: upMigrationModule,
8593
+ folder: upMigrationFolder
8753
8594
  };
8754
-
8755
- // node_modules/@miqro/query/build/query/drop-database.js
8756
- var DropDatabase = class _DropDatabase {
8757
- constructor(db, _dbName) {
8758
- this.db = db;
8759
- this._dbName = _dbName;
8760
- this._type = "drop-database";
8761
- this._ignoreDuplicate = false;
8762
- }
8763
- prepare() {
8764
- return getStatements(this.db.getExecutor().prepare(this));
8765
- }
8766
- ignoreDuplicates(ignore = true) {
8767
- this._ignoreDuplicate = ignore;
8768
- return this;
8769
- }
8770
- async yield(logger) {
8771
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8772
- }
8773
- clone() {
8774
- const ret = new _DropDatabase(this.db, this._dbName);
8775
- ret._ignoreDuplicate = this._ignoreDuplicate;
8776
- return ret;
8777
- }
8595
+ var down = {
8596
+ file: downMigration,
8597
+ module: downMigrationModule,
8598
+ folder: downMigrationFolder
8778
8599
  };
8779
8600
 
8780
- // node_modules/@miqro/query/build/executors/sqlite3-cli/lib.js
8781
- var import_child_process = require("child_process");
8782
- var SQLITE_CONFIG_SCHEMA2 = {
8783
- type: "object",
8784
- mode: "remove_extra",
8785
- properties: {
8786
- storage: "string"
8787
- }
8788
- };
8789
- async function sqlite3CLIExecutor(config) {
8790
- const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA2);
8791
- if (!databaseOptions) {
8792
- throw new Error("config not valid");
8793
- }
8794
- (config.logger ? config.logger : console).error(`sqlite3-cli is affected by sql injection. do not use! only for testing!`);
8795
- return {
8796
- // we just use the sqlite3Executor prepare function
8797
- prepare: sqlite3ExecutorPrepare,
8798
- disconnect: async function sqlite3ExecutorDisconnect() {
8799
- },
8800
- query: async function sqlite3Executor2(sql, values) {
8801
- return new Promise((resolve20, reject) => {
8802
- try {
8803
- let i = 0;
8804
- const raw = sql.replaceAll("?", (sub) => {
8805
- const value = values ? values[i] : void 0;
8806
- if (value === void 0) {
8807
- throw new Error("cannot convert query");
8808
- }
8809
- i++;
8810
- return `'${value}'`;
8601
+ // src/services/utils/cluster-ws.ts
8602
+ var ClusterWebSocketServer2MessageType = "$$$$ClusterWebSocketServer2Message$$$$$";
8603
+ var ClusterWebSocketServer2 = class extends WebSocketServer {
8604
+ constructor(name, options) {
8605
+ super({
8606
+ ...options,
8607
+ validate: (req) => {
8608
+ if (this.options.maxConnections !== void 0 && this.clients.size + this.remoteClients.size >= this.options.maxConnections) {
8609
+ return false;
8610
+ } else {
8611
+ return options.validate ? options.validate(req) : true;
8612
+ }
8613
+ },
8614
+ onError: (req, error2) => {
8615
+ if (process.send) {
8616
+ process.send({
8617
+ type: ClusterWebSocketServer2MessageType,
8618
+ action: "error",
8619
+ target: this.name,
8620
+ clientUUID: req.uuid,
8621
+ fromPID: String(process.pid),
8622
+ errorMessage: error2.message
8811
8623
  });
8812
- if (values && i !== values.length) {
8813
- throw new Error("cannot convert query");
8814
- }
8815
- (0, import_child_process.exec)(`sqlite3 -json "${databaseOptions.storage}" "${raw}"`, (error2, stdout, stderr) => {
8816
- try {
8817
- if (error2) {
8818
- if (stderr) {
8819
- reject(new Error(stderr));
8820
- } else {
8821
- reject(error2);
8822
- }
8823
- } else {
8824
- if (stderr) {
8825
- reject(new Error(stderr));
8826
- } else {
8827
- if (stdout) {
8828
- resolve20(JSON.parse(stdout));
8829
- } else {
8830
- resolve20([]);
8831
- }
8624
+ }
8625
+ if (options.onError) {
8626
+ options.onError(req, error2);
8627
+ }
8628
+ },
8629
+ onConnection: (req) => {
8630
+ if (process.send) {
8631
+ process.send({
8632
+ type: ClusterWebSocketServer2MessageType,
8633
+ action: "connection",
8634
+ target: this.name,
8635
+ fromPID: String(process.pid),
8636
+ clientUUID: req.uuid
8637
+ });
8638
+ }
8639
+ if (options.onConnection) {
8640
+ options.onConnection(req);
8641
+ }
8642
+ },
8643
+ onDisconnect: (req) => {
8644
+ if (process.send) {
8645
+ process.send({
8646
+ type: ClusterWebSocketServer2MessageType,
8647
+ action: "disconnection",
8648
+ target: this.name,
8649
+ fromPID: String(process.pid),
8650
+ clientUUID: req.uuid
8651
+ });
8652
+ }
8653
+ if (options.onDisconnect) {
8654
+ options.onDisconnect(req);
8655
+ }
8656
+ }
8657
+ });
8658
+ this.name = name;
8659
+ this.listener = async (data) => {
8660
+ try {
8661
+ const msg = data;
8662
+ if (msg && msg.type === ClusterWebSocketServer2MessageType && msg.target === this.name && msg.action) {
8663
+ switch (msg.action) {
8664
+ case "sync":
8665
+ if (process.send) {
8666
+ for (const clientUUID of this.clients.keys()) {
8667
+ process.send({
8668
+ type: ClusterWebSocketServer2MessageType,
8669
+ action: "connection",
8670
+ target: this.name,
8671
+ fromPID: String(process.pid),
8672
+ clientUUID
8673
+ });
8832
8674
  }
8833
8675
  }
8834
- } catch (e2) {
8835
- reject(e2);
8676
+ break;
8677
+ case "connection":
8678
+ if (!msg.clientUUID) {
8679
+ throw new Error(`action [${msg.action}] without clientUUID`);
8680
+ }
8681
+ if (!this.remoteClients.has(msg.clientUUID)) {
8682
+ this.remoteClients.add(msg.clientUUID);
8683
+ }
8684
+ break;
8685
+ case "disconnection":
8686
+ if (!msg.clientUUID) {
8687
+ throw new Error(`action [${msg.action}] without clientUUID`);
8688
+ }
8689
+ if (this.remoteClients.has(msg.clientUUID)) {
8690
+ this.remoteClients.delete(msg.clientUUID);
8691
+ }
8692
+ break;
8693
+ case "sendMessage": {
8694
+ const payload = String(msg.payload);
8695
+ if (!msg.clientUUID) {
8696
+ await super.broadcast(payload, msg.fromUUID);
8697
+ } else if (this.isConnected(msg.clientUUID)) {
8698
+ await super.writeTo(msg.clientUUID, payload);
8699
+ }
8700
+ break;
8836
8701
  }
8837
- });
8838
- } catch (e) {
8839
- reject(e);
8702
+ default:
8703
+ throw new Error(`action [${msg.action}] not supported`);
8704
+ }
8840
8705
  }
8706
+ } catch (e) {
8707
+ console.error(e);
8708
+ }
8709
+ };
8710
+ this.connect();
8711
+ }
8712
+ remoteClients = /* @__PURE__ */ new Set();
8713
+ listener;
8714
+ connect() {
8715
+ if (process.send) {
8716
+ process.removeListener("message", this.listener);
8717
+ process.on("message", this.listener);
8718
+ process.send({
8719
+ type: ClusterWebSocketServer2MessageType,
8720
+ action: "sync",
8721
+ fromPID: String(process.pid),
8722
+ target: this.name
8723
+ });
8724
+ }
8725
+ }
8726
+ dispose() {
8727
+ process.removeListener("message", this.listener);
8728
+ }
8729
+ async broadcast(payload, fromUUID) {
8730
+ if (process.send) {
8731
+ process.send({
8732
+ type: ClusterWebSocketServer2MessageType,
8733
+ action: "sendMessage",
8734
+ payload,
8735
+ target: this.name,
8736
+ fromPID: String(process.pid),
8737
+ fromUUID
8841
8738
  });
8842
8739
  }
8843
- };
8844
- }
8845
-
8846
- // node_modules/@miqro/query/build/executors/sqlite-native/lib.js
8847
- var SQLITE_CONFIG_SCHEMA3 = {
8848
- type: "object",
8849
- mode: "remove_extra",
8850
- properties: {
8851
- storage: "string"
8740
+ return super.broadcast(payload, fromUUID);
8852
8741
  }
8853
- };
8854
- async function nativeSqlite(config) {
8855
- const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA3);
8856
- if (!databaseOptions) {
8857
- throw new Error("config not valid");
8742
+ async writeTo(clientUUID, payload) {
8743
+ if (this.remoteClients.has(clientUUID)) {
8744
+ if (process.send) {
8745
+ process.send({
8746
+ type: ClusterWebSocketServer2MessageType,
8747
+ action: "sendMessage",
8748
+ clientUUID,
8749
+ target: this.name,
8750
+ fromPID: String(process.pid),
8751
+ payload
8752
+ });
8753
+ return;
8754
+ }
8755
+ }
8756
+ if (this.clients.has(clientUUID)) {
8757
+ return super.writeTo(clientUUID, payload);
8758
+ }
8858
8759
  }
8859
- const sqliteModule = await import("node:sqlite");
8860
- const driver = new sqliteModule.DatabaseSync(databaseOptions.storage);
8861
- return {
8862
- // we just use the sqlite3Executor prepare function
8863
- prepare: sqlite3ExecutorPrepare,
8864
- disconnect: async function sqlite3ExecutorDisconnect() {
8865
- return driver.close();
8866
- },
8867
- query: async function sqlite3Executor2(sql, values) {
8868
- return new Promise((resolve20, reject) => {
8869
- try {
8870
- if (values) {
8871
- for (let i = 0; i < values.length; i++) {
8872
- switch (typeof values[i]) {
8873
- case "object":
8874
- if (values[i] instanceof Date) {
8875
- values[i] = values[i].toString();
8876
- }
8877
- break;
8878
- case "boolean":
8879
- values[i] = values[i] ? 1 : 0;
8880
- break;
8760
+ isUUIDValid(uuid) {
8761
+ return !this.clients.has(uuid) && !this.remoteClients.has(uuid);
8762
+ }
8763
+ };
8764
+
8765
+ // src/services/utils/cluster-cache.ts
8766
+ var ClusterCacheType = "$$$$$$$$$$$ClusterCacheType$$$$$$$$$$$";
8767
+ var ClusterCache = class {
8768
+ constructor(name, logger) {
8769
+ this.name = name;
8770
+ this.logger = logger;
8771
+ this.listener = async (data) => {
8772
+ try {
8773
+ const msg = data;
8774
+ if (msg && msg.key && msg.action && msg.type === ClusterCacheType && msg.fromPID !== process.pid, (msg.action === "set_add" || msg.action === "set" || msg.action === "unset" || msg.action === "set_delete" || msg.action === "array_push") && msg.target === this.name) {
8775
+ this.logger?.debug("remote cluster cache message from [%s] [%s] [%s] [%s]", msg.fromPID, msg.target, msg.action, msg.key);
8776
+ switch (msg.action) {
8777
+ case "unset":
8778
+ this.localCache.delete(msg.key);
8779
+ break;
8780
+ case "set":
8781
+ this.localCache.set(msg.key, msg.value);
8782
+ break;
8783
+ case "set_add": {
8784
+ const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
8785
+ if (!(list instanceof Set)) {
8786
+ throw new Error("cannot apply push on non array");
8881
8787
  }
8788
+ if (list.has(msg.value)) {
8789
+ list.add(msg.value);
8790
+ }
8791
+ this.localCache.set(msg.key, list);
8792
+ break;
8793
+ }
8794
+ case "set_delete": {
8795
+ const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
8796
+ if (!(list instanceof Set)) {
8797
+ throw new Error("cannot apply push on non array");
8798
+ }
8799
+ if (list.has(msg.value)) {
8800
+ list.delete(msg.value);
8801
+ }
8802
+ this.localCache.set(msg.key, list);
8803
+ break;
8804
+ }
8805
+ case "array_push": {
8806
+ const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : [];
8807
+ if (!(list instanceof Array)) {
8808
+ throw new Error("cannot apply push on non array");
8809
+ }
8810
+ list.push(msg.value);
8811
+ this.localCache.set(msg.key, list);
8812
+ break;
8882
8813
  }
8883
8814
  }
8884
- const stmt = driver.prepare(sql);
8885
- stmt.setReadBigInts(true);
8886
- if (values && values.length > 0) {
8887
- const ret = stmt.all(...values);
8888
- resolve20(ret);
8889
- } else {
8890
- const ret = stmt.all();
8891
- resolve20(ret);
8892
- }
8893
- } catch (e) {
8894
- reject(e);
8895
8815
  }
8896
- });
8816
+ } catch (e) {
8817
+ this.logger?.error(e);
8818
+ }
8819
+ };
8820
+ this.connect();
8821
+ }
8822
+ localCache = /* @__PURE__ */ new Map();
8823
+ //private logger: Logger;
8824
+ listener;
8825
+ connect() {
8826
+ if (process.send) {
8827
+ process.removeListener("message", this.listener);
8828
+ process.on("message", this.listener);
8897
8829
  }
8898
- };
8899
- }
8900
-
8901
- // node_modules/@miqro/query/build/db.js
8902
- var Database = class {
8903
- constructor(config) {
8904
- this.config = config;
8905
- this.status = "disconnected";
8906
- this.executor = null;
8907
- parser.parse(config, DATABASE_CONFIG_SCHEMA, "no_extra");
8908
- this.executor = null;
8909
8830
  }
8910
- async connect() {
8911
- if (this.status !== "disconnected") {
8912
- throw new Error(`cannot connect while ${this.status}`);
8831
+ disconnect() {
8832
+ process.removeListener("message", this.listener);
8833
+ }
8834
+ get(key) {
8835
+ this.logger?.trace("get(%s)", key);
8836
+ return this.localCache.get(key);
8837
+ }
8838
+ set(key, value) {
8839
+ this.localCache.set(key, value);
8840
+ this.logger?.trace("set(%s, ...)", key);
8841
+ if (process.send) {
8842
+ setTimeout(() => {
8843
+ process.send({
8844
+ type: ClusterCacheType,
8845
+ action: "set",
8846
+ target: this.name,
8847
+ fromPID: process.pid,
8848
+ key,
8849
+ value
8850
+ });
8851
+ }, 10);
8913
8852
  }
8914
- if (this.executor !== null) {
8915
- throw new Error(`cannot connect executor exists!`);
8853
+ }
8854
+ unset(key) {
8855
+ this.logger?.trace("unset(%s)", key);
8856
+ this.localCache.delete(key);
8857
+ if (process.send) {
8858
+ setTimeout(() => {
8859
+ process.send({
8860
+ type: ClusterCacheType,
8861
+ target: this.name,
8862
+ action: "unset",
8863
+ fromPID: process.pid,
8864
+ key
8865
+ });
8866
+ }, 10);
8916
8867
  }
8917
- this.status = "connecting";
8918
- try {
8919
- this.executor = await getExecutor(this.config);
8920
- this.status = "connected";
8921
- } catch (e) {
8922
- this.status = "error";
8923
- throw e;
8868
+ }
8869
+ has(key) {
8870
+ this.logger?.trace("has(%s)", key);
8871
+ return this.localCache.has(key);
8872
+ }
8873
+ set_add(key, value) {
8874
+ this.logger?.trace("push(%s)", key);
8875
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8876
+ if (!(list instanceof Set)) {
8877
+ throw new Error("cannot apply on non Set");
8878
+ }
8879
+ if (list.has(value)) {
8880
+ list.add(value);
8881
+ }
8882
+ this.localCache.set(key, list);
8883
+ if (process.send) {
8884
+ setTimeout(() => {
8885
+ process.send({
8886
+ type: ClusterCacheType,
8887
+ target: this.name,
8888
+ action: "set_add",
8889
+ fromPID: process.pid,
8890
+ key,
8891
+ value
8892
+ });
8893
+ }, 10);
8924
8894
  }
8925
8895
  }
8926
- async disconnect() {
8927
- if (this.status !== "connected") {
8928
- throw new Error(`cannot disconnect while ${this.status}`);
8896
+ set_delete(key, value) {
8897
+ this.logger?.trace("delete(%s)", key);
8898
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8899
+ if (!(list instanceof Set)) {
8900
+ throw new Error("cannot apply on non Set");
8929
8901
  }
8930
- this.status = "disconnecting";
8931
- try {
8932
- await this.getExecutor().disconnect();
8933
- this.executor = null;
8934
- this.status = "disconnected";
8935
- } catch (e) {
8936
- this.status = "error";
8937
- throw e;
8902
+ if (list.has(value)) {
8903
+ list.delete(value);
8904
+ }
8905
+ this.localCache.set(key, list);
8906
+ if (process.send) {
8907
+ setTimeout(() => {
8908
+ process.send({
8909
+ type: ClusterCacheType,
8910
+ target: this.name,
8911
+ action: "set_delete",
8912
+ fromPID: process.pid,
8913
+ key,
8914
+ value
8915
+ });
8916
+ }, 10);
8917
+ }
8918
+ }
8919
+ set_has(key, value) {
8920
+ this.logger?.trace("set_has(%s)", key);
8921
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8922
+ if (!(list instanceof Set)) {
8923
+ throw new Error("cannot apply on non Set");
8938
8924
  }
8925
+ const ret = list.has(value);
8926
+ this.localCache.set(key, list);
8927
+ return ret;
8939
8928
  }
8940
- getExecutor() {
8941
- if (!this.executor) {
8942
- throw new Error("executor not initialized!");
8929
+ set_clear(key) {
8930
+ this.logger?.trace("set_clear(%s)", key);
8931
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8932
+ if (!(list instanceof Set)) {
8933
+ throw new Error("cannot apply on non Set");
8943
8934
  }
8944
- return this.executor;
8935
+ list.clear();
8936
+ this.localCache.set(key, list);
8945
8937
  }
8946
- async query(sql, values, logger) {
8947
- const l = logger ? logger : this.config.logger ? this.config.logger : void 0;
8948
- try {
8949
- l?.log(sql);
8950
- const result = await this.getExecutor().query(sql, values);
8951
- return result;
8952
- } catch (e) {
8953
- l?.error(e);
8954
- throw e;
8938
+ array_push(key, value) {
8939
+ this.logger?.trace("array_push(%s)", key);
8940
+ const list = this.localCache.has(key) ? this.localCache.get(key) : [];
8941
+ if (!(list instanceof Array)) {
8942
+ throw new Error("cannot apply on non Array");
8943
+ }
8944
+ list.push(value);
8945
+ this.localCache.set(key, list);
8946
+ if (process.send) {
8947
+ setTimeout(() => {
8948
+ process.send({
8949
+ type: ClusterCacheType,
8950
+ target: this.name,
8951
+ action: "array_push",
8952
+ fromPID: process.pid,
8953
+ key,
8954
+ value
8955
+ });
8956
+ }, 10);
8955
8957
  }
8956
8958
  }
8957
- async transaction(transactionCB, logger) {
8958
- try {
8959
- await this.query("BEGIN", void 0, logger);
8960
- const ret = await transactionCB(this, logger);
8961
- await this.query("COMMIT", void 0, logger);
8962
- return ret;
8963
- } catch (e) {
8964
- await this.query("ROLLBACK", void 0, logger);
8965
- throw e;
8959
+ array_clear(key) {
8960
+ this.logger?.trace("array_clear(%s)", key);
8961
+ if (this.localCache.has(key) && !(this.localCache.get(key) instanceof Array)) {
8962
+ throw new Error("cannot apply on non Array");
8966
8963
  }
8964
+ this.localCache.set(key, []);
8967
8965
  }
8968
- createDatabase(dbName) {
8969
- return new CreateDatabase(this, dbName);
8966
+ };
8967
+
8968
+ // src/services/utils/cache.ts
8969
+ var LocalCache = class {
8970
+ constructor(name, logger) {
8971
+ this.name = name;
8972
+ this.logger = logger;
8970
8973
  }
8971
- createTable(table, definition) {
8972
- return new CreateTable(this, table, definition);
8974
+ localCache = /* @__PURE__ */ new Map();
8975
+ dispose() {
8973
8976
  }
8974
- dropTable(table) {
8975
- return new DropTable(this, table);
8977
+ get(key) {
8978
+ this.logger?.trace("get(%s)", key);
8979
+ return this.localCache.get(key);
8976
8980
  }
8977
- dropDatabase(dbname) {
8978
- return new DropDatabase(this, dbname);
8981
+ set(key, value) {
8982
+ this.localCache.set(key, value);
8983
+ this.logger?.trace("set(%s, ...)", key);
8979
8984
  }
8980
- alterTable(table, inTransaction) {
8981
- return new AlterTable(this, table, inTransaction);
8985
+ unset(key) {
8986
+ this.logger?.trace("unset(%s)", key);
8987
+ this.localCache.delete(key);
8982
8988
  }
8983
- insert(table) {
8984
- return new Insert(this, table);
8989
+ has(key) {
8990
+ this.logger?.trace("has(%s)", key);
8991
+ return this.localCache.has(key);
8985
8992
  }
8986
- select() {
8987
- return new Select(this);
8993
+ set_add(key, value) {
8994
+ this.logger?.trace("set_add(%s)", key);
8995
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8996
+ if (!(list instanceof Set)) {
8997
+ throw new Error("cannot apply on non Set");
8998
+ }
8999
+ if (list.has(value)) {
9000
+ list.add(value);
9001
+ }
9002
+ this.localCache.set(key, list);
8988
9003
  }
8989
- count() {
8990
- return new Count(this);
9004
+ set_delete(key, value) {
9005
+ this.logger?.trace("set_delete(%s)", key);
9006
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
9007
+ if (!(list instanceof Set)) {
9008
+ throw new Error("cannot apply on non Set");
9009
+ }
9010
+ if (list.has(value)) {
9011
+ list.delete(value);
9012
+ }
9013
+ this.localCache.set(key, list);
8991
9014
  }
8992
- update(table) {
8993
- return new Update(this, table);
9015
+ set_has(key, value) {
9016
+ this.logger?.trace("set_has(%s)", key);
9017
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
9018
+ if (!(list instanceof Set)) {
9019
+ throw new Error("cannot apply on non Set");
9020
+ }
9021
+ const ret = list.has(value);
9022
+ this.localCache.set(key, list);
9023
+ return ret;
8994
9024
  }
8995
- delete(table) {
8996
- return new Delete(this, table);
9025
+ set_clear(key) {
9026
+ this.logger?.trace("set_clear(%s)", key);
9027
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
9028
+ if (!(list instanceof Set)) {
9029
+ throw new Error("cannot apply on non Set");
9030
+ }
9031
+ list.clear();
9032
+ this.localCache.set(key, list);
8997
9033
  }
8998
- where() {
8999
- return new Where();
9034
+ array_push(key, value) {
9035
+ this.logger?.trace("array_push(%s)", key);
9036
+ const list = this.localCache.has(key) ? this.localCache.get(key) : [];
9037
+ if (!(list instanceof Array)) {
9038
+ throw new Error("cannot apply on non Array");
9039
+ }
9040
+ list.push(value);
9041
+ this.localCache.set(key, list);
9000
9042
  }
9001
- };
9002
- async function getExecutor(config) {
9003
- switch (config.dialect) {
9004
- case "node:sqlite":
9005
- return await nativeSqlite(config);
9006
- case "sqlite3-cli":
9007
- return await sqlite3CLIExecutor(config);
9008
- case "pg":
9009
- return await postgresExecutor(config);
9010
- case "sqlite3":
9011
- return await sqlite3Executor(config);
9012
- default:
9013
- if (config.executor) {
9014
- return config.executor;
9015
- }
9016
- throw new Error("dialect [" + config.dialect + "] not defined");
9043
+ array_clear(key) {
9044
+ this.logger?.trace("array_clear(%s)", key);
9045
+ if (this.localCache.has(key) && !(this.localCache.get(key) instanceof Array)) {
9046
+ throw new Error("cannot apply on non Array");
9047
+ }
9048
+ this.localCache.set(key, []);
9017
9049
  }
9018
- }
9019
-
9020
- // node_modules/@miqro/query/build/migrations/lib.js
9021
- var lib_exports = {};
9022
- __export(lib_exports, {
9023
- down: () => down,
9024
- getSortedMigrations: () => getMigrationFolderSortedFiles,
9025
- init: () => initMigrationsTable,
9026
- up: () => up
9027
- });
9028
-
9029
- // node_modules/@miqro/query/build/migrations/utils.js
9030
- var import_fs = require("fs");
9031
- var import_path = require("path");
9050
+ };
9032
9051
 
9033
- // node_modules/@miqro/query/build/migrations/constants.js
9034
- var MIGRATIONS_TABLE_NAME = "migrations";
9035
- var MIGRATIONS_SCHEMA = {
9036
- name: {
9037
- type: "string",
9038
- primaryKey: true,
9039
- allowNull: false
9052
+ // src/services/utils/websocketmanager.ts
9053
+ init_constants();
9054
+ var WebSocketManager = class {
9055
+ runningGlobalWSMap = /* @__PURE__ */ new Map();
9056
+ logger = null;
9057
+ name;
9058
+ avoidLogSocket;
9059
+ constructor(options) {
9060
+ this.onUpgrade = this.onUpgrade.bind(this);
9061
+ this.logger = options && options.logger ? options.logger : null;
9062
+ this.name = options && options.name ? options.name : "WebSocketManager";
9063
+ this.avoidLogSocket = options && options.avoidLogSocket ? options.avoidLogSocket : false;
9040
9064
  }
9041
- };
9042
- var NULL_LOGGER = {
9043
- error: (...args) => {
9044
- },
9045
- log: (...args) => {
9065
+ deleteWS(path) {
9066
+ const ws = this.runningGlobalWSMap.get(path);
9067
+ this.disconnectAllFrom(path);
9068
+ ws.dispose();
9069
+ this.runningGlobalWSMap.delete(path);
9046
9070
  }
9047
- };
9048
-
9049
- // node_modules/@miqro/query/build/migrations/utils.js
9050
- async function upMigrationFolder(db, migrationsFolderPath, logger, importFN) {
9051
- const startMS = Date.now();
9052
- logger?.log("\n\n====== [running migrations folder] ======\n====== [%s] ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath));
9053
- await initMigrationsTable(db, NULL_LOGGER);
9054
- const migrations = getMigrationFolderSortedFiles(migrationsFolderPath);
9055
- for (const migrationName of migrations) {
9056
- const migrationPath = (0, import_path.resolve)(migrationsFolderPath, migrationName);
9057
- await upMigration(db, migrationPath, logger, importFN);
9071
+ deleteAllWS() {
9072
+ for (const path of this.runningGlobalWSMap.keys()) {
9073
+ this.deleteWS(path);
9074
+ }
9058
9075
  }
9059
- const took = Date.now() - startMS;
9060
- logger?.log("\n\n====== [running migrations folder done] ======\n====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath), took);
9061
- return migrations;
9062
- }
9063
- async function downMigrationFolder(db, migrationsFolderPath, logger, importFN) {
9064
- const startMS = Date.now();
9065
- logger?.log("\n\n====== [running migrations folder] ======\n====== [%s] ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath));
9066
- await initMigrationsTable(db, NULL_LOGGER);
9067
- const migrations = getMigrationFolderSortedFiles(migrationsFolderPath).reverse();
9068
- for (const migrationName of migrations) {
9069
- const migrationPath = (0, import_path.resolve)(migrationsFolderPath, migrationName);
9070
- await downMigration(db, migrationPath, logger, importFN);
9076
+ getWS(path) {
9077
+ return this.runningGlobalWSMap.get(path);
9078
+ }
9079
+ replaceALLWS(list) {
9080
+ this.deleteAllWS();
9081
+ for (const wsConfig of list) {
9082
+ if (!wsConfig.disabled) {
9083
+ if (this.runningGlobalWSMap.has(wsConfig.path)) {
9084
+ throw new Error(`ws on path ${wsConfig.path} already setup!`);
9085
+ }
9086
+ this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
9087
+ const server2 = new ClusterWebSocketServer2(wsConfig.path, wsConfig);
9088
+ this.runningGlobalWSMap.set(wsConfig.path, server2);
9089
+ }
9090
+ }
9091
+ }
9092
+ replaceALLWSBuLOGSocket(list) {
9093
+ for (const path of this.runningGlobalWSMap.keys()) {
9094
+ if (path !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
9095
+ this.deleteWS(path);
9096
+ }
9097
+ }
9098
+ for (const wsConfig of list) {
9099
+ if (!wsConfig.disabled) {
9100
+ if (wsConfig.path !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
9101
+ if (this.runningGlobalWSMap.has(wsConfig.path)) {
9102
+ throw new Error(`ws on path ${wsConfig.path} already setup!`);
9103
+ }
9104
+ this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
9105
+ const server2 = new ClusterWebSocketServer2(this.name + wsConfig.path, wsConfig);
9106
+ this.runningGlobalWSMap.set(wsConfig.path, server2);
9107
+ }
9108
+ }
9109
+ }
9071
9110
  }
9072
- const took = Date.now() - startMS;
9073
- logger?.log("\n\n====== [running migrations folder done] ======\n====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath), took);
9074
- return migrations;
9075
- }
9076
- async function upMigration(db, migrationPath, logger, importFN) {
9077
- return runMigration(db, migrationPath, false, logger ? logger : db.config.logger, importFN);
9078
- }
9079
- async function upMigrationModule(db, migrationName, migrationModule, logger) {
9080
- return runMigrationModule(db, migrationName, migrationModule, false, logger ? logger : db.config.logger);
9081
- }
9082
- async function downMigrationModule(db, migrationName, migrationModule, logger) {
9083
- return runMigrationModule(db, migrationName, migrationModule, true, logger ? logger : db.config.logger);
9084
- }
9085
- async function downMigration(db, migrationPath, logger, importFN) {
9086
- return runMigration(db, migrationPath, true, logger ? logger : db.config.logger, importFN);
9087
- }
9088
- async function initMigrationsTable(db, logger) {
9089
- return db.createTable(MIGRATIONS_TABLE_NAME, MIGRATIONS_SCHEMA).ignoreDuplicates(true).yield(logger);
9090
- }
9091
- function getMigrationFolderSortedFiles(migrationsFolderPath) {
9092
- const files = (0, import_fs.readdirSync)(migrationsFolderPath);
9093
- return files.map((file) => {
9094
- const ext = (0, import_path.extname)(file);
9095
- if (ext === ".js" || ext === ".mjs" || ext === ".ts" || ext === ".tsx" || ext === ".tsx") {
9096
- const firstDash = file.indexOf("-");
9097
- if (firstDash !== -1) {
9098
- const number = parseInt(file.substring(0, firstDash), 10);
9099
- if (!isNaN(number)) {
9100
- return {
9101
- number,
9102
- file
9103
- };
9111
+ /*public setupWS(path: string, server: ClusterWebSocketServer2) {
9112
+ if (this.runningGlobalWSMap.has(path)) {
9113
+ throw new Error(`ws on path ${path} already setup!`);
9114
+ }
9115
+ this.runningGlobalWSMap.set(path, server);
9116
+ }*/
9117
+ disconnectAllFrom(path) {
9118
+ try {
9119
+ this.logger?.debug("disconnect all from [%s]", path);
9120
+ const ws = this.getWS(path);
9121
+ if (ws) {
9122
+ const clients = ws.clients.values();
9123
+ if (clients) {
9124
+ for (const client of clients) {
9125
+ try {
9126
+ client.socket.destroy();
9127
+ } catch (e2) {
9128
+ this.logger?.error("error disconnecting web socket client");
9129
+ this.logger?.error(e2);
9130
+ }
9131
+ }
9104
9132
  }
9105
9133
  }
9134
+ } catch (e) {
9135
+ this.logger?.error("error disconnecting web socket clients");
9136
+ this.logger?.error(e.message);
9106
9137
  }
9107
- return {
9108
- number: 0,
9109
- file: ""
9110
- };
9111
- }).filter((file) => file.file !== "").sort((a, b) => {
9112
- return a.number - b.number;
9113
- }).map((file) => file.file);
9114
- }
9115
- async function runMigrationModule(db, migrationName, migrationModule, down2 = false, logger) {
9116
- const startMS = Date.now();
9117
- const alreadyRun = (await db.select().from(MIGRATIONS_TABLE_NAME).column("name").limit(1).eq("name", migrationName).yield(NULL_LOGGER)).length > 0;
9118
- if (down2) {
9119
- if (alreadyRun) {
9120
- logger?.log(" ====== [%s] ======", (0, import_path.relative)(process.cwd(), migrationName));
9121
- await migrationModule.down(db, logger);
9122
- await db.delete(MIGRATIONS_TABLE_NAME).eq("name", migrationName).yield(NULL_LOGGER);
9123
- const took = Date.now() - startMS;
9124
- logger?.log(" ====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
9125
- } else {
9126
- const took = Date.now() - startMS;
9127
- logger?.log(" ====== skipping down [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
9138
+ }
9139
+ disconnectAllButLOGSocket() {
9140
+ try {
9141
+ for (const wsPath of this.runningGlobalWSMap.keys()) {
9142
+ if (wsPath !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
9143
+ this.disconnectAllFrom(wsPath);
9144
+ }
9145
+ }
9146
+ } catch (e) {
9147
+ this.logger?.error("error disconnecting web socket clients");
9148
+ this.logger?.error(e.message);
9128
9149
  }
9129
- } else {
9130
- if (alreadyRun) {
9131
- const took = Date.now() - startMS;
9132
- logger?.log(" ====== skipping up [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
9133
- } else {
9134
- logger?.log(" ====== [%s] ======", (0, import_path.relative)(process.cwd(), migrationName));
9135
- await migrationModule.up(db, logger);
9136
- await db.insert(MIGRATIONS_TABLE_NAME).column("name").value([{
9137
- name: migrationName
9138
- }]).ignoreDuplicates(true).yield(NULL_LOGGER);
9139
- const took = Date.now() - startMS;
9140
- logger?.log(" ====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
9150
+ }
9151
+ disconnectAll() {
9152
+ try {
9153
+ for (const wsPath of this.runningGlobalWSMap.keys()) {
9154
+ this.disconnectAllFrom(wsPath);
9155
+ }
9156
+ } catch (e) {
9157
+ this.logger?.error("error disconnecting web socket clients");
9158
+ this.logger?.error(e.message);
9159
+ }
9160
+ }
9161
+ onUpgrade(req, socket, head) {
9162
+ try {
9163
+ const wsServer = this.getWS(req.path);
9164
+ if (wsServer) {
9165
+ return wsServer.onUpgrade(req, socket, head);
9166
+ } else {
9167
+ socket.destroy();
9168
+ }
9169
+ } catch (e) {
9170
+ this.logger?.error(e);
9141
9171
  }
9142
9172
  }
9143
- }
9144
- async function runMigration(db, migrationPath, down2 = false, logger, importFN) {
9145
- const migrationName = (0, import_path.basename)(migrationPath).substring(0, (0, import_path.basename)(migrationPath).length - (0, import_path.extname)(migrationPath).length);
9146
- const migrationModule = (await (importFN ? importFN(migrationPath) : import(migrationPath))).default;
9147
- return runMigrationModule(db, migrationName, migrationModule, down2, logger);
9148
- }
9149
-
9150
- // node_modules/@miqro/query/build/migrations/lib.js
9151
- var up = {
9152
- file: upMigration,
9153
- module: upMigrationModule,
9154
- folder: upMigrationFolder
9155
- };
9156
- var down = {
9157
- file: downMigration,
9158
- module: downMigrationModule,
9159
- folder: downMigrationFolder
9160
9173
  };
9161
9174
 
9162
9175
  // src/services/utils/db-manager.ts
9176
+ var import_node_cluster = __toESM(require("node:cluster"), 1);
9163
9177
  var DBManager = class {
9164
9178
  map = /* @__PURE__ */ new Map();
9165
9179
  options;
@@ -9187,6 +9201,18 @@ var DBManager = class {
9187
9201
  return db;
9188
9202
  }
9189
9203
  }
9204
+ async connectAll() {
9205
+ this.options?.logger?.debug("connection all db connections");
9206
+ const tR = [];
9207
+ for (const name of this.map.keys()) {
9208
+ const db = this.map.get(name);
9209
+ if (db && db.status === "disconnected") {
9210
+ this.options?.logger?.debug("connecting db connection [%s]", name);
9211
+ tR.push(db.connect());
9212
+ }
9213
+ }
9214
+ await Promise.all(tR);
9215
+ }
9190
9216
  async closeAll() {
9191
9217
  this.options?.logger?.debug("closing all db connections");
9192
9218
  for (const name of this.map.keys()) {
@@ -11699,15 +11725,6 @@ async function inflateJSX(inFile, options) {
11699
11725
  throw e;
11700
11726
  }
11701
11727
  }
11702
- async function importAPIRoute(inFile, logger) {
11703
- const mod = (await importJSXFile(inFile, logger)).default;
11704
- const module2 = typeof mod === "function" ? { handler: mod } : parser2.parse(mod, APIRouteSchema, (0, import_node_path5.basename)(inFile));
11705
- if (module2 !== void 0) {
11706
- return module2;
11707
- } else {
11708
- throw new Error(`error with module [${inFile}] undefined`);
11709
- }
11710
- }
11711
11728
  var APIOptionsSchema = {
11712
11729
  type: "object?",
11713
11730
  properties: {
@@ -11728,6 +11745,7 @@ var APIOptionsSchema = {
11728
11745
  },
11729
11746
  ...RouteOptionsSchema.properties
11730
11747
  }
11748
+ //mode:"add_extra"
11731
11749
  };
11732
11750
  var HTMLModuleSchema = {
11733
11751
  type: "object",
@@ -11737,6 +11755,7 @@ var HTMLModuleSchema = {
11737
11755
  },
11738
11756
  apiOptions: APIOptionsSchema
11739
11757
  }
11758
+ //mode:"add_extra"
11740
11759
  };
11741
11760
  var JSONModuleSchema = {
11742
11761
  type: "object",
@@ -11746,13 +11765,15 @@ var JSONModuleSchema = {
11746
11765
  },
11747
11766
  apiOptions: APIOptionsSchema
11748
11767
  }
11768
+ //mode:"add_extra"
11749
11769
  };
11750
11770
  var MigrationSchema = {
11751
11771
  type: "object",
11752
11772
  properties: {
11753
11773
  up: "function",
11754
11774
  down: "function"
11755
- }
11775
+ },
11776
+ mode: "add_extra"
11756
11777
  };
11757
11778
  var CORSOptionsSchema = {
11758
11779
  type: "object",
@@ -11762,6 +11783,7 @@ var CORSOptionsSchema = {
11762
11783
  methods: "string?",
11763
11784
  preflightContinue: "boolean?"
11764
11785
  }
11786
+ //mode:"add_extra"
11765
11787
  };
11766
11788
  var WSConfigSchema = {
11767
11789
  type: "object",
@@ -11774,6 +11796,7 @@ var WSConfigSchema = {
11774
11796
  onMessage: "function?",
11775
11797
  onDisconnect: "function?"
11776
11798
  }
11799
+ //mode:"add_extra"
11777
11800
  };
11778
11801
  var DBConfigSchema = {
11779
11802
  type: "object",
@@ -11784,6 +11807,7 @@ var DBConfigSchema = {
11784
11807
  dialect: "string?",
11785
11808
  name: "string"
11786
11809
  }
11810
+ //mode:"add_extra"
11787
11811
  };
11788
11812
  var ServerConfigSchema = {
11789
11813
  type: "object",
@@ -11794,6 +11818,7 @@ var ServerConfigSchema = {
11794
11818
  start: "function?",
11795
11819
  load: "function?"
11796
11820
  }
11821
+ //mode:"add_extra"
11797
11822
  };
11798
11823
  var LogConfigSchema = {
11799
11824
  type: "object",
@@ -11806,13 +11831,24 @@ var LogConfigSchema = {
11806
11831
  replaceFileTransport: "boolean?",
11807
11832
  write: "function"
11808
11833
  }
11834
+ //mode:"add_extra"
11809
11835
  };
11810
11836
  var AuthConfigSchema = {
11811
11837
  type: "object",
11812
11838
  properties: {
11813
11839
  ...SessionHandlerOptionsSchema.properties
11814
11840
  }
11841
+ //mode:"add_extra"
11815
11842
  };
11843
+ async function importAPIRoute(inFile, logger) {
11844
+ const mod = (await importJSXFile(inFile, logger)).default;
11845
+ const module2 = typeof mod === "function" ? { handler: mod } : parser2.parse(mod, APIRouteSchema, (0, import_node_path5.basename)(inFile));
11846
+ if (module2 !== void 0) {
11847
+ return module2;
11848
+ } else {
11849
+ throw new Error(`error with module [${inFile}] undefined`);
11850
+ }
11851
+ }
11816
11852
  async function importMigrationModule(inFile, logger) {
11817
11853
  const module2 = parser2.parse((await importJSXFile(inFile, logger)).default, MigrationSchema, (0, import_node_path5.basename)(inFile));
11818
11854
  if (module2 !== void 0) {
@@ -11822,7 +11858,9 @@ async function importMigrationModule(inFile, logger) {
11822
11858
  }
11823
11859
  }
11824
11860
  async function importHTMLModule(inFile, logger) {
11825
- const module2 = parser2.parse(await importJSXFile(inFile, logger), HTMLModuleSchema, (0, import_node_path5.basename)(inFile));
11861
+ const module2 = await importJSXFile(inFile, logger);
11862
+ parser2.parse(module2.default, HTMLModuleSchema.properties.default, `${(0, import_node_path5.basename)(inFile)}.default`);
11863
+ parser2.parse(module2.apiOptions, APIOptionsSchema, `${(0, import_node_path5.basename)(inFile)}.apiOptions`);
11826
11864
  if (module2 !== void 0) {
11827
11865
  return module2;
11828
11866
  } else {
@@ -11830,7 +11868,9 @@ async function importHTMLModule(inFile, logger) {
11830
11868
  }
11831
11869
  }
11832
11870
  async function importJSONModule(inFile, logger) {
11833
- const module2 = parser2.parse(await importJSXFile(inFile, logger), JSONModuleSchema, (0, import_node_path5.basename)(inFile));
11871
+ const module2 = await importJSXFile(inFile, logger);
11872
+ parser2.parse(module2.default, JSONModuleSchema.properties.default, `${(0, import_node_path5.basename)(inFile)}.default`);
11873
+ parser2.parse(module2.apiOptions, APIOptionsSchema, `${(0, import_node_path5.basename)(inFile)}.apiOptions`);
11834
11874
  if (module2 !== void 0) {
11835
11875
  return module2;
11836
11876
  } else {
@@ -13170,6 +13210,11 @@ async function watchAndServer(app) {
13170
13210
  }
13171
13211
  watchLogger?.info("watching for changes on [%s]", app.options.services.join(","));
13172
13212
  reWatch();
13213
+ return {
13214
+ stopWatch: () => {
13215
+ stopWatch();
13216
+ }
13217
+ };
13173
13218
  }
13174
13219
 
13175
13220
  // src/common/exit.ts
@@ -13326,9 +13371,6 @@ async function inflateDBMigrations(logger, service, dbName, inflateDir, errors)
13326
13371
  return false;
13327
13372
  }
13328
13373
 
13329
- // src/services/app.ts
13330
- var import_node_util3 = require("node:util");
13331
-
13332
13374
  // src/services/utils/server-interface.ts
13333
13375
  var import_node_cluster2 = __toESM(require("node:cluster"), 1);
13334
13376
  var import_node_child_process2 = require("node:child_process");
@@ -13425,9 +13467,114 @@ function getPORT() {
13425
13467
  return checkEnvVariable("PORT", "8080");
13426
13468
  }
13427
13469
 
13470
+ // src/services/utils/log-transport.ts
13471
+ var import_node_util3 = require("node:util");
13472
+ init_constants();
13473
+ function createLogProviderOptions(app) {
13474
+ const defaultConsole = ConsoleTransport();
13475
+ const defaultFile = FileTransport();
13476
+ const defaultWrite = async (args, level) => {
13477
+ try {
13478
+ const serviceNamesWithLogConfigReplaceConsole = level === void 0 && app.inflated ? Object.keys(app.inflated.logConfigMap).filter((serviceName) => app.inflated.logConfigMap[serviceName].replaceConsoleTransport) : [];
13479
+ const serviceNamesWithLogConfigReplaceFile = level === void 0 && app.inflated ? Object.keys(app.inflated.logConfigMap).filter((serviceName) => app.inflated.logConfigMap[serviceName].replaceFileTransport) : [];
13480
+ await Promise.allSettled((level === void 0 ? [
13481
+ level === void 0 && serviceNamesWithLogConfigReplaceConsole.length === 0 ? defaultConsole.write(args) : Promise.resolve(),
13482
+ level === void 0 && serviceNamesWithLogConfigReplaceFile.length === 0 ? defaultFile.write(args) : Promise.resolve()
13483
+ ] : []).concat(
13484
+ app.inflated ? Object.keys(app.inflated.logConfigMap).map((serviceName) => app.inflated.logConfigMap[serviceName]).filter((c) => c.level === level).map((c) => c.write(args)) : []
13485
+ ));
13486
+ } catch (e) {
13487
+ console.error(e);
13488
+ }
13489
+ };
13490
+ return {
13491
+ name: app.options.name,
13492
+ formatter: (args) => {
13493
+ const params = args.optionalParams;
13494
+ return (0, import_node_util3.format)(
13495
+ `${(/* @__PURE__ */ new Date()).toISOString()} PID[${process.pid}] ${args.identifier ? `[${args.identifier}] ` : ""}${args.level !== "info" ? args.level === "error" || args.level === "warn" ? `[${args.level.toUpperCase()}] ` : `[${args.level}] ` : ""}${args.message}`,
13496
+ ...params
13497
+ );
13498
+ },
13499
+ transports: [
13500
+ ...[void 0, "error", "warn", "info", "debug", "trace"].map((level) => {
13501
+ return level ? {
13502
+ level,
13503
+ write: async (args) => {
13504
+ await defaultWrite(args, level);
13505
+ }
13506
+ } : {
13507
+ write: async (args) => {
13508
+ await defaultWrite(args, void 0);
13509
+ }
13510
+ };
13511
+ }),
13512
+ {
13513
+ level: "trace",
13514
+ write: async (args) => {
13515
+ try {
13516
+ if (app.options.editor) {
13517
+ try {
13518
+ const ws = app.webSocketManager.getWS(LOG_SOCKET_PATH);
13519
+ if (ws) {
13520
+ await ws.broadcast(JSON.stringify({
13521
+ type: LOG_WRITE_EVENT,
13522
+ level: args.level,
13523
+ identifier: args.identifier,
13524
+ out: args.out
13525
+ }));
13526
+ }
13527
+ } catch (e) {
13528
+ console.error(e);
13529
+ }
13530
+ }
13531
+ } catch (e) {
13532
+ console.error(e);
13533
+ }
13534
+ }
13535
+ }
13536
+ ],
13537
+ ...app.options.logProviderOptions ? app.options.logProviderOptions : {}
13538
+ };
13539
+ }
13540
+
13541
+ // src/services/utils/admin-interface.ts
13542
+ function createAdminInterface(app) {
13543
+ const adminCache = new ClusterCache("EditorCache[" + app.options.name + "]");
13544
+ return {
13545
+ getCache: () => adminCache,
13546
+ stop: () => app.stop(),
13547
+ restart: () => app.restart(),
13548
+ reload: () => app.reload(),
13549
+ getHotReloadHTML: getHotReloadScript,
13550
+ getMigrations: () => {
13551
+ if (app.inflated) {
13552
+ const ret = [];
13553
+ for (const db of app.inflated.dbList) {
13554
+ for (const m of db.migrations) {
13555
+ ret.push(m);
13556
+ }
13557
+ }
13558
+ return ret;
13559
+ }
13560
+ return [];
13561
+ },
13562
+ getServices: () => {
13563
+ return app.options.services;
13564
+ },
13565
+ getRouteFileMap: () => {
13566
+ return app.inflated ? app.inflated.fileMap : {};
13567
+ },
13568
+ getInflateErrors: () => {
13569
+ return app.inflated ? app.inflated.errors : [];
13570
+ }
13571
+ };
13572
+ }
13573
+
13428
13574
  // src/services/app.ts
13429
13575
  var MiqroApplicationMessageType = "$$$MiqroApplicationMessageType$$$";
13430
13576
  var Miqro = class _Miqro {
13577
+ status = "stopped";
13431
13578
  options;
13432
13579
  server = null;
13433
13580
  cache;
@@ -13442,6 +13589,7 @@ var Miqro = class _Miqro {
13442
13589
  logger;
13443
13590
  loggerProvider;
13444
13591
  static initAssetsPromise = null;
13592
+ watcher;
13445
13593
  constructor(options) {
13446
13594
  this.options = {
13447
13595
  editor: false,
@@ -13450,65 +13598,7 @@ var Miqro = class _Miqro {
13450
13598
  services: [],
13451
13599
  ...options ? options : {}
13452
13600
  };
13453
- const defaultConsole = ConsoleTransport();
13454
- const defaultFile = FileTransport();
13455
- const defaultWrite = async (args, level) => {
13456
- try {
13457
- const serviceNamesWithLogConfigReplaceConsole = level === void 0 && this.inflated ? Object.keys(this.inflated.logConfigMap).filter((serviceName) => this.inflated.logConfigMap[serviceName].replaceConsoleTransport) : [];
13458
- const serviceNamesWithLogConfigReplaceFile = level === void 0 && this.inflated ? Object.keys(this.inflated.logConfigMap).filter((serviceName) => this.inflated.logConfigMap[serviceName].replaceFileTransport) : [];
13459
- await Promise.allSettled((level === void 0 ? [
13460
- level === void 0 && serviceNamesWithLogConfigReplaceConsole.length === 0 ? defaultConsole.write(args) : Promise.resolve(),
13461
- level === void 0 && serviceNamesWithLogConfigReplaceFile.length === 0 ? defaultFile.write(args) : Promise.resolve()
13462
- ] : []).concat(
13463
- this.inflated ? Object.keys(this.inflated.logConfigMap).map((serviceName) => this.inflated.logConfigMap[serviceName]).filter((c) => c.level === level).map((c) => c.write(args)) : []
13464
- ));
13465
- } catch (e) {
13466
- console.error(e);
13467
- }
13468
- };
13469
- this.loggerProvider = new LogProvider({
13470
- name: this.options.name,
13471
- formatter: ({ identifier, level, message, optionalParams }) => (0, import_node_util3.format)(`${(/* @__PURE__ */ new Date()).toISOString()} PID[${process.pid}] ${identifier ? `[${identifier}] ` : ""}${level !== "info" ? level === "error" || level === "warn" ? `[${level.toUpperCase()}] ` : `[${level}] ` : ""}${message}`, ...optionalParams),
13472
- transports: [
13473
- ...[void 0, "error", "warn", "info", "debug", "trace"].map((level) => {
13474
- return level ? {
13475
- level,
13476
- write: async (args) => {
13477
- await defaultWrite(args, level);
13478
- }
13479
- } : {
13480
- write: async (args) => {
13481
- await defaultWrite(args, void 0);
13482
- }
13483
- };
13484
- }),
13485
- {
13486
- level: "trace",
13487
- write: async (args) => {
13488
- try {
13489
- if (this.options.editor) {
13490
- try {
13491
- const ws = this.webSocketManager.getWS(LOG_SOCKET_PATH);
13492
- if (ws) {
13493
- await ws.broadcast(JSON.stringify({
13494
- type: LOG_WRITE_EVENT,
13495
- level: args.level,
13496
- identifier: args.identifier,
13497
- out: args.out
13498
- }));
13499
- }
13500
- } catch (e) {
13501
- console.error(e);
13502
- }
13503
- }
13504
- } catch (e) {
13505
- console.error(e);
13506
- }
13507
- }
13508
- }
13509
- ],
13510
- ...this.options.logProviderOptions ? this.options.logProviderOptions : {}
13511
- });
13601
+ this.loggerProvider = new LogProvider(createLogProviderOptions(this));
13512
13602
  const SERVER_IDENTIFIER = import_node_cluster3.default.isPrimary ? "" : process.env["CLUSTER_NODE_NUMBER"] ? `WORKER_${process.env["CLUSTER_NODE_NUMBER"]}`.toUpperCase() : `WORKER`;
13513
13603
  this.logger = this.options.logger ? this.options.logger : this.loggerProvider.getLogger(SERVER_IDENTIFIER);
13514
13604
  this.listener = async (data) => {
@@ -13554,56 +13644,26 @@ var Miqro = class _Miqro {
13554
13644
  port: this.options.port
13555
13645
  });
13556
13646
  this.serverRequestHandler = ServerRequestHandler(this.serverInterface);
13557
- const adminCache = new ClusterCache("EditorCache[" + this.options.name + "]");
13558
- this.adminInterface = {
13559
- getCache: () => adminCache,
13560
- stop: () => this.stop(),
13561
- restart: () => this.restart(),
13562
- reload: () => this.reload(),
13563
- getHotReloadHTML: getHotReloadScript,
13564
- getMigrations: () => {
13565
- if (this.inflated) {
13566
- const ret = [];
13567
- for (const db of this.inflated.dbList) {
13568
- for (const m of db.migrations) {
13569
- ret.push(m);
13570
- }
13571
- }
13572
- return ret;
13573
- }
13574
- return [];
13575
- },
13576
- getServices: () => {
13577
- return this.options.services;
13578
- },
13579
- getRouteFileMap: () => {
13580
- return this.inflated ? this.inflated.fileMap : {};
13581
- },
13582
- getInflateErrors: () => {
13583
- return this.inflated ? this.inflated.errors : [];
13584
- }
13585
- /*,
13586
- inflateJSX: async function inflateJSX(path, minify: boolean = true) {
13587
- return realInflateJSX(path, {
13588
- embemedJSX: true,
13589
- minify,
13590
- useExport: true
13591
- });
13592
- }*/
13593
- };
13647
+ this.adminInterface = createAdminInterface(this);
13594
13648
  setupExitHandlers(this);
13649
+ }
13650
+ connect() {
13595
13651
  if (process.send) {
13652
+ process.removeListener("message", this.listener);
13596
13653
  process.on("message", this.listener);
13597
13654
  }
13655
+ this.cache.connect();
13656
+ this.adminInterface?.getCache()?.connect();
13598
13657
  }
13599
- dispose() {
13658
+ disconnect() {
13600
13659
  if (this.server !== null) {
13601
13660
  throw new Error("already running! call stop() first");
13602
13661
  }
13603
13662
  if (process.send) {
13604
13663
  process.removeListener("message", this.listener);
13605
13664
  }
13606
- this.cache.dispose();
13665
+ this.cache.disconnect();
13666
+ this.adminInterface?.getCache()?.disconnect();
13607
13667
  this.webSocketManager.disconnectAll();
13608
13668
  this.dbManager.closeAll();
13609
13669
  }
@@ -13773,14 +13833,17 @@ var Miqro = class _Miqro {
13773
13833
  this.inflated = null;
13774
13834
  }
13775
13835
  async start() {
13776
- if (this.server !== null) {
13836
+ if (this.server !== null || this.status !== "stopped") {
13777
13837
  throw new Error("cannot start app already running.");
13778
13838
  }
13779
13839
  if (!this.isInflated()) {
13780
13840
  throw new Error("cannot start uninflated app. call await app.inflate() first.");
13781
13841
  }
13782
13842
  this.logger?.debug(" ==start==");
13843
+ this.status = "starting";
13783
13844
  this.server = void 0;
13845
+ this.connect();
13846
+ await this.dbManager.connectAll();
13784
13847
  this.server = new App({
13785
13848
  onUpgrade: (req, socket, head) => {
13786
13849
  req.server = this.serverInterface;
@@ -13811,17 +13874,24 @@ var Miqro = class _Miqro {
13811
13874
  }
13812
13875
  await notifiyServerConfig(this.logger, this.serverInterface, this.adminInterface, this.inflated.serverConfigMap, "start");
13813
13876
  if (this.options.hotreload && (import_node_cluster3.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === "0")) {
13814
- await watchAndServer(this);
13877
+ this.watcher = await watchAndServer(this);
13815
13878
  }
13816
13879
  this.logger?.debug(" ==start done==");
13880
+ this.status = "started";
13817
13881
  return this.inflated.errors && this.inflated.errors.length > 0 ? this.inflated.errors : null;
13818
13882
  }
13819
13883
  async stop() {
13820
- if (!this.server || !this.inflated) {
13884
+ if (!this.server || !this.inflated || this.status !== "started") {
13821
13885
  throw new Error("cannot stop server not running");
13822
13886
  }
13887
+ this.status = "stopping";
13888
+ if (this.watcher) {
13889
+ this.watcher.stopWatch();
13890
+ this.watcher = null;
13891
+ }
13823
13892
  const server2 = this.server;
13824
13893
  this.server = null;
13894
+ this.disconnect();
13825
13895
  this.logger?.debug(" ==stop==");
13826
13896
  this.logger?.debug("clear running server routes");
13827
13897
  server2.clear();
@@ -13831,13 +13901,14 @@ var Miqro = class _Miqro {
13831
13901
  notifiyServerConfigSync(this, "unload");
13832
13902
  this.logger?.debug("stopping");
13833
13903
  const p = server2.close();
13834
- notifiyServerConfigSync(this, "stop");
13835
13904
  await p;
13836
13905
  await pD;
13906
+ this.status = "stopped";
13907
+ notifiyServerConfigSync(this, "stop");
13837
13908
  this.logger?.debug(" ==stop done==");
13838
13909
  }
13839
13910
  async restart(avoidSend) {
13840
- if (!this.server || !this.inflated) {
13911
+ if (!this.server || !this.inflated || this.status !== "started") {
13841
13912
  throw new Error("cannot start server not running");
13842
13913
  }
13843
13914
  this.logger?.debug(" ==restart==");
@@ -13855,9 +13926,10 @@ var Miqro = class _Miqro {
13855
13926
  return ret;
13856
13927
  }
13857
13928
  async reload(avoidSend) {
13858
- if (!this.server || !this.inflated) {
13929
+ if (!this.server || !this.inflated || this.status !== "started") {
13859
13930
  throw new Error("cannot reload server not running");
13860
13931
  }
13932
+ this.status = "reloading";
13861
13933
  if (!avoidSend) {
13862
13934
  this.logger?.debug(" ==reload==");
13863
13935
  } else {
@@ -13900,6 +13972,7 @@ var Miqro = class _Miqro {
13900
13972
  });
13901
13973
  }
13902
13974
  this.logger?.debug(" ==reload done==");
13975
+ this.status = "started";
13903
13976
  return this.inflated.errors && this.inflated.errors.length > 0 ? this.inflated.errors : null;
13904
13977
  }
13905
13978
  };