@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,56 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import http, { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { SystemLogger } from '@tachybase/logger';
4
+ import { Registry, Toposort, ToposortOptions } from '@tachybase/utils';
5
+ import { IPCSocketClient } from './ipc-socket-client';
6
+ import { IPCSocketServer } from './ipc-socket-server';
7
+ import { AppSelectorMiddleware, Handler, IncomingRequest, RunOptions, StartHttpServerOptions } from './types';
8
+ export declare class Gateway extends EventEmitter {
9
+ #private;
10
+ private static instance;
11
+ /**
12
+ * use main app as default app to handle request
13
+ */
14
+ selectorMiddlewares: Toposort<AppSelectorMiddleware>;
15
+ server: http.Server | null;
16
+ ipcSocketServer: IPCSocketServer | null;
17
+ private wsServer;
18
+ private socketPath;
19
+ private handlers;
20
+ loggers: Registry<SystemLogger>;
21
+ private constructor();
22
+ static getInstance(options?: any): Gateway;
23
+ destroy(): void;
24
+ reset(): void;
25
+ addAppSelectorMiddleware(middleware: AppSelectorMiddleware, options?: ToposortOptions): void;
26
+ getLogger(appName: string, res: ServerResponse): import("winston").Logger;
27
+ responseError(res: ServerResponse, error: {
28
+ status: number;
29
+ maintaining: boolean;
30
+ message: string;
31
+ code: string;
32
+ }): void;
33
+ responseErrorWithCode(code: any, res: any, options: any): void;
34
+ requestHandler(req: IncomingMessage, res: ServerResponse): Promise<void>;
35
+ getAppSelectorMiddlewares(): Toposort<AppSelectorMiddleware>;
36
+ getRequestHandleAppName(req: IncomingRequest): Promise<string>;
37
+ getCallback(): any;
38
+ watch(): Promise<void>;
39
+ run(options: RunOptions): Promise<void>;
40
+ isStart(): boolean;
41
+ get runAt(): string;
42
+ get runAtLoop(): string;
43
+ get port(): number;
44
+ get host(): string;
45
+ isHelp(): boolean;
46
+ getStartOptions(): import("commander").OptionValues;
47
+ start(options: StartHttpServerOptions): void;
48
+ startIPCSocketServer(): void;
49
+ startHttpServer(options: StartHttpServerOptions): void;
50
+ registerHandler(handler: Handler): void;
51
+ unregisterHandler(name: string): void;
52
+ tryConnectToIPCServer(): Promise<false | IPCSocketClient>;
53
+ getIPCSocketClient(): Promise<IPCSocketClient>;
54
+ close(): void;
55
+ static getIPCSocketClient(): Promise<false | IPCSocketClient>;
56
+ }
@@ -0,0 +1,408 @@
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 __typeError = (msg) => {
8
+ throw TypeError(msg);
9
+ };
10
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
33
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
34
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
35
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
36
+ var gateway_exports = {};
37
+ __export(gateway_exports, {
38
+ Gateway: () => Gateway
39
+ });
40
+ module.exports = __toCommonJS(gateway_exports);
41
+ var import_node_crypto = require("node:crypto");
42
+ var import_node_events = require("node:events");
43
+ var import_node_fs = __toESM(require("node:fs"));
44
+ var import_node_http = __toESM(require("node:http"));
45
+ var import_node_path = require("node:path");
46
+ var import_node_url = require("node:url");
47
+ var import_node_util = require("node:util");
48
+ var import_logger = require("@tachybase/logger");
49
+ var import_utils = require("@tachybase/utils");
50
+ var import_commander = require("commander");
51
+ var import_compression = __toESM(require("compression"));
52
+ var import_koa_compose = __toESM(require("koa-compose"));
53
+ var import_qs = __toESM(require("qs"));
54
+ var import_serve_handler = __toESM(require("serve-handler"));
55
+ var import_app_supervisor = require("../app-supervisor");
56
+ var import_plugin_manager = require("../plugin-manager");
57
+ var import_errors = require("./errors");
58
+ var import_ipc_socket_client = require("./ipc-socket-client");
59
+ var import_ipc_socket_server = require("./ipc-socket-server");
60
+ var import_ws_server = require("./ws-server");
61
+ var _port, _host;
62
+ const compress = (0, import_node_util.promisify)((0, import_compression.default)());
63
+ const _Gateway = class _Gateway extends import_node_events.EventEmitter {
64
+ constructor() {
65
+ super();
66
+ /**
67
+ * use main app as default app to handle request
68
+ */
69
+ this.selectorMiddlewares = new import_utils.Toposort();
70
+ this.server = null;
71
+ this.ipcSocketServer = null;
72
+ __privateAdd(this, _port, process.env.APP_PORT ? parseInt(process.env.APP_PORT) : null);
73
+ __privateAdd(this, _host, "0.0.0.0");
74
+ this.socketPath = (0, import_node_path.resolve)(process.cwd(), "storage", "gateway.sock");
75
+ this.handlers = /* @__PURE__ */ new Map();
76
+ this.loggers = new import_utils.Registry();
77
+ this.reset();
78
+ if (process.env.SOCKET_PATH) {
79
+ this.socketPath = (0, import_node_path.resolve)(process.cwd(), process.env.SOCKET_PATH);
80
+ }
81
+ }
82
+ static getInstance(options = {}) {
83
+ if (!_Gateway.instance) {
84
+ _Gateway.instance = new _Gateway();
85
+ }
86
+ return _Gateway.instance;
87
+ }
88
+ destroy() {
89
+ this.reset();
90
+ _Gateway.instance = null;
91
+ }
92
+ reset() {
93
+ this.selectorMiddlewares = new import_utils.Toposort();
94
+ this.addAppSelectorMiddleware(
95
+ async (ctx, next) => {
96
+ var _a;
97
+ const { req } = ctx;
98
+ const appName = (_a = import_qs.default.parse((0, import_node_url.parse)(req.url).query)) == null ? void 0 : _a.__appName;
99
+ if (appName) {
100
+ ctx.resolvedAppName = appName;
101
+ }
102
+ if (req.headers["x-app"]) {
103
+ ctx.resolvedAppName = req.headers["x-app"];
104
+ }
105
+ await next();
106
+ },
107
+ {
108
+ tag: "core",
109
+ group: "core"
110
+ }
111
+ );
112
+ if (this.server) {
113
+ this.server.close();
114
+ this.server = null;
115
+ }
116
+ if (this.ipcSocketServer) {
117
+ this.ipcSocketServer.close();
118
+ this.ipcSocketServer = null;
119
+ }
120
+ }
121
+ addAppSelectorMiddleware(middleware, options) {
122
+ if (this.selectorMiddlewares.nodes.some((existingFunc) => existingFunc.toString() === middleware.toString())) {
123
+ return;
124
+ }
125
+ this.selectorMiddlewares.add(middleware, options);
126
+ this.emit("appSelectorChanged");
127
+ }
128
+ getLogger(appName, res) {
129
+ const reqId = (0, import_node_crypto.randomUUID)();
130
+ res.setHeader("X-Request-Id", reqId);
131
+ let logger = this.loggers.get(appName);
132
+ if (logger) {
133
+ return logger.child({ reqId });
134
+ }
135
+ logger = (0, import_logger.createSystemLogger)({
136
+ dirname: (0, import_logger.getLoggerFilePath)(appName),
137
+ filename: "system",
138
+ defaultMeta: {
139
+ app: appName,
140
+ module: "gateway"
141
+ }
142
+ });
143
+ this.loggers.register(appName, logger);
144
+ return logger.child({ reqId });
145
+ }
146
+ responseError(res, error) {
147
+ res.setHeader("Content-Type", "application/json");
148
+ res.statusCode = error.status;
149
+ res.end(JSON.stringify({ error }));
150
+ }
151
+ responseErrorWithCode(code, res, options) {
152
+ const log = this.getLogger(options.appName, res);
153
+ const error = (0, import_errors.applyErrorWithArgs)((0, import_errors.getErrorWithCode)(code), options);
154
+ log.error(error.message, { method: "responseErrorWithCode", error });
155
+ this.responseError(res, error);
156
+ }
157
+ async requestHandler(req, res) {
158
+ var _a;
159
+ for (const handler2 of this.handlers.values()) {
160
+ if ((_a = req.url) == null ? void 0 : _a.startsWith(handler2.prefix)) {
161
+ return handler2.callback(req, res);
162
+ }
163
+ }
164
+ const { pathname } = (0, import_node_url.parse)(req.url);
165
+ const { PLUGIN_STATICS_PATH, APP_PUBLIC_PATH } = process.env;
166
+ if (pathname.endsWith("/__umi/api/bundle-status")) {
167
+ res.statusCode = 200;
168
+ res.end("ok");
169
+ return;
170
+ }
171
+ if (pathname.startsWith(APP_PUBLIC_PATH + "storage/uploads/")) {
172
+ req.url = req.url.substring(APP_PUBLIC_PATH.length - 1);
173
+ await compress(req, res);
174
+ return (0, import_serve_handler.default)(req, res, {
175
+ public: (0, import_node_path.resolve)(process.cwd()),
176
+ directoryListing: false
177
+ });
178
+ }
179
+ if (pathname.startsWith(PLUGIN_STATICS_PATH) && !pathname.includes("/server/")) {
180
+ await compress(req, res);
181
+ const packageName = (0, import_plugin_manager.getPackageNameByExposeUrl)(pathname);
182
+ const publicDir = (0, import_plugin_manager.getPackageDirByExposeUrl)(pathname);
183
+ const destination = pathname.replace(PLUGIN_STATICS_PATH, "").replace(packageName, "");
184
+ return (0, import_serve_handler.default)(req, res, {
185
+ public: publicDir,
186
+ rewrites: [
187
+ {
188
+ source: pathname,
189
+ destination
190
+ }
191
+ ]
192
+ });
193
+ }
194
+ if (!pathname.startsWith(process.env.API_BASE_PATH) && !pathname.startsWith(process.env.EXTENSION_UI_BASE_PATH)) {
195
+ req.url = req.url.substring(APP_PUBLIC_PATH.length - 1);
196
+ await compress(req, res);
197
+ return (0, import_serve_handler.default)(req, res, {
198
+ public: process.env.SERVE_PATH ? process.env.SERVE_PATH : `${process.env.APP_CLIENT_ROOT}/dist`,
199
+ rewrites: [{ source: "/**", destination: "/index.html" }]
200
+ });
201
+ }
202
+ const handleApp = await this.getRequestHandleAppName(req);
203
+ const log = this.getLogger(handleApp, res);
204
+ await import_app_supervisor.AppSupervisor.getInstance().getApp(handleApp);
205
+ let appStatus = import_app_supervisor.AppSupervisor.getInstance().getAppStatus(handleApp, "initializing");
206
+ if (appStatus === "not_found") {
207
+ log.warn(`app not found`, { method: "requestHandler" });
208
+ this.responseErrorWithCode("APP_NOT_FOUND", res, { appName: handleApp });
209
+ return;
210
+ }
211
+ if (appStatus === "initializing") {
212
+ this.responseErrorWithCode("APP_INITIALIZING", res, { appName: handleApp });
213
+ return;
214
+ }
215
+ if (appStatus === "initialized") {
216
+ const appInstance = await import_app_supervisor.AppSupervisor.getInstance().getApp(handleApp);
217
+ appInstance.runCommand("start", "--quickstart");
218
+ appStatus = import_app_supervisor.AppSupervisor.getInstance().getAppStatus(handleApp);
219
+ }
220
+ const app = await import_app_supervisor.AppSupervisor.getInstance().getApp(handleApp);
221
+ if (appStatus !== "running") {
222
+ log.warn(`app is not running`, { method: "requestHandler", status: appStatus });
223
+ this.responseErrorWithCode(`${appStatus}`, res, { app, appName: handleApp });
224
+ return;
225
+ }
226
+ if (req.url.endsWith("/__health_check")) {
227
+ res.statusCode = 200;
228
+ res.end("ok");
229
+ return;
230
+ }
231
+ if (handleApp !== "main") {
232
+ import_app_supervisor.AppSupervisor.getInstance().touchApp(handleApp);
233
+ }
234
+ app.callback()(req, res);
235
+ }
236
+ getAppSelectorMiddlewares() {
237
+ return this.selectorMiddlewares;
238
+ }
239
+ async getRequestHandleAppName(req) {
240
+ const appSelectorMiddlewares = this.selectorMiddlewares.sort();
241
+ const ctx = {
242
+ req,
243
+ resolvedAppName: null
244
+ };
245
+ await (0, import_koa_compose.default)(appSelectorMiddlewares)(ctx);
246
+ if (!ctx.resolvedAppName) {
247
+ ctx.resolvedAppName = "main";
248
+ }
249
+ return ctx.resolvedAppName;
250
+ }
251
+ getCallback() {
252
+ return this.requestHandler.bind(this);
253
+ }
254
+ async watch() {
255
+ if (!process.env.IS_DEV_CMD) {
256
+ return;
257
+ }
258
+ const file = (0, import_node_path.resolve)(process.cwd(), "storage/app.watch.ts");
259
+ if (!import_node_fs.default.existsSync(file)) {
260
+ await import_node_fs.default.promises.writeFile(file, `export const watchId = '${(0, import_utils.uid)()}';`, "utf-8");
261
+ }
262
+ require(file);
263
+ }
264
+ async run(options) {
265
+ const isStart = this.isStart();
266
+ let ipcClient;
267
+ if (isStart) {
268
+ await this.watch();
269
+ const startOptions = this.getStartOptions();
270
+ const port = startOptions.port || process.env.APP_PORT || 3e3;
271
+ const host = startOptions.host || process.env.APP_HOST || "0.0.0.0";
272
+ this.start({
273
+ port,
274
+ host
275
+ });
276
+ } else if (!this.isHelp()) {
277
+ ipcClient = await this.tryConnectToIPCServer();
278
+ if (ipcClient) {
279
+ const response = await ipcClient.write({ type: "passCliArgv", payload: { argv: process.argv } });
280
+ ipcClient.close();
281
+ if (!["error", "not_found"].includes(response.type)) {
282
+ return;
283
+ }
284
+ }
285
+ }
286
+ if (isStart || !ipcClient) {
287
+ await (0, import_utils.createStoragePluginsSymlink)();
288
+ }
289
+ const mainApp = import_app_supervisor.AppSupervisor.getInstance().bootMainApp(options.mainAppOptions);
290
+ mainApp.runAsCLI(process.argv, {
291
+ throwError: true,
292
+ from: "node"
293
+ }).then(async () => {
294
+ if (!isStart && !await mainApp.isStarted()) {
295
+ await mainApp.stop({ logging: false });
296
+ }
297
+ }).catch(async (e) => {
298
+ if (e.code !== "commander.helpDisplayed") {
299
+ mainApp.logger.error(e);
300
+ }
301
+ if (!isStart && !await mainApp.isStarted()) {
302
+ await mainApp.stop({ logging: false });
303
+ }
304
+ });
305
+ }
306
+ isStart() {
307
+ const argv = process.argv;
308
+ return argv[2] === "start";
309
+ }
310
+ get runAt() {
311
+ return `http://${__privateGet(this, _host)}:${__privateGet(this, _port)}`;
312
+ }
313
+ get runAtLoop() {
314
+ return `http://127.0.0.1:${__privateGet(this, _port)}`;
315
+ }
316
+ get port() {
317
+ return __privateGet(this, _port);
318
+ }
319
+ get host() {
320
+ return __privateGet(this, _host);
321
+ }
322
+ isHelp() {
323
+ const argv = process.argv;
324
+ return argv[2] === "help";
325
+ }
326
+ getStartOptions() {
327
+ const argv = process.argv;
328
+ const program = new import_commander.Command();
329
+ program.allowUnknownOption().option("-s, --silent").option("-p, --port [post]").option("-h, --host [host]").option("--db-sync").parse(process.argv);
330
+ const options = program.opts();
331
+ return options;
332
+ }
333
+ start(options) {
334
+ this.startHttpServer(options);
335
+ this.startIPCSocketServer();
336
+ }
337
+ startIPCSocketServer() {
338
+ this.ipcSocketServer = import_ipc_socket_server.IPCSocketServer.buildServer(this.socketPath);
339
+ }
340
+ startHttpServer(options) {
341
+ if ((options == null ? void 0 : options.port) !== null) {
342
+ __privateSet(this, _port, options.port);
343
+ }
344
+ if (options == null ? void 0 : options.host) {
345
+ __privateSet(this, _host, options.host);
346
+ }
347
+ if (__privateGet(this, _port) === null) {
348
+ console.log("gateway port is not set, http server will not start");
349
+ return;
350
+ }
351
+ this.server = import_node_http.default.createServer(this.getCallback());
352
+ this.wsServer = new import_ws_server.WSServer();
353
+ this.server.on("upgrade", (request, socket, head) => {
354
+ const { pathname } = (0, import_node_url.parse)(request.url);
355
+ if (pathname === process.env.WS_PATH) {
356
+ this.wsServer.wss.handleUpgrade(request, socket, head, (ws) => {
357
+ this.wsServer.wss.emit("connection", ws, request);
358
+ });
359
+ } else {
360
+ socket.destroy();
361
+ }
362
+ });
363
+ this.server.listen(__privateGet(this, _port), __privateGet(this, _host), () => {
364
+ console.log(`Gateway HTTP Server running at http://${__privateGet(this, _host)}:${__privateGet(this, _port)}/`);
365
+ if (options == null ? void 0 : options.callback) {
366
+ options.callback(this.server);
367
+ }
368
+ });
369
+ }
370
+ registerHandler(handler2) {
371
+ this.handlers.set(handler2.name, handler2);
372
+ }
373
+ unregisterHandler(name) {
374
+ this.handlers.delete(name);
375
+ }
376
+ async tryConnectToIPCServer() {
377
+ try {
378
+ const ipcClient = await this.getIPCSocketClient();
379
+ return ipcClient;
380
+ } catch (e) {
381
+ return false;
382
+ }
383
+ }
384
+ async getIPCSocketClient() {
385
+ return await import_ipc_socket_client.IPCSocketClient.getConnection(this.socketPath);
386
+ }
387
+ close() {
388
+ var _a, _b;
389
+ (_a = this.server) == null ? void 0 : _a.close();
390
+ (_b = this.wsServer) == null ? void 0 : _b.close();
391
+ }
392
+ static async getIPCSocketClient() {
393
+ const socketPath = (0, import_node_path.resolve)(process.cwd(), process.env.SOCKET_PATH || "storage/gateway.sock");
394
+ try {
395
+ return await import_ipc_socket_client.IPCSocketClient.getConnection(socketPath);
396
+ } catch (error) {
397
+ return false;
398
+ }
399
+ }
400
+ };
401
+ _port = new WeakMap();
402
+ _host = new WeakMap();
403
+ __name(_Gateway, "Gateway");
404
+ let Gateway = _Gateway;
405
+ // Annotate the CommonJS export names for ESM import in node:
406
+ 0 && (module.exports = {
407
+ Gateway
408
+ });
@@ -0,0 +1,2 @@
1
+ export { Gateway } from './gateway';
2
+ export { WSServer } from './ws-server';
@@ -0,0 +1,30 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var gateway_exports = {};
19
+ __export(gateway_exports, {
20
+ Gateway: () => import_gateway.Gateway,
21
+ WSServer: () => import_ws_server.WSServer
22
+ });
23
+ module.exports = __toCommonJS(gateway_exports);
24
+ var import_gateway = require("./gateway");
25
+ var import_ws_server = require("./ws-server");
26
+ // Annotate the CommonJS export names for ESM import in node:
27
+ 0 && (module.exports = {
28
+ Gateway,
29
+ WSServer
30
+ });
@@ -0,0 +1,17 @@
1
+ import * as events from 'node:events';
2
+ import net from 'node:net';
3
+ import { Logger } from '@tachybase/logger';
4
+ export declare const writeJSON: (socket: net.Socket, data: object) => void;
5
+ export declare class IPCSocketClient extends events.EventEmitter {
6
+ client: net.Socket;
7
+ logger: Logger;
8
+ constructor(client: net.Socket);
9
+ static getConnection(serverPath: string): Promise<IPCSocketClient>;
10
+ handleServerMessage({ reqId, type, payload }: {
11
+ reqId: any;
12
+ type: any;
13
+ payload: any;
14
+ }): Promise<void>;
15
+ close(): void;
16
+ write(data: any): Promise<unknown>;
17
+ }
@@ -0,0 +1,99 @@
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 ipc_socket_client_exports = {};
30
+ __export(ipc_socket_client_exports, {
31
+ IPCSocketClient: () => IPCSocketClient,
32
+ writeJSON: () => writeJSON
33
+ });
34
+ module.exports = __toCommonJS(ipc_socket_client_exports);
35
+ var events = __toESM(require("node:events"));
36
+ var import_node_net = __toESM(require("node:net"));
37
+ var import_logger = require("@tachybase/logger");
38
+ var import_xpipe = __toESM(require("xpipe"));
39
+ const writeJSON = /* @__PURE__ */ __name((socket, data) => {
40
+ socket.write(JSON.stringify(data) + "\n", "utf8");
41
+ }, "writeJSON");
42
+ const _IPCSocketClient = class _IPCSocketClient extends events.EventEmitter {
43
+ constructor(client) {
44
+ super();
45
+ this.logger = (0, import_logger.createConsoleLogger)();
46
+ this.client = client;
47
+ this.client.on("data", (data) => {
48
+ const dataAsString = data.toString();
49
+ const messages = dataAsString.split("\n");
50
+ for (const message of messages) {
51
+ if (message.length === 0) {
52
+ continue;
53
+ }
54
+ const dataObj = JSON.parse(message);
55
+ this.handleServerMessage(dataObj);
56
+ }
57
+ });
58
+ }
59
+ static async getConnection(serverPath) {
60
+ return new Promise((resolve, reject) => {
61
+ const client = import_node_net.default.createConnection({ path: import_xpipe.default.eq(serverPath) }, () => {
62
+ resolve(new _IPCSocketClient(client));
63
+ });
64
+ client.on("error", (err) => {
65
+ reject(err);
66
+ });
67
+ });
68
+ }
69
+ async handleServerMessage({ reqId, type, payload }) {
70
+ switch (type) {
71
+ case "not_found":
72
+ break;
73
+ case "error":
74
+ this.logger.error({ reqId, message: `${payload.message}|${payload.stack}` });
75
+ break;
76
+ case "success":
77
+ this.logger.info({ reqId, message: "success" });
78
+ break;
79
+ default:
80
+ this.logger.info({ reqId, message: JSON.stringify({ type, payload }) });
81
+ break;
82
+ }
83
+ this.emit("response", { reqId, type, payload });
84
+ }
85
+ close() {
86
+ this.client.end();
87
+ }
88
+ write(data) {
89
+ writeJSON(this.client, data);
90
+ return new Promise((resolve) => this.once("response", resolve));
91
+ }
92
+ };
93
+ __name(_IPCSocketClient, "IPCSocketClient");
94
+ let IPCSocketClient = _IPCSocketClient;
95
+ // Annotate the CommonJS export names for ESM import in node:
96
+ 0 && (module.exports = {
97
+ IPCSocketClient,
98
+ writeJSON
99
+ });
@@ -0,0 +1,12 @@
1
+ import net from 'node:net';
2
+ export declare class IPCSocketServer {
3
+ socketServer: net.Server;
4
+ constructor(server: net.Server);
5
+ static buildServer(socketPath: string): IPCSocketServer;
6
+ static handleClientMessage({ reqId, type, payload }: {
7
+ reqId: any;
8
+ type: any;
9
+ payload: any;
10
+ }): Promise<string | false | import("../app-command").AppCommand>;
11
+ close(): void;
12
+ }