@modern-js/server-utils 2.0.0-beta.3 → 2.0.0-beta.6

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,13 +1,12 @@
1
- import * as os from 'os';
2
- import path, { dirname, posix } from 'path';
3
- import * as ts from 'typescript';
4
- import { createMatchPath } from '@modern-js/utils/tsconfig-paths';
5
- const isRegExpKey = str => {
6
- return str.startsWith('^') || str.endsWith('$');
1
+ import * as os from "os";
2
+ import path, { dirname, posix } from "path";
3
+ import * as ts from "typescript";
4
+ import { createMatchPath } from "@modern-js/utils/tsconfig-paths";
5
+ const isRegExpKey = (str) => {
6
+ return str.startsWith("^") || str.endsWith("$");
7
7
  };
8
8
  const resolveAliasPath = (baseUrl, filePath) => {
9
- // exclude absolute path and alias
10
- if (filePath.startsWith('.') || filePath.startsWith('..')) {
9
+ if (filePath.startsWith(".") || filePath.startsWith("..")) {
11
10
  return path.resolve(baseUrl, filePath);
12
11
  }
13
12
  return filePath;
@@ -24,10 +23,8 @@ const createAliasMatcher = (baseUrl, alias) => {
24
23
  }
25
24
  return o;
26
25
  }, []);
27
- const cacheMap = new Map();
28
-
29
- // eslint-disable-next-line consistent-return
30
- return requestedModule => {
26
+ const cacheMap = /* @__PURE__ */ new Map();
27
+ return (requestedModule) => {
31
28
  if (cacheMap.has(requestedModule)) {
32
29
  return cacheMap.get(requestedModule);
33
30
  }
@@ -48,10 +45,10 @@ const createAliasMatcher = (baseUrl, alias) => {
48
45
  const isDynamicImport = (tsBinary, node) => {
49
46
  return tsBinary.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword;
50
47
  };
51
- export function tsconfigPathsBeforeHookFactory(tsBinary, baseUrl, paths) {
48
+ function tsconfigPathsBeforeHookFactory(tsBinary, baseUrl, paths) {
52
49
  const tsPaths = {};
53
50
  const alias = {};
54
- Object.keys(paths).forEach(key => {
51
+ Object.keys(paths).forEach((key) => {
55
52
  if (Array.isArray(paths[key])) {
56
53
  tsPaths[key] = paths[key];
57
54
  } else {
@@ -59,37 +56,55 @@ export function tsconfigPathsBeforeHookFactory(tsBinary, baseUrl, paths) {
59
56
  }
60
57
  });
61
58
  const matchAliasPath = createAliasMatcher(baseUrl, alias);
62
- const matchTsPath = createMatchPath(baseUrl, tsPaths, ['main']);
59
+ const matchTsPath = createMatchPath(baseUrl, tsPaths, ["main"]);
63
60
  const matchPath = (requestedModule, readJSONSync, fileExists, extensions) => {
64
- const result = matchTsPath(requestedModule, readJSONSync, fileExists, extensions);
61
+ const result = matchTsPath(
62
+ requestedModule,
63
+ readJSONSync,
64
+ fileExists,
65
+ extensions
66
+ );
65
67
  if (result) {
66
68
  return result;
67
69
  }
68
70
  return matchAliasPath(requestedModule);
69
71
  };
70
72
  if (Object.keys(paths).length === 0) {
71
- return undefined;
73
+ return void 0;
72
74
  }
73
- return ctx => {
74
- return sf => {
75
- const visitNode = node => {
75
+ return (ctx) => {
76
+ return (sf) => {
77
+ const visitNode = (node) => {
78
+ var _a;
76
79
  if (isDynamicImport(tsBinary, node)) {
77
80
  const importPathWithQuotes = node.arguments[0].getText(sf);
78
- const text = importPathWithQuotes.slice(1, importPathWithQuotes.length - 1);
81
+ const text = importPathWithQuotes.slice(
82
+ 1,
83
+ importPathWithQuotes.length - 1
84
+ );
79
85
  const result = getNotAliasedPath(sf, matchPath, text);
80
86
  if (!result) {
81
87
  return node;
82
88
  }
83
- return tsBinary.factory.updateCallExpression(node, node.expression, node.typeArguments, tsBinary.factory.createNodeArray([tsBinary.factory.createStringLiteral(result)]));
89
+ return tsBinary.factory.updateCallExpression(
90
+ node,
91
+ node.expression,
92
+ node.typeArguments,
93
+ tsBinary.factory.createNodeArray([
94
+ tsBinary.factory.createStringLiteral(result)
95
+ ])
96
+ );
84
97
  }
85
98
  if (tsBinary.isImportDeclaration(node) || tsBinary.isExportDeclaration(node) && node.moduleSpecifier) {
86
99
  try {
87
- var _node$moduleSpecifier;
88
- const importPathWithQuotes = node === null || node === void 0 ? void 0 : (_node$moduleSpecifier = node.moduleSpecifier) === null || _node$moduleSpecifier === void 0 ? void 0 : _node$moduleSpecifier.getText();
100
+ const importPathWithQuotes = (_a = node == null ? void 0 : node.moduleSpecifier) == null ? void 0 : _a.getText();
89
101
  if (!importPathWithQuotes) {
90
102
  return node;
91
103
  }
92
- const text = importPathWithQuotes.substring(1, importPathWithQuotes.length - 1);
104
+ const text = importPathWithQuotes.substring(
105
+ 1,
106
+ importPathWithQuotes.length - 1
107
+ );
93
108
  const result = getNotAliasedPath(sf, matchPath, text);
94
109
  if (!result) {
95
110
  return node;
@@ -98,13 +113,28 @@ export function tsconfigPathsBeforeHookFactory(tsBinary, baseUrl, paths) {
98
113
  moduleSpecifier.parent = node.moduleSpecifier.parent;
99
114
  let newNode;
100
115
  if (tsBinary.isImportDeclaration(node)) {
101
- newNode = tsBinary.factory.updateImportDeclaration(node, node.decorators, node.modifiers, node.importClause, moduleSpecifier, node.assertClause);
116
+ newNode = tsBinary.factory.updateImportDeclaration(
117
+ node,
118
+ node.decorators,
119
+ node.modifiers,
120
+ node.importClause,
121
+ moduleSpecifier,
122
+ node.assertClause
123
+ );
102
124
  } else {
103
- newNode = tsBinary.factory.updateExportDeclaration(node, node.decorators, node.modifiers, node.isTypeOnly, node.exportClause, moduleSpecifier, node.assertClause);
125
+ newNode = tsBinary.factory.updateExportDeclaration(
126
+ node,
127
+ node.decorators,
128
+ node.modifiers,
129
+ node.isTypeOnly,
130
+ node.exportClause,
131
+ moduleSpecifier,
132
+ node.assertClause
133
+ );
104
134
  }
105
135
  newNode.flags = node.flags;
106
136
  return newNode;
107
- } catch (_unused) {
137
+ } catch (e) {
108
138
  return node;
109
139
  }
110
140
  }
@@ -114,44 +144,44 @@ export function tsconfigPathsBeforeHookFactory(tsBinary, baseUrl, paths) {
114
144
  };
115
145
  };
116
146
  }
117
-
118
- // fork from https://github.com/nestjs/nest-cli/blob/HEAD/lib/compiler/hooks/tsconfig-paths.hook.ts
119
147
  function getNotAliasedPath(sf, matcher, text) {
120
- let result = matcher(text, undefined, undefined, ['.ts', '.tsx', '.js', '.jsx']);
148
+ let result = matcher(text, void 0, void 0, [
149
+ ".ts",
150
+ ".tsx",
151
+ ".js",
152
+ ".jsx"
153
+ ]);
121
154
  if (!result) {
122
155
  return;
123
156
  }
124
- if (os.platform() === 'win32') {
125
- result = result.replace(/\\/g, '/');
157
+ if (os.platform() === "win32") {
158
+ result = result.replace(/\\/g, "/");
126
159
  }
127
160
  if (!path.isAbsolute(result)) {
128
- // handle alias to alias
129
- if (!result.startsWith('.') && !result.startsWith('..')) {
161
+ if (!result.startsWith(".") && !result.startsWith("..")) {
130
162
  try {
131
- // Installed packages (node modules) should take precedence over root files with the same name.
132
- // Ref: https://github.com/nestjs/nest-cli/issues/838
133
163
  const packagePath = require.resolve(result, {
134
164
  paths: [process.cwd(), ...module.paths]
135
165
  });
136
166
  if (packagePath) {
137
- // eslint-disable-next-line consistent-return
138
167
  return result;
139
168
  }
140
- } catch (_unused2) {}
169
+ } catch (e) {
170
+ }
141
171
  }
142
172
  try {
143
- // Installed packages (node modules) should take precedence over root files with the same name.
144
- // Ref: https://github.com/nestjs/nest-cli/issues/838
145
173
  const packagePath = require.resolve(text, {
146
174
  paths: [process.cwd(), ...module.paths]
147
175
  });
148
176
  if (packagePath) {
149
- // eslint-disable-next-line consistent-return
150
177
  return text;
151
178
  }
152
- } catch (_unused3) {}
179
+ } catch (e) {
180
+ }
153
181
  }
154
- const resolvedPath = posix.relative(dirname(sf.fileName), result) || './';
155
- // eslint-disable-next-line consistent-return
156
- return resolvedPath[0] === '.' ? resolvedPath : `./${resolvedPath}`;
157
- }
182
+ const resolvedPath = posix.relative(dirname(sf.fileName), result) || "./";
183
+ return resolvedPath[0] === "." ? resolvedPath : `./${resolvedPath}`;
184
+ }
185
+ export {
186
+ tsconfigPathsBeforeHookFactory
187
+ };
@@ -1,10 +1,5 @@
1
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2
- export class TypescriptLoader {
3
- constructor({
4
- appDirectory
5
- }) {
6
- _defineProperty(this, "tsBinary", void 0);
7
- _defineProperty(this, "appDirectory", void 0);
1
+ class TypescriptLoader {
2
+ constructor({ appDirectory }) {
8
3
  this.appDirectory = appDirectory;
9
4
  }
10
5
  load() {
@@ -12,13 +7,18 @@ export class TypescriptLoader {
12
7
  return this.tsBinary;
13
8
  }
14
9
  try {
15
- const tsPath = require.resolve('typescript', {
10
+ const tsPath = require.resolve("typescript", {
16
11
  paths: [this.appDirectory || process.cwd()]
17
12
  });
18
13
  const ts = require(tsPath);
19
14
  return ts;
20
15
  } catch (error) {
21
- throw new Error('TypeScript could not be found! Please, install "typescript" package.');
16
+ throw new Error(
17
+ 'TypeScript could not be found! Please, install "typescript" package.'
18
+ );
22
19
  }
23
20
  }
24
- }
21
+ }
22
+ export {
23
+ TypescriptLoader
24
+ };
@@ -1,2 +1,5 @@
1
1
  export * from "./compilers/babel";
2
- export { compile } from "./common";
2
+ import { compile } from "./common";
3
+ export {
4
+ compile
5
+ };
@@ -1,40 +1,85 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
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 __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
21
+ mod
22
+ ));
23
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+ var __async = (__this, __arguments, generator) => {
25
+ return new Promise((resolve, reject) => {
26
+ var fulfilled = (value) => {
27
+ try {
28
+ step(generator.next(value));
29
+ } catch (e) {
30
+ reject(e);
31
+ }
32
+ };
33
+ var rejected = (value) => {
34
+ try {
35
+ step(generator.throw(value));
36
+ } catch (e) {
37
+ reject(e);
38
+ }
39
+ };
40
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
41
+ step((generator = generator.apply(__this, __arguments)).next());
42
+ });
43
+ };
44
+ var common_exports = {};
45
+ __export(common_exports, {
46
+ FILE_EXTENSIONS: () => FILE_EXTENSIONS,
47
+ compile: () => compile
5
48
  });
6
- exports.compile = exports.FILE_EXTENSIONS = void 0;
7
- var path = _interopRequireWildcard(require("path"));
8
- var _utils = require("@modern-js/utils");
9
- var _typescript = require("../compilers/typescript");
10
- var _babel = require("../compilers/babel");
11
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
12
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
13
- const FILE_EXTENSIONS = ['.js', '.ts', '.mjs', '.ejs'];
14
- exports.FILE_EXTENSIONS = FILE_EXTENSIONS;
49
+ module.exports = __toCommonJS(common_exports);
50
+ var path = __toESM(require("path"));
51
+ var import_utils = require("@modern-js/utils");
52
+ var import_typescript = require("../compilers/typescript");
53
+ var import_babel = require("../compilers/babel");
54
+ const FILE_EXTENSIONS = [".js", ".ts", ".mjs", ".ejs"];
15
55
  const validateAbsolutePath = (filename, message) => {
16
56
  if (!path.isAbsolute(filename)) {
17
57
  throw new Error(message);
18
58
  }
19
59
  };
20
60
  const validateAbsolutePaths = (filenames, messageFunc) => {
21
- filenames.forEach(filename => validateAbsolutePath(filename, messageFunc(filename)));
61
+ filenames.forEach(
62
+ (filename) => validateAbsolutePath(filename, messageFunc(filename))
63
+ );
22
64
  };
23
- const compile = async (appDirectory, modernConfig, compileOptions) => {
24
- var _modernConfig$server;
25
- const {
65
+ const compile = (appDirectory, modernConfig, compileOptions) => __async(void 0, null, function* () {
66
+ var _a;
67
+ const { sourceDirs, distDir, tsconfigPath } = compileOptions;
68
+ validateAbsolutePaths(
26
69
  sourceDirs,
27
- distDir,
28
- tsconfigPath
29
- } = compileOptions;
30
- validateAbsolutePaths(sourceDirs, dir => `source dir ${dir} is not an absolute path.`);
70
+ (dir) => `source dir ${dir} is not an absolute path.`
71
+ );
31
72
  validateAbsolutePath(distDir, `dist dir ${distDir} is not an absolute path.`);
32
- const compiler = modernConfig === null || modernConfig === void 0 ? void 0 : (_modernConfig$server = modernConfig.server) === null || _modernConfig$server === void 0 ? void 0 : _modernConfig$server.compiler;
33
- const isTsProject = tsconfigPath && (await _utils.fs.pathExists(tsconfigPath));
34
- if (!isTsProject || compiler === 'babel') {
35
- await (0, _babel.compileByBabel)(appDirectory, modernConfig, compileOptions);
73
+ const compiler = (_a = modernConfig == null ? void 0 : modernConfig.server) == null ? void 0 : _a.compiler;
74
+ const isTsProject = tsconfigPath && (yield import_utils.fs.pathExists(tsconfigPath));
75
+ if (!isTsProject || compiler === "babel") {
76
+ yield (0, import_babel.compileByBabel)(appDirectory, modernConfig, compileOptions);
36
77
  } else {
37
- await (0, _typescript.compileByTs)(appDirectory, modernConfig, compileOptions);
78
+ yield (0, import_typescript.compileByTs)(appDirectory, modernConfig, compileOptions);
38
79
  }
39
- };
40
- exports.compile = compile;
80
+ });
81
+ // Annotate the CommonJS export names for ESM import in node:
82
+ 0 && (module.exports = {
83
+ FILE_EXTENSIONS,
84
+ compile
85
+ });
@@ -1,134 +1,178 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- var _exportNames = {
7
- readTsConfig: true,
8
- existTsConfigFile: true,
9
- getBabelConfig: true,
10
- resolveBabelConfig: true,
11
- compileByBabel: true
12
- };
13
- exports.resolveBabelConfig = exports.readTsConfig = exports.getBabelConfig = exports.existTsConfigFile = exports.compileByBabel = void 0;
14
- var path = _interopRequireWildcard(require("path"));
15
- var _babelPresetLib = require("@modern-js/babel-preset-lib");
16
- var _utils = require("@modern-js/utils");
17
- var _babelCompiler = require("@modern-js/babel-compiler");
18
- var _common = require("../../common");
19
- var _core = require("@babel/core");
20
- Object.keys(_core).forEach(function (key) {
21
- if (key === "default" || key === "__esModule") return;
22
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
23
- if (key in exports && exports[key] === _core[key]) return;
24
- Object.defineProperty(exports, key, {
25
- enumerable: true,
26
- get: function () {
27
- return _core[key];
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
28
20
  }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __export = (target, all) => {
25
+ for (var name in all)
26
+ __defProp(target, name, { get: all[name], enumerable: true });
27
+ };
28
+ var __copyProps = (to, from, except, desc) => {
29
+ if (from && typeof from === "object" || typeof from === "function") {
30
+ for (let key of __getOwnPropNames(from))
31
+ if (!__hasOwnProp.call(to, key) && key !== except)
32
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
33
+ }
34
+ return to;
35
+ };
36
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
39
+ mod
40
+ ));
41
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
42
+ var __async = (__this, __arguments, generator) => {
43
+ return new Promise((resolve, reject) => {
44
+ var fulfilled = (value) => {
45
+ try {
46
+ step(generator.next(value));
47
+ } catch (e) {
48
+ reject(e);
49
+ }
50
+ };
51
+ var rejected = (value) => {
52
+ try {
53
+ step(generator.throw(value));
54
+ } catch (e) {
55
+ reject(e);
56
+ }
57
+ };
58
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
59
+ step((generator = generator.apply(__this, __arguments)).next());
29
60
  });
61
+ };
62
+ var babel_exports = {};
63
+ __export(babel_exports, {
64
+ compileByBabel: () => compileByBabel,
65
+ existTsConfigFile: () => existTsConfigFile,
66
+ getBabelConfig: () => getBabelConfig,
67
+ readTsConfig: () => readTsConfig,
68
+ resolveBabelConfig: () => resolveBabelConfig
30
69
  });
31
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
32
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
33
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
34
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
35
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
70
+ module.exports = __toCommonJS(babel_exports);
71
+ var path = __toESM(require("path"));
72
+ var import_babel_preset_lib = require("@modern-js/babel-preset-lib");
73
+ var import_utils = require("@modern-js/utils");
74
+ var import_babel_compiler = require("@modern-js/babel-compiler");
75
+ var import_common = require("../../common");
76
+ __reExport(babel_exports, require("@babel/core"), module.exports);
36
77
  const readTsConfig = (tsconfigPath, noExistReturn = null) => {
37
- // 如果不存在,则返回 noExistReturn
38
- if (!_utils.fs.existsSync(tsconfigPath)) {
78
+ if (!import_utils.fs.existsSync(tsconfigPath)) {
39
79
  return noExistReturn;
40
80
  }
41
- const content = _utils.fs.readFileSync(tsconfigPath, 'utf-8');
42
- return _utils.json5.parse(content);
81
+ const content = import_utils.fs.readFileSync(tsconfigPath, "utf-8");
82
+ return import_utils.json5.parse(content);
43
83
  };
44
- exports.readTsConfig = readTsConfig;
45
- const existTsConfigFile = tsconfigAbsolutePath => {
84
+ const existTsConfigFile = (tsconfigAbsolutePath) => {
46
85
  const tsconfig = readTsConfig(tsconfigAbsolutePath);
47
86
  return Boolean(tsconfig);
48
87
  };
49
- exports.existTsConfigFile = existTsConfigFile;
50
88
  const getBabelConfig = (libPresetOption, syntaxOption) => {
51
- const chain = (0, _babelPresetLib.getBabelChain)(libPresetOption, syntaxOption);
52
- return _objectSpread({
53
- sourceType: 'unambiguous'
89
+ const chain = (0, import_babel_preset_lib.getBabelChain)(libPresetOption, syntaxOption);
90
+ return __spreadValues({
91
+ sourceType: "unambiguous"
54
92
  }, chain.toJSON());
55
93
  };
56
- exports.getBabelConfig = getBabelConfig;
57
94
  const resolveBabelConfig = (appDirectory, config, option) => {
58
- const {
59
- globalVars,
60
- alias,
61
- babelConfig,
62
- define
63
- } = config;
95
+ const { globalVars, alias, babelConfig, define } = config;
64
96
  const globalDefineVars = define && Object.entries(define).reduce((object, [key, value]) => {
65
97
  object[key] = JSON.stringify(value);
66
98
  return object;
67
99
  }, {});
68
- // alias config
69
- const aliasConfig = (0, _utils.getAliasConfig)(alias, _objectSpread({
100
+ const aliasConfig = (0, import_utils.getAliasConfig)(alias, __spreadValues({
70
101
  appDirectory
71
102
  }, option));
72
-
73
- // babel config
74
- const babelChain = (0, _babelPresetLib.getBabelChain)({
75
- appDirectory,
76
- enableReactPreset: true,
77
- enableTypescriptPreset: true,
78
- alias: aliasConfig,
79
- envVars: [],
80
- globalVars: _objectSpread(_objectSpread({}, globalVars), globalDefineVars)
81
- }, {
82
- type: option.type,
83
- syntax: option.syntax
84
- });
85
- const envOptions = babelChain.preset('@babel/preset-env').options();
86
- babelChain.preset('@babel/preset-env').use(require.resolve('@babel/preset-env'), [_objectSpread(_objectSpread({}, envOptions[0]), {}, {
87
- loose: true
88
- })]);
89
- babelChain.plugin('babel-plugin-transform-typescript-metadata').use(require.resolve('babel-plugin-transform-typescript-metadata'), []);
90
- babelChain.plugin('@babel/plugin-proposal-decorators').use(require.resolve('@babel/plugin-proposal-decorators'), [{
91
- legacy: true
92
- }]);
93
-
94
- // resolve "Definitely assigned fields cannot be initialized here, but only in the constructor."
95
- babelChain.plugin('@babel/plugin-proposal-class-properties').use(require.resolve('@babel/plugin-proposal-class-properties'), [{
96
- loose: true
97
- }]);
98
- const internalBabelConfig = _objectSpread({}, babelChain.toJSON());
99
- return (0, _babelPresetLib.applyUserBabelConfig)(internalBabelConfig, babelConfig);
103
+ const babelChain = (0, import_babel_preset_lib.getBabelChain)(
104
+ {
105
+ appDirectory,
106
+ enableReactPreset: true,
107
+ enableTypescriptPreset: true,
108
+ alias: aliasConfig,
109
+ envVars: [],
110
+ globalVars: __spreadValues(__spreadValues({}, globalVars), globalDefineVars)
111
+ },
112
+ {
113
+ type: option.type,
114
+ syntax: option.syntax
115
+ }
116
+ );
117
+ const envOptions = babelChain.preset("@babel/preset-env").options();
118
+ babelChain.preset("@babel/preset-env").use(require.resolve("@babel/preset-env"), [
119
+ __spreadProps(__spreadValues({}, envOptions[0]), {
120
+ loose: true
121
+ })
122
+ ]);
123
+ babelChain.plugin("babel-plugin-transform-typescript-metadata").use(
124
+ require.resolve("babel-plugin-transform-typescript-metadata"),
125
+ []
126
+ );
127
+ babelChain.plugin("@babel/plugin-proposal-decorators").use(require.resolve("@babel/plugin-proposal-decorators"), [
128
+ { legacy: true }
129
+ ]);
130
+ babelChain.plugin("@babel/plugin-proposal-class-properties").use(require.resolve("@babel/plugin-proposal-class-properties"), [
131
+ {
132
+ loose: true
133
+ }
134
+ ]);
135
+ const internalBabelConfig = __spreadValues({}, babelChain.toJSON());
136
+ return (0, import_babel_preset_lib.applyUserBabelConfig)(internalBabelConfig, babelConfig);
100
137
  };
101
- exports.resolveBabelConfig = resolveBabelConfig;
102
- const compileByBabel = async (appDirectory, config, compileOptions) => {
103
- const {
104
- sourceDirs,
105
- distDir,
106
- tsconfigPath
107
- } = compileOptions;
108
- const results = await Promise.all(sourceDirs.map(async sourceDir => {
109
- const babelConfig = resolveBabelConfig(appDirectory, config, {
110
- tsconfigPath: tsconfigPath ? tsconfigPath : '',
111
- syntax: 'es6+',
112
- type: 'commonjs'
113
- });
114
- if (await _utils.fs.pathExists(sourceDir)) {
115
- const basename = path.basename(sourceDir);
116
- const targetDir = path.join(distDir, basename);
117
- await _utils.fs.copy(sourceDir, targetDir, {
118
- filter: src => !['.ts', '.js'].includes(path.extname(src)) && src !== tsconfigPath
138
+ const compileByBabel = (appDirectory, config, compileOptions) => __async(void 0, null, function* () {
139
+ const { sourceDirs, distDir, tsconfigPath } = compileOptions;
140
+ const results = yield Promise.all(
141
+ sourceDirs.map((sourceDir) => __async(void 0, null, function* () {
142
+ const babelConfig = resolveBabelConfig(appDirectory, config, {
143
+ tsconfigPath: tsconfigPath ? tsconfigPath : "",
144
+ syntax: "es6+",
145
+ type: "commonjs"
119
146
  });
120
- }
121
- return (0, _babelCompiler.compiler)({
122
- rootDir: appDirectory,
123
- distDir,
124
- sourceDir,
125
- extensions: _common.FILE_EXTENSIONS
126
- }, babelConfig);
127
- }));
128
- results.forEach(result => {
147
+ if (yield import_utils.fs.pathExists(sourceDir)) {
148
+ const basename = path.basename(sourceDir);
149
+ const targetDir = path.join(distDir, basename);
150
+ yield import_utils.fs.copy(sourceDir, targetDir, {
151
+ filter: (src) => ![".ts", ".js"].includes(path.extname(src)) && src !== tsconfigPath
152
+ });
153
+ }
154
+ return (0, import_babel_compiler.compiler)(
155
+ {
156
+ rootDir: appDirectory,
157
+ distDir,
158
+ sourceDir,
159
+ extensions: import_common.FILE_EXTENSIONS
160
+ },
161
+ babelConfig
162
+ );
163
+ }))
164
+ );
165
+ results.forEach((result) => {
129
166
  if (result.code === 1) {
130
167
  throw new Error(result.message);
131
168
  }
132
169
  });
133
- };
134
- exports.compileByBabel = compileByBabel;
170
+ });
171
+ // Annotate the CommonJS export names for ESM import in node:
172
+ 0 && (module.exports = {
173
+ compileByBabel,
174
+ existTsConfigFile,
175
+ getBabelConfig,
176
+ readTsConfig,
177
+ resolveBabelConfig
178
+ });