@eggjs/mock 7.0.0-beta.19 → 7.0.0-beta.20

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/dist/agent-BKYkjoCx.js +111 -0
  2. package/dist/agent-CHCe8tnW.d.ts +24 -0
  3. package/dist/agent-DZ_fHoxJ.js +48 -0
  4. package/dist/agent_handler-DeUtoRVT.js +26 -0
  5. package/dist/app/extend/agent.d.ts +1 -1
  6. package/dist/app/extend/agent.js +3 -46
  7. package/dist/app/extend/application.d.ts +4 -174
  8. package/dist/app/extend/application.js +7 -383
  9. package/dist/app-6Bn3F5Uw.js +252 -0
  10. package/dist/app-CoypamK1.js +99 -0
  11. package/dist/app-l47a-gqT.d.ts +7 -0
  12. package/dist/app_handler-CkiK6fyC.js +55 -0
  13. package/dist/app_handler-Gp5J9X-v.d.ts +9 -0
  14. package/dist/application-BPpvw5dg.d.ts +175 -0
  15. package/dist/application-LrKwuOKn.js +385 -0
  16. package/dist/bootstrap.d.ts +9 -3
  17. package/dist/bootstrap.js +20 -3
  18. package/dist/cluster-CA_hr9eV.js +283 -0
  19. package/dist/cluster-RTfUwmUd.d.ts +126 -0
  20. package/dist/context-BIduDy1M.js +10 -0
  21. package/dist/format_options-LRnReKde.js +65 -0
  22. package/dist/index-BtBMDZg8.d.ts +78 -0
  23. package/dist/index.d.ts +10 -81
  24. package/dist/index.js +20 -45
  25. package/dist/inject_context-BxpcF-ds.js +106 -0
  26. package/dist/inject_mocha-BVf8v6El.js +38 -0
  27. package/dist/inject_mocha-Daf1Aj8M.d.ts +1 -0
  28. package/dist/inject_mocha.d.ts +1 -1
  29. package/dist/inject_mocha.js +21 -32
  30. package/dist/lib/agent_handler.d.ts +4 -1
  31. package/dist/lib/agent_handler.js +7 -24
  32. package/dist/lib/app.d.ts +5 -6
  33. package/dist/lib/app.js +12 -252
  34. package/dist/lib/app_handler.d.ts +5 -8
  35. package/dist/lib/app_handler.js +19 -54
  36. package/dist/lib/cluster.d.ts +5 -125
  37. package/dist/lib/cluster.js +5 -281
  38. package/dist/lib/context.js +1 -8
  39. package/dist/lib/format_options.d.ts +2 -2
  40. package/dist/lib/format_options.js +2 -63
  41. package/dist/lib/inject_context.js +20 -104
  42. package/dist/lib/mock_agent.js +1 -43
  43. package/dist/lib/mock_custom_loader.js +1 -33
  44. package/dist/lib/mock_http_server.js +1 -15
  45. package/dist/lib/mock_httpclient.d.ts +1 -39
  46. package/dist/lib/mock_httpclient.js +2 -108
  47. package/dist/lib/parallel/agent.d.ts +4 -23
  48. package/dist/lib/parallel/agent.js +6 -109
  49. package/dist/lib/parallel/app.d.ts +3 -2
  50. package/dist/lib/parallel/app.js +7 -97
  51. package/dist/lib/parallel/util.d.ts +1 -5
  52. package/dist/lib/parallel/util.js +2 -57
  53. package/dist/lib/restore.d.ts +1 -3
  54. package/dist/lib/restore.js +7 -14
  55. package/dist/lib/supertest.d.ts +1 -15
  56. package/dist/lib/supertest.js +3 -37
  57. package/dist/lib/types.d.ts +3 -76
  58. package/dist/lib/types.js +2 -0
  59. package/dist/lib/utils.js +1 -38
  60. package/dist/mock_agent-CxT7Q0_N.js +45 -0
  61. package/dist/mock_custom_loader-f_tHRojG.js +35 -0
  62. package/dist/mock_http_server-De0r07gr.js +17 -0
  63. package/dist/mock_httpclient-1EgQkMxi.d.ts +40 -0
  64. package/dist/mock_httpclient-B6UVI7GS.js +110 -0
  65. package/dist/register.d.ts +2 -0
  66. package/dist/register.js +22 -4
  67. package/dist/restore-BL0cE0KG.d.ts +4 -0
  68. package/dist/restore-CVQYXquh.js +16 -0
  69. package/dist/src-D22EjdGo.js +47 -0
  70. package/dist/supertest-BIds28yL.d.ts +16 -0
  71. package/dist/supertest-Cg412Los.js +39 -0
  72. package/dist/types-CPNMyF89.js +1 -0
  73. package/dist/types-CjZ-JeCo.d.ts +75 -0
  74. package/dist/util-1xYBaaoh.d.ts +6 -0
  75. package/dist/util-BpppqTXv.js +59 -0
  76. package/dist/utils-MhP_Krx1.js +40 -0
  77. package/package.json +6 -7
  78. package/dist/_virtual/rolldown_runtime.js +0 -7
@@ -1,385 +1,9 @@
1
- import { request } from "../../lib/supertest.js";
2
- import { getMockAgent, restoreMockAgent } from "../../lib/mock_agent.js";
3
- import { createMockHttpClient } from "../../lib/mock_httpclient.js";
4
- import { Application } from "egg";
5
- import assert from "node:assert";
6
- import { mock, restore } from "mm";
7
- import { debuglog } from "node:util";
8
- import fs from "node:fs";
9
- import http, { IncomingMessage } from "node:http";
10
- import mergeDescriptors from "merge-descriptors";
11
- import { isAsyncFunction, isObject } from "is-type-of";
12
- import { Logger, Transport } from "egg-logger";
1
+ import "../../mock_http_server-De0r07gr.js";
2
+ import "../../utils-MhP_Krx1.js";
3
+ import "../../supertest-Cg412Los.js";
4
+ import "../../mock_agent-CxT7Q0_N.js";
5
+ import "../../mock_httpclient-B6UVI7GS.js";
6
+ import "../../types-CPNMyF89.js";
7
+ import { ApplicationUnittest } from "../../application-LrKwuOKn.js";
13
8
 
14
- //#region src/app/extend/application.ts
15
- const debug = debuglog("egg/mock/app/extend/application");
16
- const ORIGIN_TYPES = Symbol("@eggjs/mock originTypes");
17
- const BACKGROUND_TASKS = Symbol("Application#backgroundTasks");
18
- const REUSED_CTX = Symbol("Context#reusedInSuite");
19
- var ApplicationUnittest = class extends Application {
20
- _mockHttpClient;
21
- /**
22
- * mock Context
23
- * @function App#mockContext
24
- * @param {Object} data - ctx data
25
- * @param {Object} [options] - mock ctx options
26
- * @example
27
- * ```js
28
- * const ctx = app.mockContext({
29
- * user: {
30
- * name: 'Jason'
31
- * }
32
- * });
33
- * console.log(ctx.user.name); // Jason
34
- *
35
- * // controller
36
- * module.exports = function*() {
37
- * this.body = this.user.name;
38
- * };
39
- * ```
40
- */
41
- mockContext(data, options) {
42
- data = data ?? {};
43
- function mockRequest(req$1) {
44
- for (const key in data?.headers) {
45
- mock(req$1.headers, key, data.headers[key]);
46
- mock(req$1.headers, key.toLowerCase(), data.headers[key]);
47
- }
48
- }
49
- const mockCtxStorage = this.options.mockCtxStorage ?? true;
50
- options = Object.assign({ mockCtxStorage }, options);
51
- if ("_customMockContext" in this && typeof this._customMockContext === "function") this._customMockContext(data);
52
- for (const key in data) mock(this.context, key, data[key]);
53
- const req = this.mockRequest(data);
54
- const res = new http.ServerResponse(req);
55
- if (options.reuseCtxStorage !== false) {
56
- if (this.currentContext && !this.currentContext[REUSED_CTX]) {
57
- mockRequest(this.currentContext.request.req);
58
- this.currentContext[REUSED_CTX] = true;
59
- return this.currentContext;
60
- }
61
- }
62
- const ctx = this.createContext(req, res);
63
- if (options.mockCtxStorage) mock(this.ctxStorage, "getStore", () => ctx);
64
- return ctx;
65
- }
66
- async mockContextScope(fn, data) {
67
- const ctx = this.mockContext(data, {
68
- mockCtxStorage: false,
69
- reuseCtxStorage: false
70
- });
71
- return await this.ctxStorage.run(ctx, async () => {
72
- return await fn(ctx);
73
- });
74
- }
75
- /**
76
- * mock cookie session
77
- * @function App#mockSession
78
- * @param {Object} data - session object
79
- */
80
- mockSession(data) {
81
- if (!data) return this;
82
- if (isObject(data) && !("save" in data)) Object.defineProperty(data, "save", {
83
- value: () => {},
84
- enumerable: false
85
- });
86
- mock(this.context, "session", data);
87
- return this;
88
- }
89
- /**
90
- * Mock service
91
- * @function App#mockService
92
- * @param {String} service - name
93
- * @param {String} methodName - method
94
- * @param {Object|Function|Error} fn - mock you data
95
- */
96
- mockService(service, methodName, fn) {
97
- if (typeof service === "string") {
98
- const splits = service.split(".");
99
- service = this.serviceClasses;
100
- for (const key of splits) service = service[key];
101
- service = service.prototype || service;
102
- }
103
- this._mockFn(service, methodName, fn);
104
- return this;
105
- }
106
- /**
107
- * mock service that return error
108
- * @function App#mockServiceError
109
- * @param {String} service - name
110
- * @param {String} methodName - method
111
- * @param {Error} [err] - error information
112
- */
113
- mockServiceError(service, methodName, err) {
114
- if (typeof err === "string") err = new Error(err);
115
- if (!err) err = /* @__PURE__ */ new Error(`mock ${methodName} error`);
116
- this.mockService(service, methodName, err);
117
- return this;
118
- }
119
- _mockFn(obj, name, data) {
120
- const origin = obj[name];
121
- assert(typeof origin === "function", `property ${name} in original object must be function`);
122
- if (!obj[ORIGIN_TYPES]) obj[ORIGIN_TYPES] = {};
123
- let type = obj[ORIGIN_TYPES][name];
124
- if (!type) type = obj[ORIGIN_TYPES][name] = isAsyncFunction(origin) ? "async" : "sync";
125
- if (typeof data === "function") {
126
- const fn = data;
127
- if (type === "async" && !isAsyncFunction(fn)) {
128
- mock(obj, name, function(...args) {
129
- return new Promise((resolve) => {
130
- resolve(fn.apply(this, args));
131
- });
132
- });
133
- return;
134
- }
135
- mock(obj, name, fn);
136
- return;
137
- }
138
- if (type === "async") {
139
- mock(obj, name, () => {
140
- return new Promise((resolve, reject) => {
141
- if (data instanceof Error) return reject(data);
142
- resolve(data);
143
- });
144
- });
145
- return;
146
- }
147
- mock(obj, name, () => {
148
- if (data instanceof Error) throw data;
149
- return data;
150
- });
151
- }
152
- /**
153
- * mock request
154
- * @function App#mockRequest
155
- * @param {Request} req - mock request
156
- */
157
- mockRequest(req) {
158
- req = { ...req };
159
- const headers = req.headers ?? {};
160
- for (const key in req.headers) headers[key.toLowerCase()] = req.headers[key];
161
- if (!headers["x-forwarded-for"]) headers["x-forwarded-for"] = "127.0.0.1";
162
- headers["x-mock-request-from"] = "@eggjs/mock";
163
- req.headers = headers;
164
- mergeDescriptors(req, {
165
- query: {},
166
- querystring: "",
167
- host: "127.0.0.1",
168
- hostname: "127.0.0.1",
169
- protocol: "http",
170
- secure: "false",
171
- method: "GET",
172
- url: "/",
173
- path: "/",
174
- socket: {
175
- remoteAddress: "127.0.0.1",
176
- remotePort: 7001
177
- }
178
- });
179
- return req;
180
- }
181
- /**
182
- * mock cookies
183
- * @function App#mockCookies
184
- */
185
- mockCookies(cookies) {
186
- if (!cookies) return this;
187
- const createContext = this.createContext;
188
- mock(this, "createContext", function(req, res) {
189
- const ctx = createContext.call(this, req, res);
190
- const getCookie = ctx.cookies.get;
191
- mock(ctx.cookies, "get", function(key, opts) {
192
- if (cookies[key]) return cookies[key];
193
- return getCookie.call(this, key, opts);
194
- });
195
- return ctx;
196
- });
197
- return this;
198
- }
199
- /**
200
- * mock header
201
- * @function App#mockHeaders
202
- */
203
- mockHeaders(headers) {
204
- if (!headers) return this;
205
- const getHeader = this.request.get;
206
- mock(this.request, "get", function(field) {
207
- const value = findHeaders(headers, field);
208
- if (value) return value;
209
- return getHeader.call(this, field);
210
- });
211
- return this;
212
- }
213
- /**
214
- * mock csrf
215
- * @function App#mockCsrf
216
- * @since 1.11
217
- */
218
- mockCsrf() {
219
- mock(this.context, "assertCSRF", () => {});
220
- mock(this.context, "assertCsrf", () => {});
221
- return this;
222
- }
223
- /**
224
- * mock httpclient
225
- * @alias mockHttpClient
226
- * @function App#mockHttpclient
227
- */
228
- mockHttpclient(mockUrl, mockMethod, mockResult) {
229
- return this.mockHttpClient(mockUrl, mockMethod, mockResult);
230
- }
231
- /**
232
- * mock httpclient
233
- * @function App#mockHttpClient
234
- */
235
- mockHttpClient(mockUrl, mockMethod, mockResult) {
236
- if (!this._mockHttpClient) this._mockHttpClient = createMockHttpClient(this);
237
- this._mockHttpClient(mockUrl, mockMethod, mockResult);
238
- return this;
239
- }
240
- /**
241
- * @deprecated Please use app.mockHttpClient instead of app.mockUrllib
242
- */
243
- mockUrllib(mockUrl, mockMethod, mockResult) {
244
- this.deprecate("[@eggjs/mock] Please use app.mockHttpClient instead of app.mockUrllib");
245
- return this.mockHttpClient(mockUrl, mockMethod, mockResult);
246
- }
247
- /**
248
- * get mock httpclient agent
249
- * @function App#mockHttpclientAgent
250
- */
251
- mockAgent() {
252
- return getMockAgent(this);
253
- }
254
- async mockAgentRestore() {
255
- await restoreMockAgent();
256
- }
257
- /**
258
- * @see mm#restore
259
- * @function App#mockRestore
260
- */
261
- async mockRestore() {
262
- await this.mockAgentRestore();
263
- restore();
264
- }
265
- /**
266
- * @see mm
267
- * @function App#mm
268
- */
269
- get mm() {
270
- return mock;
271
- }
272
- /**
273
- * override loadAgent
274
- * @function App#loadAgent
275
- */
276
- loadAgent() {}
277
- /**
278
- * mock serverEnv
279
- * @function App#mockEnv
280
- * @param {String} env - serverEnv
281
- */
282
- mockEnv(env) {
283
- mock(this.config, "env", env);
284
- mock(this.config, "serverEnv", env);
285
- debug("mock env: %o", env);
286
- return this;
287
- }
288
- /**
289
- * http request helper
290
- * @function App#httpRequest
291
- * @return {SupertestRequest} req - supertest request
292
- * @see https://github.com/visionmedia/supertest
293
- */
294
- httpRequest() {
295
- return request(this);
296
- }
297
- /**
298
- * collection logger message, then can be use on `expectLog()`
299
- * @param {String|Logger} [logger] - logger instance, default is `app.logger`
300
- * @function App#mockLog
301
- */
302
- mockLog(logger) {
303
- logger = logger ?? this.logger;
304
- if (typeof logger === "string") logger = this.getLogger(logger);
305
- if ("_mockLogs" in logger && logger._mockLogs) return;
306
- const transport = new Transport(logger.options);
307
- const log = logger.log;
308
- const mockLogs = [];
309
- mock(logger, "_mockLogs", mockLogs);
310
- mock(logger, "log", (level, args, meta) => {
311
- const message = transport.log(level, args, meta);
312
- mockLogs.push(message);
313
- log.apply(logger, [
314
- level,
315
- args,
316
- meta
317
- ]);
318
- });
319
- }
320
- __checkExpectLog(expectOrNot, str, logger) {
321
- logger = logger || this.logger;
322
- if (typeof logger === "string") logger = this.getLogger(logger);
323
- const filepath = logger.options.file;
324
- let content;
325
- if ("_mockLogs" in logger && logger._mockLogs) content = logger._mockLogs.join("\n");
326
- else content = fs.readFileSync(filepath, "utf8");
327
- let match;
328
- let type;
329
- if (str instanceof RegExp) {
330
- match = str.test(content);
331
- type = "RegExp";
332
- } else {
333
- match = content.includes(String(str));
334
- type = "String";
335
- }
336
- if (expectOrNot) assert(match, `Can't find ${type}:"${str}" in ${filepath}, log content: ...${content.substring(content.length - 500)}`);
337
- else assert(!match, `Find ${type}:"${str}" in ${filepath}, log content: ...${content.substring(content.length - 500)}`);
338
- }
339
- /**
340
- * expect str/regexp in the logger, if your server disk is slow, please call `mockLog()` first.
341
- * @param {String|RegExp} str - test str or regexp
342
- * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
343
- * @function App#expectLog
344
- */
345
- expectLog(str, logger) {
346
- this.__checkExpectLog(true, str, logger);
347
- }
348
- /**
349
- * not expect str/regexp in the logger, if your server disk is slow, please call `mockLog()` first.
350
- * @param {String|RegExp} str - test str or regexp
351
- * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
352
- * @function App#notExpectLog
353
- */
354
- notExpectLog(str, logger) {
355
- this.__checkExpectLog(false, str, logger);
356
- }
357
- async backgroundTasksFinished() {
358
- const tasks = this._backgroundTasks;
359
- debug("waiting %d background tasks", tasks.length);
360
- if (tasks.length === 0) return;
361
- this._backgroundTasks = [];
362
- await Promise.all(tasks);
363
- debug("finished %d background tasks", tasks.length);
364
- if (this._backgroundTasks.length) {
365
- debug("new background tasks created: %s", this._backgroundTasks.length);
366
- await this.backgroundTasksFinished();
367
- }
368
- }
369
- get _backgroundTasks() {
370
- if (!this[BACKGROUND_TASKS]) this[BACKGROUND_TASKS] = [];
371
- return this[BACKGROUND_TASKS];
372
- }
373
- set _backgroundTasks(tasks) {
374
- this[BACKGROUND_TASKS] = tasks;
375
- }
376
- };
377
- function findHeaders(headers, key) {
378
- if (!headers || !key) return null;
379
- key = key.toLowerCase();
380
- for (const headerKey in headers) if (key === headerKey.toLowerCase()) return headers[headerKey];
381
- return null;
382
- }
383
-
384
- //#endregion
385
9
  export { ApplicationUnittest as default };
@@ -0,0 +1,252 @@
1
+ import { createServer } from "./mock_http_server-De0r07gr.js";
2
+ import { getProperty, getSourceDirname, rimraf, sleep } from "./utils-MhP_Krx1.js";
3
+ import { formatOptions } from "./format_options-LRnReKde.js";
4
+ import { context } from "./context-BIduDy1M.js";
5
+ import { setCustomLoader } from "./mock_custom_loader-f_tHRojG.js";
6
+ import { strict } from "node:assert";
7
+ import path from "node:path";
8
+ import { debuglog } from "node:util";
9
+ import os from "node:os";
10
+ import { importModule } from "@eggjs/utils";
11
+ import { Base } from "sdk-base";
12
+ import { detectPort } from "detect-port";
13
+
14
+ //#region src/lib/app.ts
15
+ const debug = debuglog("egg/mock/lib/app");
16
+ const apps = /* @__PURE__ */ new Map();
17
+ const APP_INIT = Symbol("appInit");
18
+ const MESSENGER = Symbol("messenger");
19
+ const MOCK_APP_METHOD = [
20
+ "ready",
21
+ "closed",
22
+ "isClosed",
23
+ "close",
24
+ "_agent",
25
+ "_app",
26
+ "on",
27
+ "once",
28
+ "then"
29
+ ];
30
+ var MockApplicationWorker = class extends Base {
31
+ _agent;
32
+ _app;
33
+ baseDir;
34
+ [APP_INIT] = false;
35
+ _initOnListeners;
36
+ _initOnceListeners;
37
+ constructor(options) {
38
+ super({
39
+ initMethod: "_init",
40
+ ...options
41
+ });
42
+ this.baseDir = options.baseDir;
43
+ this._initOnListeners = /* @__PURE__ */ new Set();
44
+ this._initOnceListeners = /* @__PURE__ */ new Set();
45
+ }
46
+ async _init() {
47
+ if (this.options.beforeInit) {
48
+ await this.options.beforeInit(this);
49
+ this.options.beforeInit = void 0;
50
+ }
51
+ if (this.options.clean !== false) {
52
+ const logDir = path.join(this.options.baseDir, "logs");
53
+ try {
54
+ if (os.platform() === "win32") await sleep(1e3);
55
+ await rimraf(logDir);
56
+ } catch (err) {
57
+ console.error(`remove log dir ${logDir} failed: ${err.stack}`);
58
+ }
59
+ const runDir = path.join(this.options.baseDir, "run");
60
+ try {
61
+ if (os.platform() === "win32") await sleep(1e3);
62
+ await rimraf(runDir);
63
+ } catch (err) {
64
+ console.error(`remove run dir ${runDir} failed: ${err.stack}`);
65
+ }
66
+ }
67
+ this.options.clusterPort = await detectPort();
68
+ debug("[init] options: %o", this.options);
69
+ const egg = await importModule(this.options.framework);
70
+ strict(egg.Agent, `should export Agent class from framework ${this.options.framework}`);
71
+ const Agent = egg.Agent;
72
+ const agent = this._agent = new Agent({ ...this.options });
73
+ debug("agent instantiate");
74
+ await agent.ready();
75
+ debug("agent ready");
76
+ const app = this._app = new (bindMessenger(egg.Application, agent))({ ...this.options });
77
+ app.agent = agent;
78
+ Reflect.set(agent, "app", app);
79
+ Object.assign(app.context, context);
80
+ debug("app instantiate");
81
+ this[APP_INIT] = true;
82
+ debug("this[APP_INIT] = true");
83
+ this.#bindEvent();
84
+ debug("http server instantiate");
85
+ createServer(app);
86
+ await app.ready();
87
+ setCustomLoader(app);
88
+ const msg = {
89
+ action: "egg-ready",
90
+ data: this.options
91
+ };
92
+ app.messenger.onMessage(msg);
93
+ agent.messenger.onMessage(msg);
94
+ debug("app ready");
95
+ }
96
+ #bindEvent() {
97
+ debug("bind cache events to app");
98
+ for (const args of this._initOnListeners) {
99
+ debug("on(%s), use cache and pass to app", args);
100
+ this._app.on(args[0], args[1]);
101
+ this.removeListener(args[0], args[1]);
102
+ }
103
+ for (const args of this._initOnceListeners) {
104
+ debug("once(%s), use cache and pass to app", args);
105
+ this._app.once(args[0], args[1]);
106
+ this.removeListener(args[0], args[1]);
107
+ }
108
+ }
109
+ on(...args) {
110
+ if (this[APP_INIT]) {
111
+ debug("on(%s), pass to app", args);
112
+ this._app.on(args[0], args[1]);
113
+ } else {
114
+ debug("on(%s), cache it because app has not init", args);
115
+ this._initOnListeners.add(args);
116
+ super.on(args[0], args[1]);
117
+ }
118
+ return this;
119
+ }
120
+ once(...args) {
121
+ if (this[APP_INIT]) {
122
+ debug("once(%s), pass to app", args);
123
+ this._app.once(args[0], args[1]);
124
+ } else {
125
+ debug("once(%s), cache it because app has not init", args);
126
+ this._initOnceListeners.add(args);
127
+ super.on(args[0], args[1]);
128
+ }
129
+ return this;
130
+ }
131
+ /**
132
+ * close app
133
+ */
134
+ async _close() {
135
+ const baseDir = this.baseDir;
136
+ if (this._app) await this._app.close();
137
+ else await sleep(200);
138
+ if (this._agent) await this._agent.close();
139
+ apps.delete(baseDir);
140
+ debug("delete app cache %s, remain %s", baseDir, [...apps.keys()]);
141
+ if (os.platform() === "win32") await sleep(1e3);
142
+ }
143
+ /**
144
+ * @deprecated please use isClosed instead, keep compatible with old version
145
+ */
146
+ get closed() {
147
+ return this.isClosed;
148
+ }
149
+ };
150
+ function createApp(createOptions) {
151
+ const options = formatOptions({
152
+ ...createOptions,
153
+ mode: "all-in-one-process"
154
+ });
155
+ debug("[createApp] options: %o", options);
156
+ if (options.cache && apps.has(options.baseDir)) {
157
+ const app = apps.get(options.baseDir);
158
+ if (app && !app.isClosed) {
159
+ debug("use cache app %s", options.baseDir);
160
+ return app;
161
+ }
162
+ apps.delete(options.baseDir);
163
+ }
164
+ const appWorker = new MockApplicationWorker(options);
165
+ const proxyApp = new Proxy(appWorker, {
166
+ get(target, prop) {
167
+ if (MOCK_APP_METHOD.includes(prop)) return getProperty(target, prop);
168
+ if (!target[APP_INIT]) throw new Error(`can't get ${prop} before ready`);
169
+ debug("proxy handler.get %s", prop);
170
+ return target._app[prop];
171
+ },
172
+ set(target, prop, value) {
173
+ if (MOCK_APP_METHOD.includes(prop)) return true;
174
+ if (!target[APP_INIT]) throw new Error(`can't set ${prop} before ready`);
175
+ debug("proxy handler.set %s", prop);
176
+ target._app[prop] = value;
177
+ return true;
178
+ },
179
+ defineProperty(target, prop, descriptor) {
180
+ if (MOCK_APP_METHOD.includes(prop)) return true;
181
+ if (!target[APP_INIT]) throw new Error(`can't defineProperty ${prop} before ready`);
182
+ debug("proxy handler.defineProperty %s", prop);
183
+ Object.defineProperty(target._app, prop, descriptor);
184
+ return true;
185
+ },
186
+ deleteProperty(target, prop) {
187
+ if (MOCK_APP_METHOD.includes(prop)) return true;
188
+ if (!target[APP_INIT]) throw new Error(`can't delete ${prop} before ready`);
189
+ debug("proxy handler.deleteProperty %s", prop);
190
+ delete target._app[prop];
191
+ return true;
192
+ },
193
+ getOwnPropertyDescriptor(target, prop) {
194
+ if (MOCK_APP_METHOD.includes(prop)) return Object.getOwnPropertyDescriptor(target, prop);
195
+ if (!target[APP_INIT]) throw new Error(`can't getOwnPropertyDescriptor ${prop} before ready`);
196
+ debug("proxy handler.getOwnPropertyDescriptor %s", prop);
197
+ return Object.getOwnPropertyDescriptor(target._app, prop);
198
+ },
199
+ getPrototypeOf(target) {
200
+ if (!target[APP_INIT]) throw new Error("can't getPrototypeOf before ready");
201
+ debug("proxy handler.getPrototypeOf %s");
202
+ return Object.getPrototypeOf(target._app);
203
+ }
204
+ });
205
+ apps.set(options.baseDir, proxyApp);
206
+ return proxyApp;
207
+ }
208
+ function bindMessenger(ApplicationClass, agent) {
209
+ const agentMessenger = agent.messenger;
210
+ return class MessengerApplication extends ApplicationClass {
211
+ [MESSENGER];
212
+ constructor(options) {
213
+ super(options);
214
+ this.messenger.sendRandom = (action, data) => {
215
+ this.messenger.sendToAgent(action, data);
216
+ };
217
+ agentMessenger.on("egg-ready", () => {
218
+ agentMessenger.sendRandom = (action, data) => {
219
+ agentMessenger.sendToApp(action, data);
220
+ return agentMessenger;
221
+ };
222
+ });
223
+ agentMessenger.send = new Proxy(agentMessenger.send, { apply: this._sendMessage.bind(this) });
224
+ }
225
+ _sendMessage(_target, _thisArg, [action, data, to]) {
226
+ const appMessenger = this.messenger;
227
+ setImmediate(() => {
228
+ if (to === "app") appMessenger.onMessage({
229
+ action,
230
+ data
231
+ });
232
+ else agentMessenger.onMessage({
233
+ action,
234
+ data
235
+ });
236
+ });
237
+ }
238
+ get messenger() {
239
+ return this[MESSENGER];
240
+ }
241
+ set messenger(m) {
242
+ m.send = new Proxy(m.send, { apply: this._sendMessage.bind(this) });
243
+ this[MESSENGER] = m;
244
+ }
245
+ get [Symbol.for("egg#eggPath")]() {
246
+ return path.join(getSourceDirname(), "lib/tmp");
247
+ }
248
+ };
249
+ }
250
+
251
+ //#endregion
252
+ export { createApp };