@eggjs/utils 5.0.0-beta.19 → 5.0.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,11 +1,104 @@
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, getRequire, importModule, importResolve, isESM, isSupportTypeScript } from "./import.js";
5
- import { ImportResolveError } from "./error/ImportResolveError.js";
6
-
1
+ //#region src/framework.d.ts
2
+ interface Options {
3
+ baseDir: string;
4
+ framework?: string;
5
+ }
6
+ /**
7
+ * Find the framework directory, lookup order
8
+ * - specify framework path
9
+ * - get framework name from
10
+ * - use egg by default
11
+ * @param {Object} options - options
12
+ * @param {String} options.baseDir - the current directory of application
13
+ * @param {String} [options.framework] - the directory of framework
14
+ * @return {String} frameworkPath
15
+ */
16
+ declare function getFrameworkPath(options: Options): string;
17
+ //#endregion
18
+ //#region src/plugin.d.ts
19
+ interface LoaderOptions {
20
+ framework: string;
21
+ baseDir: string;
22
+ env?: string;
23
+ }
24
+ interface Plugin {
25
+ name: string;
26
+ version?: string;
27
+ enable: boolean;
28
+ implicitEnable: boolean;
29
+ path: string;
30
+ dependencies: string[];
31
+ optionalDependencies: string[];
32
+ env: string[];
33
+ from: string;
34
+ }
35
+ /**
36
+ * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/mixin/plugin.js#L203
37
+ */
38
+ declare function getPlugins(options: LoaderOptions): Promise<Record<string, Plugin>>;
39
+ interface Unit {
40
+ type: 'plugin' | 'framework' | 'app';
41
+ path: string;
42
+ }
43
+ /**
44
+ * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/egg_loader.js#L348
45
+ */
46
+ declare function getLoadUnits(options: LoaderOptions): Promise<Unit[]>;
47
+ declare function getConfig(options: LoaderOptions): Promise<Record<string, any>>;
48
+ interface IEggLoader {
49
+ loadPlugin(): Promise<void>;
50
+ loadConfig(): Promise<void>;
51
+ config: Record<string, any>;
52
+ getLoadUnits(): Unit[];
53
+ allPlugins: Record<string, Plugin>;
54
+ }
55
+ interface IEggLoaderOptions {
56
+ baseDir: string;
57
+ app: unknown;
58
+ logger: object;
59
+ EggCoreClass?: unknown;
60
+ }
61
+ type EggLoaderImplClass<T = IEggLoader> = new (options: IEggLoaderOptions) => T;
62
+ declare function getLoader(options: LoaderOptions): Promise<IEggLoader>;
63
+ declare function findEggCore(options: LoaderOptions): Promise<{
64
+ EggCore?: object;
65
+ EggLoader: EggLoaderImplClass;
66
+ }>;
67
+ //#endregion
68
+ //#region src/deprecated.d.ts
69
+ /**
70
+ * Try to get framework dir path
71
+ * If can't find any framework, try to find egg dir path
72
+ *
73
+ * @param {String} cwd - current work path
74
+ * @param {Array} [eggNames] - egg names, default is ['egg']
75
+ * @return {String} framework or egg dir path
76
+ * @deprecated
77
+ */
78
+ declare function getFrameworkOrEggPath(cwd: string, eggNames?: string[]): string;
79
+ //#endregion
80
+ //#region src/import.d.ts
81
+ interface ImportResolveOptions {
82
+ paths?: string[];
83
+ }
84
+ interface ImportModuleOptions extends ImportResolveOptions {
85
+ importDefaultOnly?: boolean;
86
+ }
87
+ declare let isESM: boolean;
88
+ declare function getRequire(): NodeRequire;
89
+ declare function getExtensions(): NodeJS.RequireExtensions;
90
+ declare function isSupportTypeScript(): boolean;
91
+ declare function importResolve(filepath: string, options?: ImportResolveOptions): string;
92
+ declare function importModule(filepath: string, options?: ImportModuleOptions): Promise<any>;
93
+ //#endregion
94
+ //#region src/error/ImportResolveError.d.ts
95
+ declare class ImportResolveError extends Error {
96
+ filepath: string;
97
+ paths: string[];
98
+ constructor(filepath: string, paths: string[], error: Error);
99
+ }
100
+ //#endregion
7
101
  //#region src/index.d.ts
8
-
9
102
  declare const _default: {
10
103
  getFrameworkPath: typeof getFrameworkPath;
11
104
  getPlugins: typeof getPlugins;
package/dist/index.js CHANGED
@@ -1,11 +1,452 @@
1
- import { ImportResolveError } from "./error/ImportResolveError.js";
2
- import { getExtensions, getRequire, 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";
1
+ import { createRequire } from "node:module";
6
2
  import path from "node:path";
7
- import fs from "node:fs/promises";
3
+ import fs, { mkdir, realpath, stat, writeFile } from "node:fs/promises";
4
+ import { debuglog } from "node:util";
5
+ import assert from "node:assert";
6
+ import fs$1, { existsSync, readFileSync, readdirSync } from "node:fs";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import os from "node:os";
8
9
 
10
+ //#region rolldown:runtime
11
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
12
+
13
+ //#endregion
14
+ //#region src/utils.ts
15
+ function readJSONSync(file) {
16
+ if (!existsSync(file)) throw new Error(`${file} is not found`);
17
+ return JSON.parse(readFileSync(file, "utf-8"));
18
+ }
19
+
20
+ //#endregion
21
+ //#region src/error/ImportResolveError.ts
22
+ var ImportResolveError = class extends Error {
23
+ filepath;
24
+ paths;
25
+ constructor(filepath, paths, error) {
26
+ const message = `${error.message}, paths: ${JSON.stringify(paths)}`;
27
+ super(message, { cause: error });
28
+ this.name = this.constructor.name;
29
+ this.filepath = filepath;
30
+ this.paths = paths;
31
+ Error.captureStackTrace(this, this.constructor);
32
+ }
33
+ };
34
+
35
+ //#endregion
36
+ //#region src/import.ts
37
+ const debug$2 = debuglog("egg/utils/import");
38
+ let isESM = true;
39
+ try {
40
+ if (typeof import.meta !== "undefined") isESM = true;
41
+ } catch {
42
+ isESM = false;
43
+ }
44
+ const supportImportMetaResolve = parseInt(process.versions.node.split(".", 1)[0], 10) >= 18;
45
+ let _customRequire;
46
+ function getRequire() {
47
+ if (!_customRequire) if (typeof __require !== "undefined") _customRequire = __require;
48
+ else _customRequire = createRequire(process.cwd());
49
+ return _customRequire;
50
+ }
51
+ function getExtensions() {
52
+ return getRequire().extensions;
53
+ }
54
+ let _supportTypeScript;
55
+ function isSupportTypeScript() {
56
+ if (_supportTypeScript === void 0) {
57
+ const extensions = getExtensions();
58
+ _supportTypeScript = extensions[".ts"] !== void 0 || process.env.VITEST === "true" || process.env.EGG_TS_ENABLE === "true" || parseInt(process.versions.node.split(".", 1)[0], 10) >= 22;
59
+ debug$2("[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);
60
+ }
61
+ return _supportTypeScript;
62
+ }
63
+ function tryToResolveFromFile(filepath) {
64
+ const type = isESM ? "module" : "commonjs";
65
+ let mainIndexFile = "";
66
+ if (type === "module") {
67
+ mainIndexFile = filepath + ".mjs";
68
+ if (fs$1.existsSync(mainIndexFile)) {
69
+ debug$2("[tryToResolveFromFile] %o, use index.mjs, type: %o", mainIndexFile, type);
70
+ return mainIndexFile;
71
+ }
72
+ mainIndexFile = filepath + ".js";
73
+ if (fs$1.existsSync(mainIndexFile)) {
74
+ debug$2("[tryToResolveFromFile] %o, use index.js, type: %o", mainIndexFile, type);
75
+ return mainIndexFile;
76
+ }
77
+ } else {
78
+ mainIndexFile = filepath + ".cjs";
79
+ if (fs$1.existsSync(mainIndexFile)) {
80
+ debug$2("[tryToResolveFromFile] %o, use index.cjs, type: %o", mainIndexFile, type);
81
+ return mainIndexFile;
82
+ }
83
+ mainIndexFile = filepath + ".js";
84
+ if (fs$1.existsSync(mainIndexFile)) {
85
+ debug$2("[tryToResolveFromFile] %o, use index.js, type: %o", mainIndexFile, type);
86
+ return mainIndexFile;
87
+ }
88
+ }
89
+ if (!isSupportTypeScript()) return;
90
+ mainIndexFile = filepath + ".ts";
91
+ if (fs$1.existsSync(mainIndexFile)) {
92
+ debug$2("[tryToResolveFromFile] %o, use index.ts, type: %o", mainIndexFile, type);
93
+ return mainIndexFile;
94
+ }
95
+ }
96
+ function tryToResolveByDirnameFromPackage(dirname, pkg) {
97
+ const defaultMainFile = isESM ? pkg.module ?? pkg.main : pkg.main;
98
+ if (defaultMainFile) {
99
+ const mainIndexFilePath$1 = path.join(dirname, defaultMainFile);
100
+ if (fs$1.existsSync(mainIndexFilePath$1)) {
101
+ debug$2("[tryToResolveByDirnameFromPackage] %o, use pkg.main or pkg.module: %o, isESM: %s", mainIndexFilePath$1, defaultMainFile, isESM);
102
+ return mainIndexFilePath$1;
103
+ }
104
+ }
105
+ if (pkg.exports?.["."]) {
106
+ const pkgType = pkg.type ?? "commonjs";
107
+ const defaultExport = pkg.exports["."];
108
+ let mainIndexFilePath$1 = "";
109
+ if (typeof defaultExport === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport);
110
+ else if (pkgType === "module") {
111
+ if (typeof defaultExport.import === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport.import);
112
+ else if (typeof defaultExport.import?.default === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport.import.default);
113
+ } else if (typeof defaultExport.require === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport.require);
114
+ else if (typeof defaultExport.require?.default === "string") mainIndexFilePath$1 = path.join(dirname, defaultExport.require.default);
115
+ if (mainIndexFilePath$1 && fs$1.existsSync(mainIndexFilePath$1)) {
116
+ debug$2("[tryToResolveByDirnameFromPackage] %o, use pkg.exports[.]: %o, pkg.type: %o", mainIndexFilePath$1, defaultExport, pkgType);
117
+ return mainIndexFilePath$1;
118
+ }
119
+ }
120
+ const type = pkg?.type ?? (isESM ? "module" : "commonjs");
121
+ if (type === "module") {
122
+ const mainIndexFilePath$1 = path.join(dirname, "index.mjs");
123
+ if (fs$1.existsSync(mainIndexFilePath$1)) {
124
+ debug$2("[tryToResolveByDirnameFromPackage] %o, use index.mjs, pkg.type: %o", mainIndexFilePath$1, type);
125
+ return mainIndexFilePath$1;
126
+ }
127
+ const mainIndexMjsFilePath = path.join(dirname, "index.js");
128
+ if (fs$1.existsSync(mainIndexMjsFilePath)) {
129
+ debug$2("[tryToResolveByDirnameFromPackage] %o, use index.js, pkg.type: %o", mainIndexMjsFilePath, type);
130
+ return mainIndexMjsFilePath;
131
+ }
132
+ } else {
133
+ const mainIndexFilePath$1 = path.join(dirname, "index.cjs");
134
+ if (fs$1.existsSync(mainIndexFilePath$1)) {
135
+ debug$2("[tryToResolveByDirnameFromPackage] %o, use index.cjs, pkg.type: %o", mainIndexFilePath$1, type);
136
+ return mainIndexFilePath$1;
137
+ }
138
+ const mainIndexCjsFilePath = path.join(dirname, "index.js");
139
+ if (fs$1.existsSync(mainIndexCjsFilePath)) {
140
+ debug$2("[tryToResolveByDirnameFromPackage] %o, use index.js, pkg.type: %o", mainIndexCjsFilePath, type);
141
+ return mainIndexCjsFilePath;
142
+ }
143
+ }
144
+ if (!isSupportTypeScript()) return;
145
+ const mainIndexFile = pkg.tshy?.exports?.["."] ?? "index.ts";
146
+ const mainIndexFilePath = path.join(dirname, mainIndexFile);
147
+ if (fs$1.existsSync(mainIndexFilePath)) return mainIndexFilePath;
148
+ }
149
+ function tryToResolveByDirname(dirname) {
150
+ let pkg = {};
151
+ const pkgFile = path.join(dirname, "package.json");
152
+ if (fs$1.existsSync(pkgFile)) pkg = JSON.parse(fs$1.readFileSync(pkgFile, "utf-8"));
153
+ return tryToResolveByDirnameFromPackage(dirname, pkg);
154
+ }
155
+ function isRelativePath(filepath) {
156
+ return filepath.startsWith("./") || filepath.startsWith("../") || filepath.startsWith(".\\") || filepath.startsWith("..\\");
157
+ }
158
+ function tryToResolveFromAbsoluteFile(filepath) {
159
+ let moduleFilePath;
160
+ const stat$1 = fs$1.statSync(filepath, { throwIfNoEntry: false });
161
+ if (stat$1?.isDirectory()) {
162
+ moduleFilePath = tryToResolveByDirname(filepath);
163
+ if (moduleFilePath) return moduleFilePath;
164
+ } else if (stat$1?.isFile()) return filepath;
165
+ moduleFilePath = tryToResolveFromFile(filepath);
166
+ if (moduleFilePath) return moduleFilePath;
167
+ const parentDir = path.dirname(filepath);
168
+ const basename = path.basename(filepath);
169
+ const pkgFile = path.join(parentDir, "package.json");
170
+ if (fs$1.existsSync(pkgFile)) {
171
+ const pkg = JSON.parse(fs$1.readFileSync(pkgFile, "utf-8"));
172
+ const key = `./${basename}`;
173
+ if (pkg.exports?.[key]) return path.join(parentDir, pkg.exports[key]);
174
+ }
175
+ }
176
+ function importResolve(filepath, options) {
177
+ const paths = options?.paths ?? [process.cwd()];
178
+ debug$2("[importResolve] filepath: %o, options: %j, paths: %j", filepath, options, paths);
179
+ let moduleFilePath;
180
+ const isAbsolute = path.isAbsolute(filepath);
181
+ if (isAbsolute) {
182
+ moduleFilePath = tryToResolveFromAbsoluteFile(filepath);
183
+ if (moduleFilePath) {
184
+ debug$2("[importResolve:isAbsolute] %o => %o", filepath, moduleFilePath);
185
+ return moduleFilePath;
186
+ }
187
+ } else if (isRelativePath(filepath)) for (const p of paths) {
188
+ const resolvedPath = path.resolve(p, filepath);
189
+ moduleFilePath = tryToResolveFromAbsoluteFile(resolvedPath);
190
+ if (moduleFilePath) {
191
+ debug$2("[importResolve:isRelativePath] %o => %o => %o", filepath, resolvedPath, moduleFilePath);
192
+ return moduleFilePath;
193
+ }
194
+ }
195
+ for (const p of paths) {
196
+ let resolvedPath = path.join(p, "node_modules", filepath);
197
+ moduleFilePath = tryToResolveFromAbsoluteFile(resolvedPath);
198
+ if (moduleFilePath) {
199
+ debug$2("[importResolve:node_modules] %o => %o => %o", filepath, resolvedPath, moduleFilePath);
200
+ return moduleFilePath;
201
+ }
202
+ let parentPath = path.dirname(p);
203
+ if (path.basename(parentPath) === "node_modules") {
204
+ resolvedPath = path.join(parentPath, filepath);
205
+ moduleFilePath = tryToResolveFromAbsoluteFile(resolvedPath);
206
+ if (moduleFilePath) {
207
+ debug$2("[importResolve:node_modules] %o => %o => %o", filepath, resolvedPath, moduleFilePath);
208
+ return moduleFilePath;
209
+ }
210
+ }
211
+ parentPath = path.dirname(parentPath);
212
+ if (path.basename(parentPath) === "node_modules") {
213
+ resolvedPath = path.join(parentPath, filepath);
214
+ moduleFilePath = tryToResolveFromAbsoluteFile(resolvedPath);
215
+ if (moduleFilePath) {
216
+ debug$2("[importResolve:node_modules] %o => %o => %o", filepath, resolvedPath, moduleFilePath);
217
+ return moduleFilePath;
218
+ }
219
+ }
220
+ }
221
+ const extname = path.extname(filepath);
222
+ if (!isAbsolute && extname === ".json" || !isESM) moduleFilePath = getRequire().resolve(filepath, { paths });
223
+ else if (supportImportMetaResolve) {
224
+ try {
225
+ moduleFilePath = import.meta.resolve(filepath);
226
+ } catch (err) {
227
+ debug$2("[importResolve:error] import.meta.resolve %o => %o, options: %o", filepath, err, options);
228
+ throw new ImportResolveError(filepath, paths, err);
229
+ }
230
+ if (moduleFilePath.startsWith("file://")) moduleFilePath = fileURLToPath(moduleFilePath);
231
+ debug$2("[importResolve] import.meta.resolve %o => %o", filepath, moduleFilePath);
232
+ if (!fs$1.statSync(moduleFilePath, { throwIfNoEntry: false })?.isFile()) throw new TypeError(`Cannot find module ${filepath}, because ${moduleFilePath} does not exists`);
233
+ } else moduleFilePath = getRequire().resolve(filepath);
234
+ debug$2("[importResolve:success] %o, options: %o => %o, isESM: %s", filepath, options, moduleFilePath, isESM);
235
+ return moduleFilePath;
236
+ }
237
+ async function importModule(filepath, options) {
238
+ const moduleFilePath = importResolve(filepath, options);
239
+ let obj;
240
+ if (isESM) {
241
+ const fileUrl = pathToFileURL(moduleFilePath).toString();
242
+ obj = await import(fileUrl);
243
+ debug$2("[importModule:success] await import %o", fileUrl);
244
+ if (obj?.default?.__esModule === true && "default" in obj?.default) obj = obj.default;
245
+ if (options?.importDefaultOnly) {
246
+ if ("default" in obj) obj = obj.default;
247
+ }
248
+ } else {
249
+ obj = __require(moduleFilePath);
250
+ debug$2("[importModule] require %o", moduleFilePath);
251
+ if (obj?.__esModule === true && "default" in obj) obj = obj.default;
252
+ }
253
+ if (debug$2.enabled) debug$2("[importModule] return %o => keys: %j, typeof obj: %s", filepath, obj ? Object.keys(obj) : obj, typeof obj);
254
+ return obj;
255
+ }
256
+
257
+ //#endregion
258
+ //#region src/framework.ts
259
+ const debug$1 = debuglog("egg/utils/framework");
260
+ const initCwd = process.cwd();
261
+ /**
262
+ * Find the framework directory, lookup order
263
+ * - specify framework path
264
+ * - get framework name from
265
+ * - use egg by default
266
+ * @param {Object} options - options
267
+ * @param {String} options.baseDir - the current directory of application
268
+ * @param {String} [options.framework] - the directory of framework
269
+ * @return {String} frameworkPath
270
+ */
271
+ function getFrameworkPath(options) {
272
+ const { framework, baseDir } = options;
273
+ const pkgPath = path.join(baseDir, "package.json");
274
+ assert(existsSync(pkgPath), `${pkgPath} should exist`);
275
+ const moduleDir = path.join(baseDir, "node_modules");
276
+ if (framework) {
277
+ if (path.isAbsolute(framework)) {
278
+ assert(existsSync(framework), `${framework} should exist`);
279
+ return framework;
280
+ }
281
+ return assertAndReturn(framework, moduleDir, baseDir);
282
+ }
283
+ const pkg = readJSONSync(pkgPath);
284
+ if (pkg.egg?.framework) return assertAndReturn(pkg.egg.framework, moduleDir, baseDir);
285
+ return assertAndReturn("egg", moduleDir, baseDir);
286
+ }
287
+ function assertAndReturn(frameworkName, moduleDir, baseDir) {
288
+ const moduleDirs = new Set([
289
+ moduleDir,
290
+ path.join(process.cwd(), "node_modules"),
291
+ path.join(initCwd, "node_modules")
292
+ ]);
293
+ try {
294
+ let globalModuleDir;
295
+ if (frameworkName.startsWith("@") && frameworkName.includes("/")) globalModuleDir = path.join(importResolve(`${frameworkName}/package.json`, { paths: [baseDir] }), "../../..");
296
+ else globalModuleDir = path.join(importResolve(`${frameworkName}/package.json`, { paths: [baseDir] }), "../..");
297
+ moduleDirs.add(globalModuleDir);
298
+ } catch {}
299
+ for (const moduleDir$1 of moduleDirs) {
300
+ const frameworkPath = path.join(moduleDir$1, frameworkName);
301
+ if (existsSync(frameworkPath)) {
302
+ debug$1("[assertAndReturn] frameworkPath: %s, moduleDirs: %o", frameworkPath, moduleDirs);
303
+ return frameworkPath;
304
+ }
305
+ }
306
+ throw new Error(`${frameworkName} is not found in ${Array.from(moduleDirs)}`);
307
+ }
308
+
309
+ //#endregion
310
+ //#region src/plugin.ts
311
+ const debug = debuglog("egg/utils/plugin");
312
+ const tmpDir = os.tmpdir();
313
+ function noop() {}
314
+ const logger = {
315
+ debug: noop,
316
+ info: noop,
317
+ warn: noop,
318
+ error: noop
319
+ };
320
+ /**
321
+ * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/mixin/plugin.js#L203
322
+ */
323
+ async function getPlugins(options) {
324
+ const loader = await getLoader(options);
325
+ await loader.loadPlugin();
326
+ return loader.allPlugins;
327
+ }
328
+ /**
329
+ * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/egg_loader.js#L348
330
+ */
331
+ async function getLoadUnits(options) {
332
+ const loader = await getLoader(options);
333
+ await loader.loadPlugin();
334
+ return loader.getLoadUnits();
335
+ }
336
+ async function getConfig(options) {
337
+ const loader = await getLoader(options);
338
+ await loader.loadPlugin();
339
+ await loader.loadConfig();
340
+ return loader.config;
341
+ }
342
+ async function exists(filepath) {
343
+ try {
344
+ await stat(filepath);
345
+ return true;
346
+ } catch {
347
+ return false;
348
+ }
349
+ }
350
+ async function getLoader(options) {
351
+ assert(options.framework, "framework is required");
352
+ assert(await exists(options.framework), `${options.framework} should exist`);
353
+ if (!(options.baseDir && await exists(options.baseDir))) {
354
+ options.baseDir = path.join(tmpDir, "egg_utils", `${Date.now()}`, "tmp_app");
355
+ await mkdir(options.baseDir, { recursive: true });
356
+ await writeFile(path.join(options.baseDir, "package.json"), JSON.stringify({
357
+ name: "tmp_app",
358
+ type: "module"
359
+ }));
360
+ debug("[getLoader] create baseDir: %o", options.baseDir);
361
+ }
362
+ const { EggCore, EggLoader } = await findEggCore(options);
363
+ const mod = await importModule(options.framework);
364
+ const Application = mod.Application ?? mod.default?.Application;
365
+ assert(Application, `Application not export on ${options.framework}`);
366
+ if (options.env) process.env.EGG_SERVER_ENV = options.env;
367
+ return new EggLoader({
368
+ baseDir: options.baseDir,
369
+ logger,
370
+ app: Object.create(Application.prototype),
371
+ EggCoreClass: EggCore
372
+ });
373
+ }
374
+ async function findEggCore(options) {
375
+ const baseDirRealpath = await realpath(options.baseDir);
376
+ const paths = [await realpath(options.framework), baseDirRealpath];
377
+ try {
378
+ const { EggCore, EggLoader } = await importModule("egg", { paths });
379
+ if (EggLoader) return {
380
+ EggCore,
381
+ EggLoader
382
+ };
383
+ } catch (err) {
384
+ debug("[findEggCore] import \"egg\" from paths:%o error: %o", paths, err);
385
+ }
386
+ const names = ["@eggjs/core", "egg-core"];
387
+ for (const name of names) {
388
+ try {
389
+ const { EggCore, EggLoader } = await importModule(name, { paths });
390
+ if (EggLoader) return {
391
+ EggCore,
392
+ EggLoader
393
+ };
394
+ } catch (err) {
395
+ debug("[findEggCore] import \"%s\" from paths:%o error: %o", name, paths, err);
396
+ }
397
+ try {
398
+ const { EggCore, EggLoader } = await importModule(name);
399
+ if (EggLoader) return {
400
+ EggCore,
401
+ EggLoader
402
+ };
403
+ } catch (err) {
404
+ debug("[findEggCore] import \"%s\" error: %o", name, err);
405
+ }
406
+ let eggCorePath = path.join(options.baseDir, `node_modules/${name}`);
407
+ if (!await exists(eggCorePath)) eggCorePath = path.join(options.framework, `node_modules/${name}`);
408
+ if (await exists(eggCorePath)) return await importModule(eggCorePath);
409
+ }
410
+ assert(false, `Can't find ${names.join(" or ")} from ${options.baseDir} and ${options.framework}`);
411
+ }
412
+
413
+ //#endregion
414
+ //#region src/deprecated.ts
415
+ /**
416
+ * Try to get framework dir path
417
+ * If can't find any framework, try to find egg dir path
418
+ *
419
+ * @param {String} cwd - current work path
420
+ * @param {Array} [eggNames] - egg names, default is ['egg']
421
+ * @return {String} framework or egg dir path
422
+ * @deprecated
423
+ */
424
+ function getFrameworkOrEggPath(cwd, eggNames) {
425
+ eggNames = eggNames || ["egg"];
426
+ const moduleDir = path.join(cwd, "node_modules");
427
+ if (!existsSync(moduleDir)) return "";
428
+ const pkgFile = path.join(cwd, "package.json");
429
+ if (existsSync(pkgFile)) {
430
+ const pkg = readJSONSync(pkgFile);
431
+ if (pkg.egg && pkg.egg.framework) return path.join(moduleDir, pkg.egg.framework);
432
+ }
433
+ const names = readdirSync(moduleDir);
434
+ for (const name of names) {
435
+ const pkgfile = path.join(moduleDir, name, "package.json");
436
+ if (!existsSync(pkgfile)) continue;
437
+ const pkg = readJSONSync(pkgfile);
438
+ if (pkg.dependencies) {
439
+ for (const eggName of eggNames) if (pkg.dependencies[eggName]) return path.join(moduleDir, name);
440
+ }
441
+ }
442
+ for (const eggName of eggNames) {
443
+ const pkgfile = path.join(moduleDir, eggName, "package.json");
444
+ if (existsSync(pkgfile)) return path.join(moduleDir, eggName);
445
+ }
446
+ return "";
447
+ }
448
+
449
+ //#endregion
9
450
  //#region src/index.ts
10
451
  var src_default = {
11
452
  getFrameworkPath,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eggjs/utils",
3
- "version": "5.0.0-beta.19",
3
+ "version": "5.0.0-beta.20",
4
4
  "engines": {
5
5
  "node": ">=22.18.0"
6
6
  },
@@ -1,7 +0,0 @@
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,13 +0,0 @@
1
- //#region src/deprecated.d.ts
2
- /**
3
- * Try to get framework dir path
4
- * If can't find any framework, try to find egg dir path
5
- *
6
- * @param {String} cwd - current work path
7
- * @param {Array} [eggNames] - egg names, default is ['egg']
8
- * @return {String} framework or egg dir path
9
- * @deprecated
10
- */
11
- declare function getFrameworkOrEggPath(cwd: string, eggNames?: string[]): string;
12
- //#endregion
13
- export { getFrameworkOrEggPath };
@@ -1,41 +0,0 @@
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 };
@@ -1,8 +0,0 @@
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 };
@@ -1,16 +0,0 @@
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,18 +0,0 @@
1
- //#region src/framework.d.ts
2
- interface Options {
3
- baseDir: string;
4
- framework?: string;
5
- }
6
- /**
7
- * Find the framework directory, lookup order
8
- * - specify framework path
9
- * - get framework name from
10
- * - use egg by default
11
- * @param {Object} options - options
12
- * @param {String} options.baseDir - the current directory of application
13
- * @param {String} [options.framework] - the directory of framework
14
- * @return {String} frameworkPath
15
- */
16
- declare function getFrameworkPath(options: Options): string;
17
- //#endregion
18
- export { getFrameworkPath };
package/dist/framework.js DELETED
@@ -1,60 +0,0 @@
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 };
package/dist/import.d.ts DELETED
@@ -1,15 +0,0 @@
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 getRequire(): NodeRequire;
10
- declare function getExtensions(): NodeJS.RequireExtensions;
11
- declare function isSupportTypeScript(): boolean;
12
- declare function importResolve(filepath: string, options?: ImportResolveOptions): string;
13
- declare function importModule(filepath: string, options?: ImportModuleOptions): Promise<any>;
14
- //#endregion
15
- export { ImportModuleOptions, ImportResolveOptions, getExtensions, getRequire, importModule, importResolve, isESM, isSupportTypeScript };
package/dist/import.js DELETED
@@ -1,231 +0,0 @@
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, getRequire, importModule, importResolve, isESM, isSupportTypeScript };
package/dist/plugin.d.ts DELETED
@@ -1,51 +0,0 @@
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 };
package/dist/plugin.js DELETED
@@ -1,112 +0,0 @@
1
- import { importModule } from "./import.js";
2
- import path from "node:path";
3
- import { mkdir, realpath, stat, writeFile } from "node:fs/promises";
4
- import { debuglog } from "node:util";
5
- import assert from "node:assert";
6
- import os from "node:os";
7
-
8
- //#region src/plugin.ts
9
- const debug = debuglog("egg/utils/plugin");
10
- const tmpDir = os.tmpdir();
11
- function noop() {}
12
- const logger = {
13
- debug: noop,
14
- info: noop,
15
- warn: noop,
16
- error: noop
17
- };
18
- /**
19
- * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/mixin/plugin.js#L203
20
- */
21
- async function getPlugins(options) {
22
- const loader = await getLoader(options);
23
- await loader.loadPlugin();
24
- return loader.allPlugins;
25
- }
26
- /**
27
- * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/egg_loader.js#L348
28
- */
29
- async function getLoadUnits(options) {
30
- const loader = await getLoader(options);
31
- await loader.loadPlugin();
32
- return loader.getLoadUnits();
33
- }
34
- async function getConfig(options) {
35
- const loader = await getLoader(options);
36
- await loader.loadPlugin();
37
- await loader.loadConfig();
38
- return loader.config;
39
- }
40
- async function exists(filepath) {
41
- try {
42
- await stat(filepath);
43
- return true;
44
- } catch {
45
- return false;
46
- }
47
- }
48
- async function getLoader(options) {
49
- assert(options.framework, "framework is required");
50
- assert(await exists(options.framework), `${options.framework} should exist`);
51
- if (!(options.baseDir && await exists(options.baseDir))) {
52
- options.baseDir = path.join(tmpDir, "egg_utils", `${Date.now()}`, "tmp_app");
53
- await mkdir(options.baseDir, { recursive: true });
54
- await writeFile(path.join(options.baseDir, "package.json"), JSON.stringify({
55
- name: "tmp_app",
56
- type: "module"
57
- }));
58
- debug("[getLoader] create baseDir: %o", options.baseDir);
59
- }
60
- const { EggCore, EggLoader } = await findEggCore(options);
61
- const mod = await importModule(options.framework);
62
- const Application = mod.Application ?? mod.default?.Application;
63
- assert(Application, `Application not export on ${options.framework}`);
64
- if (options.env) process.env.EGG_SERVER_ENV = options.env;
65
- return new EggLoader({
66
- baseDir: options.baseDir,
67
- logger,
68
- app: Object.create(Application.prototype),
69
- EggCoreClass: EggCore
70
- });
71
- }
72
- async function findEggCore(options) {
73
- const baseDirRealpath = await realpath(options.baseDir);
74
- const paths = [await realpath(options.framework), baseDirRealpath];
75
- try {
76
- const { EggCore, EggLoader } = await importModule("egg", { paths });
77
- if (EggLoader) return {
78
- EggCore,
79
- EggLoader
80
- };
81
- } catch (err) {
82
- debug("[findEggCore] import \"egg\" from paths:%o error: %o", paths, err);
83
- }
84
- const names = ["@eggjs/core", "egg-core"];
85
- for (const name of names) {
86
- try {
87
- const { EggCore, EggLoader } = await importModule(name, { paths });
88
- if (EggLoader) return {
89
- EggCore,
90
- EggLoader
91
- };
92
- } catch (err) {
93
- debug("[findEggCore] import \"%s\" from paths:%o error: %o", name, paths, err);
94
- }
95
- try {
96
- const { EggCore, EggLoader } = await importModule(name);
97
- if (EggLoader) return {
98
- EggCore,
99
- EggLoader
100
- };
101
- } catch (err) {
102
- debug("[findEggCore] import \"%s\" error: %o", name, err);
103
- }
104
- let eggCorePath = path.join(options.baseDir, `node_modules/${name}`);
105
- if (!await exists(eggCorePath)) eggCorePath = path.join(options.framework, `node_modules/${name}`);
106
- if (await exists(eggCorePath)) return await importModule(eggCorePath);
107
- }
108
- assert(false, `Can't find ${names.join(" or ")} from ${options.baseDir} and ${options.framework}`);
109
- }
110
-
111
- //#endregion
112
- export { findEggCore, getConfig, getLoadUnits, getLoader, getPlugins };
package/dist/utils.js DELETED
@@ -1,12 +0,0 @@
1
- import path from "node:path";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { fileURLToPath } from "node:url";
4
-
5
- //#region src/utils.ts
6
- function readJSONSync(file) {
7
- if (!existsSync(file)) throw new Error(`${file} is not found`);
8
- return JSON.parse(readFileSync(file, "utf-8"));
9
- }
10
-
11
- //#endregion
12
- export { readJSONSync };