@midwayjs/core 3.12.0-beta.1 → 3.12.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013 - Now midwayjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -197,6 +197,9 @@ class BaseFramework {
197
197
  ctx.getAttr = (key) => {
198
198
  return ctx.requestContext.getAttr(key);
199
199
  };
200
+ ctx.getApp = () => {
201
+ return this.getApplication();
202
+ };
200
203
  return ctx;
201
204
  },
202
205
  addConfigObject: (obj) => {
@@ -1,33 +1,12 @@
1
- export interface CreateDataSourceInstanceOptions {
2
- /**
3
- * @default false
4
- */
5
- validateConnection?: boolean;
6
- /**
7
- * @default true
8
- */
9
- cacheInstance?: boolean | undefined;
10
- }
11
- interface DataSourceConfig extends CreateDataSourceInstanceOptions {
12
- dataSource: {
13
- entities?: Array<string | unknown>;
14
- [key: string]: unknown;
15
- };
16
- }
17
- export declare abstract class DataSourceManager<T> {
1
+ import { ModuleLoadType, DataSourceManagerConfigOption } from '../interface';
2
+ export declare abstract class DataSourceManager<T, ConnectionOpts extends Record<string, any> = Record<string, any>> {
18
3
  protected dataSource: Map<string, T>;
19
- protected options: Partial<DataSourceConfig>;
4
+ protected options: DataSourceManagerConfigOption<ConnectionOpts>;
20
5
  protected modelMapping: WeakMap<object, any>;
21
6
  private innerDefaultDataSourceName;
22
- protected initDataSource(dataSourceConfig: {
23
- dataSource: {
24
- entities?: Array<string | unknown>;
25
- [key: string]: unknown;
26
- };
27
- cacheInstance?: boolean;
28
- validateConnection?: boolean;
29
- }, appDirOrOptions: {
30
- appDir: string;
7
+ protected initDataSource(dataSourceConfig: DataSourceManagerConfigOption<ConnectionOpts>, baseDirOrOptions: {
8
+ baseDir: string;
9
+ entitiesConfigKey?: string;
31
10
  } | string): Promise<void>;
32
11
  /**
33
12
  * get a data source instance
@@ -45,7 +24,10 @@ export declare abstract class DataSourceManager<T> {
45
24
  * @param dataSourceName
46
25
  */
47
26
  isConnected(dataSourceName: string): Promise<boolean>;
48
- createInstance(config: any, clientName: any, options?: CreateDataSourceInstanceOptions): Promise<T | void>;
27
+ createInstance(config: any, clientName: any, options?: {
28
+ validateConnection?: boolean;
29
+ cacheInstance?: boolean | undefined;
30
+ }): Promise<T | void>;
49
31
  /**
50
32
  * get data source name by model or repository
51
33
  * @param modelOrRepository
@@ -59,6 +41,5 @@ export declare abstract class DataSourceManager<T> {
59
41
  getDefaultDataSourceName(): string;
60
42
  }
61
43
  export declare function formatGlobString(globString: string): string[];
62
- export declare function globModels(globString: string, appDir: string): any[];
63
- export {};
44
+ export declare function globModels(globString: string, appDir: string, loadMode?: ModuleLoadType): Promise<any[]>;
64
45
  //# sourceMappingURL=dataSourceManager.d.ts.map
@@ -11,6 +11,7 @@ const path_1 = require("path");
11
11
  const types_1 = require("../util/types");
12
12
  const constants_1 = require("../constants");
13
13
  const util_1 = require("util");
14
+ const util_2 = require("../util");
14
15
  const debug = (0, util_1.debuglog)('midway:debug');
15
16
  class DataSourceManager {
16
17
  constructor() {
@@ -18,25 +19,27 @@ class DataSourceManager {
18
19
  this.options = {};
19
20
  this.modelMapping = new WeakMap();
20
21
  }
21
- async initDataSource(dataSourceConfig, appDirOrOptions) {
22
+ async initDataSource(dataSourceConfig, baseDirOrOptions) {
22
23
  this.options = dataSourceConfig;
23
24
  if (!this.options.dataSource) {
24
25
  throw new error_1.MidwayParameterError('[DataSourceManager] must set options.dataSource.');
25
26
  }
26
- if (typeof appDirOrOptions === 'string') {
27
- appDirOrOptions = {
28
- appDir: appDirOrOptions,
27
+ if (typeof baseDirOrOptions === 'string') {
28
+ baseDirOrOptions = {
29
+ baseDir: baseDirOrOptions,
30
+ entitiesConfigKey: 'entities',
29
31
  };
30
32
  }
31
33
  for (const dataSourceName in dataSourceConfig.dataSource) {
32
34
  const dataSourceOptions = dataSourceConfig.dataSource[dataSourceName];
33
- if (dataSourceOptions['entities']) {
35
+ const userEntities = dataSourceOptions[baseDirOrOptions.entitiesConfigKey];
36
+ if (userEntities) {
34
37
  const entities = new Set();
35
38
  // loop entities and glob files to model
36
- for (const entity of dataSourceOptions['entities']) {
39
+ for (const entity of userEntities) {
37
40
  if (typeof entity === 'string') {
38
41
  // string will be glob file
39
- const models = globModels(entity, appDirOrOptions.appDir);
42
+ const models = await globModels(entity, baseDirOrOptions.baseDir);
40
43
  for (const model of models) {
41
44
  entities.add(model);
42
45
  this.modelMapping.set(model, dataSourceName);
@@ -48,8 +51,9 @@ class DataSourceManager {
48
51
  this.modelMapping.set(entity, dataSourceName);
49
52
  }
50
53
  }
51
- dataSourceOptions['entities'] = Array.from(entities);
52
- debug(`[core]: DataManager load ${dataSourceOptions['entities'].length} models from ${dataSourceName}.`);
54
+ dataSourceOptions[baseDirOrOptions.entitiesConfigKey] =
55
+ Array.from(entities);
56
+ debug(`[core]: DataManager load ${dataSourceOptions[baseDirOrOptions.entitiesConfigKey].length} models from ${dataSourceName}.`);
53
57
  }
54
58
  // create data source
55
59
  const opts = {
@@ -153,7 +157,7 @@ function formatGlobString(globString) {
153
157
  return pattern;
154
158
  }
155
159
  exports.formatGlobString = formatGlobString;
156
- function globModels(globString, appDir) {
160
+ async function globModels(globString, appDir, loadMode) {
157
161
  const pattern = formatGlobString(globString);
158
162
  const models = [];
159
163
  // string will be glob file
@@ -162,7 +166,9 @@ function globModels(globString, appDir) {
162
166
  ignore: constants_1.IGNORE_PATTERN,
163
167
  });
164
168
  for (const file of files) {
165
- const exports = require(file);
169
+ const exports = await (0, util_2.loadModule)(file, {
170
+ loadMode,
171
+ });
166
172
  if (types_1.Types.isClass(exports)) {
167
173
  models.push(exports);
168
174
  }
@@ -6,6 +6,7 @@ const glob_1 = require("@midwayjs/glob");
6
6
  const error_1 = require("../error");
7
7
  const constants_1 = require("../constants");
8
8
  const decorator_1 = require("../decorator");
9
+ const util_1 = require("../util");
9
10
  class AbstractFileDetector {
10
11
  constructor(options) {
11
12
  this.options = options;
@@ -110,7 +111,9 @@ class CommonJSFileDetector extends AbstractFileDetector {
110
111
  }
111
112
  };
112
113
  for (const file of fileResults) {
113
- const exports = await import(file);
114
+ const exports = await (0, util_1.loadModule)(file, {
115
+ loadMode: 'esm',
116
+ });
114
117
  // add module to set
115
118
  container.bindClass(exports, {
116
119
  namespace: this.options.namespace,
@@ -41,10 +41,14 @@ export declare const FUNCTION_INJECT_KEY = "midway:function_inject_key";
41
41
  export declare const MIDWAY_LOGGER_WRITEABLE_DIR = "MIDWAY_LOGGER_WRITEABLE_DIR";
42
42
  export declare const REQUEST_CTX_KEY = "ctx";
43
43
  export declare const REQUEST_OBJ_CTX_KEY = "_req_ctx";
44
+ export declare const CONTAINER_OBJ_SCOPE = "_obj_scope";
44
45
  export declare const HTTP_SERVER_KEY = "_midway_http_server";
45
46
  export declare const REQUEST_CTX_LOGGER_CACHE_KEY = "_midway_ctx_logger_cache";
46
47
  export declare const ASYNC_CONTEXT_KEY: unique symbol;
47
48
  export declare const ASYNC_CONTEXT_MANAGER_KEY = "MIDWAY_ASYNC_CONTEXT_MANAGER_KEY";
48
49
  export declare const DEFAULT_PATTERN: string[];
49
50
  export declare const IGNORE_PATTERN: string[];
51
+ export declare const SINGLETON_CONTAINER_CTX: {
52
+ _MAIN_CTX_: boolean;
53
+ };
50
54
  //# sourceMappingURL=constants.d.ts.map
package/dist/constants.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.IGNORE_PATTERN = exports.DEFAULT_PATTERN = exports.ASYNC_CONTEXT_MANAGER_KEY = exports.ASYNC_CONTEXT_KEY = exports.REQUEST_CTX_LOGGER_CACHE_KEY = exports.HTTP_SERVER_KEY = exports.REQUEST_OBJ_CTX_KEY = exports.REQUEST_CTX_KEY = exports.MIDWAY_LOGGER_WRITEABLE_DIR = exports.FUNCTION_INJECT_KEY = exports.KEYS = void 0;
3
+ exports.SINGLETON_CONTAINER_CTX = exports.IGNORE_PATTERN = exports.DEFAULT_PATTERN = exports.ASYNC_CONTEXT_MANAGER_KEY = exports.ASYNC_CONTEXT_KEY = exports.REQUEST_CTX_LOGGER_CACHE_KEY = exports.HTTP_SERVER_KEY = exports.CONTAINER_OBJ_SCOPE = exports.REQUEST_OBJ_CTX_KEY = exports.REQUEST_CTX_KEY = exports.MIDWAY_LOGGER_WRITEABLE_DIR = exports.FUNCTION_INJECT_KEY = exports.KEYS = void 0;
4
4
  /**
5
5
  * 静态参数
6
6
  *
@@ -44,6 +44,7 @@ exports.FUNCTION_INJECT_KEY = 'midway:function_inject_key';
44
44
  exports.MIDWAY_LOGGER_WRITEABLE_DIR = 'MIDWAY_LOGGER_WRITEABLE_DIR';
45
45
  exports.REQUEST_CTX_KEY = 'ctx';
46
46
  exports.REQUEST_OBJ_CTX_KEY = '_req_ctx';
47
+ exports.CONTAINER_OBJ_SCOPE = '_obj_scope';
47
48
  exports.HTTP_SERVER_KEY = '_midway_http_server';
48
49
  exports.REQUEST_CTX_LOGGER_CACHE_KEY = '_midway_ctx_logger_cache';
49
50
  exports.ASYNC_CONTEXT_KEY = Symbol('ASYNC_CONTEXT_KEY');
@@ -57,4 +58,5 @@ exports.DEFAULT_PATTERN = [
57
58
  '**/**.cjs',
58
59
  ];
59
60
  exports.IGNORE_PATTERN = ['**/**.d.ts', '**/**.d.mts', '**/**.d.cts'];
61
+ exports.SINGLETON_CONTAINER_CTX = { _MAIN_CTX_: true };
60
62
  //# sourceMappingURL=constants.js.map
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { IFileDetector, IIdentifierRelationShip, IMidwayContainer, IModuleStore, IObjectDefinition, IObjectDefinitionRegistry, ObjectContext, ObjectIdentifier } from '../interface';
2
+ import { IFileDetector, IIdentifierRelationShip, IMidwayContainer, IModuleStore, IObjectDefinition, IObjectDefinitionRegistry, ObjectContext, ObjectIdentifier, ScopeEnum } from '../interface';
3
3
  import { ManagedResolverFactory } from './managedResolverFactory';
4
4
  import * as EventEmitter from 'events';
5
5
  export declare class MidwayContainer implements IMidwayContainer, IModuleStore {
@@ -9,7 +9,9 @@ export declare class MidwayContainer implements IMidwayContainer, IModuleStore {
9
9
  private moduleMap;
10
10
  private _objectCreateEventTarget;
11
11
  parent: IMidwayContainer;
12
- protected ctx: {};
12
+ protected ctx: {
13
+ _MAIN_CTX_: boolean;
14
+ };
13
15
  private fileDetector;
14
16
  private attrMap;
15
17
  private _namespaceSet;
@@ -79,5 +81,6 @@ export declare class MidwayContainer implements IMidwayContainer, IModuleStore {
79
81
  getNamespaceList(): string[];
80
82
  hasDefinition(identifier: ObjectIdentifier): boolean;
81
83
  hasObject(identifier: ObjectIdentifier): boolean;
84
+ getInstanceScope(instance: any): ScopeEnum | undefined;
82
85
  }
83
86
  //# sourceMappingURL=container.d.ts.map
@@ -186,8 +186,8 @@ class MidwayContainer {
186
186
  this._identifierMapping = null;
187
187
  this.moduleMap = null;
188
188
  this.parent = null;
189
- // 仅仅用于兼容requestContainer的ctx
190
- this.ctx = {};
189
+ // 仅仅用于兼容 requestContainer ctx
190
+ this.ctx = constants_1.SINGLETON_CONTAINER_CTX;
191
191
  this.attrMap = new Map();
192
192
  this._namespaceSet = null;
193
193
  this.parent = parent;
@@ -502,6 +502,12 @@ class MidwayContainer {
502
502
  hasObject(identifier) {
503
503
  return this.registry.hasObject(identifier);
504
504
  }
505
+ getInstanceScope(instance) {
506
+ if (instance[constants_1.CONTAINER_OBJ_SCOPE]) {
507
+ return instance[constants_1.CONTAINER_OBJ_SCOPE];
508
+ }
509
+ return undefined;
510
+ }
505
511
  }
506
512
  exports.MidwayContainer = MidwayContainer;
507
513
  //# sourceMappingURL=container.js.map
@@ -1,4 +1,4 @@
1
- import { IManagedResolver, IObjectDefinition, IManagedResolverFactoryCreateOptions, IMidwayContainer, IManagedInstance, InjectModeEnum, ObjectIdentifier } from '../interface';
1
+ import { IManagedInstance, IManagedResolver, IManagedResolverFactoryCreateOptions, IMidwayContainer, InjectModeEnum, IObjectDefinition, ObjectIdentifier } from '../interface';
2
2
  export declare class ManagedReference implements IManagedInstance {
3
3
  type: string;
4
4
  name: string;
@@ -50,5 +50,6 @@ export declare class ManagedResolverFactory {
50
50
  depthFirstSearch(identifier: string, definition: IObjectDefinition, depth?: string[]): boolean;
51
51
  private getObjectEventTarget;
52
52
  private checkSingletonInvokeRequest;
53
+ private setInstanceScope;
53
54
  }
54
55
  //# sourceMappingURL=managedResolverFactory.d.ts.map
@@ -163,12 +163,18 @@ class ManagedResolverFactory {
163
163
  context: this.context,
164
164
  definition,
165
165
  });
166
- if (definition.isSingletonScope() && definition.id) {
167
- this.singletonCache.set(definition.id, inst);
168
- }
169
- // for request scope
170
- if (definition.isRequestScope() && definition.id) {
171
- this.context.registerObject(definition.id, inst);
166
+ if (definition.id) {
167
+ if (definition.isSingletonScope()) {
168
+ this.singletonCache.set(definition.id, inst);
169
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Singleton);
170
+ }
171
+ else if (definition.isRequestScope()) {
172
+ this.context.registerObject(definition.id, inst);
173
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Request);
174
+ }
175
+ else {
176
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Prototype);
177
+ }
172
178
  }
173
179
  this.removeCreateStatus(definition, true);
174
180
  return inst;
@@ -217,6 +223,7 @@ class ManagedResolverFactory {
217
223
  if (definition.isRequestScope() &&
218
224
  definition.constructor.name === 'ObjectDefinition') {
219
225
  debug('id = %s inject ctx', definition.id);
226
+ // set related ctx
220
227
  Object.defineProperty(inst, constants_1.REQUEST_OBJ_CTX_KEY, {
221
228
  value: this.context.get(constants_1.REQUEST_CTX_KEY),
222
229
  writable: false,
@@ -253,14 +260,20 @@ class ManagedResolverFactory {
253
260
  context: this.context,
254
261
  definition,
255
262
  });
256
- if (definition.isSingletonScope() && definition.id) {
257
- debug(`id = ${definition.id}(${definition.name}) set to singleton cache`);
258
- this.singletonCache.set(definition.id, inst);
259
- }
260
- // for request scope
261
- if (definition.isRequestScope() && definition.id) {
262
- debug(`id = ${definition.id}(${definition.name}) set to register object`);
263
- this.context.registerObject(definition.id, inst);
263
+ if (definition.id) {
264
+ if (definition.isSingletonScope()) {
265
+ debug(`id = ${definition.id}(${definition.name}) set to singleton cache`);
266
+ this.singletonCache.set(definition.id, inst);
267
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Singleton);
268
+ }
269
+ else if (definition.isRequestScope()) {
270
+ debug(`id = ${definition.id}(${definition.name}) set to register object`);
271
+ this.context.registerObject(definition.id, inst);
272
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Request);
273
+ }
274
+ else {
275
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Prototype);
276
+ }
264
277
  }
265
278
  this.removeCreateStatus(definition, true);
266
279
  return inst;
@@ -409,6 +422,20 @@ class ManagedResolverFactory {
409
422
  }
410
423
  return true;
411
424
  }
425
+ setInstanceScope(inst, scope) {
426
+ if (typeof inst === 'object') {
427
+ if (scope === interface_1.ScopeEnum.Request &&
428
+ inst[constants_1.REQUEST_OBJ_CTX_KEY] === constants_1.SINGLETON_CONTAINER_CTX) {
429
+ scope = interface_1.ScopeEnum.Singleton;
430
+ }
431
+ Object.defineProperty(inst, constants_1.CONTAINER_OBJ_SCOPE, {
432
+ value: scope,
433
+ writable: false,
434
+ enumerable: false,
435
+ configurable: false,
436
+ });
437
+ }
438
+ }
412
439
  }
413
440
  exports.ManagedResolverFactory = ManagedResolverFactory;
414
441
  //# sourceMappingURL=managedResolverFactory.js.map
@@ -7,6 +7,8 @@ export declare class MidwayRequestContainer extends MidwayContainer {
7
7
  get<T = any>(identifier: any, args?: any): T;
8
8
  getAsync<T = any>(identifier: any, args?: any): Promise<T>;
9
9
  ready(): Promise<void>;
10
- getContext(): {};
10
+ getContext(): {
11
+ _MAIN_CTX_: boolean;
12
+ };
11
13
  }
12
14
  //# sourceMappingURL=requestContainer.d.ts.map
@@ -23,7 +23,7 @@ function ServerlessTrigger(type, metadata = {}) {
23
23
  type,
24
24
  methodName: functionName,
25
25
  metadata,
26
- }, target.constructor);
26
+ }, target);
27
27
  };
28
28
  }
29
29
  exports.ServerlessTrigger = ServerlessTrigger;
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ export { MidwayDecoratorService } from './service/decoratorService';
17
17
  export { MidwayMockService } from './service/mockService';
18
18
  export { RouterInfo, DynamicRouterInfo, RouterPriority, RouterCollectorOptions, MidwayWebRouterService, } from './service/webRouterService';
19
19
  export { MidwayServerlessFunctionService, WebRouterCollector, } from './service/slsFunctionService';
20
- export { CreateDataSourceInstanceOptions, DataSourceManager, } from './common/dataSourceManager';
20
+ export { DataSourceManager } from './common/dataSourceManager';
21
21
  export * from './service/pipelineService';
22
22
  export * from './common/loggerFactory';
23
23
  export * from './common/serviceFactory';
@@ -33,7 +33,7 @@ export { AsyncContextManager, ASYNC_ROOT_CONTEXT, AsyncContext, } from './common
33
33
  export * from './decorator';
34
34
  export * from './decorator/decoratorManager';
35
35
  export * from './decorator/constant';
36
- export { safelyGet, safeRequire, loadModule, delegateTargetPrototypeMethod, delegateTargetMethod, delegateTargetProperties, delegateTargetAllPrototypeMethod, deprecatedOutput, transformRequestObjectByType, pathMatching, wrapMiddleware, wrapAsync, } from './util/';
36
+ export { safelyGet, safeRequire, loadModule, delegateTargetPrototypeMethod, delegateTargetMethod, delegateTargetProperties, delegateTargetAllPrototypeMethod, deprecatedOutput, transformRequestObjectByType, pathMatching, wrapMiddleware, wrapAsync, isTypeScriptEnvironment, } from './util/';
37
37
  export { extend } from './util/extend';
38
38
  export * from './util/webRouterParam';
39
39
  export * from './util/contextUtil';
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.FORMAT = exports.FileUtils = exports.PathFileUtil = exports.Types = exports.Utils = exports.sleep = exports.retryWith = exports.retryWithAsync = exports.extend = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.loadModule = exports.safeRequire = exports.safelyGet = exports.ASYNC_ROOT_CONTEXT = exports.DataSourceManager = exports.WebRouterCollector = exports.MidwayServerlessFunctionService = exports.MidwayWebRouterService = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.FunctionalConfiguration = exports.createConfiguration = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
17
+ exports.FORMAT = exports.FileUtils = exports.PathFileUtil = exports.Types = exports.Utils = exports.sleep = exports.retryWith = exports.retryWithAsync = exports.extend = exports.isTypeScriptEnvironment = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.loadModule = exports.safeRequire = exports.safelyGet = exports.ASYNC_ROOT_CONTEXT = exports.DataSourceManager = exports.WebRouterCollector = exports.MidwayServerlessFunctionService = exports.MidwayWebRouterService = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.FunctionalConfiguration = exports.createConfiguration = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
18
18
  __exportStar(require("./interface"), exports);
19
19
  __exportStar(require("./context/container"), exports);
20
20
  var requestContainer_1 = require("./context/requestContainer");
@@ -84,6 +84,7 @@ Object.defineProperty(exports, "transformRequestObjectByType", { enumerable: tru
84
84
  Object.defineProperty(exports, "pathMatching", { enumerable: true, get: function () { return util_1.pathMatching; } });
85
85
  Object.defineProperty(exports, "wrapMiddleware", { enumerable: true, get: function () { return util_1.wrapMiddleware; } });
86
86
  Object.defineProperty(exports, "wrapAsync", { enumerable: true, get: function () { return util_1.wrapAsync; } });
87
+ Object.defineProperty(exports, "isTypeScriptEnvironment", { enumerable: true, get: function () { return util_1.isTypeScriptEnvironment; } });
87
88
  var extend_1 = require("./util/extend");
88
89
  Object.defineProperty(exports, "extend", { enumerable: true, get: function () { return extend_1.extend; } });
89
90
  __exportStar(require("./util/webRouterParam"), exports);
@@ -368,15 +368,25 @@ export type ServiceFactoryConfigOption<OPTIONS> = {
368
368
  };
369
369
  defaultClientName?: string;
370
370
  };
371
- export type DataSourceManagerConfigOption<OPTIONS> = {
371
+ export type CreateDataSourceInstanceOptions = {
372
+ /**
373
+ * @default false
374
+ */
375
+ validateConnection?: boolean;
376
+ /**
377
+ * @default true
378
+ */
379
+ cacheInstance?: boolean | undefined;
380
+ };
381
+ export type DataSourceManagerConfigOption<OPTIONS, ENTITY_CONFIG_KEY extends string = 'entities'> = {
372
382
  default?: PowerPartial<OPTIONS>;
373
383
  defaultDataSourceName?: string;
374
384
  dataSource?: {
375
385
  [key: string]: PowerPartial<{
376
- entities: any[];
386
+ [keyName in ENTITY_CONFIG_KEY]: any[];
377
387
  } & OPTIONS>;
378
388
  };
379
- };
389
+ } & CreateDataSourceInstanceOptions;
380
390
  type ConfigType<T> = T extends (...args: any[]) => any ? Writable<PowerPartial<ReturnType<T>>> : Writable<PowerPartial<T>>;
381
391
  /**
382
392
  * Get definition from config
@@ -593,6 +603,11 @@ export interface IMidwayContainer extends IObjectFactory, WithFn<IObjectLifeCycl
593
603
  * @param key
594
604
  */
595
605
  getAttr<T>(key: string): T;
606
+ /**
607
+ * Get instance IoC container scope
608
+ * @param instance
609
+ */
610
+ getInstanceScope(instance: any): ScopeEnum | undefined;
596
611
  }
597
612
  /**
598
613
  * @deprecated
@@ -619,8 +634,8 @@ export interface IInformationService {
619
634
  }
620
635
  export interface IEnvironmentService {
621
636
  getCurrentEnvironment(): string;
622
- setCurrentEnvironment(environment: string): any;
623
637
  isDevelopmentEnvironment(): boolean;
638
+ getModuleLoadType(): ModuleLoadType;
624
639
  }
625
640
  export declare enum MidwayProcessTypeEnum {
626
641
  APPLICATION = "APPLICATION",
@@ -645,6 +660,10 @@ export interface Context {
645
660
  * @param key
646
661
  */
647
662
  getAttr<T>(key: string): T;
663
+ /**
664
+ * Get current related application instance.
665
+ */
666
+ getApp(): IMidwayApplication;
648
667
  }
649
668
  export type IMidwayContext<FrameworkContext = unknown> = Context & FrameworkContext;
650
669
  export type NextFunction = () => Promise<any>;
@@ -799,6 +818,7 @@ export interface IMidwayBaseApplication<CTX extends IMidwayContext> {
799
818
  getNamespace(): string;
800
819
  }
801
820
  export type IMidwayApplication<T extends IMidwayContext = IMidwayContext, FrameworkApplication = unknown> = IMidwayBaseApplication<T> & FrameworkApplication;
821
+ export type ModuleLoadType = 'commonjs' | 'esm';
802
822
  export interface IMidwayBootstrapOptions {
803
823
  [customPropertyKey: string]: any;
804
824
  baseDir?: string;
@@ -810,6 +830,7 @@ export interface IMidwayBootstrapOptions {
810
830
  */
811
831
  configurationModule?: any | any[];
812
832
  imports?: any | any[];
833
+ moduleLoadType?: ModuleLoadType;
813
834
  moduleDetector?: IFileDetector | false;
814
835
  logger?: boolean | ILogger;
815
836
  /**
@@ -1,8 +1,11 @@
1
- import { IEnvironmentService } from '../interface';
1
+ import { IEnvironmentService, ModuleLoadType } from '../interface';
2
2
  export declare class MidwayEnvironmentService implements IEnvironmentService {
3
3
  protected environment: string;
4
+ protected moduleLoadType: ModuleLoadType;
4
5
  getCurrentEnvironment(): string;
5
6
  setCurrentEnvironment(environment: string): void;
6
7
  isDevelopmentEnvironment(): boolean;
8
+ setModuleLoadType(moduleLoadType: ModuleLoadType): void;
9
+ getModuleLoadType(): ModuleLoadType;
7
10
  }
8
11
  //# sourceMappingURL=environmentService.d.ts.map
@@ -11,6 +11,9 @@ const interface_1 = require("../interface");
11
11
  const util_1 = require("../util");
12
12
  const decorator_1 = require("../decorator");
13
13
  let MidwayEnvironmentService = class MidwayEnvironmentService {
14
+ constructor() {
15
+ this.moduleLoadType = 'commonjs';
16
+ }
14
17
  getCurrentEnvironment() {
15
18
  if (!this.environment) {
16
19
  this.environment = (0, util_1.getCurrentEnvironment)();
@@ -23,6 +26,12 @@ let MidwayEnvironmentService = class MidwayEnvironmentService {
23
26
  isDevelopmentEnvironment() {
24
27
  return (0, util_1.isDevelopmentEnvironment)(this.environment);
25
28
  }
29
+ setModuleLoadType(moduleLoadType) {
30
+ this.moduleLoadType = moduleLoadType;
31
+ }
32
+ getModuleLoadType() {
33
+ return this.moduleLoadType;
34
+ }
26
35
  };
27
36
  MidwayEnvironmentService = __decorate([
28
37
  (0, decorator_1.Provide)(),
@@ -14,13 +14,23 @@ const interface_1 = require("../interface");
14
14
  const util_1 = require("../util");
15
15
  const path_1 = require("path");
16
16
  const decorator_1 = require("../decorator");
17
+ const fs_1 = require("fs");
17
18
  let MidwayInformationService = class MidwayInformationService {
18
19
  init() {
19
20
  if (this.baseDir) {
20
21
  if (!this.appDir) {
21
22
  this.appDir = (0, path_1.dirname)(this.baseDir);
22
23
  }
23
- this.pkg = (0, util_1.safeRequire)((0, path_1.join)(this.appDir, 'package.json')) || {};
24
+ const pkgPath = (0, path_1.join)(this.appDir, 'package.json');
25
+ if ((0, fs_1.existsSync)(pkgPath)) {
26
+ const content = (0, fs_1.readFileSync)(pkgPath, {
27
+ encoding: 'utf-8',
28
+ });
29
+ this.pkg = JSON.parse(content);
30
+ }
31
+ else {
32
+ this.pkg = {};
33
+ }
24
34
  }
25
35
  else {
26
36
  this.pkg = {};
package/dist/setup.js CHANGED
@@ -88,29 +88,28 @@ async function prepareGlobalApplicationContext(globalOptions) {
88
88
  applicationContext.registerObject('baseDir', baseDir);
89
89
  applicationContext.registerObject('appDir', appDir);
90
90
  debug('[core]: set default file detector');
91
+ if (!globalOptions.moduleLoadType) {
92
+ globalOptions.moduleLoadType = 'commonjs';
93
+ }
91
94
  // set module detector
92
95
  if (globalOptions.moduleDetector !== false) {
93
- const pkgJSON = await (0, _1.loadModule)((0, path_1.join)(appDir, 'package.json'), {
94
- safeLoad: true,
95
- enableCache: false,
96
- });
97
- const loadMode = (pkgJSON === null || pkgJSON === void 0 ? void 0 : pkgJSON.type) === 'module' ? 'esm' : 'commonjs';
98
- debug('[core]: module load mode = %s', loadMode);
96
+ debug('[core]: set module load type = %s', globalOptions.moduleLoadType);
99
97
  // set default entry file
100
98
  if (!globalOptions.imports) {
101
99
  globalOptions.imports = [
102
- await (0, _1.loadModule)((0, path_1.join)(baseDir, 'configuration'), {
103
- loadMode,
100
+ await (0, _1.loadModule)((0, path_1.join)(baseDir, `configuration${(0, _1.isTypeScriptEnvironment)() ? '.ts' : '.js'}`), {
101
+ loadMode: globalOptions.moduleLoadType,
104
102
  safeLoad: true,
105
103
  }),
106
104
  ];
107
105
  }
108
106
  if (globalOptions.moduleDetector === undefined) {
109
- if (loadMode === 'esm') {
107
+ if (globalOptions.moduleLoadType === 'esm') {
110
108
  applicationContext.setFileDetector(new _1.ESModuleFileDetector({
111
109
  loadDir: baseDir,
112
110
  ignore: (_d = globalOptions.ignore) !== null && _d !== void 0 ? _d : [],
113
111
  }));
112
+ globalOptions.moduleLoadType = 'esm';
114
113
  }
115
114
  else {
116
115
  applicationContext.setFileDetector(new _1.CommonJSFileDetector({
@@ -230,6 +229,9 @@ function prepareGlobalApplicationContextSync(globalOptions) {
230
229
  }
231
230
  }
232
231
  printStepDebugInfo('Init MidwayConfigService, MidwayAspectService and MidwayDecoratorService');
232
+ // init default environment
233
+ const environmentService = applicationContext.get(_1.MidwayEnvironmentService);
234
+ environmentService.setModuleLoadType(globalOptions.moduleLoadType);
233
235
  // init default config
234
236
  const configService = applicationContext.get(_1.MidwayConfigService);
235
237
  configService.add([
@@ -3,10 +3,8 @@
3
3
  /// <reference types="node" />
4
4
  import http = require('http');
5
5
  import https = require('https');
6
- type MethodType = 'GET' | 'POST';
7
6
  type MimeType = 'text' | 'json' | undefined;
8
7
  interface IOptions extends https.RequestOptions {
9
- method?: MethodType;
10
8
  headers?: any;
11
9
  contentType?: MimeType;
12
10
  dataType?: MimeType;
@@ -23,10 +23,10 @@ async function makeHttpRequest(url, options = {}) {
23
23
  const whatwgUrl = new URL(url);
24
24
  const client = whatwgUrl.protocol === 'https:' ? https : http;
25
25
  options.method = (options.method || 'GET').toUpperCase();
26
- const { contentType, dataType, method, timeout = 5000, ...otherOptions } = options;
26
+ const { contentType, dataType, method, timeout = 5000, headers: customHeaders, ...otherOptions } = options;
27
27
  const headers = {
28
28
  Accept: mimeMap[dataType] || mimeMap.octet,
29
- ...options.headers,
29
+ ...customHeaders,
30
30
  };
31
31
  let data;
32
32
  if (method === 'GET' && options.data) {
@@ -122,6 +122,7 @@ export declare function getParamNames(func: any): string[];
122
122
  export declare function generateRandomId(): string;
123
123
  export declare function merge(target: any, src: any): any;
124
124
  export declare function toAsyncFunction<T extends (...args: any[]) => any>(method: T): (...args: Parameters<T>) => Promise<ReturnType<T>>;
125
+ export declare function isTypeScriptEnvironment(): boolean;
125
126
  export declare const Utils: {
126
127
  sleep: typeof sleep;
127
128
  getParamNames: typeof getParamNames;
@@ -132,5 +133,6 @@ export declare const Utils: {
132
133
  toAsyncFunction: typeof toAsyncFunction;
133
134
  safeStringify: typeof safeStringify;
134
135
  safeParse: typeof safeParse;
136
+ isTypeScriptEnvironment: typeof isTypeScriptEnvironment;
135
137
  };
136
138
  //# sourceMappingURL=index.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Utils = exports.toAsyncFunction = exports.merge = exports.generateRandomId = exports.getParamNames = exports.sleep = exports.wrapAsync = exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.loadModule = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
3
+ exports.Utils = exports.isTypeScriptEnvironment = exports.toAsyncFunction = exports.merge = exports.generateRandomId = exports.getParamNames = exports.sleep = exports.wrapAsync = exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.loadModule = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
4
4
  const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
6
  const util_1 = require("util");
@@ -74,7 +74,15 @@ const loadModule = async (p, options = {}) => {
74
74
  return require(p);
75
75
  }
76
76
  else {
77
- return await import(p);
77
+ // if json file, import need add options
78
+ if (p.endsWith('.json')) {
79
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
80
+ // @ts-ignore
81
+ return (await import(p, { assert: { type: 'json' } })).default;
82
+ }
83
+ else {
84
+ return await import(p);
85
+ }
78
86
  }
79
87
  }
80
88
  else {
@@ -467,6 +475,15 @@ function toAsyncFunction(method) {
467
475
  }
468
476
  }
469
477
  exports.toAsyncFunction = toAsyncFunction;
478
+ function isTypeScriptEnvironment() {
479
+ const TS_MODE_PROCESS_FLAG = process.env.MIDWAY_TS_MODE;
480
+ if ('false' === TS_MODE_PROCESS_FLAG) {
481
+ return false;
482
+ }
483
+ // eslint-disable-next-line node/no-deprecated-api
484
+ return TS_MODE_PROCESS_FLAG === 'true' || !!require.extensions['.ts'];
485
+ }
486
+ exports.isTypeScriptEnvironment = isTypeScriptEnvironment;
470
487
  exports.Utils = {
471
488
  sleep,
472
489
  getParamNames,
@@ -477,5 +494,6 @@ exports.Utils = {
477
494
  toAsyncFunction,
478
495
  safeStringify: flatted_1.safeStringify,
479
496
  safeParse: flatted_1.safeParse,
497
+ isTypeScriptEnvironment,
480
498
  };
481
499
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.12.0-beta.1",
3
+ "version": "3.12.0",
4
4
  "description": "midway core",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -42,5 +42,5 @@
42
42
  "engines": {
43
43
  "node": ">=12"
44
44
  },
45
- "gitHead": "a603d2348d6141f8f723901498f03a162a037708"
45
+ "gitHead": "0e9a08cd078c4c4dedfa753a8c1025806cc0b0a2"
46
46
  }