@midwayjs/core 3.12.0-beta.1 → 3.12.0-beta.2

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.
@@ -1,3 +1,4 @@
1
+ import { ModuleLoadType } from '../interface';
1
2
  export interface CreateDataSourceInstanceOptions {
2
3
  /**
3
4
  * @default false
@@ -59,6 +60,6 @@ export declare abstract class DataSourceManager<T> {
59
60
  getDefaultDataSourceName(): string;
60
61
  }
61
62
  export declare function formatGlobString(globString: string): string[];
62
- export declare function globModels(globString: string, appDir: string): any[];
63
+ export declare function globModels(globString: string, appDir: string, loadMode?: ModuleLoadType): Promise<any[]>;
63
64
  export {};
64
65
  //# 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() {
@@ -36,7 +37,7 @@ class DataSourceManager {
36
37
  for (const entity of dataSourceOptions['entities']) {
37
38
  if (typeof entity === 'string') {
38
39
  // string will be glob file
39
- const models = globModels(entity, appDirOrOptions.appDir);
40
+ const models = await globModels(entity, appDirOrOptions.appDir);
40
41
  for (const model of models) {
41
42
  entities.add(model);
42
43
  this.modelMapping.set(model, dataSourceName);
@@ -153,7 +154,7 @@ function formatGlobString(globString) {
153
154
  return pattern;
154
155
  }
155
156
  exports.formatGlobString = formatGlobString;
156
- function globModels(globString, appDir) {
157
+ async function globModels(globString, appDir, loadMode) {
157
158
  const pattern = formatGlobString(globString);
158
159
  const models = [];
159
160
  // string will be glob file
@@ -162,7 +163,9 @@ function globModels(globString, appDir) {
162
163
  ignore: constants_1.IGNORE_PATTERN,
163
164
  });
164
165
  for (const file of files) {
165
- const exports = require(file);
166
+ const exports = await (0, util_2.loadModule)(file, {
167
+ loadMode,
168
+ });
166
169
  if (types_1.Types.isClass(exports)) {
167
170
  models.push(exports);
168
171
  }
@@ -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,
package/dist/index.d.ts CHANGED
@@ -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);
@@ -619,8 +619,8 @@ export interface IInformationService {
619
619
  }
620
620
  export interface IEnvironmentService {
621
621
  getCurrentEnvironment(): string;
622
- setCurrentEnvironment(environment: string): any;
623
622
  isDevelopmentEnvironment(): boolean;
623
+ getModuleLoadType(): ModuleLoadType;
624
624
  }
625
625
  export declare enum MidwayProcessTypeEnum {
626
626
  APPLICATION = "APPLICATION",
@@ -799,6 +799,7 @@ export interface IMidwayBaseApplication<CTX extends IMidwayContext> {
799
799
  getNamespace(): string;
800
800
  }
801
801
  export type IMidwayApplication<T extends IMidwayContext = IMidwayContext, FrameworkApplication = unknown> = IMidwayBaseApplication<T> & FrameworkApplication;
802
+ export type ModuleLoadType = 'commonjs' | 'esm';
802
803
  export interface IMidwayBootstrapOptions {
803
804
  [customPropertyKey: string]: any;
804
805
  baseDir?: string;
@@ -810,6 +811,7 @@ export interface IMidwayBootstrapOptions {
810
811
  */
811
812
  configurationModule?: any | any[];
812
813
  imports?: any | any[];
814
+ moduleLoadType?: ModuleLoadType;
813
815
  moduleDetector?: IFileDetector | false;
814
816
  logger?: boolean | ILogger;
815
817
  /**
@@ -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([
@@ -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-beta.2",
4
4
  "description": "midway core",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",