@eggjs/utils 3.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/plugin.ts ADDED
@@ -0,0 +1,162 @@
1
+ import { debuglog } from 'node:util';
2
+ import path from 'node:path';
3
+ import assert from 'node:assert';
4
+ import os from 'node:os';
5
+ import { stat, mkdir, writeFile, realpath } from 'node:fs/promises';
6
+ import { importModule } from './import.js';
7
+
8
+ const debug = debuglog('@eggjs/utils:plugin');
9
+
10
+ const tmpDir = os.tmpdir();
11
+
12
+ function noop() {}
13
+
14
+ const logger = {
15
+ debug: noop,
16
+ info: noop,
17
+ warn: noop,
18
+ error: noop,
19
+ };
20
+
21
+ export interface LoaderOptions {
22
+ framework: string;
23
+ baseDir: string;
24
+ env?: string;
25
+ }
26
+
27
+ export interface Plugin {
28
+ name: string;
29
+ version?: string;
30
+ enable: boolean;
31
+ implicitEnable: boolean;
32
+ path: string;
33
+ dependencies: string[];
34
+ optionalDependencies: string[];
35
+ env: string[];
36
+ from: string;
37
+ }
38
+
39
+ /**
40
+ * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/mixin/plugin.js#L203
41
+ */
42
+ export async function getPlugins(options: LoaderOptions) {
43
+ const loader = await getLoader(options);
44
+ await loader.loadPlugin();
45
+ return loader.allPlugins;
46
+ }
47
+
48
+ interface Unit {
49
+ type: 'plugin' | 'framework' | 'app';
50
+ path: string;
51
+ }
52
+
53
+ /**
54
+ * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/egg_loader.js#L348
55
+ */
56
+ export async function getLoadUnits(options: LoaderOptions) {
57
+ const loader = await getLoader(options);
58
+ await loader.loadPlugin();
59
+ return loader.getLoadUnits();
60
+ }
61
+
62
+ export async function getConfig(options: LoaderOptions) {
63
+ const loader = await getLoader(options);
64
+ await loader.loadPlugin();
65
+ await loader.loadConfig();
66
+ return loader.config;
67
+ }
68
+
69
+ async function exists(filepath: string) {
70
+ try {
71
+ await stat(filepath);
72
+ return true;
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+
78
+ interface IEggLoader {
79
+ loadPlugin(): Promise<void>;
80
+ loadConfig(): Promise<void>;
81
+ config: Record<string, any>;
82
+ getLoadUnits(): Unit[];
83
+ allPlugins: Record<string, Plugin>;
84
+ }
85
+
86
+ interface IEggLoaderOptions {
87
+ baseDir: string;
88
+ app: unknown;
89
+ logger: object;
90
+ EggCoreClass?: unknown;
91
+ }
92
+
93
+ type EggLoaderImplClass<T = IEggLoader> = new(options: IEggLoaderOptions) => T;
94
+
95
+ async function getLoader(options: LoaderOptions) {
96
+ assert(options.framework, 'framework is required');
97
+ assert(await exists(options.framework), `${options.framework} should exist`);
98
+ if (!(options.baseDir && await exists(options.baseDir))) {
99
+ options.baseDir = path.join(tmpDir, 'egg_utils', `${Date.now()}`, 'tmp_app');
100
+ await mkdir(options.baseDir, { recursive: true });
101
+ await writeFile(path.join(options.baseDir, 'package.json'), JSON.stringify({
102
+ name: 'tmp_app',
103
+ }));
104
+ debug('[getLoader] create baseDir: %o', options.baseDir);
105
+ }
106
+
107
+ const { EggCore, EggLoader } = await findEggCore(options);
108
+ const mod = await importModule(options.framework);
109
+ const Application = mod.Application ?? mod.default?.Application;
110
+ assert(Application, `Application not export on ${options.framework}`);
111
+ if (options.env) {
112
+ process.env.EGG_SERVER_ENV = options.env;
113
+ }
114
+ return new EggLoader({
115
+ baseDir: options.baseDir,
116
+ logger,
117
+ app: Object.create(Application.prototype),
118
+ EggCoreClass: EggCore,
119
+ });
120
+ }
121
+
122
+ async function findEggCore(options: LoaderOptions): Promise<{ EggCore?: object; EggLoader: EggLoaderImplClass }> {
123
+ const baseDirRealpath = await realpath(options.baseDir);
124
+ const frameworkRealpath = await realpath(options.framework);
125
+ const paths = [ frameworkRealpath, baseDirRealpath ];
126
+ // custom framework => egg => @eggjs/core
127
+ try {
128
+ const { EggCore, EggLoader } = await importModule('egg', { paths });
129
+ if (EggLoader) {
130
+ return { EggCore, EggLoader };
131
+ }
132
+ } catch (err: any) {
133
+ debug('[findEggCore] import "egg" from paths:%o error: %o', paths, err);
134
+ }
135
+
136
+ const name = '@eggjs/core';
137
+ // egg => egg-core
138
+ try {
139
+ const { EggCore, EggLoader } = await importModule(name, { paths });
140
+ if (EggLoader) {
141
+ return { EggCore, EggLoader };
142
+ }
143
+ } catch (err: any) {
144
+ debug('[findEggCore] import "%s" from paths:%o error: %o', name, paths, err);
145
+ }
146
+
147
+ try {
148
+ const { EggCore, EggLoader } = await importModule(name);
149
+ if (EggLoader) {
150
+ return { EggCore, EggLoader };
151
+ }
152
+ } catch (err: any) {
153
+ debug('[findEggCore] import "%s" error: %o', name, err);
154
+ }
155
+
156
+ let eggCorePath = path.join(options.baseDir, `node_modules/${name}`);
157
+ if (!(await exists(eggCorePath))) {
158
+ eggCorePath = path.join(options.framework, `node_modules/${name}`);
159
+ }
160
+ assert(await exists(eggCorePath), `Can't find ${name} from ${options.baseDir} and ${options.framework}`);
161
+ return await importModule(eggCorePath);
162
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+
3
+ export function readJSONSync(file: string) {
4
+ if (!existsSync(file)) {
5
+ throw new Error(`${file} is not found`);
6
+ }
7
+ return JSON.parse(readFileSync(file, 'utf-8'));
8
+ }
package/lib/deprecated.js DELETED
@@ -1,59 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getFrameworkOrEggPath = void 0;
7
- const node_path_1 = __importDefault(require("node:path"));
8
- const node_fs_1 = require("node:fs");
9
- const utils_1 = require("./utils");
10
- /**
11
- * Try to get framework dir path
12
- * If can't find any framework, try to find egg dir path
13
- *
14
- * @param {String} cwd - current work path
15
- * @param {Array} [eggNames] - egg names, default is ['egg']
16
- * @return {String} framework or egg dir path
17
- * @deprecated
18
- */
19
- function getFrameworkOrEggPath(cwd, eggNames) {
20
- eggNames = eggNames || ['egg'];
21
- const moduleDir = node_path_1.default.join(cwd, 'node_modules');
22
- if (!(0, node_fs_1.existsSync)(moduleDir)) {
23
- return '';
24
- }
25
- // try to get framework
26
- // 1. try to read egg.framework property on package.json
27
- const pkgFile = node_path_1.default.join(cwd, 'package.json');
28
- if ((0, node_fs_1.existsSync)(pkgFile)) {
29
- const pkg = (0, utils_1.readJSONSync)(pkgFile);
30
- if (pkg.egg && pkg.egg.framework) {
31
- return node_path_1.default.join(moduleDir, pkg.egg.framework);
32
- }
33
- }
34
- // 2. try the module dependencies includes eggNames
35
- const names = (0, node_fs_1.readdirSync)(moduleDir);
36
- for (const name of names) {
37
- const pkgfile = node_path_1.default.join(moduleDir, name, 'package.json');
38
- if (!(0, node_fs_1.existsSync)(pkgfile)) {
39
- continue;
40
- }
41
- const pkg = (0, utils_1.readJSONSync)(pkgfile);
42
- if (pkg.dependencies) {
43
- for (const eggName of eggNames) {
44
- if (pkg.dependencies[eggName]) {
45
- return node_path_1.default.join(moduleDir, name);
46
- }
47
- }
48
- }
49
- }
50
- // try to get egg
51
- for (const eggName of eggNames) {
52
- const pkgfile = node_path_1.default.join(moduleDir, eggName, 'package.json');
53
- if ((0, node_fs_1.existsSync)(pkgfile)) {
54
- return node_path_1.default.join(moduleDir, eggName);
55
- }
56
- }
57
- return '';
58
- }
59
- exports.getFrameworkOrEggPath = getFrameworkOrEggPath;
package/lib/index.d.ts DELETED
@@ -1,14 +0,0 @@
1
- import { getFrameworkPath } from './framework';
2
- import { getPlugins, getConfig, getLoadUnits } from './plugin';
3
- import { getFrameworkOrEggPath } from './deprecated';
4
- export { getFrameworkPath } from './framework';
5
- export { getPlugins, getConfig, getLoadUnits } from './plugin';
6
- export { getFrameworkOrEggPath } from './deprecated';
7
- declare const _default: {
8
- getFrameworkPath: typeof getFrameworkPath;
9
- getPlugins: typeof getPlugins;
10
- getConfig: typeof getConfig;
11
- getLoadUnits: typeof getLoadUnits;
12
- getFrameworkOrEggPath: typeof getFrameworkOrEggPath;
13
- };
14
- export default _default;
package/lib/index.js DELETED
@@ -1,21 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getFrameworkOrEggPath = exports.getLoadUnits = exports.getConfig = exports.getPlugins = exports.getFrameworkPath = void 0;
4
- const framework_1 = require("./framework");
5
- const plugin_1 = require("./plugin");
6
- const deprecated_1 = require("./deprecated");
7
- // support import { getFrameworkPath } from '@eggjs/utils'
8
- var framework_2 = require("./framework");
9
- Object.defineProperty(exports, "getFrameworkPath", { enumerable: true, get: function () { return framework_2.getFrameworkPath; } });
10
- var plugin_2 = require("./plugin");
11
- Object.defineProperty(exports, "getPlugins", { enumerable: true, get: function () { return plugin_2.getPlugins; } });
12
- Object.defineProperty(exports, "getConfig", { enumerable: true, get: function () { return plugin_2.getConfig; } });
13
- Object.defineProperty(exports, "getLoadUnits", { enumerable: true, get: function () { return plugin_2.getLoadUnits; } });
14
- var deprecated_2 = require("./deprecated");
15
- Object.defineProperty(exports, "getFrameworkOrEggPath", { enumerable: true, get: function () { return deprecated_2.getFrameworkOrEggPath; } });
16
- // support import utils from '@eggjs/utils'
17
- exports.default = {
18
- getFrameworkPath: framework_1.getFrameworkPath,
19
- getPlugins: plugin_1.getPlugins, getConfig: plugin_1.getConfig, getLoadUnits: plugin_1.getLoadUnits,
20
- getFrameworkOrEggPath: deprecated_1.getFrameworkOrEggPath,
21
- };
package/lib/plugin.js DELETED
@@ -1,98 +0,0 @@
1
- "use strict";
2
- /* eslint-disable @typescript-eslint/no-var-requires */
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.getConfig = exports.getLoadUnits = exports.getPlugins = void 0;
8
- const node_path_1 = __importDefault(require("node:path"));
9
- const node_assert_1 = __importDefault(require("node:assert"));
10
- const node_os_1 = __importDefault(require("node:os"));
11
- const node_fs_1 = require("node:fs");
12
- const tmpDir = node_os_1.default.tmpdir();
13
- // eslint-disable-next-line @typescript-eslint/no-empty-function
14
- function noop() { }
15
- const logger = {
16
- debug: noop,
17
- info: noop,
18
- warn: noop,
19
- error: noop,
20
- };
21
- /**
22
- * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/mixin/plugin.js#L203
23
- */
24
- function getPlugins(options) {
25
- const loader = getLoader(options);
26
- loader.loadPlugin();
27
- return loader.allPlugins;
28
- }
29
- exports.getPlugins = getPlugins;
30
- /**
31
- * @see https://github.com/eggjs/egg-core/blob/2920f6eade07959d25f5c4f96b154d3fbae877db/lib/loader/egg_loader.js#L348
32
- */
33
- function getLoadUnits(options) {
34
- const loader = getLoader(options);
35
- loader.loadPlugin();
36
- return loader.getLoadUnits();
37
- }
38
- exports.getLoadUnits = getLoadUnits;
39
- function getConfig(options) {
40
- const loader = getLoader(options);
41
- loader.loadPlugin();
42
- loader.loadConfig();
43
- return loader.config;
44
- }
45
- exports.getConfig = getConfig;
46
- function getLoader(options) {
47
- let { framework, baseDir, env } = options;
48
- (0, node_assert_1.default)(framework, 'framework is required');
49
- (0, node_assert_1.default)((0, node_fs_1.existsSync)(framework), `${framework} should exist`);
50
- if (!(baseDir && (0, node_fs_1.existsSync)(baseDir))) {
51
- baseDir = node_path_1.default.join(tmpDir, String(Date.now()), 'tmpapp');
52
- (0, node_fs_1.mkdirSync)(baseDir, { recursive: true });
53
- (0, node_fs_1.writeFileSync)(node_path_1.default.join(baseDir, 'package.json'), JSON.stringify({ name: 'tmpapp' }));
54
- }
55
- const EggLoader = findEggCore({ baseDir, framework });
56
- const { Application } = require(framework);
57
- if (env)
58
- process.env.EGG_SERVER_ENV = env;
59
- return new EggLoader({
60
- baseDir,
61
- logger,
62
- app: Object.create(Application.prototype),
63
- });
64
- }
65
- function findEggCore({ baseDir, framework }) {
66
- const baseDirRealpath = (0, node_fs_1.realpathSync)(baseDir);
67
- const frameworkRealpath = (0, node_fs_1.realpathSync)(framework);
68
- // custom framework => egg => egg/lib/loader/index.js
69
- try {
70
- return require(require.resolve('egg/lib/loader', {
71
- paths: [frameworkRealpath, baseDirRealpath],
72
- })).EggLoader;
73
- }
74
- catch {
75
- // ignore
76
- }
77
- const name = 'egg-core';
78
- // egg => egg-core
79
- try {
80
- return require(require.resolve(name, {
81
- paths: [frameworkRealpath, baseDirRealpath],
82
- })).EggLoader;
83
- }
84
- catch {
85
- // ignore
86
- }
87
- try {
88
- return require(name).EggLoader;
89
- }
90
- catch {
91
- let eggCorePath = node_path_1.default.join(baseDir, `node_modules/${name}`);
92
- if (!(0, node_fs_1.existsSync)(eggCorePath)) {
93
- eggCorePath = node_path_1.default.join(framework, `node_modules/${name}`);
94
- }
95
- (0, node_assert_1.default)((0, node_fs_1.existsSync)(eggCorePath), `Can't find ${name} from ${baseDir} and ${framework}`);
96
- return require(eggCorePath).EggLoader;
97
- }
98
- }
package/lib/utils.js DELETED
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readJSONSync = void 0;
4
- const node_fs_1 = require("node:fs");
5
- function readJSONSync(file) {
6
- if (!(0, node_fs_1.existsSync)(file)) {
7
- throw new Error(`${file} is not found`);
8
- }
9
- return JSON.parse((0, node_fs_1.readFileSync)(file, 'utf-8'));
10
- }
11
- exports.readJSONSync = readJSONSync;
File without changes
File without changes
File without changes