@tego/core 1.3.44

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 (152) hide show
  1. package/LICENSE +201 -0
  2. package/lib/acl/available-action.d.ts +5 -0
  3. package/lib/acl/available-action.js +62 -0
  4. package/lib/acl/index.d.ts +2 -0
  5. package/lib/acl/index.js +49 -0
  6. package/lib/aes-encryptor.d.ts +11 -0
  7. package/lib/aes-encryptor.js +116 -0
  8. package/lib/app-command.d.ts +12 -0
  9. package/lib/app-command.js +76 -0
  10. package/lib/app-supervisor.d.ts +61 -0
  11. package/lib/app-supervisor.js +299 -0
  12. package/lib/application.d.ts +354 -0
  13. package/lib/application.js +878 -0
  14. package/lib/cache/index.d.ts +3 -0
  15. package/lib/cache/index.js +35 -0
  16. package/lib/commands/console.d.ts +3 -0
  17. package/lib/commands/console.js +48 -0
  18. package/lib/commands/create-migration.d.ts +3 -0
  19. package/lib/commands/create-migration.js +80 -0
  20. package/lib/commands/db-auth.d.ts +3 -0
  21. package/lib/commands/db-auth.js +28 -0
  22. package/lib/commands/db-clean.d.ts +3 -0
  23. package/lib/commands/db-clean.js +31 -0
  24. package/lib/commands/db-sync.d.ts +3 -0
  25. package/lib/commands/db-sync.js +40 -0
  26. package/lib/commands/destroy.d.ts +3 -0
  27. package/lib/commands/destroy.js +30 -0
  28. package/lib/commands/index.d.ts +2 -0
  29. package/lib/commands/index.js +71 -0
  30. package/lib/commands/install.d.ts +3 -0
  31. package/lib/commands/install.js +33 -0
  32. package/lib/commands/migrator.d.ts +3 -0
  33. package/lib/commands/migrator.js +31 -0
  34. package/lib/commands/pm.d.ts +3 -0
  35. package/lib/commands/pm.js +75 -0
  36. package/lib/commands/refresh.d.ts +3 -0
  37. package/lib/commands/refresh.js +31 -0
  38. package/lib/commands/restart.d.ts +3 -0
  39. package/lib/commands/restart.js +35 -0
  40. package/lib/commands/start.d.ts +3 -0
  41. package/lib/commands/start.js +74 -0
  42. package/lib/commands/stop.d.ts +3 -0
  43. package/lib/commands/stop.js +34 -0
  44. package/lib/commands/upgrade.d.ts +3 -0
  45. package/lib/commands/upgrade.js +29 -0
  46. package/lib/cron/cron-job-manager.d.ts +25 -0
  47. package/lib/cron/cron-job-manager.js +89 -0
  48. package/lib/environment.d.ts +10 -0
  49. package/lib/environment.js +73 -0
  50. package/lib/errors/application-not-install.d.ts +4 -0
  51. package/lib/errors/application-not-install.js +35 -0
  52. package/lib/errors/handler.d.ts +3 -0
  53. package/lib/errors/handler.js +41 -0
  54. package/lib/errors/plugin-command-error.d.ts +2 -0
  55. package/lib/errors/plugin-command-error.js +31 -0
  56. package/lib/errors/plugin-not-exist.d.ts +2 -0
  57. package/lib/errors/plugin-not-exist.js +31 -0
  58. package/lib/gateway/errors.d.ts +22 -0
  59. package/lib/gateway/errors.js +138 -0
  60. package/lib/gateway/gateway.d.ts +56 -0
  61. package/lib/gateway/gateway.js +408 -0
  62. package/lib/gateway/index.d.ts +2 -0
  63. package/lib/gateway/index.js +30 -0
  64. package/lib/gateway/ipc-socket-client.d.ts +17 -0
  65. package/lib/gateway/ipc-socket-client.js +99 -0
  66. package/lib/gateway/ipc-socket-server.d.ts +12 -0
  67. package/lib/gateway/ipc-socket-server.js +140 -0
  68. package/lib/gateway/types.d.ts +25 -0
  69. package/lib/gateway/types.js +15 -0
  70. package/lib/gateway/ws-server.d.ts +63 -0
  71. package/lib/gateway/ws-server.js +335 -0
  72. package/lib/helper.d.ts +11 -0
  73. package/lib/helper.js +193 -0
  74. package/lib/helpers/application-version.d.ts +10 -0
  75. package/lib/helpers/application-version.js +77 -0
  76. package/lib/helpers/multiple-instance-manager.d.ts +6 -0
  77. package/lib/helpers/multiple-instance-manager.js +40 -0
  78. package/lib/index.d.ts +10 -0
  79. package/lib/index.js +57 -0
  80. package/lib/locale/index.d.ts +1 -0
  81. package/lib/locale/index.js +21 -0
  82. package/lib/locale/locale.d.ts +22 -0
  83. package/lib/locale/locale.js +166 -0
  84. package/lib/locale/resource.d.ts +1 -0
  85. package/lib/locale/resource.js +74 -0
  86. package/lib/main-data-source.d.ts +4 -0
  87. package/lib/main-data-source.js +45 -0
  88. package/lib/middlewares/data-template.d.ts +2 -0
  89. package/lib/middlewares/data-template.js +39 -0
  90. package/lib/middlewares/data-wrapping.d.ts +3 -0
  91. package/lib/middlewares/data-wrapping.js +90 -0
  92. package/lib/middlewares/db2resource.d.ts +6 -0
  93. package/lib/middlewares/db2resource.js +76 -0
  94. package/lib/middlewares/extract-client-ip.d.ts +2 -0
  95. package/lib/middlewares/extract-client-ip.js +37 -0
  96. package/lib/middlewares/i18n.d.ts +1 -0
  97. package/lib/middlewares/i18n.js +44 -0
  98. package/lib/middlewares/index.d.ts +3 -0
  99. package/lib/middlewares/index.js +32 -0
  100. package/lib/middlewares/parse-variables.d.ts +1 -0
  101. package/lib/middlewares/parse-variables.js +84 -0
  102. package/lib/migration.d.ts +12 -0
  103. package/lib/migration.js +47 -0
  104. package/lib/migrations/20230912193824-package-name-unique.d.ts +6 -0
  105. package/lib/migrations/20230912193824-package-name-unique.js +52 -0
  106. package/lib/migrations/20230912294620-update-pkg.d.ts +6 -0
  107. package/lib/migrations/20230912294620-update-pkg.js +58 -0
  108. package/lib/migrations/20240106082756-update-plugins.d.ts +6 -0
  109. package/lib/migrations/20240106082756-update-plugins.js +44 -0
  110. package/lib/migrations/20240705000001-remove-pkgs-approval.d.ts +6 -0
  111. package/lib/migrations/20240705000001-remove-pkgs-approval.js +47 -0
  112. package/lib/notice/index.d.ts +25 -0
  113. package/lib/notice/index.js +91 -0
  114. package/lib/plugin-manager/clientStaticUtils.d.ts +24 -0
  115. package/lib/plugin-manager/clientStaticUtils.js +156 -0
  116. package/lib/plugin-manager/constants.d.ts +7 -0
  117. package/lib/plugin-manager/constants.js +120 -0
  118. package/lib/plugin-manager/deps.d.ts +2 -0
  119. package/lib/plugin-manager/deps.js +68 -0
  120. package/lib/plugin-manager/index.d.ts +2 -0
  121. package/lib/plugin-manager/index.js +23 -0
  122. package/lib/plugin-manager/middleware.d.ts +2 -0
  123. package/lib/plugin-manager/middleware.js +36 -0
  124. package/lib/plugin-manager/options/collection.d.ts +2 -0
  125. package/lib/plugin-manager/options/collection.js +39 -0
  126. package/lib/plugin-manager/options/resource.d.ts +15 -0
  127. package/lib/plugin-manager/options/resource.js +185 -0
  128. package/lib/plugin-manager/plugin-manager-repository.d.ts +27 -0
  129. package/lib/plugin-manager/plugin-manager-repository.js +136 -0
  130. package/lib/plugin-manager/plugin-manager.d.ts +205 -0
  131. package/lib/plugin-manager/plugin-manager.js +1032 -0
  132. package/lib/plugin-manager/types.d.ts +15 -0
  133. package/lib/plugin-manager/types.js +15 -0
  134. package/lib/plugin-manager/utils.d.ts +101 -0
  135. package/lib/plugin-manager/utils.js +513 -0
  136. package/lib/plugin-manager/web-service.d.ts +6 -0
  137. package/lib/plugin-manager/web-service.js +116 -0
  138. package/lib/plugin.d.ts +125 -0
  139. package/lib/plugin.js +359 -0
  140. package/lib/pub-sub-manager/handler-manager.d.ts +28 -0
  141. package/lib/pub-sub-manager/handler-manager.js +149 -0
  142. package/lib/pub-sub-manager/index.d.ts +3 -0
  143. package/lib/pub-sub-manager/index.js +25 -0
  144. package/lib/pub-sub-manager/memory-pub-sub-adapter.d.ts +21 -0
  145. package/lib/pub-sub-manager/memory-pub-sub-adapter.js +82 -0
  146. package/lib/pub-sub-manager/pub-sub-manager.d.ts +19 -0
  147. package/lib/pub-sub-manager/pub-sub-manager.js +108 -0
  148. package/lib/pub-sub-manager/types.d.ts +20 -0
  149. package/lib/pub-sub-manager/types.js +15 -0
  150. package/lib/sync-message-manager.d.ts +16 -0
  151. package/lib/sync-message-manager.js +112 -0
  152. package/package.json +58 -0
@@ -0,0 +1,878 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var application_exports = {};
30
+ __export(application_exports, {
31
+ Application: () => Application,
32
+ Logger: () => import_winston.Logger,
33
+ default: () => application_default
34
+ });
35
+ module.exports = __toCommonJS(application_exports);
36
+ var import_node_crypto = require("node:crypto");
37
+ var import_node_path = require("node:path");
38
+ var import_actions = require("@tachybase/actions");
39
+ var import_auth = require("@tachybase/auth");
40
+ var import_data_source = require("@tachybase/data-source");
41
+ var import_database = __toESM(require("@tachybase/database"));
42
+ var import_logger = require("@tachybase/logger");
43
+ var import_utils = require("@tachybase/utils");
44
+ var import_commander = require("commander");
45
+ var import_glob = require("glob");
46
+ var import_koa = __toESM(require("koa"));
47
+ var import_koa_compose = __toESM(require("koa-compose"));
48
+ var import_lodash = __toESM(require("lodash"));
49
+ var import_nanoid = require("nanoid");
50
+ var import_semver = __toESM(require("semver"));
51
+ var import_package = __toESM(require("../package.json"));
52
+ var import_acl = require("./acl");
53
+ var import_aes_encryptor = __toESM(require("./aes-encryptor"));
54
+ var import_app_command = require("./app-command");
55
+ var import_app_supervisor = require("./app-supervisor");
56
+ var import_cache2 = require("./cache");
57
+ var import_commands = require("./commands");
58
+ var import_cron_job_manager = require("./cron/cron-job-manager");
59
+ var import_environment = require("./environment");
60
+ var import_application_not_install = require("./errors/application-not-install");
61
+ var import_gateway = require("./gateway");
62
+ var import_helper = require("./helper");
63
+ var import_application_version = require("./helpers/application-version");
64
+ var import_locale = require("./locale");
65
+ var import_main_data_source = require("./main-data-source");
66
+ var import_middlewares = require("./middlewares");
67
+ var import_data_template = require("./middlewares/data-template");
68
+ var import_notice = require("./notice");
69
+ var import_plugin_manager = require("./plugin-manager");
70
+ var import_pub_sub_manager = require("./pub-sub-manager");
71
+ var import_sync_message_manager = require("./sync-message-manager");
72
+ var import_winston = require("winston");
73
+ const _Application = class _Application extends import_koa.default {
74
+ constructor(options) {
75
+ super();
76
+ this.options = options;
77
+ /**
78
+ * @internal
79
+ */
80
+ this.stopped = false;
81
+ /**
82
+ * @internal
83
+ */
84
+ this.ready = false;
85
+ /**
86
+ * @internal
87
+ */
88
+ this.activatedCommand = null;
89
+ /**
90
+ * @internal
91
+ */
92
+ this.running = false;
93
+ /**
94
+ * @internal
95
+ */
96
+ this.perfHistograms = /* @__PURE__ */ new Map();
97
+ this.plugins = /* @__PURE__ */ new Map();
98
+ this._appSupervisor = import_app_supervisor.AppSupervisor.getInstance();
99
+ this._authenticated = false;
100
+ this._maintaining = false;
101
+ this.currentId = (0, import_nanoid.nanoid)();
102
+ this.modules = {};
103
+ this.middlewareSourceMap = /* @__PURE__ */ new WeakMap();
104
+ // WebSocket 事件处理器集合
105
+ this.wsEventHandlers = {
106
+ close: /* @__PURE__ */ new Set(),
107
+ error: /* @__PURE__ */ new Set(),
108
+ message: /* @__PURE__ */ new Set(),
109
+ connection: /* @__PURE__ */ new Set()
110
+ };
111
+ this.context.reqId = (0, import_node_crypto.randomUUID)();
112
+ this.rawOptions = this.name === "main" ? import_lodash.default.cloneDeep(options) : {};
113
+ this.init();
114
+ this._appSupervisor.addApp(this);
115
+ this._noticeManager = new import_notice.NoticeManager(this);
116
+ this.setMaxListeners(100);
117
+ this.initWSEventHandlers();
118
+ }
119
+ get noticeManager() {
120
+ return this._noticeManager;
121
+ }
122
+ /**
123
+ * @internal
124
+ */
125
+ get loaded() {
126
+ return this._loaded;
127
+ }
128
+ /**
129
+ * @internal
130
+ */
131
+ get maintainingMessage() {
132
+ return this._maintainingMessage;
133
+ }
134
+ get environment() {
135
+ return this._env;
136
+ }
137
+ get aesEncryptor() {
138
+ return this._aesEncryptor;
139
+ }
140
+ get cronJobManager() {
141
+ return this._cronJobManager;
142
+ }
143
+ get mainDataSource() {
144
+ var _a;
145
+ return (_a = this.dataSourceManager) == null ? void 0 : _a.dataSources.get("main");
146
+ }
147
+ get db() {
148
+ if (!this.mainDataSource) {
149
+ return null;
150
+ }
151
+ return this.mainDataSource.collectionManager.db;
152
+ }
153
+ get logger() {
154
+ return this._logger;
155
+ }
156
+ get resourcer() {
157
+ return this.mainDataSource.resourceManager;
158
+ }
159
+ get cacheManager() {
160
+ return this._cacheManager;
161
+ }
162
+ get cache() {
163
+ return this._cache;
164
+ }
165
+ /**
166
+ * @internal
167
+ */
168
+ set cache(cache) {
169
+ this._cache = cache;
170
+ }
171
+ get cli() {
172
+ return this._cli;
173
+ }
174
+ get i18n() {
175
+ return this._i18n;
176
+ }
177
+ get pm() {
178
+ return this._pm;
179
+ }
180
+ get acl() {
181
+ return this.mainDataSource.acl;
182
+ }
183
+ get authManager() {
184
+ return this._authManager;
185
+ }
186
+ /**
187
+ * This method is deprecated and should not be used.
188
+ * Use {@link #localeManager} instead.
189
+ * @deprecated
190
+ */
191
+ get locales() {
192
+ return this._locales;
193
+ }
194
+ get localeManager() {
195
+ return this._locales;
196
+ }
197
+ get version() {
198
+ return this._version;
199
+ }
200
+ /**
201
+ * Use {@link logger}
202
+ * @deprecated
203
+ */
204
+ get log() {
205
+ return this._logger;
206
+ }
207
+ get name() {
208
+ return this.options.name || "main";
209
+ }
210
+ get dataSourceManager() {
211
+ return this._dataSourceManager;
212
+ }
213
+ /**
214
+ * @internal
215
+ */
216
+ getMaintaining() {
217
+ return this._maintainingCommandStatus;
218
+ }
219
+ /**
220
+ * @internal
221
+ */
222
+ setMaintaining(_maintainingCommandStatus) {
223
+ this._maintainingCommandStatus = _maintainingCommandStatus;
224
+ this.emit("maintaining", _maintainingCommandStatus);
225
+ if (_maintainingCommandStatus.status === "command_end") {
226
+ this._maintaining = false;
227
+ return;
228
+ }
229
+ this._maintaining = true;
230
+ }
231
+ /**
232
+ * @internal
233
+ */
234
+ setMaintainingMessage(message) {
235
+ this._maintainingMessage = message;
236
+ this.emit("maintainingMessageChanged", {
237
+ message: this._maintainingMessage,
238
+ maintainingStatus: this._maintainingCommandStatus
239
+ });
240
+ }
241
+ /**
242
+ * This method is deprecated and should not be used.
243
+ * Use {@link #this.version.get()} instead.
244
+ * @deprecated
245
+ */
246
+ getVersion() {
247
+ return import_package.default.version;
248
+ }
249
+ // @ts-ignore
250
+ use(middleware, options) {
251
+ this.middlewareSourceMap.set(middleware, (0, import_utils.getCurrentStacks)());
252
+ this.middleware.add(middleware, options);
253
+ return this;
254
+ }
255
+ /**
256
+ * @internal
257
+ */
258
+ callback() {
259
+ const fn = (0, import_koa_compose.default)(this.middleware.nodes);
260
+ if (!this.listenerCount("error")) this.on("error", this.onerror);
261
+ return (req, res) => {
262
+ const ctx = this.createContext(req, res);
263
+ return this.handleRequest(ctx, fn);
264
+ };
265
+ }
266
+ /**
267
+ * This method is deprecated and should not be used.
268
+ * Use {@link #this.db.collection()} instead.
269
+ * @deprecated
270
+ */
271
+ collection(options) {
272
+ return this.db.collection(options);
273
+ }
274
+ /**
275
+ * This method is deprecated and should not be used.
276
+ * Use {@link #this.resourcer.define()} instead.
277
+ * @deprecated
278
+ */
279
+ resource(options) {
280
+ return this.resourcer.define(options);
281
+ }
282
+ /**
283
+ * This method is deprecated and should not be used.
284
+ * Use {@link #this.resourcer.registerActions()} instead.
285
+ * @deprecated
286
+ */
287
+ actions(handlers, options) {
288
+ return this.resourcer.registerActions(handlers);
289
+ }
290
+ command(name, desc, opts) {
291
+ return this.cli.command(name, desc, opts).allowUnknownOption();
292
+ }
293
+ findCommand(name) {
294
+ return this.cli._findCommand(name);
295
+ }
296
+ /**
297
+ * @internal
298
+ */
299
+ async reInit() {
300
+ if (!this._loaded) {
301
+ return;
302
+ }
303
+ this.logger.info("app reinitializing");
304
+ if (this.cacheManager) {
305
+ await this.cacheManager.close();
306
+ }
307
+ if (this.pubSubManager) {
308
+ await this.pubSubManager.close();
309
+ }
310
+ const oldDb = this.db;
311
+ this.init();
312
+ if (!oldDb.closed()) {
313
+ await oldDb.close();
314
+ }
315
+ this._loaded = false;
316
+ }
317
+ async load(options) {
318
+ if (this._loaded) {
319
+ return;
320
+ }
321
+ if (options == null ? void 0 : options.reload) {
322
+ this.setMaintainingMessage("app reload");
323
+ this.logger.info(`app.reload()`, { method: "load" });
324
+ if (this.cacheManager) {
325
+ await this.cacheManager.close();
326
+ }
327
+ const oldDb = this.db;
328
+ this.init();
329
+ if (!oldDb.closed()) {
330
+ await oldDb.close();
331
+ }
332
+ }
333
+ this._aesEncryptor = await import_aes_encryptor.default.create(this);
334
+ this._cacheManager = await (0, import_cache2.createCacheManager)(this, this.options.cacheManager);
335
+ this.setMaintainingMessage("init plugins");
336
+ await this.pm.initPlugins();
337
+ this.setMaintainingMessage("start load");
338
+ this.setMaintainingMessage("emit beforeLoad");
339
+ if ((options == null ? void 0 : options.hooks) !== false) {
340
+ await this.emitAsync("beforeLoad", this, options);
341
+ }
342
+ await this.pm.load(options);
343
+ if (options == null ? void 0 : options.sync) {
344
+ await this.db.sync();
345
+ }
346
+ this.setMaintainingMessage("emit afterLoad");
347
+ if ((options == null ? void 0 : options.hooks) !== false) {
348
+ await this.emitAsync("afterLoad", this, options);
349
+ }
350
+ this._loaded = true;
351
+ }
352
+ async reload(options) {
353
+ this.logger.debug(`start reload`, { method: "reload" });
354
+ this._loaded = false;
355
+ await this.emitAsync("beforeReload", this, options);
356
+ await this.load({
357
+ ...options,
358
+ reload: true
359
+ });
360
+ this.logger.debug("emit afterReload", { method: "reload" });
361
+ this.setMaintainingMessage("emit afterReload");
362
+ await this.emitAsync("afterReload", this, options);
363
+ this.logger.debug(`finish reload`, { method: "reload" });
364
+ }
365
+ /**
366
+ * This method is deprecated and should not be used.
367
+ * Use {@link this.pm.get()} instead.
368
+ * @deprecated
369
+ */
370
+ getPlugin(name) {
371
+ return this.pm.get(name);
372
+ }
373
+ /**
374
+ * This method is deprecated and should not be used.
375
+ * Use {@link this.runAsCLI()} instead.
376
+ * @deprecated
377
+ */
378
+ async parse(argv = process.argv) {
379
+ return this.runAsCLI(argv);
380
+ }
381
+ async authenticate() {
382
+ if (this._authenticated) {
383
+ return;
384
+ }
385
+ this._authenticated = true;
386
+ await this.db.auth();
387
+ await this.db.checkVersion();
388
+ await this.db.prepare();
389
+ }
390
+ async runCommand(command, ...args) {
391
+ return await this.runAsCLI([command, ...args], { from: "user" });
392
+ }
393
+ async runCommandThrowError(command, ...args) {
394
+ return await this.runAsCLI([command, ...args], { from: "user", throwError: true });
395
+ }
396
+ createCLI() {
397
+ const command = new import_app_command.AppCommand("tachybase").usage("[command] [options]").hook("preAction", async (_2, actionCommand) => {
398
+ this._actionCommand = actionCommand;
399
+ this.activatedCommand = {
400
+ name: (0, import_helper.getCommandFullName)(actionCommand)
401
+ };
402
+ this.setMaintaining({
403
+ status: "command_begin",
404
+ command: this.activatedCommand
405
+ });
406
+ this.setMaintaining({
407
+ status: "command_running",
408
+ command: this.activatedCommand
409
+ });
410
+ if (actionCommand["_authenticate"]) {
411
+ await this.authenticate();
412
+ }
413
+ if (actionCommand["_preload"]) {
414
+ await this.load();
415
+ }
416
+ }).hook("postAction", async (_2, actionCommand) => {
417
+ var _a;
418
+ if (((_a = this._maintainingStatusBeforeCommand) == null ? void 0 : _a.error) && this._started) {
419
+ await this.restart();
420
+ }
421
+ });
422
+ command.exitOverride((err) => {
423
+ if (err instanceof import_commander.CommanderError && err.code === "commander.helpDisplayed" || err.code === "commander.help") {
424
+ return;
425
+ }
426
+ throw err;
427
+ });
428
+ return command;
429
+ }
430
+ /**
431
+ * @internal
432
+ */
433
+ async loadMigrations(options) {
434
+ const { directory, context, namespace } = options;
435
+ const migrations = {
436
+ beforeLoad: [],
437
+ afterSync: [],
438
+ afterLoad: []
439
+ };
440
+ const extensions = ["js", "ts"];
441
+ const patten = `${directory}/*.{${extensions.join(",")}}`;
442
+ const files = (0, import_glob.globSync)(patten, {
443
+ ignore: ["**/*.d.ts"]
444
+ }).filter((f) => !f.endsWith(".d.ts"));
445
+ const appVersion = await this.version.get();
446
+ for (const file of files) {
447
+ let filename = (0, import_node_path.basename)(file);
448
+ filename = filename.substring(0, filename.lastIndexOf(".")) || filename;
449
+ const Migration = await (0, import_utils.importModule)(file);
450
+ const m = new Migration({ app: this, db: this.db, ...context });
451
+ if (!m.appVersion || import_semver.default.satisfies(appVersion, m.appVersion, { includePrerelease: true })) {
452
+ m.name = `${filename}/${namespace}`;
453
+ migrations[m.on || "afterLoad"].push(m);
454
+ }
455
+ }
456
+ return migrations;
457
+ }
458
+ /**
459
+ * @internal
460
+ */
461
+ async loadCoreMigrations() {
462
+ const migrations = await this.loadMigrations({
463
+ directory: (0, import_node_path.resolve)(__dirname, "migrations"),
464
+ namespace: "@tego/core"
465
+ });
466
+ return {
467
+ beforeLoad: {
468
+ up: /* @__PURE__ */ __name(async () => {
469
+ this.logger.debug("run core migrations(beforeLoad)");
470
+ const migrator = this.db.createMigrator({ migrations: migrations.beforeLoad });
471
+ await migrator.up();
472
+ }, "up")
473
+ },
474
+ afterSync: {
475
+ up: /* @__PURE__ */ __name(async () => {
476
+ this.logger.debug("run core migrations(afterSync)");
477
+ const migrator = this.db.createMigrator({ migrations: migrations.afterSync });
478
+ await migrator.up();
479
+ }, "up")
480
+ },
481
+ afterLoad: {
482
+ up: /* @__PURE__ */ __name(async () => {
483
+ this.logger.debug("run core migrations(afterLoad)");
484
+ const migrator = this.db.createMigrator({ migrations: migrations.afterLoad });
485
+ await migrator.up();
486
+ }, "up")
487
+ }
488
+ };
489
+ }
490
+ /**
491
+ * @internal
492
+ */
493
+ async loadPluginCommands() {
494
+ this.logger.debug("load plugin commands");
495
+ await this.pm.loadCommands();
496
+ }
497
+ /**
498
+ * @internal
499
+ */
500
+ async runAsCLI(argv = process.argv, options) {
501
+ if (this.activatedCommand) {
502
+ return;
503
+ }
504
+ if (options.reqId) {
505
+ this.context.reqId = options.reqId;
506
+ this._logger = this._logger.child({ reqId: this.context.reqId });
507
+ }
508
+ this._maintainingStatusBeforeCommand = this._maintainingCommandStatus;
509
+ try {
510
+ const commandName = (options == null ? void 0 : options.from) === "user" ? argv[0] : argv[2];
511
+ if (!this.cli.hasCommand(commandName)) {
512
+ await this.pm.loadCommands();
513
+ }
514
+ const command = await this.cli.parseAsync(argv, options);
515
+ this.setMaintaining({
516
+ status: "command_end",
517
+ command: this.activatedCommand
518
+ });
519
+ return command;
520
+ } catch (error) {
521
+ this.logger.error("run command error", error);
522
+ if (!this.activatedCommand) {
523
+ this.activatedCommand = {
524
+ name: "unknown"
525
+ };
526
+ }
527
+ this.setMaintaining({
528
+ status: "command_error",
529
+ command: this.activatedCommand,
530
+ error
531
+ });
532
+ } finally {
533
+ const _actionCommand = this._actionCommand;
534
+ if (_actionCommand) {
535
+ const options2 = _actionCommand["options"];
536
+ _actionCommand["_optionValues"] = {};
537
+ _actionCommand["_optionValueSources"] = {};
538
+ _actionCommand["options"] = [];
539
+ for (const option of options2) {
540
+ _actionCommand.addOption(option);
541
+ }
542
+ }
543
+ this._actionCommand = null;
544
+ this.activatedCommand = null;
545
+ }
546
+ }
547
+ async start(options = {}) {
548
+ if (this._started) {
549
+ return;
550
+ }
551
+ this._started = true;
552
+ if (options.checkInstall && !await this.isInstalled()) {
553
+ throw new import_application_not_install.ApplicationNotInstall(
554
+ `Application ${this.name} is not installed, Please run 'pnpm tachybase install' command first`
555
+ );
556
+ }
557
+ this.setMaintainingMessage("starting app...");
558
+ if (this.db.closed()) {
559
+ await this.db.reconnect();
560
+ }
561
+ this.setMaintainingMessage("emit beforeStart");
562
+ await this.emitAsync("beforeStart", this, options);
563
+ this.setMaintainingMessage("emit afterStart");
564
+ await this.emitAsync("afterStart", this, options);
565
+ this.setMaintainingMessage("app started success!");
566
+ await this.emitStartedEvent(options);
567
+ this.stopped = false;
568
+ }
569
+ /**
570
+ * @internal
571
+ */
572
+ async emitStartedEvent(options = {}) {
573
+ await this.emitAsync("__started", this, {
574
+ maintainingStatus: import_lodash.default.cloneDeep(this._maintainingCommandStatus),
575
+ options
576
+ });
577
+ }
578
+ async isStarted() {
579
+ return this._started;
580
+ }
581
+ /**
582
+ * @internal
583
+ */
584
+ async tryReloadOrRestart(options = {}) {
585
+ if (this._started) {
586
+ await this.restart(options);
587
+ } else {
588
+ await this.reload(options);
589
+ }
590
+ }
591
+ async restart(options = {}) {
592
+ if (!this._started) {
593
+ return;
594
+ }
595
+ this.logger.info("restarting...");
596
+ this._started = false;
597
+ await this.emitAsync("beforeStop");
598
+ await this.reload(options);
599
+ await this.start(options);
600
+ this.emit("__restarted", this, options);
601
+ }
602
+ async stop(options = {}) {
603
+ const log = options.logging === false ? {
604
+ debug() {
605
+ },
606
+ warn() {
607
+ },
608
+ info() {
609
+ },
610
+ error() {
611
+ }
612
+ } : this.logger;
613
+ log.debug("stop app...", { method: "stop" });
614
+ this.setMaintainingMessage("stopping app...");
615
+ if (this.stopped) {
616
+ log.warn(`app is stopped`, { method: "stop" });
617
+ return;
618
+ }
619
+ await this.emitAsync("beforeStop", this, options);
620
+ try {
621
+ if (!this.db.closed()) {
622
+ log.info(`close db`, { method: "stop" });
623
+ await this.db.close();
624
+ }
625
+ } catch (e) {
626
+ log.error(e.message, { method: "stop", err: e.stack });
627
+ }
628
+ if (this.cacheManager) {
629
+ await this.cacheManager.close();
630
+ }
631
+ await this.emitAsync("afterStop", this, options);
632
+ this.stopped = true;
633
+ log.info(`app has stopped`, { method: "stop" });
634
+ this._started = false;
635
+ }
636
+ async destroy(options = {}) {
637
+ this.logger.debug("start destroy app", { method: "destory" });
638
+ this.setMaintainingMessage("destroying app...");
639
+ await this.emitAsync("beforeDestroy", this, options);
640
+ await this.stop(options);
641
+ this.logger.debug("emit afterDestroy", { method: "destory" });
642
+ await this.emitAsync("afterDestroy", this, options);
643
+ this.logger.debug("finish destroy app", { method: "destory" });
644
+ }
645
+ async isInstalled() {
646
+ return await this.db.collectionExistsInDb("applicationVersion") || await this.db.collectionExistsInDb("collections");
647
+ }
648
+ async install(options = {}) {
649
+ var _a;
650
+ const reinstall = options.clean || options.force;
651
+ if (reinstall) {
652
+ await this.db.clean({ drop: true });
653
+ }
654
+ if (await this.isInstalled()) {
655
+ this.logger.warn("app is installed");
656
+ return;
657
+ }
658
+ await this.reInit();
659
+ await this.db.sync();
660
+ await this.load({ hooks: false });
661
+ this.logger.debug("emit beforeInstall", { method: "install" });
662
+ this.setMaintainingMessage("call beforeInstall hook...");
663
+ await this.emitAsync("beforeInstall", this, options);
664
+ await this.pm.install();
665
+ await this.version.update();
666
+ this.logger.debug("emit afterInstall", { method: "install" });
667
+ this.setMaintainingMessage("call afterInstall hook...");
668
+ await this.emitAsync("afterInstall", this, options);
669
+ if ((_a = this._maintainingStatusBeforeCommand) == null ? void 0 : _a.error) {
670
+ return;
671
+ }
672
+ if (this._started) {
673
+ await this.restart();
674
+ }
675
+ }
676
+ async upgrade(options = {}) {
677
+ this.logger.info("upgrading...");
678
+ await this.reInit();
679
+ const migrator1 = await this.loadCoreMigrations();
680
+ await migrator1.beforeLoad.up();
681
+ await this.db.sync();
682
+ await migrator1.afterSync.up();
683
+ await this.pm.initPresetPlugins();
684
+ const migrator2 = await this.pm.loadPresetMigrations();
685
+ await migrator2.beforeLoad.up();
686
+ await this.pm.load();
687
+ await this.db.sync();
688
+ await migrator2.afterSync.up();
689
+ await this.pm.upgrade();
690
+ await this.pm.initOtherPlugins();
691
+ const migrator3 = await this.pm.loadOtherMigrations();
692
+ await migrator3.beforeLoad.up();
693
+ await this.load({ sync: true });
694
+ await migrator3.afterSync.up();
695
+ await this.pm.upgrade();
696
+ await migrator1.afterLoad.up();
697
+ await migrator2.afterLoad.up();
698
+ await migrator3.afterLoad.up();
699
+ await this.pm.repository.updateVersions();
700
+ await this.version.update();
701
+ await this.emitAsync("afterUpgrade", this, options);
702
+ await this.restart();
703
+ }
704
+ toJSON() {
705
+ return {
706
+ appName: this.name,
707
+ name: this.name
708
+ };
709
+ }
710
+ /**
711
+ * @internal
712
+ */
713
+ reInitEvents() {
714
+ for (const eventName of this.eventNames()) {
715
+ for (const listener of this.listeners(eventName)) {
716
+ if (listener["_reinitializable"]) {
717
+ this.removeListener(eventName, listener);
718
+ }
719
+ }
720
+ }
721
+ }
722
+ createLogger(options) {
723
+ const { dirname } = options;
724
+ return (0, import_logger.createLogger)({
725
+ ...options,
726
+ dirname: (0, import_logger.getLoggerFilePath)(this.name || "main", dirname || "")
727
+ });
728
+ }
729
+ init() {
730
+ var _a;
731
+ const options = this.options;
732
+ this._logger = (0, import_logger.createSystemLogger)({
733
+ dirname: (0, import_logger.getLoggerFilePath)(this.name),
734
+ filename: "system",
735
+ seperateError: true,
736
+ ...(_a = options.logger) == null ? void 0 : _a.system
737
+ }).child({
738
+ reqId: this.context.reqId,
739
+ app: this.name,
740
+ module: "application"
741
+ });
742
+ this.reInitEvents();
743
+ this.middleware = new import_utils.Toposort();
744
+ this.plugins = /* @__PURE__ */ new Map();
745
+ if (this.db) {
746
+ this.db.removeAllListeners();
747
+ }
748
+ this.createMainDataSource(options);
749
+ this._env = new import_environment.Environment();
750
+ this._cronJobManager = new import_cron_job_manager.CronJobManager(this);
751
+ this._cli = this.createCLI();
752
+ this._i18n = (0, import_helper.createI18n)(options);
753
+ this.pubSubManager = (0, import_pub_sub_manager.createPubSubManager)(this, options.pubSubManager);
754
+ this.syncMessageManager = new import_sync_message_manager.SyncMessageManager(this, options.syncMessageManager);
755
+ this.context.db = this.db;
756
+ this.context.resourcer = this.resourcer;
757
+ this.context.cacheManager = this._cacheManager;
758
+ this.context.cache = this._cache;
759
+ const plugins = this._pm ? this._pm.options.plugins : options.plugins;
760
+ this._pm = new import_plugin_manager.PluginManager({
761
+ app: this,
762
+ plugins: plugins || []
763
+ });
764
+ this._authManager = new import_auth.AuthManager({
765
+ authKey: "X-Authenticator",
766
+ default: "basic",
767
+ ...this.options.authManager
768
+ });
769
+ this.resource({
770
+ name: "auth",
771
+ actions: import_auth.actions
772
+ });
773
+ this._dataSourceManager.use(this._authManager.middleware(), { tag: "auth" });
774
+ this.resourcer.use(this._authManager.middleware(), { tag: "auth" });
775
+ if (this.options.acl !== false) {
776
+ this.resourcer.use(this.acl.middleware(), { tag: "acl", after: ["auth"] });
777
+ }
778
+ this._dataSourceManager.use(import_middlewares.parseVariables, {
779
+ group: "parseVariables",
780
+ after: "acl"
781
+ });
782
+ this._dataSourceManager.use(import_data_template.dataTemplate, { group: "dataTemplate", after: "acl" });
783
+ this._locales = new import_locale.Locale((0, import_helper.createAppProxy)(this));
784
+ if (options.perfHooks) {
785
+ (0, import_helper.enablePerfHooks)(this);
786
+ }
787
+ (0, import_helper.registerMiddlewares)(this, options);
788
+ if (options.registerActions !== false) {
789
+ (0, import_actions.registerActions)(this);
790
+ }
791
+ (0, import_commands.registerCli)(this);
792
+ this._version = new import_application_version.ApplicationVersion(this);
793
+ }
794
+ createMainDataSource(options) {
795
+ const mainDataSourceInstance = new import_main_data_source.MainDataSource({
796
+ name: "main",
797
+ database: this.createDatabase(options),
798
+ acl: (0, import_acl.createACL)(),
799
+ resourceManager: (0, import_helper.createResourcer)(options)
800
+ });
801
+ this._dataSourceManager = new import_data_source.DataSourceManager();
802
+ this.dataSourceManager.dataSources.set("main", mainDataSourceInstance);
803
+ }
804
+ createDatabase(options) {
805
+ const sqlLogger = this.createLogger({
806
+ filename: "sql",
807
+ level: "debug"
808
+ });
809
+ const logging = /* @__PURE__ */ __name((msg) => {
810
+ if (typeof msg === "string") {
811
+ msg = msg.replace(/[\r\n]/gm, "").replace(/\s+/g, " ");
812
+ }
813
+ if (msg.includes("INSERT INTO")) {
814
+ msg = msg.substring(0, 2e3) + "...";
815
+ }
816
+ sqlLogger.debug({ message: msg, app: this.name, reqId: this.context.reqId });
817
+ }, "logging");
818
+ const dbOptions = options.database instanceof import_database.default ? options.database.options : options.database;
819
+ const db = new import_database.default({
820
+ ...dbOptions,
821
+ logging: dbOptions.logging ? logging : false,
822
+ migrator: {
823
+ context: { app: this }
824
+ },
825
+ logger: this._logger.child({ module: "database" })
826
+ });
827
+ return db;
828
+ }
829
+ /**
830
+ * 初始化 WebSocket 事件处理
831
+ * 注册应用级别的事件,用于与 WSServer 通信
832
+ */
833
+ initWSEventHandlers() {
834
+ this.on("ws:registerEventHandler", ({ eventType, handler }) => {
835
+ this.registerWSEventHandler(eventType, handler);
836
+ });
837
+ this.on("ws:removeEventHandler", ({ eventType, handler }) => {
838
+ this.removeWSEventHandler(eventType, handler);
839
+ });
840
+ }
841
+ /**
842
+ * 为 WebSocket 事件注册处理函数
843
+ * 这是一个适配器方法,将事件处理函数注册到 Gateway 的 WSServer
844
+ * @param eventType 事件类型
845
+ * @param handler 事件处理函数
846
+ */
847
+ registerWSEventHandler(eventType, handler) {
848
+ const gateway = import_gateway.Gateway.getInstance();
849
+ const wsServer = gateway["wsServer"];
850
+ if (wsServer) {
851
+ wsServer.registerAppEventHandler(this.name, eventType, handler);
852
+ }
853
+ return this;
854
+ }
855
+ /**
856
+ * 移除 WebSocket 事件处理函数
857
+ * @param eventType 事件类型
858
+ * @param handler 事件处理函数
859
+ */
860
+ removeWSEventHandler(eventType, handler) {
861
+ const gateway = import_gateway.Gateway.getInstance();
862
+ const wsServer = gateway["wsServer"];
863
+ if (wsServer) {
864
+ wsServer.removeAppEventHandler(this.name, eventType, handler);
865
+ }
866
+ return this;
867
+ }
868
+ };
869
+ __name(_Application, "Application");
870
+ _Application.KEY_CORE_APP_PREFIX = "KEY_CORE_APP_";
871
+ let Application = _Application;
872
+ (0, import_utils.applyMixins)(Application, [import_utils.AsyncEmitter]);
873
+ var application_default = Application;
874
+ // Annotate the CommonJS export names for ESM import in node:
875
+ 0 && (module.exports = {
876
+ Application,
877
+ Logger
878
+ });