@eggjs/utils 4.4.1 → 4.5.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.
Files changed (57) hide show
  1. package/README.md +1 -6
  2. package/dist/_virtual/rolldown_runtime.js +7 -0
  3. package/dist/{commonjs/deprecated.d.ts → deprecated.d.ts} +4 -1
  4. package/dist/deprecated.js +41 -0
  5. package/dist/error/ImportResolveError.d.ts +8 -0
  6. package/dist/error/ImportResolveError.js +16 -0
  7. package/dist/{commonjs/framework.d.ts → framework.d.ts} +6 -4
  8. package/dist/framework.js +60 -0
  9. package/dist/import.d.ts +14 -0
  10. package/dist/import.js +231 -0
  11. package/dist/index.d.ts +28 -0
  12. package/dist/index.js +45 -0
  13. package/dist/plugin.d.ts +51 -0
  14. package/dist/plugin.js +112 -0
  15. package/dist/utils.js +12 -0
  16. package/package.json +26 -58
  17. package/dist/commonjs/deprecated.js +0 -59
  18. package/dist/commonjs/error/ImportResolveError.d.ts +0 -5
  19. package/dist/commonjs/error/ImportResolveError.js +0 -17
  20. package/dist/commonjs/error/index.d.ts +0 -1
  21. package/dist/commonjs/error/index.js +0 -18
  22. package/dist/commonjs/framework.js +0 -84
  23. package/dist/commonjs/import.d.ts +0 -11
  24. package/dist/commonjs/import.js +0 -326
  25. package/dist/commonjs/index.d.ts +0 -26
  26. package/dist/commonjs/index.js +0 -79
  27. package/dist/commonjs/package.json +0 -3
  28. package/dist/commonjs/plugin.d.ts +0 -49
  29. package/dist/commonjs/plugin.js +0 -127
  30. package/dist/commonjs/utils.d.ts +0 -2
  31. package/dist/commonjs/utils.js +0 -25
  32. package/dist/esm/deprecated.d.ts +0 -10
  33. package/dist/esm/deprecated.js +0 -53
  34. package/dist/esm/error/ImportResolveError.d.ts +0 -5
  35. package/dist/esm/error/ImportResolveError.js +0 -13
  36. package/dist/esm/error/index.d.ts +0 -1
  37. package/dist/esm/error/index.js +0 -2
  38. package/dist/esm/framework.d.ts +0 -16
  39. package/dist/esm/framework.js +0 -78
  40. package/dist/esm/import.d.ts +0 -11
  41. package/dist/esm/import.js +0 -316
  42. package/dist/esm/index.d.ts +0 -26
  43. package/dist/esm/index.js +0 -51
  44. package/dist/esm/package.json +0 -3
  45. package/dist/esm/plugin.d.ts +0 -49
  46. package/dist/esm/plugin.js +0 -117
  47. package/dist/esm/utils.d.ts +0 -2
  48. package/dist/esm/utils.js +0 -18
  49. package/dist/package.json +0 -4
  50. package/src/deprecated.ts +0 -58
  51. package/src/error/ImportResolveError.ts +0 -13
  52. package/src/error/index.ts +0 -1
  53. package/src/framework.ts +0 -92
  54. package/src/import.ts +0 -344
  55. package/src/index.ts +0 -58
  56. package/src/plugin.ts +0 -167
  57. package/src/utils.ts +0 -19
package/README.md CHANGED
@@ -1,16 +1,11 @@
1
1
  # @eggjs/utils
2
2
 
3
3
  [![NPM version][npm-image]][npm-url]
4
- [![CI](https://github.com/eggjs/utils/actions/workflows/nodejs.yml/badge.svg)](https://github.com/eggjs/utils/actions/workflows/nodejs.yml)
5
- [![Test coverage][codecov-image]][codecov-url]
6
4
  [![npm download][download-image]][download-url]
7
5
  [![Node.js Version](https://img.shields.io/node/v/@eggjs/utils.svg?style=flat)](https://nodejs.org/en/download/)
8
- [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com)
9
6
 
10
7
  [npm-image]: https://img.shields.io/npm/v/@eggjs/utils.svg?style=flat-square
11
8
  [npm-url]: https://npmjs.org/package/@eggjs/utils
12
- [codecov-image]: https://codecov.io/github/eggjs/utils/coverage.svg?branch=master
13
- [codecov-url]: https://codecov.io/github/eggjs/utils?branch=master
14
9
  [download-image]: https://img.shields.io/npm/dm/@eggjs/utils.svg?style=flat-square
15
10
  [download-url]: https://npmjs.org/package/@eggjs/utils
16
11
 
@@ -53,6 +48,6 @@ npm i @eggjs/utils
53
48
 
54
49
  ## Contributors
55
50
 
56
- [![Contributors](https://contrib.rocks/image?repo=eggjs/utils)](https://github.com/eggjs/utils/graphs/contributors)
51
+ [![Contributors](https://contrib.rocks/image?repo=eggjs/egg)](https://github.com/eggjs/egg/graphs/contributors)
57
52
 
58
53
  Made with [contributors-img](https://contrib.rocks).
@@ -0,0 +1,7 @@
1
+ import { createRequire } from "node:module";
2
+
3
+ //#region rolldown:runtime
4
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
5
+
6
+ //#endregion
7
+ export { __require };
@@ -1,3 +1,4 @@
1
+ //#region src/deprecated.d.ts
1
2
  /**
2
3
  * Try to get framework dir path
3
4
  * If can't find any framework, try to find egg dir path
@@ -7,4 +8,6 @@
7
8
  * @return {String} framework or egg dir path
8
9
  * @deprecated
9
10
  */
10
- export declare function getFrameworkOrEggPath(cwd: string, eggNames?: string[]): string;
11
+ declare function getFrameworkOrEggPath(cwd: string, eggNames?: string[]): string;
12
+ //#endregion
13
+ export { getFrameworkOrEggPath };
@@ -0,0 +1,41 @@
1
+ import { readJSONSync } from "./utils.js";
2
+ import path from "node:path";
3
+ import { existsSync, readdirSync } from "node:fs";
4
+
5
+ //#region src/deprecated.ts
6
+ /**
7
+ * Try to get framework dir path
8
+ * If can't find any framework, try to find egg dir path
9
+ *
10
+ * @param {String} cwd - current work path
11
+ * @param {Array} [eggNames] - egg names, default is ['egg']
12
+ * @return {String} framework or egg dir path
13
+ * @deprecated
14
+ */
15
+ function getFrameworkOrEggPath(cwd, eggNames) {
16
+ eggNames = eggNames || ["egg"];
17
+ const moduleDir = path.join(cwd, "node_modules");
18
+ if (!existsSync(moduleDir)) return "";
19
+ const pkgFile = path.join(cwd, "package.json");
20
+ if (existsSync(pkgFile)) {
21
+ const pkg = readJSONSync(pkgFile);
22
+ if (pkg.egg && pkg.egg.framework) return path.join(moduleDir, pkg.egg.framework);
23
+ }
24
+ const names = readdirSync(moduleDir);
25
+ for (const name of names) {
26
+ const pkgfile = path.join(moduleDir, name, "package.json");
27
+ if (!existsSync(pkgfile)) continue;
28
+ const pkg = readJSONSync(pkgfile);
29
+ if (pkg.dependencies) {
30
+ for (const eggName of eggNames) if (pkg.dependencies[eggName]) return path.join(moduleDir, name);
31
+ }
32
+ }
33
+ for (const eggName of eggNames) {
34
+ const pkgfile = path.join(moduleDir, eggName, "package.json");
35
+ if (existsSync(pkgfile)) return path.join(moduleDir, eggName);
36
+ }
37
+ return "";
38
+ }
39
+
40
+ //#endregion
41
+ export { getFrameworkOrEggPath };
@@ -0,0 +1,8 @@
1
+ //#region src/error/ImportResolveError.d.ts
2
+ declare class ImportResolveError extends Error {
3
+ filepath: string;
4
+ paths: string[];
5
+ constructor(filepath: string, paths: string[], error: Error);
6
+ }
7
+ //#endregion
8
+ export { ImportResolveError };
@@ -0,0 +1,16 @@
1
+ //#region src/error/ImportResolveError.ts
2
+ var ImportResolveError = class extends Error {
3
+ filepath;
4
+ paths;
5
+ constructor(filepath, paths, error) {
6
+ const message = `${error.message}, paths: ${JSON.stringify(paths)}`;
7
+ super(message, { cause: error });
8
+ this.name = this.constructor.name;
9
+ this.filepath = filepath;
10
+ this.paths = paths;
11
+ Error.captureStackTrace(this, this.constructor);
12
+ }
13
+ };
14
+
15
+ //#endregion
16
+ export { ImportResolveError };
@@ -1,6 +1,7 @@
1
+ //#region src/framework.d.ts
1
2
  interface Options {
2
- baseDir: string;
3
- framework?: string;
3
+ baseDir: string;
4
+ framework?: string;
4
5
  }
5
6
  /**
6
7
  * Find the framework directory, lookup order
@@ -12,5 +13,6 @@ interface Options {
12
13
  * @param {String} [options.framework] - the directory of framework
13
14
  * @return {String} frameworkPath
14
15
  */
15
- export declare function getFrameworkPath(options: Options): string;
16
- export {};
16
+ declare function getFrameworkPath(options: Options): string;
17
+ //#endregion
18
+ export { getFrameworkPath };
@@ -0,0 +1,60 @@
1
+ import { readJSONSync } from "./utils.js";
2
+ import { importResolve } from "./import.js";
3
+ import path from "node:path";
4
+ import { debuglog } from "node:util";
5
+ import assert from "node:assert";
6
+ import { existsSync } from "node:fs";
7
+
8
+ //#region src/framework.ts
9
+ const debug = debuglog("egg/utils/framework");
10
+ const initCwd = process.cwd();
11
+ /**
12
+ * Find the framework directory, lookup order
13
+ * - specify framework path
14
+ * - get framework name from
15
+ * - use egg by default
16
+ * @param {Object} options - options
17
+ * @param {String} options.baseDir - the current directory of application
18
+ * @param {String} [options.framework] - the directory of framework
19
+ * @return {String} frameworkPath
20
+ */
21
+ function getFrameworkPath(options) {
22
+ const { framework, baseDir } = options;
23
+ const pkgPath = path.join(baseDir, "package.json");
24
+ assert(existsSync(pkgPath), `${pkgPath} should exist`);
25
+ const moduleDir = path.join(baseDir, "node_modules");
26
+ if (framework) {
27
+ if (path.isAbsolute(framework)) {
28
+ assert(existsSync(framework), `${framework} should exist`);
29
+ return framework;
30
+ }
31
+ return assertAndReturn(framework, moduleDir, baseDir);
32
+ }
33
+ const pkg = readJSONSync(pkgPath);
34
+ if (pkg.egg?.framework) return assertAndReturn(pkg.egg.framework, moduleDir, baseDir);
35
+ return assertAndReturn("egg", moduleDir, baseDir);
36
+ }
37
+ function assertAndReturn(frameworkName, moduleDir, baseDir) {
38
+ const moduleDirs = new Set([
39
+ moduleDir,
40
+ path.join(process.cwd(), "node_modules"),
41
+ path.join(initCwd, "node_modules")
42
+ ]);
43
+ try {
44
+ let globalModuleDir;
45
+ if (frameworkName.startsWith("@") && frameworkName.includes("/")) globalModuleDir = path.join(importResolve(`${frameworkName}/package.json`, { paths: [baseDir] }), "../../..");
46
+ else globalModuleDir = path.join(importResolve(`${frameworkName}/package.json`, { paths: [baseDir] }), "../..");
47
+ moduleDirs.add(globalModuleDir);
48
+ } catch {}
49
+ for (const moduleDir$1 of moduleDirs) {
50
+ const frameworkPath = path.join(moduleDir$1, frameworkName);
51
+ if (existsSync(frameworkPath)) {
52
+ debug("[assertAndReturn] frameworkPath: %s, moduleDirs: %o", frameworkPath, moduleDirs);
53
+ return frameworkPath;
54
+ }
55
+ }
56
+ throw new Error(`${frameworkName} is not found in ${Array.from(moduleDirs)}`);
57
+ }
58
+
59
+ //#endregion
60
+ export { getFrameworkPath };
@@ -0,0 +1,14 @@
1
+ //#region src/import.d.ts
2
+ interface ImportResolveOptions {
3
+ paths?: string[];
4
+ }
5
+ interface ImportModuleOptions extends ImportResolveOptions {
6
+ importDefaultOnly?: boolean;
7
+ }
8
+ declare let isESM: boolean;
9
+ declare function getExtensions(): NodeJS.RequireExtensions;
10
+ declare function isSupportTypeScript(): boolean;
11
+ declare function importResolve(filepath: string, options?: ImportResolveOptions): string;
12
+ declare function importModule(filepath: string, options?: ImportModuleOptions): Promise<any>;
13
+ //#endregion
14
+ export { ImportModuleOptions, ImportResolveOptions, getExtensions, importModule, importResolve, isESM, isSupportTypeScript };
package/dist/import.js ADDED
@@ -0,0 +1,231 @@
1
+ import { __require } from "./_virtual/rolldown_runtime.js";
2
+ import { ImportResolveError } from "./error/ImportResolveError.js";
3
+ import { createRequire } from "node:module";
4
+ import path from "node:path";
5
+ import { debuglog } from "node:util";
6
+ import fs from "node:fs";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+
9
+ //#region src/import.ts
10
+ const debug = debuglog("egg/utils/import");
11
+ let isESM = true;
12
+ try {
13
+ if (typeof import.meta !== "undefined") isESM = true;
14
+ } catch {
15
+ isESM = false;
16
+ }
17
+ const supportImportMetaResolve = parseInt(process.versions.node.split(".", 1)[0], 10) >= 18;
18
+ let _customRequire;
19
+ function getRequire() {
20
+ if (!_customRequire) if (typeof __require !== "undefined") _customRequire = __require;
21
+ else _customRequire = createRequire(process.cwd());
22
+ return _customRequire;
23
+ }
24
+ function getExtensions() {
25
+ return getRequire().extensions;
26
+ }
27
+ let _supportTypeScript;
28
+ function isSupportTypeScript() {
29
+ if (_supportTypeScript === void 0) {
30
+ const extensions = getExtensions();
31
+ _supportTypeScript = extensions[".ts"] !== void 0 || process.env.VITEST === "true" || process.env.EGG_TS_ENABLE === "true" || parseInt(process.versions.node.split(".", 1)[0], 10) >= 22;
32
+ debug("[isSupportTypeScript] %o, extensions: %j, process.env.VITEST: %j, process.env.EGG_TS_ENABLE: %j, node version: %s", _supportTypeScript, Object.keys(extensions), process.env.VITEST, process.env.EGG_TS_ENABLE, process.versions.node);
33
+ }
34
+ return _supportTypeScript;
35
+ }
36
+ function tryToResolveFromFile(filepath) {
37
+ const type = isESM ? "module" : "commonjs";
38
+ let mainIndexFile = "";
39
+ if (type === "module") {
40
+ mainIndexFile = filepath + ".mjs";
41
+ if (fs.existsSync(mainIndexFile)) {
42
+ debug("[tryToResolveFromFile] %o, use index.mjs, type: %o", mainIndexFile, type);
43
+ return mainIndexFile;
44
+ }
45
+ mainIndexFile = filepath + ".js";
46
+ if (fs.existsSync(mainIndexFile)) {
47
+ debug("[tryToResolveFromFile] %o, use index.js, type: %o", mainIndexFile, type);
48
+ return mainIndexFile;
49
+ }
50
+ } else {
51
+ mainIndexFile = filepath + ".cjs";
52
+ if (fs.existsSync(mainIndexFile)) {
53
+ debug("[tryToResolveFromFile] %o, use index.cjs, type: %o", mainIndexFile, type);
54
+ return mainIndexFile;
55
+ }
56
+ mainIndexFile = filepath + ".js";
57
+ if (fs.existsSync(mainIndexFile)) {
58
+ debug("[tryToResolveFromFile] %o, use index.js, type: %o", mainIndexFile, type);
59
+ return mainIndexFile;
60
+ }
61
+ }
62
+ if (!isSupportTypeScript()) return;
63
+ mainIndexFile = filepath + ".ts";
64
+ if (fs.existsSync(mainIndexFile)) {
65
+ debug("[tryToResolveFromFile] %o, use index.ts, type: %o", mainIndexFile, type);
66
+ return mainIndexFile;
67
+ }
68
+ }
69
+ function tryToResolveByDirnameFromPackage(dirname, pkg) {
70
+ const defaultMainFile = isESM ? pkg.module ?? pkg.main : pkg.main;
71
+ if (defaultMainFile) {
72
+ const mainIndexFilePath$1 = path.join(dirname, defaultMainFile);
73
+ if (fs.existsSync(mainIndexFilePath$1)) {
74
+ debug("[tryToResolveByDirnameFromPackage] %o, use pkg.main or pkg.module: %o, isESM: %s", mainIndexFilePath$1, defaultMainFile, isESM);
75
+ return mainIndexFilePath$1;
76
+ }
77
+ }
78
+ if (pkg.exports?.["."]) {
79
+ const pkgType = pkg.type ?? "commonjs";
80
+ const defaultExport = pkg.exports["."];
81
+ let mainIndexFilePath$1 = "";
82
+ if (typeof defaultExport === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport);
83
+ else if (pkgType === "module") {
84
+ if (typeof defaultExport.import === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport.import);
85
+ else if (typeof defaultExport.import?.default === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport.import.default);
86
+ } else if (typeof defaultExport.require === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport.require);
87
+ else if (typeof defaultExport.require?.default === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport.require.default);
88
+ if (mainIndexFilePath$1 && fs.existsSync(mainIndexFilePath$1)) {
89
+ debug("[tryToResolveByDirnameFromPackage] %o, use pkg.exports[.]: %o, pkg.type: %o", mainIndexFilePath$1, defaultExport, pkgType);
90
+ return mainIndexFilePath$1;
91
+ }
92
+ }
93
+ const type = pkg?.type ?? (isESM ? "module" : "commonjs");
94
+ if (type === "module") {
95
+ const mainIndexFilePath$1 = path.join(dirname, "index.mjs");
96
+ if (fs.existsSync(mainIndexFilePath$1)) {
97
+ debug("[tryToResolveByDirnameFromPackage] %o, use index.mjs, pkg.type: %o", mainIndexFilePath$1, type);
98
+ return mainIndexFilePath$1;
99
+ }
100
+ const mainIndexMjsFilePath = path.join(dirname, "index.js");
101
+ if (fs.existsSync(mainIndexMjsFilePath)) {
102
+ debug("[tryToResolveByDirnameFromPackage] %o, use index.js, pkg.type: %o", mainIndexMjsFilePath, type);
103
+ return mainIndexMjsFilePath;
104
+ }
105
+ } else {
106
+ const mainIndexFilePath$1 = path.join(dirname, "index.cjs");
107
+ if (fs.existsSync(mainIndexFilePath$1)) {
108
+ debug("[tryToResolveByDirnameFromPackage] %o, use index.cjs, pkg.type: %o", mainIndexFilePath$1, type);
109
+ return mainIndexFilePath$1;
110
+ }
111
+ const mainIndexCjsFilePath = path.join(dirname, "index.js");
112
+ if (fs.existsSync(mainIndexCjsFilePath)) {
113
+ debug("[tryToResolveByDirnameFromPackage] %o, use index.js, pkg.type: %o", mainIndexCjsFilePath, type);
114
+ return mainIndexCjsFilePath;
115
+ }
116
+ }
117
+ if (!isSupportTypeScript()) return;
118
+ const mainIndexFile = pkg.tshy?.exports?.["."] ?? "index.ts";
119
+ const mainIndexFilePath = path.join(dirname, mainIndexFile);
120
+ if (fs.existsSync(mainIndexFilePath)) return mainIndexFilePath;
121
+ }
122
+ function tryToResolveByDirname(dirname) {
123
+ let pkg = {};
124
+ const pkgFile = path.join(dirname, "package.json");
125
+ if (fs.existsSync(pkgFile)) pkg = JSON.parse(fs.readFileSync(pkgFile, "utf-8"));
126
+ return tryToResolveByDirnameFromPackage(dirname, pkg);
127
+ }
128
+ function isRelativePath(filepath) {
129
+ return filepath.startsWith("./") || filepath.startsWith("../") || filepath.startsWith(".\\") || filepath.startsWith("..\\");
130
+ }
131
+ function tryToResolveFromAbsoluteFile(filepath) {
132
+ let moduleFilePath;
133
+ const stat = fs.statSync(filepath, { throwIfNoEntry: false });
134
+ if (stat?.isDirectory()) {
135
+ moduleFilePath = tryToResolveByDirname(filepath);
136
+ if (moduleFilePath) return moduleFilePath;
137
+ } else if (stat?.isFile()) return filepath;
138
+ moduleFilePath = tryToResolveFromFile(filepath);
139
+ if (moduleFilePath) return moduleFilePath;
140
+ const parentDir = path.dirname(filepath);
141
+ const basename = path.basename(filepath);
142
+ const pkgFile = path.join(parentDir, "package.json");
143
+ if (fs.existsSync(pkgFile)) {
144
+ const pkg = JSON.parse(fs.readFileSync(pkgFile, "utf-8"));
145
+ const key = `./${basename}`;
146
+ if (pkg.exports?.[key]) return path.join(parentDir, pkg.exports[key]);
147
+ }
148
+ }
149
+ function importResolve(filepath, options) {
150
+ const paths = options?.paths ?? [process.cwd()];
151
+ debug("[importResolve] filepath: %o, options: %j, paths: %j", filepath, options, paths);
152
+ let moduleFilePath;
153
+ const isAbsolute = path.isAbsolute(filepath);
154
+ if (isAbsolute) {
155
+ moduleFilePath = tryToResolveFromAbsoluteFile(filepath);
156
+ if (moduleFilePath) {
157
+ debug("[importResolve:isAbsolute] %o => %o", filepath, moduleFilePath);
158
+ return moduleFilePath;
159
+ }
160
+ } else if (isRelativePath(filepath)) for (const p of paths) {
161
+ const resolvedPath = path.resolve(p, filepath);
162
+ moduleFilePath = tryToResolveFromAbsoluteFile(resolvedPath);
163
+ if (moduleFilePath) {
164
+ debug("[importResolve:isRelativePath] %o => %o => %o", filepath, resolvedPath, moduleFilePath);
165
+ return moduleFilePath;
166
+ }
167
+ }
168
+ for (const p of paths) {
169
+ let resolvedPath = path.join(p, "node_modules", filepath);
170
+ moduleFilePath = tryToResolveFromAbsoluteFile(resolvedPath);
171
+ if (moduleFilePath) {
172
+ debug("[importResolve:node_modules] %o => %o => %o", filepath, resolvedPath, moduleFilePath);
173
+ return moduleFilePath;
174
+ }
175
+ let parentPath = path.dirname(p);
176
+ if (path.basename(parentPath) === "node_modules") {
177
+ resolvedPath = path.join(parentPath, filepath);
178
+ moduleFilePath = tryToResolveFromAbsoluteFile(resolvedPath);
179
+ if (moduleFilePath) {
180
+ debug("[importResolve:node_modules] %o => %o => %o", filepath, resolvedPath, moduleFilePath);
181
+ return moduleFilePath;
182
+ }
183
+ }
184
+ parentPath = path.dirname(parentPath);
185
+ if (path.basename(parentPath) === "node_modules") {
186
+ resolvedPath = path.join(parentPath, filepath);
187
+ moduleFilePath = tryToResolveFromAbsoluteFile(resolvedPath);
188
+ if (moduleFilePath) {
189
+ debug("[importResolve:node_modules] %o => %o => %o", filepath, resolvedPath, moduleFilePath);
190
+ return moduleFilePath;
191
+ }
192
+ }
193
+ }
194
+ const extname = path.extname(filepath);
195
+ if (!isAbsolute && extname === ".json" || !isESM) moduleFilePath = getRequire().resolve(filepath, { paths });
196
+ else if (supportImportMetaResolve) {
197
+ try {
198
+ moduleFilePath = import.meta.resolve(filepath);
199
+ } catch (err) {
200
+ debug("[importResolve:error] import.meta.resolve %o => %o, options: %o", filepath, err, options);
201
+ throw new ImportResolveError(filepath, paths, err);
202
+ }
203
+ if (moduleFilePath.startsWith("file://")) moduleFilePath = fileURLToPath(moduleFilePath);
204
+ debug("[importResolve] import.meta.resolve %o => %o", filepath, moduleFilePath);
205
+ if (!fs.statSync(moduleFilePath, { throwIfNoEntry: false })?.isFile()) throw new TypeError(`Cannot find module ${filepath}, because ${moduleFilePath} does not exists`);
206
+ } else moduleFilePath = getRequire().resolve(filepath);
207
+ debug("[importResolve:success] %o, options: %o => %o, isESM: %s", filepath, options, moduleFilePath, isESM);
208
+ return moduleFilePath;
209
+ }
210
+ async function importModule(filepath, options) {
211
+ const moduleFilePath = importResolve(filepath, options);
212
+ let obj;
213
+ if (isESM) {
214
+ const fileUrl = pathToFileURL(moduleFilePath).toString();
215
+ obj = await import(fileUrl);
216
+ debug("[importModule:success] await import %o", fileUrl);
217
+ if (obj?.default?.__esModule === true && "default" in obj?.default) obj = obj.default;
218
+ if (options?.importDefaultOnly) {
219
+ if ("default" in obj) obj = obj.default;
220
+ }
221
+ } else {
222
+ obj = __require(moduleFilePath);
223
+ debug("[importModule] require %o", moduleFilePath);
224
+ if (obj?.__esModule === true && "default" in obj) obj = obj.default;
225
+ }
226
+ if (debug.enabled) debug("[importModule] return %o => keys: %j, typeof obj: %s", filepath, obj ? Object.keys(obj) : obj, typeof obj);
227
+ return obj;
228
+ }
229
+
230
+ //#endregion
231
+ export { getExtensions, importModule, importResolve, isESM, isSupportTypeScript };
@@ -0,0 +1,28 @@
1
+ import { getFrameworkPath } from "./framework.js";
2
+ import { findEggCore, getConfig, getLoadUnits, getLoader, getPlugins } from "./plugin.js";
3
+ import { getFrameworkOrEggPath } from "./deprecated.js";
4
+ import { ImportModuleOptions, ImportResolveOptions, getExtensions, importModule, importResolve, isESM, isSupportTypeScript } from "./import.js";
5
+ import { ImportResolveError } from "./error/ImportResolveError.js";
6
+
7
+ //#region src/index.d.ts
8
+
9
+ declare const _default: {
10
+ getFrameworkPath: typeof getFrameworkPath;
11
+ getPlugins: typeof getPlugins;
12
+ getConfig: typeof getConfig;
13
+ getLoadUnits: typeof getLoadUnits;
14
+ getFrameworkOrEggPath: typeof getFrameworkOrEggPath;
15
+ };
16
+ declare const EggType: {
17
+ readonly framework: "framework";
18
+ readonly plugin: "plugin";
19
+ readonly application: "application";
20
+ readonly unknown: "unknown";
21
+ };
22
+ type EggType = (typeof EggType)[keyof typeof EggType];
23
+ /**
24
+ * Detect the type of egg project
25
+ */
26
+ declare function detectType(baseDir: string): Promise<keyof typeof EggType>;
27
+ //#endregion
28
+ export { EggType, ImportModuleOptions, ImportResolveError, ImportResolveOptions, _default as default, detectType, findEggCore, getConfig, getExtensions, getFrameworkOrEggPath, getFrameworkPath, getLoadUnits, getLoader, getPlugins, importModule, importResolve, isESM, isSupportTypeScript };
package/dist/index.js ADDED
@@ -0,0 +1,45 @@
1
+ import { ImportResolveError } from "./error/ImportResolveError.js";
2
+ import { getExtensions, importModule, importResolve, isESM, isSupportTypeScript } from "./import.js";
3
+ import { getFrameworkPath } from "./framework.js";
4
+ import { findEggCore, getConfig, getLoadUnits, getLoader, getPlugins } from "./plugin.js";
5
+ import { getFrameworkOrEggPath } from "./deprecated.js";
6
+ import path from "node:path";
7
+ import fs from "node:fs/promises";
8
+
9
+ //#region src/index.ts
10
+ var src_default = {
11
+ getFrameworkPath,
12
+ getPlugins,
13
+ getConfig,
14
+ getLoadUnits,
15
+ getFrameworkOrEggPath
16
+ };
17
+ const EggType = {
18
+ framework: "framework",
19
+ plugin: "plugin",
20
+ application: "application",
21
+ unknown: "unknown"
22
+ };
23
+ /**
24
+ * Detect the type of egg project
25
+ */
26
+ async function detectType(baseDir) {
27
+ const pkgFile = path.join(baseDir, "package.json");
28
+ let pkg;
29
+ try {
30
+ await fs.access(pkgFile);
31
+ } catch {
32
+ return EggType.unknown;
33
+ }
34
+ try {
35
+ pkg = JSON.parse(await fs.readFile(pkgFile, "utf-8"));
36
+ } catch {
37
+ return EggType.unknown;
38
+ }
39
+ if (pkg.egg?.framework) return EggType.framework;
40
+ if (pkg.eggPlugin?.name) return EggType.plugin;
41
+ return EggType.application;
42
+ }
43
+
44
+ //#endregion
45
+ export { EggType, ImportResolveError, src_default as default, detectType, findEggCore, getConfig, getExtensions, getFrameworkOrEggPath, getFrameworkPath, getLoadUnits, getLoader, getPlugins, importModule, importResolve, isESM, isSupportTypeScript };
@@ -0,0 +1,51 @@
1
+ //#region src/plugin.d.ts
2
+ interface LoaderOptions {
3
+ framework: string;
4
+ baseDir: string;
5
+ env?: string;
6
+ }
7
+ interface Plugin {
8
+ name: string;
9
+ version?: string;
10
+ enable: boolean;
11
+ implicitEnable: boolean;
12
+ path: string;
13
+ dependencies: string[];
14
+ optionalDependencies: string[];
15
+ env: string[];
16
+ from: string;
17
+ }
18
+ /**
19
+ * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/mixin/plugin.js#L203
20
+ */
21
+ declare function getPlugins(options: LoaderOptions): Promise<Record<string, Plugin>>;
22
+ interface Unit {
23
+ type: 'plugin' | 'framework' | 'app';
24
+ path: string;
25
+ }
26
+ /**
27
+ * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/egg_loader.js#L348
28
+ */
29
+ declare function getLoadUnits(options: LoaderOptions): Promise<Unit[]>;
30
+ declare function getConfig(options: LoaderOptions): Promise<Record<string, any>>;
31
+ interface IEggLoader {
32
+ loadPlugin(): Promise<void>;
33
+ loadConfig(): Promise<void>;
34
+ config: Record<string, any>;
35
+ getLoadUnits(): Unit[];
36
+ allPlugins: Record<string, Plugin>;
37
+ }
38
+ interface IEggLoaderOptions {
39
+ baseDir: string;
40
+ app: unknown;
41
+ logger: object;
42
+ EggCoreClass?: unknown;
43
+ }
44
+ type EggLoaderImplClass<T = IEggLoader> = new (options: IEggLoaderOptions) => T;
45
+ declare function getLoader(options: LoaderOptions): Promise<IEggLoader>;
46
+ declare function findEggCore(options: LoaderOptions): Promise<{
47
+ EggCore?: object;
48
+ EggLoader: EggLoaderImplClass;
49
+ }>;
50
+ //#endregion
51
+ export { findEggCore, getConfig, getLoadUnits, getLoader, getPlugins };