From 40e8695ddccf21769f1c63d6026e31cad3b9fc79 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Wed, 26 Mar 2025 21:14:05 +0800 Subject: [PATCH 01/10] feat: use oxlint --- .eslintignore | 5 -- .eslintrc | 6 -- .husky/pre-commit | 1 + .oxlintrc.json | 142 ++++++++++++++++++++++++++++++++++++++++++++++ .prettierignore | 2 + .prettierrc | 6 ++ package.json | 20 +++++-- 7 files changed, 166 insertions(+), 16 deletions(-) delete mode 100644 .eslintignore delete mode 100644 .eslintrc create mode 100644 .husky/pre-commit create mode 100644 .oxlintrc.json create mode 100644 .prettierignore create mode 100644 .prettierrc diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 6857b828..00000000 --- a/.eslintignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules -coverage -benchmark -fixtures -.vscode diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index 9bcdb468..00000000 --- a/.eslintrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": [ - "eslint-config-egg/typescript", - "eslint-config-egg/lib/rules/enforce-node-prefix" - ] -} diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 00000000..2312dc58 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +npx lint-staged diff --git a/.oxlintrc.json b/.oxlintrc.json new file mode 100644 index 00000000..10f56564 --- /dev/null +++ b/.oxlintrc.json @@ -0,0 +1,142 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "env": { + "node": true, + "mocha": true + }, + "categories": { + "correctness": "error", + "perf": "error", + "nursery": "error", + "restriction": "error", + "style": "error", + "pedantic": "error", + "suspicious": "error" + }, + "plugins": [ + "import", + "typescript", + "unicorn", + "jsdoc", + "node", + "promise", + "oxc" + ], + "rules": { + // eslint + "constructor-super": "error", + "getter-return": "error", + "no-undef": "error", + "no-unreachable": "error", + "no-var": "error", + "no-eq-null": "error", + "no-await-in-loop": "allow", + "eqeqeq": ["error", "smart"], + "init-declarations": "allow", + "curly": "allow", + "no-ternary": "allow", + "max-params": ["error", 5], + "no-await-expression-member": "error", + "no-continue": "allow", + "guard-for-in": "allow", + "func-style": "allow", + "sort-imports": "allow", + "yoda": "allow", + "sort-keys": "allow", + "no-magic-numbers": "allow", + "no-duplicate-imports": "error", + "no-multi-assign": "error", + "func-names": "error", + "default-param-last": "error", + "prefer-object-spread": "error", + "no-undefined": "allow", + "no-plusplus": "allow", + // maybe warn + "no-console": "warn", + "no-extraneous-class": "allow", + "no-empty-function": "error", + "max-depth": ["error", 6], + "max-lines-per-function": "allow", + "no-lonely-if": "error", + "max-lines": "allow", + "require-await": "allow", + "max-nested-callbacks": ["error", 5], + "max-classes-per-file": "allow", + "radix": "allow", + "no-negated-condition": "error", + "no-else-return": "error", + "no-throw-literal": "error", + + // import + "import/exports-last": "allow", + "import/max-dependencies": "allow", + "import/no-cycle": "error", + "import/no-anonymous-default-export": "allow", + "import/no-namespace": "error", + "import/named": "error", + "import/export": "error", + "import/no-default-export": "allow", + "import/unambiguous": "error", + + // promise + "promise/no-return-wrap": "error", + "promise/param-names": "error", + "promise/prefer-await-to-callbacks": "error", + "promise/prefer-await-to-then": "error", + "promise/prefer-catch": "error", + "promise/no-return-in-finally": "error", + "promise/avoid-new": "error", + + // unicorn + "unicorn/error-message": "error", + "unicorn/no-null": "allow", + "unicorn/filename-case": "allow", + "unicorn/prefer-structured-clone": "error", + "unicorn/prefer-logical-operator-over-ternary": "error", + "unicorn/prefer-number-properties": "error", + "unicorn/prefer-array-some": "error", + "unicorn/prefer-string-slice": "error", + // "unicorn/no-null": "error", + "unicorn/throw-new-error": "error", + "unicorn/catch-error-name": "allow", + "unicorn/prefer-spread": "allow", + "unicorn/numeric-separators-style": "error", + "unicorn/prefer-string-raw": "error", + "unicorn/text-encoding-identifier-case": "error", + "unicorn/no-array-for-each": "error", + "unicorn/explicit-length-check": "error", + "unicorn/no-lonely-if": "error", + "unicorn/no-useless-undefined": "allow", + "unicorn/prefer-date-now": "error", + "unicorn/no-static-only-class": "allow", + "unicorn/no-typeof-undefined": "error", + "unicorn/prefer-negative-index": "error", + "unicorn/no-anonymous-default-export": "allow", + + // oxc + "oxc/no-map-spread": "error", + "oxc/no-rest-spread-properties": "allow", + "oxc/no-optional-chaining": "allow", + "oxc/no-async-await": "allow", + + // typescript + "typescript/explicit-function-return-type": "allow", + "typescript/consistent-type-imports": "error", + "typescript/consistent-type-definitions": "error", + "typescript/consistent-indexed-object-style": "allow", + "typescript/no-inferrable-types": "error", + "typescript/array-type": "error", + "typescript/no-non-null-assertion": "error", + "typescript/no-explicit-any": "error", + "typescript/no-import-type-side-effects": "error", + "typescript/no-dynamic-delete": "error", + "typescript/prefer-ts-expect-error": "error", + "typescript/ban-ts-comment": "error", + "typescript/prefer-enum-initializers": "error", + + // jsdoc + "jsdoc/require-returns": "allow", + "jsdoc/require-param": "allow" + }, + "ignorePatterns": ["index.d.ts", "test/fixtures/**", "__snapshots__"] +} diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..9ffa84db --- /dev/null +++ b/.prettierignore @@ -0,0 +1,2 @@ +CHANGELOG.md +__snapshots__ diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000..43aee1a4 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,6 @@ +{ + "singleQuote": true, + "trailingComma": "es5", + "tabWidth": 2, + "arrowParens": "avoid" +} diff --git a/package.json b/package.json index 3ea8f57f..6726d981 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "description": "A core plugin framework based on @eggjs/koa", "scripts": { "clean": "rimraf dist", - "lint": "eslint src test --ext ts", + "lint": "oxlint", "pretest": "npm run clean && npm run lint -- --fix && npm run prepublishOnly", "test": "egg-bin test", "posttest": "npm run clean", @@ -18,7 +18,15 @@ "preci": "npm run clean && npm run lint && npm run prepublishOnly", "ci": "egg-bin cov", "postci": "npm run clean", - "prepublishOnly": "tshy && tshy-after && attw --pack" + "prepublishOnly": "tshy && tshy-after && attw --pack", + "prepare": "husky" + }, + "lint-staged": { + "*": "prettier --write --ignore-unknown --cache", + "*.{ts,js,json,md,yml}": [ + "prettier --ignore-unknown --write", + "oxlint --fix" + ] }, "repository": { "type": "git", @@ -51,7 +59,7 @@ "utility": "^2.1.0" }, "devDependencies": { - "@arethetypeswrong/cli": "^0.17.1", + "@arethetypeswrong/cli": "^0.17.4", "@eggjs/bin": "7", "@eggjs/supertest": "^8.1.1", "@eggjs/tsconfig": "1", @@ -60,8 +68,10 @@ "@types/node": "22", "await-event": "2", "coffee": "5", - "eslint": "8", - "eslint-config-egg": "14", + "husky": "9", + "lint-staged": "15", + "oxlint": "^0.16.2", + "prettier": "3", "gals": "1", "js-yaml": "3", "mm": "^4.0.2", From 0bc5489d2702835279f28c916316b8ab76d1eef8 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Wed, 26 Mar 2025 21:46:45 +0800 Subject: [PATCH 02/10] f --- .oxlintrc.json | 2 +- benchmark/middleware/app/middleware/async.js | 2 +- example/middleware/hello.ts | 2 +- src/egg.ts | 8 +- src/lifecycle.ts | 2 +- src/loader/egg_loader.ts | 152 ++++++++++--------- src/loader/file_loader.ts | 9 +- src/utils/sequencify.ts | 8 +- 8 files changed, 101 insertions(+), 84 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index 10f56564..896cdcb7 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -138,5 +138,5 @@ "jsdoc/require-returns": "allow", "jsdoc/require-param": "allow" }, - "ignorePatterns": ["index.d.ts", "test/fixtures/**", "__snapshots__"] + "ignorePatterns": ["index.d.ts", "test/fixtures/**", "__snapshots__", "test", "benchmark"] } diff --git a/benchmark/middleware/app/middleware/async.js b/benchmark/middleware/app/middleware/async.js index 5eb47c67..666fc468 100644 --- a/benchmark/middleware/app/middleware/async.js +++ b/benchmark/middleware/app/middleware/async.js @@ -2,7 +2,7 @@ let index = 0; -module.exports = function () { +module.exports = function exports() { return async (ctx, next) => { await next(); ctx.body.push(`async middleware #${++index}`); diff --git a/example/middleware/hello.ts b/example/middleware/hello.ts index 5649fb8d..722fac1f 100644 --- a/example/middleware/hello.ts +++ b/example/middleware/hello.ts @@ -1,4 +1,4 @@ -import { MiddlewareFunc } from '../../src/index.js'; +import type { MiddlewareFunc } from '../../src/index.js'; export const hello: MiddlewareFunc = async (ctx, next) => { console.log('Hello middleware'); diff --git a/src/egg.ts b/src/egg.ts index 55a27853..5770a1e5 100644 --- a/src/egg.ts +++ b/src/egg.ts @@ -9,8 +9,10 @@ import type { MiddlewareFunc as KoaMiddlewareFunc, Next, } from '@eggjs/koa'; -import { EggConsoleLogger, Logger } from 'egg-logger'; -import { RegisterOptions, ResourcesController, EggRouter as Router } from '@eggjs/router'; +import type { Logger } from 'egg-logger'; +import { EggConsoleLogger } from 'egg-logger'; +import type { RegisterOptions, ResourcesController} from '@eggjs/router'; +import { EggRouter as Router } from '@eggjs/router'; import type { ReadyFunctionArg } from 'get-ready'; import { BaseContextClass } from './base_context_class.js'; import { Timing } from './utils/timing.js'; @@ -18,7 +20,7 @@ import type { Fun } from './utils/index.js'; import { Lifecycle } from './lifecycle.js'; import { EggLoader } from './loader/egg_loader.js'; import utils from './utils/index.js'; -import { EggAppConfig } from './types.js'; +import type { EggAppConfig } from './types.js'; import { Singleton, type SingletonCreateMethod, type SingletonOptions, } from './singleton.js'; diff --git a/src/lifecycle.ts b/src/lifecycle.ts index 9c118b27..4a55411e 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -368,7 +368,7 @@ export class Lifecycle extends EventEmitter { }) { const { scope, ready, timingKeyPrefix, scopeFullName } = args; if (typeof scope !== 'function') { - throw new Error('boot only support function'); + throw new TypeError('boot only support function'); } // get filename from stack if scopeFullName is undefined diff --git a/src/loader/egg_loader.ts b/src/loader/egg_loader.ts index 24224279..b04fb56e 100644 --- a/src/loader/egg_loader.ts +++ b/src/loader/egg_loader.ts @@ -2,6 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import assert from 'node:assert'; import { debuglog, inspect } from 'node:util'; + import { homedir } from 'node-homedir'; import { isAsyncFunction, isClass, isGeneratorFunction, isObject, isPromise } from 'is-type-of'; import type { Logger } from 'egg-logger'; @@ -14,9 +15,10 @@ import { register as tsconfigPathsRegister } from 'tsconfig-paths'; import { isESM, isSupportTypeScript } from '@eggjs/utils'; import { pathMatching, type PathMatchingOptions } from 'egg-path-matching'; import { now, diff } from 'performance-ms'; -import { CaseStyle, FULLPATH, FileLoader, FileLoaderOptions } from './file_loader.js'; -import { ContextLoader, ContextLoaderOptions } from './context_loader.js'; -import utils, { Fun } from '../utils/index.js'; + +import { type FileLoaderOptions, CaseStyle, FULLPATH, FileLoader } from './file_loader.js'; +import { type ContextLoaderOptions, ContextLoader } from './context_loader.js'; +import utils, { type Fun } from '../utils/index.js'; import sequencify from '../utils/sequencify.js'; import { Timing } from '../utils/timing.js'; import type { @@ -27,7 +29,7 @@ import type { EggAppConfig, EggAppInfo, EggPluginInfo } from '../types.js'; const debug = debuglog('@eggjs/core/loader/egg_loader'); -const originalPrototypes: Record = { +const originalPrototypes: Record = { request: Request.prototype, response: Response.prototype, context: KoaContext.prototype, @@ -62,6 +64,7 @@ export class EggLoader { #requiredCount = 0; readonly options: EggLoaderOptions; readonly timing: Timing; + // oxlint-disable-next-line typescript/no-explicit-any readonly pkg: Record; readonly eggPaths: string[]; readonly serverEnv: string; @@ -99,7 +102,8 @@ export class EggLoader { // skip require tsconfig-paths if tsconfig.json not exists const tsConfigFile = path.join(this.options.baseDir, 'tsconfig.json'); if (fs.existsSync(tsConfigFile)) { - tsconfigPathsRegister({ cwd: this.options.baseDir } as any); + // @ts-expect-error only cwd is required + tsconfigPathsRegister({ cwd: this.options.baseDir }); } else { this.logger.info( '[@eggjs/core/egg_loader] skip register "tsconfig-paths" because tsconfig.json not exists at %s', @@ -143,9 +147,7 @@ export class EggLoader { * @member {String} EggLoader#serverScope * @see AppInfo#serverScope */ - this.serverScope = options.serverScope !== undefined - ? options.serverScope - : this.getServerScope(); + this.serverScope = options.serverScope ?? this.getServerScope(); /** * @member {AppInfo} EggLoader#appInfo @@ -168,7 +170,7 @@ export class EggLoader { /** * Get {@link AppInfo#env} - * @return {String} env + * @returns {String} env * @see AppInfo#env * @private * @since 1.0.0 @@ -185,7 +187,10 @@ export class EggLoader { serverEnv = process.env.EGG_SERVER_ENV; } - if (!serverEnv) { + if (serverEnv) { + serverEnv = serverEnv.trim(); + } else { + // oxlint-disable-next-line eslint/no-lonely-if if (process.env.NODE_ENV === 'test') { serverEnv = 'unittest'; } else if (process.env.NODE_ENV === 'production') { @@ -193,8 +198,6 @@ export class EggLoader { } else { serverEnv = 'local'; } - } else { - serverEnv = serverEnv.trim(); } return serverEnv; @@ -202,16 +205,16 @@ export class EggLoader { /** * Get {@link AppInfo#scope} - * @return {String} serverScope + * @returns {String} serverScope * @private */ protected getServerScope(): string { - return process.env.EGG_SERVER_SCOPE || ''; + return process.env.EGG_SERVER_SCOPE ?? ''; } /** * Get {@link AppInfo#name} - * @return {String} appname + * @returns {String} appname * @private * @since 1.0.0 */ @@ -226,7 +229,7 @@ export class EggLoader { /** * Get home directory - * @return {String} home directory + * @returns {String} home directory * @since 3.4.0 */ getHomedir(): string { @@ -236,7 +239,7 @@ export class EggLoader { /** * Get app info - * @return {AppInfo} appInfo + * @returns {AppInfo} appInfo * @since 1.0.0 */ protected getAppInfo(): EggAppInfo { @@ -312,7 +315,7 @@ export class EggLoader { /** * Get {@link EggLoader#eggPaths} - * @return {Array} framework directories + * @returns {Array} framework directories * @see {@link EggLoader#eggPaths} * @private * @since 1.0.0 @@ -593,7 +596,7 @@ export class EggLoader { async #mergePluginConfig(plugin: EggPluginInfo) { let pkg; let config; - const pluginPackage = path.join(plugin.path!, 'package.json'); + const pluginPackage = path.join(plugin.path as string, 'package.json'); if (await utils.existsPath(pluginPackage)) { pkg = await readJSON(pluginPackage); config = pkg.eggPlugin; @@ -601,7 +604,7 @@ export class EggLoader { plugin.version = pkg.version; } // support commonjs and esm dist files - plugin.path = await this.#formatPluginPathFromPackageJSON(plugin.path!, pkg); + plugin.path = await this.#formatPluginPathFromPackageJSON(plugin.path as string, pkg); } const logger = this.options.logger; @@ -631,7 +634,7 @@ export class EggLoader { protected getOrderPlugins(allPlugins: Record, enabledPluginNames: string[], appPlugins: Record) { // no plugins enabled - if (!enabledPluginNames.length) { + if (enabledPluginNames.length === 0) { return []; } @@ -639,7 +642,7 @@ export class EggLoader { debug('Got plugins %j after sequencify', result); // catch error when result.sequence is empty - if (!result.sequence.length) { + if (result.sequence.length === 0) { const err = new Error( `sequencify plugins has problem, missing: [${result.missingTasks}], recursive: [${result.recursiveDependencies}]`); // find plugins which is required by the missing plugin @@ -660,7 +663,7 @@ export class EggLoader { // log the plugins that be enabled implicitly const implicitEnabledPlugins: string[] = []; const requireMap: Record = {}; - result.sequence.forEach(name => { + for (const name of result.sequence) { for (const depName of allPlugins[name].dependencies) { if (!requireMap[depName]) { requireMap[depName] = []; @@ -673,7 +676,7 @@ export class EggLoader { allPlugins[name].enable = true; allPlugins[name].implicitEnable = true; } - }); + } for (const [ name, dependents ] of Object.entries(requireMap)) { // note:`dependents` will not includes `optionalDependencies` @@ -684,7 +687,7 @@ export class EggLoader { // - configclient required by [rpcClient] // - monitor required by [rpcClient] // - diamond required by [rpcClient] - if (implicitEnabledPlugins.length) { + if (implicitEnabledPlugins.length > 0) { let message = implicitEnabledPlugins .map(name => ` - ${name} required by [${requireMap[name]}]`) .join('\n'); @@ -693,7 +696,7 @@ export class EggLoader { // should warn when the plugin is disabled by app const disabledPlugins = implicitEnabledPlugins.filter( name => appPlugins[name] && appPlugins[name].enable === false); - if (disabledPlugins.length) { + if (disabledPlugins.length > 0) { message = disabledPlugins .map(name => ` - ${name} required by [${requireMap[name]}]`) .join('\n'); @@ -771,17 +774,13 @@ export class EggLoader { if (exports.import) { realPluginPath = path.join(pluginPath, exports.import); } - } else { - if (exports.require) { - realPluginPath = path.join(pluginPath, exports.require); - } + } else if (exports.require) { + realPluginPath = path.join(pluginPath, exports.require); } - if (exports.typescript && isSupportTypeScript()) { - if (!(await exists(realPluginPath))) { - // if require/import path not exists, use typescript path for development stage - realPluginPath = path.join(pluginPath, exports.typescript); - debug('[formatPluginPathFromPackageJSON] use typescript path %o', realPluginPath); - } + if (exports.typescript && isSupportTypeScript() && !(await exists(realPluginPath))) { + // if require/import path not exists, use typescript path for development stage + realPluginPath = path.join(pluginPath, exports.typescript); + debug('[formatPluginPathFromPackageJSON] use typescript path %o', realPluginPath); } } return realPluginPath; @@ -795,7 +794,8 @@ export class EggLoader { const plugin = plugins[name]; let targetPlugin = targets[name]; if (!targetPlugin) { - targetPlugin = targets[name] = {} as EggPluginInfo; + targetPlugin = {} as EggPluginInfo; + targets[name] = targetPlugin; } if (targetPlugin.package && targetPlugin.package === plugin.package) { this.logger.warn('[@eggjs/core] plugin %s has been defined that is %j, but you define again in %s', @@ -809,7 +809,7 @@ export class EggLoader { if (value === undefined) { continue; } - if (Reflect.get(targetPlugin, prop) && Array.isArray(value) && !value.length) { + if (Reflect.get(targetPlugin, prop) && Array.isArray(value) && value.length === 0) { continue; } Reflect.set(targetPlugin, prop, value); @@ -819,6 +819,7 @@ export class EggLoader { /** end Plugin loader */ /** start Config loader */ + // oxlint-disable-next-line typescript/no-explicit-any configMeta: Record; config: EggAppConfig; @@ -867,8 +868,13 @@ export class EggLoader { extend(true, target, envConfig); // You can manipulate the order of app.config.coreMiddleware and app.config.appMiddleware in app.js - target.coreMiddleware = target.coreMiddlewares = target.coreMiddleware || []; - target.appMiddleware = target.appMiddlewares = target.middleware || []; + target.coreMiddleware = target.coreMiddleware || []; + // alias for coreMiddleware + target.coreMiddlewares = target.coreMiddleware; + + target.appMiddleware = target.middleware || []; + // alias for appMiddleware + target.appMiddlewares = target.appMiddleware; this.config = target; debug('[loadConfig] all config: %o', this.config); @@ -880,6 +886,7 @@ export class EggLoader { 'config.default', `config.${this.serverEnv}`, ]; + // oxlint-disable-next-line typescript/no-explicit-any const target: Record = {}; for (const filename of names) { const config = await this.#loadConfig(this.options.baseDir, filename, undefined, 'app'); @@ -900,7 +907,11 @@ export class EggLoader { if (filename === 'config.default' && !filepath) { filepath = this.resolveModule(path.join(dirpath, 'config/config')); } - const config: Record = await this.loadFile(filepath!, this.appInfo, extraInject); + if (!filepath) { + return; + } + // oxlint-disable-next-line typescript/no-explicit-any + const config: Record = await this.loadFile(filepath, this.appInfo, extraInject); if (!config) return; if (isPlugin || isApp) { assert(!config.coreMiddleware, 'Can not define coreMiddleware in app or plugin'); @@ -909,7 +920,7 @@ export class EggLoader { assert(!config.middleware, 'Can not define middleware in ' + filepath); } // store config meta, check where is the property of config come from. - this.#setConfigMeta(config, filepath!); + this.#setConfigMeta(config, filepath); return config; } @@ -917,20 +928,21 @@ export class EggLoader { const envConfigStr = process.env.EGG_APP_CONFIG; if (!envConfigStr) return; try { - const envConfig: Record = JSON.parse(envConfigStr); + const envConfig: Record = JSON.parse(envConfigStr); this.#setConfigMeta(envConfig, ''); return envConfig; - } catch (err) { + } catch { this.options.logger.warn('[egg-loader] process.env.EGG_APP_CONFIG is not invalid JSON: %s', envConfigStr); } } - #setConfigMeta(config: Record, filepath: string) { + #setConfigMeta(config: Record, filepath: string) { config = extend(true, {}, config); this.#setConfig(config, filepath); extend(true, this.configMeta, config); } + // oxlint-disable-next-line typescript/no-explicit-any #setConfig(obj: Record, filepath: string) { for (const key of Object.keys(obj)) { const val = obj[key]; @@ -1010,7 +1022,7 @@ export class EggLoader { * can be override in top level framework to support load `app/extends/{name}.js` * * @param {String} name - filename which may be `app/extend/{name}.js` - * @return {Array} filepaths extend file paths + * @returns {Array} filepaths extend file paths * @private */ protected getExtendFilePaths(name: string): string[] { @@ -1042,7 +1054,7 @@ export class EggLoader { const mergeRecord = new Map(); for (const rawFilepath of filepaths) { - const filepath = this.resolveModule(rawFilepath)!; + const filepath = this.resolveModule(rawFilepath); if (!filepath) { // debug('loadExtend %o not found', rawFilepath); continue; @@ -1059,7 +1071,7 @@ export class EggLoader { ext = ext.prototype; } const properties = Object.getOwnPropertyNames(ext) - .concat(Object.getOwnPropertySymbols(ext) as any[]) + .concat(Object.getOwnPropertySymbols(ext) as unknown as string[]) .filter(name => name !== 'constructor'); // ignore class constructor for extend for (const property of properties) { @@ -1069,7 +1081,7 @@ export class EggLoader { } // Copy descriptor - let descriptor = Object.getOwnPropertyDescriptor(ext, property); + let descriptor = Object.getOwnPropertyDescriptor(ext, property) as PropertyDescriptor; let originalDescriptor = Object.getOwnPropertyDescriptor(proto, property); if (!originalDescriptor) { // try to get descriptor from originalPrototypes @@ -1090,7 +1102,7 @@ export class EggLoader { descriptor.get = originalDescriptor.get; } } - Object.defineProperty(proto, property, descriptor!); + Object.defineProperty(proto, property, descriptor); mergeRecord.set(property, filepath); } debug('merge %j to %s from %s', properties, name, filepath); @@ -1313,13 +1325,11 @@ export class EggLoader { if (isGeneratorFunction(obj)) { throw new TypeError(`Support for generators was removed, fullpath: ${opt.path}`); } - if (!isClass(obj) && !isAsyncFunction(obj)) { - if (typeof obj === 'function') { - obj = obj(this.app); - debug('[loadController] after init(app) => %o, meta: %j', obj, opt); - if (isGeneratorFunction(obj)) { - throw new TypeError(`Support for generators was removed, fullpath: ${opt.path}`); - } + if (!isClass(obj) && !isAsyncFunction(obj) && typeof obj === 'function') { + obj = obj(this.app); + debug('[loadController] after init(app) => %o, meta: %j', obj, opt); + if (isGeneratorFunction(obj)) { + throw new TypeError(`Support for generators was removed, fullpath: ${opt.path}`); } } if (isClass(obj)) { @@ -1416,14 +1426,14 @@ export class EggLoader { * * @param {String} filepath - fullpath * @param {Array} inject - pass rest arguments into the function when invoke - * @return {Object} exports + * @returns {Object} exports * @example * ```js * app.loader.loadFile(path.join(app.options.baseDir, 'config/router.js')); - * ``` + * ``` * @since 1.0.0 */ - async loadFile(filepath: string, ...inject: any[]) { + async loadFile(filepath: string, ...inject: unknown[]) { const fullpath = filepath && this.resolveModule(filepath); if (!fullpath) { return null; @@ -1445,7 +1455,7 @@ export class EggLoader { /** * @param {String} filepath - fullpath - * @return {Object} exports + * @returns {Object} exports * @private */ async requireFile(filepath: string) { @@ -1468,7 +1478,7 @@ export class EggLoader { * 2. framework * 3. app * - * @return {Array} loadUnits + * @returns {Array} loadUnits * @since 1.0.0 */ getLoadUnits(): EggDirInfo[] { @@ -1480,7 +1490,7 @@ export class EggLoader { if (this.orderPlugins) { for (const plugin of this.orderPlugins) { this.dirs.push({ - path: plugin.path!, + path: plugin.path as string, type: 'plugin', }); } @@ -1581,7 +1591,7 @@ export class EggLoader { let fullPath; try { fullPath = utils.resolvePath(filepath); - } catch (err: any) { + } catch { // debug('[resolveModule] Module %o resolve error: %s', filepath, err.stack); return undefined; } @@ -1593,7 +1603,7 @@ export class EggLoader { } function depCompatible(plugin: EggPluginInfo & { dep?: string[] }) { - if (plugin.dep && !(Array.isArray(plugin.dependencies) && plugin.dependencies.length)) { + if (plugin.dep && !(Array.isArray(plugin.dependencies) && plugin.dependencies.length > 0)) { plugin.dependencies = plugin.dep; delete plugin.dep; } @@ -1644,6 +1654,7 @@ function debugMiddlewareWrapper(mw: MiddlewareFunc): MiddlewareFunc { // wrap the controller class, yield a object with middlewares function wrapControllerClass(Controller: typeof BaseContextClass, fullPath: string) { let proto = Controller.prototype; + // oxlint-disable-next-line typescript/no-explicit-any const ret: Record = {}; // tracing the prototype chain while (proto !== Object.prototype) { @@ -1657,7 +1668,7 @@ function wrapControllerClass(Controller: typeof BaseContextClass, fullPath: stri // skip getter, setter & non-function properties const d = Object.getOwnPropertyDescriptor(proto, key); // prevent to override sub method - if (typeof d?.value === 'function' && !ret.hasOwnProperty(key)) { + if (typeof d?.value === 'function' && !Object.hasOwn(ret, key)) { const controllerMethodName = `${Controller.name}.${key}`; if (isGeneratorFunction(d.value)) { throw new TypeError( @@ -1673,18 +1684,21 @@ function wrapControllerClass(Controller: typeof BaseContextClass, fullPath: stri } function controllerMethodToMiddleware(Controller: typeof BaseContextClass, key: string) { - return function classControllerMiddleware(this: Context, ...args: any[]) { - const controller: any = new Controller(this); + return function classControllerMiddleware(this: Context, ...args: unknown[]) { + const controller = new Controller(this); if (!this.app.config.controller?.supportParams) { args = [ this ]; } + // @ts-expect-error key exists return controller[key](...args); }; } // wrap the method of the object, method can receive ctx as it's first argument +// oxlint-disable-next-line typescript/no-explicit-any function wrapObject(obj: Record, fullPath: string, prefix?: string) { const keys = Object.keys(obj); + // oxlint-disable-next-line typescript/no-explicit-any const ret: Record = {}; prefix = prefix ?? ''; for (const key of keys) { @@ -1709,7 +1723,7 @@ function wrapObject(obj: Record, fullPath: string, prefix?: string) } function objectFunctionToMiddleware(func: Fun) { - async function objectControllerMiddleware(this: Context, ...args: any[]) { + async function objectControllerMiddleware(this: Context, ...args: unknown[]) { if (!this.app.config.controller?.supportParams) { args = [ this ]; } diff --git a/src/loader/file_loader.ts b/src/loader/file_loader.ts index 542b8b7b..c59032e6 100644 --- a/src/loader/file_loader.ts +++ b/src/loader/file_loader.ts @@ -5,7 +5,8 @@ import path from 'node:path'; import globby from 'globby'; import { isClass, isGeneratorFunction, isAsyncFunction, isPrimitive } from 'is-type-of'; import { isSupportTypeScript } from '@eggjs/utils'; -import utils, { Fun } from '../utils/index.js'; +import type { Fun } from '../utils/index.js'; +import utils from '../utils/index.js'; const debug = debuglog('@eggjs/core/file_loader'); @@ -279,7 +280,7 @@ async function getExports(fullpath: string, options: FileLoaderOptions, pathName } function defaultCamelize(filepath: string, caseStyle: CaseStyle) { - const properties = filepath.substring(0, filepath.lastIndexOf('.')).split('/'); + const properties = filepath.slice(0, filepath.lastIndexOf('.')).split('/'); return properties.map(property => { if (!/^[a-z][a-z0-9_-]*$/i.test(property)) { throw new Error(`${property} is not match 'a-z0-9_-' in ${filepath}`); @@ -291,7 +292,7 @@ function defaultCamelize(filepath: string, caseStyle: CaseStyle) { // FooBar.js > FooBar // FooBar.js > FooBar // FooBar.js > fooBar (if lowercaseFirst is true) - property = property.replace(/[_-][a-z]/ig, s => s.substring(1).toUpperCase()); + property = property.replaceAll(/[_-][a-z]/ig, s => s.slice(1).toUpperCase()); let first = property[0]; switch (caseStyle) { case 'lower': @@ -303,6 +304,6 @@ function defaultCamelize(filepath: string, caseStyle: CaseStyle) { case 'camel': default: } - return first + property.substring(1); + return first + property.slice(1); }); } diff --git a/src/utils/sequencify.ts b/src/utils/sequencify.ts index 41d39f06..c1a7708c 100644 --- a/src/utils/sequencify.ts +++ b/src/utils/sequencify.ts @@ -26,12 +26,12 @@ function sequence(tasks: Record, names: string[], result nest.push(name); recursive.push(...nest.slice(0)); nest.pop(); - } else if (node.dependencies.length || node.optionalDependencies.length) { + } else if (node.dependencies.length > 0 || node.optionalDependencies.length > 0) { nest.push(name); - if (node.dependencies.length) { + if (node.dependencies.length > 0) { sequence(tasks, node.dependencies, result, missing, recursive, nest, optional, name); } - if (node.optionalDependencies.length) { + if (node.optionalDependencies.length > 0) { sequence(tasks, node.optionalDependencies, result, missing, recursive, nest, true, name); } nest.pop(); @@ -58,7 +58,7 @@ export default function sequencify(tasks: Record, names: sequence(tasks, names, result, missing, recursive, [], false, 'app'); - if (missing.length || recursive.length) { + if (missing.length > 0 || recursive.length > 0) { result.sequence = []; // results are incomplete at best, completely wrong at worst, remove them to avoid confusion } From 8e17c794a2a75c5b5287e41d94d51f9309da0160 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Thu, 27 Mar 2025 20:46:27 +0800 Subject: [PATCH 03/10] f --- .oxlintrc.json | 6 +++--- src/egg.ts | 43 ++++++++++++++++++++++++++----------------- src/lifecycle.ts | 25 ++++++++++++++----------- src/utils/index.ts | 9 ++++++--- 4 files changed, 49 insertions(+), 34 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index 896cdcb7..4fd221fc 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -51,8 +51,7 @@ "prefer-object-spread": "error", "no-undefined": "allow", "no-plusplus": "allow", - // maybe warn - "no-console": "warn", + "no-console": "allow", "no-extraneous-class": "allow", "no-empty-function": "error", "max-depth": ["error", 6], @@ -81,7 +80,7 @@ // promise "promise/no-return-wrap": "error", "promise/param-names": "error", - "promise/prefer-await-to-callbacks": "error", + "promise/prefer-await-to-callbacks": "allow", "promise/prefer-await-to-then": "error", "promise/prefer-catch": "error", "promise/no-return-in-finally": "error", @@ -112,6 +111,7 @@ "unicorn/no-typeof-undefined": "error", "unicorn/prefer-negative-index": "error", "unicorn/no-anonymous-default-export": "allow", + "unicorn/prefer-event-target": "allow", // oxc "oxc/no-map-spread": "error", diff --git a/src/egg.ts b/src/egg.ts index 5770a1e5..4dad0dcd 100644 --- a/src/egg.ts +++ b/src/egg.ts @@ -1,25 +1,22 @@ /* eslint-disable prefer-spread */ import assert from 'node:assert'; import { debuglog } from 'node:util'; + import { Application as KoaApplication, Context as KoaContext, Request as KoaRequest, Response as KoaResponse, + type MiddlewareFunc as KoaMiddlewareFunc, + type Next, } from '@eggjs/koa'; -import type { - MiddlewareFunc as KoaMiddlewareFunc, - Next, -} from '@eggjs/koa'; -import type { Logger } from 'egg-logger'; -import { EggConsoleLogger } from 'egg-logger'; -import type { RegisterOptions, ResourcesController} from '@eggjs/router'; -import { EggRouter as Router } from '@eggjs/router'; +import { EggConsoleLogger, type Logger } from 'egg-logger'; +import { EggRouter as Router, type RegisterOptions, type ResourcesController } from '@eggjs/router'; import type { ReadyFunctionArg } from 'get-ready'; + import { BaseContextClass } from './base_context_class.js'; import { Timing } from './utils/timing.js'; -import type { Fun } from './utils/index.js'; import { Lifecycle } from './lifecycle.js'; import { EggLoader } from './loader/egg_loader.js'; -import utils from './utils/index.js'; +import utils, { type Fun } from './utils/index.js'; import type { EggAppConfig } from './types.js'; import { Singleton, type SingletonCreateMethod, type SingletonOptions, @@ -32,6 +29,7 @@ export const EGG_LOADER = Symbol.for('egg#loader'); export interface EggCoreOptions { baseDir: string; type: 'application' | 'agent'; + // eslint-disable-next-line typescript/no-explicit-any plugins?: any; serverScope?: string; env?: string; @@ -98,7 +96,7 @@ export class Context extends KoaContext { } // export @eggjs/core types -export type MiddlewareFunc = KoaMiddlewareFunc; +export type MiddlewareFunc = KoaMiddlewareFunc; export class EggCore extends KoaApplication { options: EggCoreOptions; @@ -114,11 +112,13 @@ export class EggCore extends KoaApplication { #router?: Router; /** auto inject on loadService() */ + // eslint-disable-next-line typescript/no-explicit-any readonly serviceClasses: Record = {}; /** auto inject on loadController() */ + // eslint-disable-next-line typescript/no-explicit-any readonly controller: Record = {}; /** auto inject on loadMiddleware() */ - readonly middlewares: Record MiddlewareFunc> = {}; + readonly middlewares: Record MiddlewareFunc> = {}; /** * @class @@ -251,7 +251,7 @@ export class EggCore extends KoaApplication { * override koa's app.use, support generator function * @since 1.0.0 */ - use(fn: MiddlewareFunc) { + use(fn: MiddlewareFunc) { assert(typeof fn === 'function', 'app.use() requires a function'); debug('[use] add middleware: %o', fn._name || fn.name || '-'); this.middleware.push(fn as unknown as KoaMiddlewareFunc); @@ -418,8 +418,8 @@ export class EggCore extends KoaApplication { if (this.#router) { return this.#router; } - const router = this.#router = new Router({ sensitive: true }, this); - return router; + this.#router = new Router({ sensitive: true }, this); + return this.#router; } /** @@ -428,7 +428,7 @@ export class EggCore extends KoaApplication { * @param {Object} params - more parameters * @return {String} url */ - url(name: string, params?: any): string { + url(name: string, params?: Parameters[1]): string { return this.router.url(name, params); } @@ -437,6 +437,7 @@ export class EggCore extends KoaApplication { // 'all', 'resources', 'register', 'redirect' head(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; head(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; + // eslint-disable-next-line typescript/no-explicit-any head(...args: any): EggCore { this.router.head.apply(this.router, args); return this; @@ -449,36 +450,42 @@ export class EggCore extends KoaApplication { // } get(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; get(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; + // eslint-disable-next-line typescript/no-explicit-any get(...args: any): EggCore { this.router.get.apply(this.router, args); return this; } put(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; put(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; + // eslint-disable-next-line typescript/no-explicit-any put(...args: any): EggCore { this.router.put.apply(this.router, args); return this; } patch(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; patch(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; + // eslint-disable-next-line typescript/no-explicit-any patch(...args: any): EggCore { this.router.patch.apply(this.router, args); return this; } post(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; post(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; + // eslint-disable-next-line typescript/no-explicit-any post(...args: any): EggCore { this.router.post.apply(this.router, args); return this; } delete(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; delete(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; + // eslint-disable-next-line typescript/no-explicit-any delete(...args: any): EggCore { this.router.delete.apply(this.router, args); return this; } del(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; del(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; + // eslint-disable-next-line typescript/no-explicit-any del(...args: any): EggCore { this.router.del.apply(this.router, args); return this; @@ -486,6 +493,7 @@ export class EggCore extends KoaApplication { all(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; all(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; + // eslint-disable-next-line typescript/no-explicit-any all(...args: any): EggCore { this.router.all.apply(this.router, args); return this; @@ -495,12 +503,13 @@ export class EggCore extends KoaApplication { resources(prefix: string, middleware: MiddlewareFunc, controller: string | ResourcesController): EggCore; resources(name: string, prefix: string, controller: string | ResourcesController): EggCore; resources(name: string, prefix: string, middleware: MiddlewareFunc, controller: string | ResourcesController): EggCore; + // eslint-disable-next-line typescript/no-explicit-any resources(...args: any): EggCore { this.router.resources.apply(this.router, args); return this; } - redirect(source: string, destination: string, status: number = 301) { + redirect(source: string, destination: string, status = 301) { this.router.redirect(source, destination, status); return this; } diff --git a/src/lifecycle.ts b/src/lifecycle.ts index 4a55411e..9fc13aa3 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -1,11 +1,12 @@ import assert from 'node:assert'; import { EventEmitter } from 'node:events'; import { debuglog, format } from 'node:util'; + import { isClass } from 'is-type-of'; -import { Ready as ReadyObject } from 'get-ready'; -import type { ReadyFunctionArg } from 'get-ready'; +import { Ready as ReadyObject, type ReadyFunctionArg } from 'get-ready'; import { Ready } from 'ready-callback'; import { EggConsoleLogger } from 'egg-logger'; + import utils from './utils/index.js'; import type { Fun } from './utils/index.js'; import type { EggCore } from './egg.js'; @@ -54,7 +55,7 @@ export interface ILifecycleBoot { beforeClose?(): Promise; } -export type BootImplClass = new(...args: any[]) => T; +export type BootImplClass = new(...args: unknown[]) => T; export interface LifecycleOptions { baseDir: string; @@ -89,7 +90,7 @@ export class Lifecycle extends EventEmitter { this.timing.start(`${this.options.app.type} Start`); // get app timeout from env or use default timeout 10 second - const eggReadyTimeoutEnv = parseInt(process.env.EGG_READY_TIMEOUT_ENV || '10000'); + const eggReadyTimeoutEnv = Number.parseInt(process.env.EGG_READY_TIMEOUT_ENV || '10000'); assert( Number.isInteger(eggReadyTimeoutEnv), `process.env.EGG_READY_TIMEOUT_ENV ${process.env.EGG_READY_TIMEOUT_ENV} should be able to parseInt.`); @@ -139,7 +140,7 @@ export class Lifecycle extends EventEmitter { const timingKey = `${timingKeyPrefix} in ` + utils.getResolvedFilename(name, this.app.baseDir); this.timing.start(timingKey); debug('register legacyReadyCallback'); - return function legacyReadyCallback(...args: any[]) { + return function legacyReadyCallback(...args: unknown[]) { timing.end(timingKey); debug('end legacyReadyCallback'); cb(...args); @@ -355,8 +356,8 @@ export class Lifecycle extends EventEmitter { #delegateReadyEvent(ready: Ready) { ready.once('error', (err?: Error) => ready.ready(err)); - ready.on('ready_timeout', (id: any) => this.emit('ready_timeout', id)); - ready.on('ready_stat', (data: any) => this.emit('ready_stat', data)); + ready.on('ready_timeout', (id: unknown) => this.emit('ready_timeout', id)); + ready.on('ready_stat', (data: unknown) => this.emit('ready_stat', data)); ready.on('error', (err?: Error) => this.emit('error', err)); } @@ -381,19 +382,21 @@ export class Lifecycle extends EventEmitter { const done = ready.readyCallback(name); // ensure scope executes after load completed - process.nextTick(() => { - utils.callFn(scope).then(() => { + process.nextTick(async () => { + try { + await utils.callFn(scope); debug('[registerReadyCallback] end name: %o', name); done(); this.timing.end(timingKey); - }, (err: Error) => { + } catch (e) { + let err = e as Error; // avoid non-stringify error: TypeError: Cannot convert object to primitive value if (!(err instanceof Error)) { err = new Error(format('%s', err)); } done(err); this.timing.end(timingKey); - }); + } }); } } diff --git a/src/utils/index.ts b/src/utils/index.ts index 7bdb8026..e6188771 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -3,11 +3,12 @@ import path from 'node:path'; import fs from 'node:fs'; import { stat } from 'node:fs/promises'; import BuiltinModule from 'node:module'; + import { importResolve, importModule } from '@eggjs/utils'; const debug = debuglog('@eggjs/core/utils'); -export type Fun = (...args: any[]) => any; +export type Fun = (...args: unknown[]) => unknown; // Guard against poorly mocked module constructors. const Module = typeof module !== 'undefined' && module.constructor.length > 1 @@ -15,6 +16,7 @@ const Module = typeof module !== 'undefined' && module.constructor.length > 1 /* istanbul ignore next */ : BuiltinModule; +// eslint-disable-next-line typescript/no-explicit-any const extensions = (Module as any)._extensions; const extensionNames = Object.keys(extensions).concat([ '.cjs', '.mjs' ]); debug('Module extensions: %j', extensionNames); @@ -28,6 +30,7 @@ function getCalleeFromStack(withLine?: boolean, stackIndex?: number) { Error.stackTraceLimit = 5; // capture the stack + // eslint-disable-next-line typescript/no-explicit-any const obj: any = {}; Error.captureStackTrace(obj); let callSite = obj.stack[stackIndex]; @@ -102,7 +105,7 @@ export default { methods: [ 'head', 'options', 'get', 'put', 'patch', 'post', 'delete' ], - async callFn(fn: Fun, args?: any[], ctx?: any) { + async callFn(fn: Fun, args?: unknown[], ctx?: unknown) { args = args || []; if (typeof fn !== 'function') return; return ctx ? fn.call(ctx, ...args) : fn(...args); @@ -120,6 +123,6 @@ export default { * Capture call site stack from v8. * https://github.com/v8/v8/wiki/Stack-Trace-API */ -function prepareObjectStackTrace(_obj: any, stack: any) { +function prepareObjectStackTrace(_obj: unknown, stack: unknown) { return stack; } From 9a78e39213f633c0838bde40b77eba50d7806d50 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Thu, 27 Mar 2025 21:51:40 +0800 Subject: [PATCH 04/10] f --- .oxlintrc.json | 3 ++- src/egg.ts | 33 +++++++++++------------ src/lifecycle.ts | 2 +- src/loader/context_loader.ts | 6 ++--- src/loader/egg_loader.ts | 10 +------ src/loader/file_loader.ts | 39 +++++++++++++-------------- src/singleton.ts | 8 +++--- src/types.ts | 1 + src/utils/index.ts | 8 +++--- src/utils/sequencify.ts | 10 ++++--- src/utils/timing.ts | 16 +++++------ test/loader/mixin/load_plugin.test.ts | 3 ++- 12 files changed, 66 insertions(+), 73 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index 4fd221fc..b269a92d 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -118,6 +118,7 @@ "oxc/no-rest-spread-properties": "allow", "oxc/no-optional-chaining": "allow", "oxc/no-async-await": "allow", + "oxc/no-barrel-file": "allow", // typescript "typescript/explicit-function-return-type": "allow", @@ -127,7 +128,7 @@ "typescript/no-inferrable-types": "error", "typescript/array-type": "error", "typescript/no-non-null-assertion": "error", - "typescript/no-explicit-any": "error", + "typescript/no-explicit-any": "allow", "typescript/no-import-type-side-effects": "error", "typescript/no-dynamic-delete": "error", "typescript/prefer-ts-expect-error": "error", diff --git a/src/egg.ts b/src/egg.ts index 4dad0dcd..8529b2bf 100644 --- a/src/egg.ts +++ b/src/egg.ts @@ -29,7 +29,6 @@ export const EGG_LOADER = Symbol.for('egg#loader'); export interface EggCoreOptions { baseDir: string; type: 'application' | 'agent'; - // eslint-disable-next-line typescript/no-explicit-any plugins?: any; serverScope?: string; env?: string; @@ -112,10 +111,10 @@ export class EggCore extends KoaApplication { #router?: Router; /** auto inject on loadService() */ - // eslint-disable-next-line typescript/no-explicit-any + readonly serviceClasses: Record = {}; /** auto inject on loadController() */ - // eslint-disable-next-line typescript/no-explicit-any + readonly controller: Record = {}; /** auto inject on loadMiddleware() */ readonly middlewares: Record MiddlewareFunc> = {}; @@ -123,8 +122,8 @@ export class EggCore extends KoaApplication { /** * @class * @param {Object} options - options - * @param {String} [options.baseDir=process.cwd()] - the directory of application - * @param {String} [options.type=application|agent] - whether it's running in app worker or agent worker + * @param {String} [options.baseDir] - the directory of application + * @param {String} [options.type] - whether it's running in app worker or agent worker * @param {Object} [options.plugins] - custom plugins * @since 1.0.0 */ @@ -365,7 +364,7 @@ export class EggCore extends KoaApplication { * @param {object} opts - * - {Number} [timeout=10000] - emit `ready_timeout` when it doesn't finish but reach the timeout * - {Boolean} [isWeakDep=false] - whether it's a weak dependency - * @return {Function} - a callback + * @returns {Function} - a callback * @example * const done = app.readyCallback('mysql'); * mysql.ready(done); @@ -400,7 +399,7 @@ export class EggCore extends KoaApplication { * * If error is thrown when it's closing, the promise will reject. * It will also reject after following call. - * @return {Promise} promise + * @returns {Promise} promise * @since 1.0.0 */ async close(): Promise { @@ -426,7 +425,7 @@ export class EggCore extends KoaApplication { * Alias to {@link Router#url} * @param {String} name - Router name * @param {Object} params - more parameters - * @return {String} url + * @returns {String} url */ url(name: string, params?: Parameters[1]): string { return this.router.url(name, params); @@ -437,7 +436,7 @@ export class EggCore extends KoaApplication { // 'all', 'resources', 'register', 'redirect' head(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; head(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - // eslint-disable-next-line typescript/no-explicit-any + head(...args: any): EggCore { this.router.head.apply(this.router, args); return this; @@ -450,42 +449,42 @@ export class EggCore extends KoaApplication { // } get(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; get(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - // eslint-disable-next-line typescript/no-explicit-any + get(...args: any): EggCore { this.router.get.apply(this.router, args); return this; } put(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; put(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - // eslint-disable-next-line typescript/no-explicit-any + put(...args: any): EggCore { this.router.put.apply(this.router, args); return this; } patch(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; patch(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - // eslint-disable-next-line typescript/no-explicit-any + patch(...args: any): EggCore { this.router.patch.apply(this.router, args); return this; } post(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; post(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - // eslint-disable-next-line typescript/no-explicit-any + post(...args: any): EggCore { this.router.post.apply(this.router, args); return this; } delete(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; delete(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - // eslint-disable-next-line typescript/no-explicit-any + delete(...args: any): EggCore { this.router.delete.apply(this.router, args); return this; } del(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; del(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - // eslint-disable-next-line typescript/no-explicit-any + del(...args: any): EggCore { this.router.del.apply(this.router, args); return this; @@ -493,7 +492,7 @@ export class EggCore extends KoaApplication { all(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; all(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - // eslint-disable-next-line typescript/no-explicit-any + all(...args: any): EggCore { this.router.all.apply(this.router, args); return this; @@ -503,7 +502,7 @@ export class EggCore extends KoaApplication { resources(prefix: string, middleware: MiddlewareFunc, controller: string | ResourcesController): EggCore; resources(name: string, prefix: string, controller: string | ResourcesController): EggCore; resources(name: string, prefix: string, middleware: MiddlewareFunc, controller: string | ResourcesController): EggCore; - // eslint-disable-next-line typescript/no-explicit-any + resources(...args: any): EggCore { this.router.resources.apply(this.router, args); return this; diff --git a/src/lifecycle.ts b/src/lifecycle.ts index 9fc13aa3..6d228d4d 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -55,7 +55,7 @@ export interface ILifecycleBoot { beforeClose?(): Promise; } -export type BootImplClass = new(...args: unknown[]) => T; +export type BootImplClass = new(...args: any[]) => T; export interface LifecycleOptions { baseDir: string; diff --git a/src/loader/context_loader.ts b/src/loader/context_loader.ts index 5a0866bd..9f7ea39f 100644 --- a/src/loader/context_loader.ts +++ b/src/loader/context_loader.ts @@ -71,14 +71,14 @@ export class ContextLoader extends FileLoader { ...options, target, }); - this.#inject = this.options.inject!; + this.#inject = this.options.inject as Record; const app = this.#inject; const property = options.property; // define ctx.service Object.defineProperty(app.context, property, { get() { - // eslint-disable-next-line @typescript-eslint/no-this-alias + // oxlint-disable-next-line unicorn/no-this-assignment, typescript/no-this-alias const ctx = this; // distinguish property cache, // cache's lifecycle is the same with this context instance @@ -90,7 +90,7 @@ export class ContextLoader extends FileLoader { let instance = classLoader.get(property); if (!instance) { instance = getInstance(target, ctx); - classLoader.set(property, instance!); + classLoader.set(property, instance as ClassLoader); } return instance; }, diff --git a/src/loader/egg_loader.ts b/src/loader/egg_loader.ts index b04fb56e..f220f8ba 100644 --- a/src/loader/egg_loader.ts +++ b/src/loader/egg_loader.ts @@ -19,7 +19,7 @@ import { now, diff } from 'performance-ms'; import { type FileLoaderOptions, CaseStyle, FULLPATH, FileLoader } from './file_loader.js'; import { type ContextLoaderOptions, ContextLoader } from './context_loader.js'; import utils, { type Fun } from '../utils/index.js'; -import sequencify from '../utils/sequencify.js'; +import { sequencify } from '../utils/sequencify.js'; import { Timing } from '../utils/timing.js'; import type { Context, EggCore, MiddlewareFunc, @@ -64,7 +64,6 @@ export class EggLoader { #requiredCount = 0; readonly options: EggLoaderOptions; readonly timing: Timing; - // oxlint-disable-next-line typescript/no-explicit-any readonly pkg: Record; readonly eggPaths: string[]; readonly serverEnv: string; @@ -819,7 +818,6 @@ export class EggLoader { /** end Plugin loader */ /** start Config loader */ - // oxlint-disable-next-line typescript/no-explicit-any configMeta: Record; config: EggAppConfig; @@ -886,7 +884,6 @@ export class EggLoader { 'config.default', `config.${this.serverEnv}`, ]; - // oxlint-disable-next-line typescript/no-explicit-any const target: Record = {}; for (const filename of names) { const config = await this.#loadConfig(this.options.baseDir, filename, undefined, 'app'); @@ -910,7 +907,6 @@ export class EggLoader { if (!filepath) { return; } - // oxlint-disable-next-line typescript/no-explicit-any const config: Record = await this.loadFile(filepath, this.appInfo, extraInject); if (!config) return; if (isPlugin || isApp) { @@ -942,7 +938,6 @@ export class EggLoader { extend(true, this.configMeta, config); } - // oxlint-disable-next-line typescript/no-explicit-any #setConfig(obj: Record, filepath: string) { for (const key of Object.keys(obj)) { const val = obj[key]; @@ -1654,7 +1649,6 @@ function debugMiddlewareWrapper(mw: MiddlewareFunc): MiddlewareFunc { // wrap the controller class, yield a object with middlewares function wrapControllerClass(Controller: typeof BaseContextClass, fullPath: string) { let proto = Controller.prototype; - // oxlint-disable-next-line typescript/no-explicit-any const ret: Record = {}; // tracing the prototype chain while (proto !== Object.prototype) { @@ -1695,10 +1689,8 @@ function controllerMethodToMiddleware(Controller: typeof BaseContextClass, key: } // wrap the method of the object, method can receive ctx as it's first argument -// oxlint-disable-next-line typescript/no-explicit-any function wrapObject(obj: Record, fullPath: string, prefix?: string) { const keys = Object.keys(obj); - // oxlint-disable-next-line typescript/no-explicit-any const ret: Record = {}; prefix = prefix ?? ''; for (const key of keys) { diff --git a/src/loader/file_loader.ts b/src/loader/file_loader.ts index c59032e6..fa0be021 100644 --- a/src/loader/file_loader.ts +++ b/src/loader/file_loader.ts @@ -2,11 +2,12 @@ import assert from 'node:assert'; import fs from 'node:fs'; import { debuglog } from 'node:util'; import path from 'node:path'; + import globby from 'globby'; import { isClass, isGeneratorFunction, isAsyncFunction, isPrimitive } from 'is-type-of'; import { isSupportTypeScript } from '@eggjs/utils'; -import type { Fun } from '../utils/index.js'; -import utils from '../utils/index.js'; + +import utils, { type Fun } from '../utils/index.js'; const debug = debuglog('@eggjs/core/file_loader'); @@ -27,6 +28,7 @@ export interface FileLoaderOptions { /** directories to be loaded */ directory: string | string[]; /** attach the target object from loaded files */ + target: Record; /** match the files when load, support glob, default to all js files */ match?: string | string[]; @@ -39,6 +41,7 @@ export interface FileLoaderOptions { /** determine whether override the property when get the same name */ override?: boolean; /** an object that be the argument when invoke the function */ + inject?: Record; /** a function that filter the exports which can be loaded */ filter?: FileLoaderFilter; @@ -102,7 +105,7 @@ export class FileLoader { /** * attach items to target object. Mapping the directory to properties. * `app/controller/group/repository.js` => `target.group.repository` - * @return {Object} target + * @returns {Object} target * @since 1.0.0 */ async load(): Promise { @@ -112,12 +115,13 @@ export class FileLoader { debug('loading item: %o', item); // item { properties: [ 'a', 'b', 'c'], exports } // => target.a.b.c = exports + // oxlint-disable-next-line unicorn/no-array-reduce item.properties.reduce((target, property, index) => { let obj; const properties = item.properties.slice(0, index + 1).join('.'); if (index === item.properties.length - 1) { - if (property in target) { - if (!this.options.override) throw new Error(`can't overwrite property '${properties}' from ${target[property][FULLPATH]} by ${item.fullpath}`); + if (property in target && !this.options.override) { + throw new Error(`can't overwrite property '${properties}' from ${target[property][FULLPATH]} by ${item.fullpath}`); } obj = item.exports; if (obj && !isPrimitive(obj)) { @@ -158,17 +162,17 @@ export class FileLoader { * `Properties` is an array that contains the directory of a filepath. * * `Exports` depends on type, if exports is a function, it will be called. if initializer is specified, it will be called with exports for customizing. - * @return {Array} items + * @returns {Array} items * @since 1.0.0 */ protected async parse(): Promise { let files = this.options.match; - if (!files) { + if (files) { + files = Array.isArray(files) ? files : [ files ]; + } else { files = isSupportTypeScript() ? [ '**/*.(js|ts)', '!**/*.d.ts' ] : [ '**/*.js' ]; - } else { - files = Array.isArray(files) ? files : [ files ]; } let ignore = this.options.ignore; @@ -208,7 +212,7 @@ export class FileLoader { const exports = await getExports(fullpath, this.options, pathName); // ignore exports when it's null or false returned by filter function - if (exports == null || (filter && filter(exports) === false)) { + if (exports === null || exports === undefined || (filter && filter(exports) === false)) { continue; } @@ -270,7 +274,7 @@ async function getExports(fullpath: string, options: FileLoaderOptions, pathName // } if (options.call && typeof exports === 'function') { exports = exports(options.inject); - if (exports != null) { + if (exports !== null && exports !== undefined) { return exports; } } @@ -294,15 +298,10 @@ function defaultCamelize(filepath: string, caseStyle: CaseStyle) { // FooBar.js > fooBar (if lowercaseFirst is true) property = property.replaceAll(/[_-][a-z]/ig, s => s.slice(1).toUpperCase()); let first = property[0]; - switch (caseStyle) { - case 'lower': - first = first.toLowerCase(); - break; - case 'upper': - first = first.toUpperCase(); - break; - case 'camel': - default: + if (caseStyle === CaseStyle.lower) { + first = first.toLowerCase(); + } else if (caseStyle === CaseStyle.upper) { + first = first.toUpperCase(); } return first + property.slice(1); }); diff --git a/src/singleton.ts b/src/singleton.ts index 4fb2d957..ebbf1f36 100644 --- a/src/singleton.ts +++ b/src/singleton.ts @@ -48,10 +48,10 @@ export class Singleton { // multi client, use app[name].getSingletonInstance(id) if (options.clients) { - Object.keys(options.clients).forEach(id => { + for (const id of Object.keys(options.clients)) { const client = this.createInstance(options.clients[id], id); this.clients.set(id, client); - }); + } this.#setClientToApp(this); return; } @@ -95,14 +95,14 @@ export class Singleton { * @deprecated please use `getSingletonInstance(id)` instead */ get(id: string) { - return this.clients.get(id)!; + return this.clients.get(id) as T; } /** * Get singleton instance by id */ getSingletonInstance(id: string) { - return this.clients.get(id)!; + return this.clients.get(id) as T; } createInstance(config: Record, clientName: string) { diff --git a/src/types.ts b/src/types.ts index e9cccc83..fbf03d08 100644 --- a/src/types.ts +++ b/src/types.ts @@ -46,6 +46,7 @@ export interface CustomLoaderConfigItem { loadunit?: boolean; } + export interface EggAppConfig extends Record { coreMiddleware: string[]; middleware: string[]; diff --git a/src/utils/index.ts b/src/utils/index.ts index e6188771..1ba8e088 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -16,7 +16,7 @@ const Module = typeof module !== 'undefined' && module.constructor.length > 1 /* istanbul ignore next */ : BuiltinModule; -// eslint-disable-next-line typescript/no-explicit-any + const extensions = (Module as any)._extensions; const extensionNames = Object.keys(extensions).concat([ '.cjs', '.mjs' ]); debug('Module extensions: %j', extensionNames); @@ -30,7 +30,7 @@ function getCalleeFromStack(withLine?: boolean, stackIndex?: number) { Error.stackTraceLimit = 5; // capture the stack - // eslint-disable-next-line typescript/no-explicit-any + const obj: any = {}; Error.captureStackTrace(obj); let callSite = obj.stack[stackIndex]; @@ -86,8 +86,8 @@ export default { } const obj = await importModule(filepath, { importDefaultOnly: true }); return obj; - } catch (e: any) { - if (!e.message && typeof e !== 'string') { + } catch (e) { + if (!(e instanceof Error)) { // ts error: test/fixtures/apps/app-ts/app/extend/context.ts(5,17): error TS2339: Property 'url' does not exist on type 'Context' console.trace(e); throw e; diff --git a/src/utils/sequencify.ts b/src/utils/sequencify.ts index c1a7708c..20085711 100644 --- a/src/utils/sequencify.ts +++ b/src/utils/sequencify.ts @@ -12,10 +12,12 @@ export interface SequencifyTask { optionalDependencies: string[]; } -function sequence(tasks: Record, names: string[], result: SequencifyResult, +// oxlint-disable-next-line max-params +function sequence(tasks: Record, + names: string[], result: SequencifyResult, missing: string[], recursive: string[], nest: string[], optional: boolean, parent: string) { - names.forEach(function(name) { + for (const name of names) { if (result.requires[name]) return; const node = tasks[name]; @@ -43,12 +45,12 @@ function sequence(tasks: Record, names: string[], result if (!result.sequence.includes(name)) { result.sequence.push(name); } - }); + } } // tasks: object with keys as task names // names: array of task names -export default function sequencify(tasks: Record, names: string[]) { +export function sequencify(tasks: Record, names: string[]) { const result: SequencifyResult = { sequence: [], requires: {}, diff --git a/src/utils/timing.ts b/src/utils/timing.ts index cb053ffc..82d6a2ca 100644 --- a/src/utils/timing.ts +++ b/src/utils/timing.ts @@ -15,12 +15,11 @@ export interface TimingItem { export class Timing { #enable: boolean; - #startTime: number | null; + #startTime: number; #map: Map; #list: TimingItem[]; constructor() { this.#enable = true; - this.#startTime = null; this.#map = new Map(); this.#list = []; this.init(); @@ -46,7 +45,7 @@ export class Timing { } start = start || Date.now(); - if (this.#startTime === null) { + if (!this.#startTime) { this.#startTime = start; } const item: TimingItem = { @@ -63,9 +62,8 @@ export class Timing { end(name?: string) { if (!name || !this.#enable) return; - assert(this.#map.has(name), `should run timing.start('${name}') first`); - - const item = this.#map.get(name)!; + const item = this.#map.get(name); + assert(item, `should run timing.start('${name}') first`); item.end = Date.now(); item.duration = item.end - item.start; debug('end %j', item); @@ -91,8 +89,8 @@ export class Timing { itemToString(timelineEnd: number, item: TimingItem, times: number) { const isEnd = typeof item.duration === 'number'; - const duration = isEnd ? item.duration! : timelineEnd - item.start; - const offset = item.start - this.#startTime!; + const duration = isEnd ? item.duration as number : timelineEnd - item.start; + const offset = item.start - this.#startTime; const status = `${duration}ms${isEnd ? '' : ' NOT_END'}`; const timespan = Math.floor(Number((offset * times).toFixed(6))); let timeline = Math.floor(Number((duration * times).toFixed(6))); @@ -103,7 +101,7 @@ export class Timing { toString(prefix = 'egg start timeline:', width = 50) { const timelineEnd = Date.now(); - const timelineDuration = timelineEnd - this.#startTime!; + const timelineDuration = timelineEnd - this.#startTime; let times = 1; if (timelineDuration > width) { times = width / timelineDuration; diff --git a/test/loader/mixin/load_plugin.test.ts b/test/loader/mixin/load_plugin.test.ts index e64c14aa..be1f7db6 100644 --- a/test/loader/mixin/load_plugin.test.ts +++ b/test/loader/mixin/load_plugin.test.ts @@ -574,10 +574,11 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { assert.equal(loader.allPlugins.zzz.path, getFilepath('load-plugin-config-override/plugins/zzz')); }); - it('should support optionalDependencies', async () => { + it.only('should support optionalDependencies', async () => { app = createApp('plugin-optional-dependencies'); const loader = app.loader; await loader.loadPlugin(); + console.log(loader.orderPlugins.map(p => p.name)); assert.deepEqual(loader.orderPlugins.slice(2).map(p => p.name), [ 'package', 'e', 'b', 'a', 'f' ]); }); From 2a05a99ad44330c0ff80c2489aadabe1423ea335 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Thu, 27 Mar 2025 22:09:14 +0800 Subject: [PATCH 05/10] f --- src/utils/sequencify.ts | 9 ++++++--- test/index.test.ts | 2 ++ test/loader/mixin/load_plugin.test.ts | 5 ++--- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/utils/sequencify.ts b/src/utils/sequencify.ts index 20085711..571df9cd 100644 --- a/src/utils/sequencify.ts +++ b/src/utils/sequencify.ts @@ -18,11 +18,14 @@ function sequence(tasks: Record, missing: string[], recursive: string[], nest: string[], optional: boolean, parent: string) { for (const name of names) { - if (result.requires[name]) return; - + if (result.requires[name]) { + continue; + } const node = tasks[name]; if (!node) { - if (optional === true) return; + if (optional === true) { + continue; + } missing.push(name); } else if (nest.includes(name)) { nest.push(name); diff --git a/test/index.test.ts b/test/index.test.ts index 1fec7387..bc66d08b 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -1,4 +1,5 @@ import { strict as assert } from 'node:assert'; +// oxlint-disable-next-line no-namespace import * as EggCore from '../src/index.js'; import type { EggAppConfig } from '../src/index.js'; @@ -31,6 +32,7 @@ describe('test/index.test.ts', () => { 'Router', 'Singleton', 'Timing', + 'sequencify', 'utils', ]); }); diff --git a/test/loader/mixin/load_plugin.test.ts b/test/loader/mixin/load_plugin.test.ts index be1f7db6..df63d61d 100644 --- a/test/loader/mixin/load_plugin.test.ts +++ b/test/loader/mixin/load_plugin.test.ts @@ -574,12 +574,11 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { assert.equal(loader.allPlugins.zzz.path, getFilepath('load-plugin-config-override/plugins/zzz')); }); - it.only('should support optionalDependencies', async () => { + it('should support optionalDependencies', async () => { app = createApp('plugin-optional-dependencies'); const loader = app.loader; await loader.loadPlugin(); - console.log(loader.orderPlugins.map(p => p.name)); - assert.deepEqual(loader.orderPlugins.slice(2).map(p => p.name), [ 'package', 'e', 'b', 'a', 'f' ]); + assert.deepEqual(loader.orderPlugins.map(p => p.name), [ 'session', 'zzz', 'package', 'e', 'b', 'a', 'f' ]); }); it('should warn when redefine plugin', async () => { From a55969ffda56b7a47727997b42ca8bafd67923d9 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Fri, 28 Mar 2025 22:05:02 +0800 Subject: [PATCH 06/10] f --- .oxlintrc.json | 17 +- test/egg-ts.test.ts | 65 ++- test/egg.test.ts | 462 ++++++++++--------- test/helper.ts | 13 +- test/loader/context_loader.test.ts | 8 +- test/loader/egg_loader.test.ts | 16 +- test/loader/file_loader.test.ts | 35 +- test/loader/get_app_info.test.ts | 6 +- test/loader/get_appname.test.ts | 5 +- test/loader/get_framework_paths.test.ts | 31 +- test/loader/get_load_units.test.ts | 6 +- test/loader/get_server_env.test.ts | 6 +- test/loader/load_file.test.ts | 41 +- test/loader/mixin/load_config.test.ts | 46 +- test/loader/mixin/load_controller.test.ts | 261 ++++++++--- test/loader/mixin/load_custom_app.test.ts | 7 +- test/loader/mixin/load_custom_loader.test.ts | 14 +- test/loader/mixin/load_extend.test.ts | 6 +- test/loader/mixin/load_extend_class.test.ts | 6 +- test/loader/mixin/load_helper_extend.test.ts | 3 +- test/loader/mixin/load_middleware.test.ts | 65 ++- test/loader/mixin/load_plugin.test.ts | 219 +++++---- test/loader/mixin/load_service.test.ts | 24 +- test/singleton.test.ts | 45 +- test/utils/index.test.ts | 54 ++- test/utils/router.test.ts | 116 +++-- test/utils/timing.test.ts | 19 +- 27 files changed, 985 insertions(+), 611 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index b269a92d..89516a53 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -139,5 +139,20 @@ "jsdoc/require-returns": "allow", "jsdoc/require-param": "allow" }, - "ignorePatterns": ["index.d.ts", "test/fixtures/**", "__snapshots__", "test", "benchmark"] + "overrides": [ + { + "rules": { + "unicorn/no-array-for-each": "allow", + "promise/avoid-new": "allow", + "max-nested-callbacks": "allow" + }, + "files": ["test/**/*.ts"] + } + ], + "ignorePatterns": [ + "index.d.ts", + "test/fixtures/**", + "__snapshots__", + "benchmark" + ] } diff --git a/test/egg-ts.test.ts b/test/egg-ts.test.ts index 29dfa7f8..5cbbd9fe 100644 --- a/test/egg-ts.test.ts +++ b/test/egg-ts.test.ts @@ -1,9 +1,11 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { mm } from 'mm'; import { request } from '@eggjs/supertest'; import coffee from 'coffee'; + import { utils } from '../src/index.js'; -import { Application, createApp, getFilepath } from './helper.js'; +import { createApp, getFilepath, type Application } from './helper.js'; describe('test/egg-ts.test.ts', () => { let app: Application | undefined; @@ -14,7 +16,9 @@ describe('test/egg-ts.test.ts', () => { }); afterEach(async () => { - app && await app.close(); + if (app) { + await app.close(); + } app = undefined; return mm.restore(); // delete require.extensions['.ts']; @@ -143,7 +147,7 @@ describe('test/egg-ts.test.ts', () => { it.skip('should not load ts files while EGG_TYPESCRIPT was true but no extensions', async () => { mm(process.env, 'EGG_TYPESCRIPT', 'true'); - mm(utils, 'extensions', [ '.js', '.json' ]); + mm(utils, 'extensions', ['.js', '.json']); app = createApp('egg-ts-js'); await app.loader.loadService(); assert(app.serviceClasses.lord); @@ -152,11 +156,20 @@ describe('test/egg-ts.test.ts', () => { it.skip('should compile app-ts without error', async () => { await coffee - .spawn('node', [ '--require', 'ts-node/register/type-check', getFilepath('app-ts/app.ts') ], { - env: Object.assign({}, process.env, { - TS_NODE_PROJECT: getFilepath('app-ts/tsconfig.json'), - }), - }) + .spawn( + 'node', + [ + '--require', + 'ts-node/register/type-check', + getFilepath('app-ts/app.ts'), + ], + { + env: { + ...process.env, + TS_NODE_PROJECT: getFilepath('app-ts/tsconfig.json'), + }, + } + ) .debug() .expect('code', 0) .end(); @@ -164,14 +177,29 @@ describe('test/egg-ts.test.ts', () => { it.skip('should compile error with app-ts/error', async () => { await coffee - .spawn('node', [ '--require', 'ts-node/register/type-check', getFilepath('app-ts/app-error.ts') ], { - env: Object.assign({}, process.env, { - TS_NODE_PROJECT: getFilepath('app-ts/tsconfig.json'), - }), - }) + .spawn( + 'node', + [ + '--require', + 'ts-node/register/type-check', + getFilepath('app-ts/app-error.ts'), + ], + { + env: { + ...process.env, + TS_NODE_PROJECT: getFilepath('app-ts/tsconfig.json'), + }, + } + ) .debug() - .expect('stderr', /Property 'abb' does not exist on type 'EggCore<{ env: string; }>'/) - .expect('stderr', /Property 'abc' does not exist on type 'typeof BaseContextClass'/) + .expect( + 'stderr', + /Property 'abb' does not exist on type 'EggCore<{ env: string; }>'/ + ) + .expect( + 'stderr', + /Property 'abc' does not exist on type 'typeof BaseContextClass'/ + ) .expect('stderr', /'loadPlugin' is protected/) .expect('stderr', /'loadConfig' is protected/) .expect('stderr', /'loadApplicationExtend' is protected/) @@ -183,7 +211,10 @@ describe('test/egg-ts.test.ts', () => { .expect('stderr', /'loadCustomAgent' is protected/) .expect('stderr', /'loadService' is protected/) .expect('stderr', /'loadController' is protected/) - .expect('stderr', /Property 'checkEnvType' does not exist on type 'string'/) + .expect( + 'stderr', + /Property 'checkEnvType' does not exist on type 'string'/ + ) .expect('stderr', /'ctx' is protected/) .expect('code', 1) .end(); diff --git a/test/egg.test.ts b/test/egg.test.ts index 9a6b095f..b2ae3ee3 100644 --- a/test/egg.test.ts +++ b/test/egg.test.ts @@ -1,13 +1,17 @@ +// oxlint-disable promise/catch-or-return, promise/prefer-catch, promise/prefer-await-to-then, promise/no-callback-in-promise + import util from 'node:util'; import path from 'node:path'; -import { strict as assert } from 'node:assert'; +import { strict as assert } from 'node:assert/strict'; import fs from 'node:fs/promises'; import { setTimeout as sleep } from 'node:timers/promises'; + import { mm } from 'mm'; import { request } from '@eggjs/supertest'; import { pending } from 'pedding'; import coffee from 'coffee'; -import { createApp, getFilepath, Application } from './helper.js'; + +import { createApp, getFilepath, type Application } from './helper.js'; import { EggCore } from '../src/index.js'; describe('test/egg.test.ts', () => { @@ -53,42 +57,53 @@ describe('test/egg.test.ts', () => { }); it('should not set value expect for application and agent', () => { - assert.throws(() => { - new EggCore({ - type: 'nothing', - } as any); - }, /options.type should be application or agent/); + assert.throws( + () => + new EggCore({ + // @ts-expect-error test error + type: 'nothing', + }), + /options.type should be application or agent/ + ); }); it('should throw options.baseDir required', () => { - assert.throws(() => { - new EggCore({ - baseDir: 1, - } as any); - }, /options.baseDir required, and must be a string/); + assert.throws( + () => + new EggCore({ + // @ts-expect-error test error + baseDir: 1, + }), + /options.baseDir required, and must be a string/ + ); }); it('should throw options.baseDir not exist', () => { - assert.throws(() => { - new EggCore({ - baseDir: 'not-exist', - }); - }, /not-exist not exists/); + assert.throws( + () => + new EggCore({ + baseDir: 'not-exist', + }), + /not-exist not exists/ + ); }); it('should throw options.baseDir is not a directory', () => { - assert.throws(() => { - new EggCore({ - baseDir: getFilepath('egg/index.js'), - }); - }, /not a directory|no such file or directory/); + assert.throws( + () => + new EggCore({ + baseDir: getFilepath('egg/index.js'), + }), + /not a directory|no such file or directory/ + ); }); it('should throw process.env.EGG_READY_TIMEOUT_ENV should be able to parseInt', () => { mm(process.env, 'EGG_READY_TIMEOUT_ENV', 'notAnNumber'); - assert.throws(() => { - new EggCore(); - }, /process.env.EGG_READY_TIMEOUT_ENV notAnNumber should be able to parseInt/); + assert.throws( + () => new EggCore(), + /process.env.EGG_READY_TIMEOUT_ENV notAnNumber should be able to parseInt/ + ); }); }); @@ -144,7 +159,10 @@ describe('test/egg.test.ts', () => { it('should log info when plugin is not ready', done => { app = createApp('notready'); mm(app.console, 'warn', (message: string, b: any, a: any) => { - assert.equal(message, '[@eggjs/core/lifecycle:ready_timeout] %s seconds later %s was still unable to finish.'); + assert.equal( + message, + '[@eggjs/core/lifecycle:ready_timeout] %s seconds later %s was still unable to finish.' + ); assert.equal(b, 10); assert.equal(a, 'a'); // console.log(app.timing.toString()); @@ -162,11 +180,19 @@ describe('test/egg.test.ts', () => { app.loader.loadAll(); let message = ''; mm(app.console, 'info', (a: any, b: any, c: any) => { - message += util.format.apply(null, [ a, b, c ]); + message += util.format(a, b, c); }); app.ready(() => { - assert(/\[@eggjs\/core\/lifecycle:ready_stat] end ready task a, remain \["b"]/.test(message)); - assert(/\[@eggjs\/core\/lifecycle:ready_stat] end ready task b, remain \[]/.test(message)); + assert( + /\[@eggjs\/core\/lifecycle:ready_stat] end ready task a, remain \["b"]/.test( + message + ) + ); + assert( + /\[@eggjs\/core\/lifecycle:ready_stat] end ready task b, remain \[]/.test( + message + ) + ); // console.log(app.timing.toString()); done(); }); @@ -188,10 +214,26 @@ describe('test/egg.test.ts', () => { app = createApp('beforestart'); await app.loader.loadAll(); await app.ready(); - assert.equal((app as any).beforeStartFunction, true, 'beforeStartFunction'); - assert.equal((app as any).beforeStartGeneratorFunction, true, 'beforeStartGeneratorFunction'); - assert.equal((app as any).beforeStartAsyncFunction, true, 'beforeStartAsyncFunction'); - assert.equal((app as any).beforeStartTranslateAsyncFunction, true, 'beforeStartTranslateAsyncFunction'); + assert.equal( + (app as any).beforeStartFunction, + true, + 'beforeStartFunction' + ); + assert.equal( + (app as any).beforeStartGeneratorFunction, + true, + 'beforeStartGeneratorFunction' + ); + assert.equal( + (app as any).beforeStartAsyncFunction, + true, + 'beforeStartAsyncFunction' + ); + assert.equal( + (app as any).beforeStartTranslateAsyncFunction, + true, + 'beforeStartTranslateAsyncFunction' + ); }); it('should beforeStart execute success with EGG_READY_TIMEOUT_ENV', async () => { @@ -199,24 +241,33 @@ describe('test/egg.test.ts', () => { app = createApp('beforestart-with-timeout-env'); await app.loader.loadAll(); await app.ready(); - assert.equal((app as any).beforeStartFunction, true, 'beforeStartFunction'); + assert.equal( + (app as any).beforeStartFunction, + true, + 'beforeStartFunction' + ); const timeline = app.timing.toString(); // console.log(timeline); assert.match(timeline, /#14 Before Start in app.js:4:7/); }); - it('should beforeStart execute timeout without EGG_READY_TIMEOUT_ENV too short', function(done) { + it('should beforeStart execute timeout without EGG_READY_TIMEOUT_ENV too short', done => { done = pending(2, done); mm(process.env, 'EGG_READY_TIMEOUT_ENV', '1000'); app = createApp('beforestart-with-timeout-env'); app.loader.loadAll().then(done, done); app.once('ready_timeout', id => { - const file = path.normalize('test/fixtures/beforestart-with-timeout-env/app.js'); + const file = path.normalize( + 'test/fixtures/beforestart-with-timeout-env/app.js' + ); assert(id.includes(file)); const timeline = app.timing.toString(); // console.log(timeline); assert.match(timeline, /▇ \[\d+ms NOT_END] - #1 application Start/); - assert.match(timeline, /▇ \[\d+ms NOT_END] - #14 Before Start in app.js:4:7/); + assert.match( + timeline, + /▇ \[\d+ms NOT_END] - #14 Before Start in app.js:4:7/ + ); done(); }); }); @@ -269,11 +320,11 @@ describe('test/egg.test.ts', () => { app.close().then(done, done); }); - it('should return a promise', done => { + it('should return a promise', async () => { app = createApp('close'); const promise = app.close(); assert(promise instanceof Promise); - promise.then(done, done); + await promise; }); it('should throw when close error', done => { @@ -341,8 +392,10 @@ describe('test/egg.test.ts', () => { assert.equal((app as any).closeAsyncFn, true, 'closeAsyncFn'); assert.equal((app as any).onlyOnce, false, 'onlyOnce'); assert.equal((app as any).closeEvent, 'after', 'closeEvent'); - assert.equal((app as any).closeOrderArray.join(','), - 'closeAsyncFn,closeGeneratorFn,closeFn'); + assert.equal( + (app as any).closeOrderArray.join(','), + 'closeAsyncFn,closeGeneratorFn,closeFn' + ); }); it('should throw when call beforeClose without function', () => { @@ -384,7 +437,8 @@ describe('test/egg.test.ts', () => { describe.skip('run with DEBUG', () => { it('should ready', async () => { mm(process.env, 'DEBUG', '*'); - await coffee.fork(getFilepath('run-with-debug/index.js')) + await coffee + .fork(getFilepath('run-with-debug/index.js')) .debug() .expect('code', 0) .end(); @@ -475,7 +529,8 @@ describe('test/egg.test.ts', () => { assert(json.length === 28); assert(json[1].name === 'application Start'); - assert(json[1].end! - json[1].start === json[1].duration); + assert(json[1].end); + assert.equal(json[1].end - json[1].start, json[1].duration); assert(json[1].pid === process.pid); // loadPlugin @@ -497,7 +552,9 @@ describe('test/egg.test.ts', () => { assert(json[13].name === 'Require(7) app.js'); assert.equal(json[14].name, 'Before Start in app.js:9:7'); assert(json[15].name === 'Before Start in mock Block'); - assert(json[16].name === 'readyCallback in mockReadyCallbackWithoutFunction'); + assert( + json[16].name === 'readyCallback in mockReadyCallbackWithoutFunction' + ); assert(json[17].name === 'Load "proxy" to Context'); assert(json[18].name === 'Load Controller'); @@ -534,7 +591,8 @@ describe('test/egg.test.ts', () => { assert(json.length === 14); assert.equal(json[1].name, 'application Start'); - assert.equal(json[1].end! - json[1].start, json[1].duration); + assert(json[1].end); + assert.equal(json[1].end - json[1].start, json[1].duration); assert.equal(json[1].pid, process.pid); // loadPlugin @@ -559,14 +617,20 @@ describe('test/egg.test.ts', () => { describe.skip('script timing', () => { it('should work', async () => { const fixtureApp = getFilepath('timing'); - await coffee.fork(path.join(fixtureApp, 'index.js')) + await coffee + .fork(path.join(fixtureApp, 'index.js')) .beforeScript(path.join(fixtureApp, 'preload')) .debug() .expect('code', 0) .end(); - const timingJSON = await fs.readFile(path.join(fixtureApp, 'timing.json'), 'utf8'); + const timingJSON = await fs.readFile( + path.join(fixtureApp, 'timing.json'), + 'utf8' + ); const timing = JSON.parse(timingJSON); - const scriptStart = timing.find((item: any) => item.name === 'Script Start'); + const scriptStart = timing.find( + (item: any) => item.name === 'Script Start' + ); assert(scriptStart); assert(scriptStart.start); assert(scriptStart.end); @@ -581,60 +645,52 @@ describe('test/egg.test.ts', () => { const app = createApp('boot'); await app.loader.loadAll(); await app.ready(); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'app.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'app.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + ]); await sleep(10); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'app.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - 'didReady', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'app.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + 'didReady', + ]); await app.lifecycle.triggerServerDidReady(); await sleep(10); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'app.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - 'didReady', - 'serverDidReady', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'app.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + 'didReady', + 'serverDidReady', + ]); await app.close(); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'app.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - 'didReady', - 'serverDidReady', - 'beforeClose', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'app.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + 'didReady', + 'serverDidReady', + 'beforeClose', + ]); }); }); @@ -645,68 +701,58 @@ describe('test/egg.test.ts', () => { await app.loader.loadConfig(); await app.loader.loadAgentExtend(); await app.loader.loadCustomAgent(); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'agent.js in plugin', - 'configDidLoad in app', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'agent.js in plugin', + 'configDidLoad in app', + ]); await app.ready(); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'agent.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'agent.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + ]); await sleep(10); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'agent.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - 'didReady', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'agent.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + 'didReady', + ]); await app.lifecycle.triggerServerDidReady(); await sleep(10); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'agent.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - 'didReady', - 'serverDidReady', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'agent.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + 'didReady', + 'serverDidReady', + ]); await app.close(); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'agent.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - 'didReady', - 'serverDidReady', - 'beforeClose', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'agent.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + 'didReady', + 'serverDidReady', + 'beforeClose', + ]); }); }); }); @@ -737,17 +783,18 @@ describe('test/egg.test.ts', () => { error = e; } assert.strictEqual(error.message, 'didLoad error'); - assert.deepStrictEqual((app as any).bootLog, [ 'configDidLoad' ]); + assert.deepStrictEqual((app as any).bootLog, ['configDidLoad']); await sleep(10); - assert.deepStrictEqual((app as any).bootLog, [ 'configDidLoad', 'didReady' ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad', + 'didReady', + ]); await app.close(); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad', - 'didReady', - 'beforeClose', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad', + 'didReady', + 'beforeClose', + ]); // console.log(app.timing.toString()); assert.match(app.timing.toString(), /egg start timeline:/); assert.match(app.timing.toString(), /#1 application Start/); @@ -765,10 +812,17 @@ describe('test/egg.test.ts', () => { } catch (e) { error = e; } - assert.deepStrictEqual((app as any).bootLog, [ 'configDidLoad', 'didLoad' ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad', + 'didLoad', + ]); assert.strictEqual(error.message, 'willReady error'); await sleep(10); - assert.deepStrictEqual((app as any).bootLog, [ 'configDidLoad', 'didLoad', 'didReady' ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad', + 'didLoad', + 'didReady', + ]); await app.close(); // assert.deepStrictEqual( // (app as any).bootLog, @@ -788,7 +842,11 @@ describe('test/egg.test.ts', () => { await app.loader.loadAll(); await app.ready(); - assert.deepStrictEqual((app as any).bootLog, [ 'configDidLoad', 'didLoad', 'willReady' ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad', + 'didLoad', + 'willReady', + ]); let error: any; try { await new Promise((_resolve, reject) => { @@ -799,14 +857,12 @@ describe('test/egg.test.ts', () => { } assert.strictEqual(error.message, 'didReady error'); await app.close(); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad', - 'didLoad', - 'willReady', - 'beforeClose', - ]); + assert.deepStrictEqual((app as any).bootLog, [ + 'configDidLoad', + 'didLoad', + 'willReady', + 'beforeClose', + ]); }); }); @@ -841,34 +897,30 @@ describe('test/egg.test.ts', () => { const app = createApp('boot'); await app.loader.loadAll(); await app.ready(); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'app.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - ]); + assert.deepEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'app.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + ]); app.ready(() => { (app as any).bootLog.push('readyFunction'); }); await sleep(10); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'configDidLoad in plugin', - 'app.js in plugin', - 'configDidLoad in app', - 'didLoad', - 'beforeStart', - 'willReady', - 'ready', - 'readyFunction', - 'didReady', - ]); + assert.deepEqual((app as any).bootLog, [ + 'configDidLoad in plugin', + 'app.js in plugin', + 'configDidLoad in app', + 'didLoad', + 'beforeStart', + 'willReady', + 'ready', + 'readyFunction', + 'didReady', + ]); await app.close(); }); }); @@ -898,13 +950,11 @@ describe('test/egg.test.ts', () => { const app = createApp('boot-before-close'); await app.loader.loadAll(); await app.close(); - assert.deepStrictEqual( - (app as any).bootLog, - [ - 'beforeClose in app', - 'beforeClose in plugin', - 'beforeClose in plugin dep', - ]); + assert.deepEqual((app as any).bootLog, [ + 'beforeClose in app', + 'beforeClose in plugin', + 'beforeClose in plugin dep', + ]); }); }); }); diff --git a/test/helper.ts b/test/helper.ts index f8e7b716..9fd59737 100644 --- a/test/helper.ts +++ b/test/helper.ts @@ -1,7 +1,11 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import { EggCore } from '../src/index.js'; -import { Application, EggCoreInitOptions } from './fixtures/egg-esm/index.js'; + +import type { EggCore } from '../src/index.js'; +import { + Application, + type EggCoreInitOptions, +} from './fixtures/egg-esm/index.js'; export { Application } from './fixtures/egg-esm/index.js'; @@ -16,7 +20,10 @@ export function getFilepath(name: string) { return filepath; } -export function createApp(name: string, options?: EggCoreInitOptions & { Application?: typeof EggCore }): Application { +export function createApp( + name: string, + options?: EggCoreInitOptions & { Application?: typeof EggCore } +): Application { const baseDir = getFilepath(name); options = options ?? {}; options.baseDir = baseDir; diff --git a/test/loader/context_loader.test.ts b/test/loader/context_loader.test.ts index f3dae817..4faf9003 100644 --- a/test/loader/context_loader.test.ts +++ b/test/loader/context_loader.test.ts @@ -1,5 +1,6 @@ import { request } from '@eggjs/supertest'; -import { getFilepath, createApp, Application } from '../helper.js'; + +import { createApp, getFilepath, type Application } from '../helper.js'; describe('test/loader/context_loader.test.ts', () => { let app: Application; @@ -67,10 +68,7 @@ describe('test/loader/context_loader.test.ts', () => { .expect('pathname.a.b.c') .expect(200); - await request(app.callback()) - .get('/config') - .expect('config') - .expect(200); + await request(app.callback()).get('/config').expect('config').expect(200); }); it('should load file with service', () => { diff --git a/test/loader/egg_loader.test.ts b/test/loader/egg_loader.test.ts index 0f5c71c2..f88a8fa6 100644 --- a/test/loader/egg_loader.test.ts +++ b/test/loader/egg_loader.test.ts @@ -1,9 +1,11 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; import os from 'node:os'; import path from 'node:path'; + import { mm } from 'mm'; import { getPlugins } from '@eggjs/utils'; -import { Application, createApp, getFilepath } from '../helper.js'; + +import { createApp, getFilepath, type Application } from '../helper.js'; import { EggLoader } from '../../src/index.js'; describe('test/loader/egg_loader.test.ts', () => { @@ -68,7 +70,11 @@ describe('test/loader/egg_loader.test.ts', () => { logger: console, } as any); - let ret = await loader.loadFile(getFilepath('load_file/function.js'), 1, 2); + let ret = await loader.loadFile( + getFilepath('load_file/function.js'), + 1, + 2 + ); assert.equal(ret[0], 1); assert.equal(ret[1], 2); @@ -81,7 +87,7 @@ describe('test/loader/egg_loader.test.ts', () => { it('should be loaded by loadToApp, support symbol property', async () => { const baseDir = getFilepath('load_to_app'); const directory = path.join(baseDir, 'app/model'); - const prop = Symbol(); + const prop = Symbol('prop'); const app = {}; const loader = new EggLoader({ baseDir, @@ -95,7 +101,7 @@ describe('test/loader/egg_loader.test.ts', () => { it('should be loaded by loadToContext', async () => { const baseDir = getFilepath('load_to_app'); const directory = path.join(baseDir, 'app/service'); - const prop = Symbol(); + const prop = Symbol('prop'); const app = { context: {} }; const loader = new EggLoader({ baseDir, diff --git a/test/loader/file_loader.test.ts b/test/loader/file_loader.test.ts index 0591b348..1b575345 100644 --- a/test/loader/file_loader.test.ts +++ b/test/loader/file_loader.test.ts @@ -1,4 +1,6 @@ -import { strict as assert } from 'node:assert'; +// oxlint-disable promise/catch-or-return, promise/prefer-catch, promise/prefer-await-to-then, promise/no-callback-in-promise, promise/avoid-new + +import assert from 'node:assert/strict'; import path from 'node:path'; import { isClass } from 'is-type-of'; import yaml from 'js-yaml'; @@ -51,15 +53,12 @@ describe('test/loader/file_loader.test.ts', () => { foo: {}, }, }; - await assert.rejects( - async () => { - await new FileLoader({ - directory: path.join(dirBase, 'services'), - target: app.services, - }).load(); - }, - /can't overwrite property 'foo'/, - ); + await assert.rejects(async () => { + await new FileLoader({ + directory: path.join(dirBase, 'services'), + target: app.services, + }).load(); + }, /can't overwrite property 'foo'/); }); it('should not overwrite property from loading', async () => { @@ -152,7 +151,7 @@ describe('test/loader/file_loader.test.ts', () => { await new FileLoader({ directory: path.join(dirBase, 'ignore'), target: app.services, - ignore: [ 'util/a.js', 'util/b/b.js' ], + ignore: ['util/a.js', 'util/b/b.js'], }).load(); assert.equal(app.services.a.a, 1); }); @@ -182,7 +181,10 @@ describe('test/loader/file_loader.test.ts', () => { assert(app.dao.TestClass); assert.deepEqual(app.dao.TestClass.user, { name: 'kai.fangk' }); assert.equal(app.dao.TestClass.app, app); - assert.equal(app.dao.TestClass.path, path.join(dirBase, 'dao/TestClass.js')); + assert.equal( + app.dao.TestClass.path, + path.join(dirBase, 'dao/TestClass.js') + ); assert.deepEqual(app.dao.testFunction.user, { name: 'kai.fangk' }); assert.deepEqual(app.dao.testReturnFunction.user, { name: 'kai.fangk' }); }); @@ -321,7 +323,7 @@ describe('test/loader/file_loader.test.ts', () => { return filepath .replace('.js', '') .split('/') - .map(property => property.replace(/_/g, '')); + .map(property => property.replaceAll('_', '')); }, }).load(); @@ -371,7 +373,8 @@ describe('test/loader/file_loader.test.ts', () => { assert.equal(inject.b, true); - new target.a(inject); + const instance = new target.a(inject); + assert(instance); assert.equal(inject.a, true); }); @@ -384,7 +387,7 @@ describe('test/loader/file_loader.test.ts', () => { return Array.isArray(obj); }, }).load(); - assert.deepEqual(Object.keys(target), [ 'arr' ]); + assert.deepEqual(Object.keys(target), ['arr']); await new FileLoader({ directory: path.join(dirBase, 'filter'), @@ -393,6 +396,6 @@ describe('test/loader/file_loader.test.ts', () => { return isClass(obj); }, }).load(); - assert.deepEqual(Object.keys(target), [ 'arr', 'class' ]); + assert.deepEqual(Object.keys(target), ['arr', 'class']); }); }); diff --git a/test/loader/get_app_info.test.ts b/test/loader/get_app_info.test.ts index 289265e6..bcdfd540 100644 --- a/test/loader/get_app_info.test.ts +++ b/test/loader/get_app_info.test.ts @@ -1,6 +1,8 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { mm } from 'mm'; -import { Application, createApp, getFilepath } from '../helper.js'; + +import { createApp, getFilepath, type Application } from '../helper.js'; describe('test/loader/get_app_info.test.ts', () => { let app: Application; diff --git a/test/loader/get_appname.test.ts b/test/loader/get_appname.test.ts index e0b42c7f..1cae2158 100644 --- a/test/loader/get_appname.test.ts +++ b/test/loader/get_appname.test.ts @@ -1,5 +1,6 @@ -import { strict as assert } from 'node:assert'; -import { Application, createApp, getFilepath } from '../helper.js'; +import assert from 'node:assert/strict'; + +import { createApp, getFilepath, type Application } from '../helper.js'; describe('test/loader/get_appname.test.ts', () => { let app: Application; diff --git a/test/loader/get_framework_paths.test.ts b/test/loader/get_framework_paths.test.ts index 69f542e0..6363e039 100644 --- a/test/loader/get_framework_paths.test.ts +++ b/test/loader/get_framework_paths.test.ts @@ -1,7 +1,9 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { mm } from 'mm'; import { importModule } from '@eggjs/utils'; -import { Application, createApp, getFilepath } from '../helper.js'; + +import { createApp, getFilepath, type Application } from '../helper.js'; import { EggLoader, EggCore } from '../../src/index.js'; describe('test/loader/get_framework_paths.test.ts', () => { @@ -15,11 +17,14 @@ describe('test/loader/get_framework_paths.test.ts', () => { if (process.platform === 'win32') { eggPaths = eggPaths.map(filepath => filepath.toLowerCase()); } - assert.deepEqual(eggPaths, [ getFilepath('egg-esm') ]); + assert.deepEqual(eggPaths, [getFilepath('egg-esm')]); }); it('should get from framework using symbol', async () => { - const Application = await importModule(getFilepath('framework-symbol/index.js'), { importDefaultOnly: true }); + const Application = await importModule( + getFilepath('framework-symbol/index.js'), + { importDefaultOnly: true } + ); app = createApp('eggpath', { Application, }); @@ -31,7 +36,10 @@ describe('test/loader/get_framework_paths.test.ts', () => { }); it.skip('should throw when one of the Application do not specify symbol', async () => { - const AppClass = await importModule(getFilepath('framework-nosymbol/index.js'), { importDefaultOnly: true }); + const AppClass = await importModule( + getFilepath('framework-nosymbol/index.js'), + { importDefaultOnly: true } + ); assert.throws(() => { const app = createApp('eggpath', { Application: AppClass, @@ -42,7 +50,9 @@ describe('test/loader/get_framework_paths.test.ts', () => { it('should remove dulplicate eggPath', async () => { app = createApp('eggpath', { - Application: await importModule(getFilepath('framework-dulp/index.js'), { importDefaultOnly: true }), + Application: await importModule(getFilepath('framework-dulp/index.js'), { + importDefaultOnly: true, + }), }); assert.deepEqual(app.loader.eggPaths, [ getFilepath('egg'), @@ -64,7 +74,9 @@ describe('test/loader/get_framework_paths.test.ts', () => { get [Symbol.for('egg#eggPath')]() { return getFilepath('egg-esm'); } - close() {} + close() { + // empty + } } app = createApp('eggpath', { @@ -77,7 +89,10 @@ describe('test/loader/get_framework_paths.test.ts', () => { it('should assert eggPath type', async () => { await assert.rejects(async () => { createApp('eggpath', { - Application: await importModule(getFilepath('framework-wrong-eggpath/index.js'), { importDefaultOnly: true }), + Application: await importModule( + getFilepath('framework-wrong-eggpath/index.js'), + { importDefaultOnly: true } + ), }); }, /Symbol.for\('egg#eggPath'\) should be string/); }); diff --git a/test/loader/get_load_units.test.ts b/test/loader/get_load_units.test.ts index 391df5a2..de5a97ed 100644 --- a/test/loader/get_load_units.test.ts +++ b/test/loader/get_load_units.test.ts @@ -1,6 +1,8 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { mm } from 'mm'; -import { Application, createApp, getFilepath } from '../helper.js'; + +import { createApp, getFilepath, type Application } from '../helper.js'; describe('test/loader/get_load_units.test.ts', () => { let app: Application; diff --git a/test/loader/get_server_env.test.ts b/test/loader/get_server_env.test.ts index 182ed73b..3998d41c 100644 --- a/test/loader/get_server_env.test.ts +++ b/test/loader/get_server_env.test.ts @@ -1,6 +1,8 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { mm } from 'mm'; -import { Application, createApp } from '../helper.js'; + +import { createApp, type Application } from '../helper.js'; describe('test/loader/get_server_env.test.ts', () => { let app: Application; diff --git a/test/loader/load_file.test.ts b/test/loader/load_file.test.ts index 46fbb22d..306a2c35 100644 --- a/test/loader/load_file.test.ts +++ b/test/loader/load_file.test.ts @@ -1,6 +1,8 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { mm } from 'mm'; -import { createApp, Application, getFilepath } from '../helper.js'; + +import { createApp, getFilepath, type Application } from '../helper.js'; describe('test/loader/load_file.test.ts', () => { let app: Application; @@ -17,8 +19,12 @@ describe('test/loader/load_file.test.ts', () => { it('should load file when exports is function', async () => { app = createApp('load_file'); - const exports = await app.loader.loadFile(getFilepath('load_file/function.js'), 1, 2); - assert.deepEqual(exports, [ 1, 2 ]); + const exports = await app.loader.loadFile( + getFilepath('load_file/function.js'), + 1, + 2 + ); + assert.deepEqual(exports, [1, 2]); }); it('should throw with filepath when file syntax error', async () => { @@ -30,46 +36,57 @@ describe('test/loader/load_file.test.ts', () => { it('should load custom file', async () => { app = createApp('load_file'); - let result = (await app.loader.loadFile(getFilepath('load_file/no-js.yml'))).toString(); + const buf = await app.loader.loadFile(getFilepath('load_file/no-js.yml')); + let result = buf.toString(); if (process.platform === 'win32') { - result = result.replace(/\r\n/g, '\n'); + result = result.replaceAll(String.raw`\r\n`, '\n'); } assert.equal(result, '---\nmap:\n a: 1\n b: 2'); }); it('should load cjs module file which returns function returning a promise', async () => { app = createApp('load_file'); - const result = (await app.loader.loadFile(getFilepath('load_file/promise_function.js'))); + const result = await app.loader.loadFile( + getFilepath('load_file/promise_function.js') + ); assert.deepEqual(result, { clients: 'Test Config' }); }); it('should load cjs module file which returns async function', async () => { app = createApp('load_file'); - const result = (await app.loader.loadFile(getFilepath('load_file/async.js'))); + const result = await app.loader.loadFile(getFilepath('load_file/async.js')); assert.deepEqual(result, { clients: 'Test Config' }); }); it('should load compiled es module file', async () => { app = createApp('load_file'); - const result = (await app.loader.loadFile(getFilepath('load_file/es-module-default.js'))); + const result = await app.loader.loadFile( + getFilepath('load_file/es-module-default.js') + ); assert(result.fn); }); it('should load compiled es module file which default = null', async () => { app = createApp('load_file'); - const result = (await app.loader.loadFile(getFilepath('load_file/es-module-default-null.js'))); + const result = await app.loader.loadFile( + getFilepath('load_file/es-module-default-null.js') + ); assert.equal(result, null); }); it('should load compiled es module file which default = function returning a promise', async () => { app = createApp('load_file'); - const result = (await app.loader.loadFile(getFilepath('load_file/es-module-default-promise.js'))); + const result = await app.loader.loadFile( + getFilepath('load_file/es-module-default-promise.js') + ); assert.deepEqual(result, { clients: 'Test Config' }); }); it('should load compiled es module file which default = async function', async () => { app = createApp('load_file'); - const result = (await app.loader.loadFile(getFilepath('load_file/es-module-default-async.js'))); + const result = await app.loader.loadFile( + getFilepath('load_file/es-module-default-async.js') + ); assert.deepEqual(result, { clients: 'Test Config' }); }); }); diff --git a/test/loader/mixin/load_config.test.ts b/test/loader/mixin/load_config.test.ts index ac0e40e4..cd01e95e 100644 --- a/test/loader/mixin/load_config.test.ts +++ b/test/loader/mixin/load_config.test.ts @@ -1,8 +1,10 @@ import path from 'node:path'; -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { mm } from 'mm'; + import { EggCore } from '../../../src/index.js'; -import { Application, createApp, getFilepath } from '../../helper.js'; +import { createApp, getFilepath, type Application } from '../../helper.js'; describe('test/loader/mixin/load_config.test.ts', () => { let app: Application; @@ -19,9 +21,9 @@ describe('test/loader/mixin/load_config.test.ts', () => { // 支持嵌套覆盖 assert.deepEqual(loader.config.urllib, { keepAlive: false, - keepAliveTimeout: 30000, - timeout: 30000, - maxSockets: Infinity, + keepAliveTimeout: 30_000, + timeout: 30_000, + maxSockets: Number.POSITIVE_INFINITY, maxFreeSockets: 256, }); }); @@ -55,12 +57,16 @@ describe('test/loader/mixin/load_config.test.ts', () => { }); it('should override config by env.EGG_APP_CONFIG', async () => { - mm(process.env, 'EGG_APP_CONFIG', JSON.stringify({ - egg: 'env_egg', - foo: { - bar: 'env_bar', - }, - })); + mm( + process.env, + 'EGG_APP_CONFIG', + JSON.stringify({ + egg: 'env_egg', + foo: { + bar: 'env_bar', + }, + }) + ); app = createApp('config-env-app-config'); const loader = app.loader; await loader.loadPlugin(); @@ -107,7 +113,11 @@ describe('test/loader/mixin/load_config.test.ts', () => { await loader.loadConfig(); throw new Error('should not run'); } catch (err: any) { - assert(err.message.includes(`Can not define middleware in ${path.join(pluginDir, 'config/config.default.js')}`)); + assert( + err.message.includes( + `Can not define middleware in ${path.join(pluginDir, 'config/config.default.js')}` + ) + ); } }); @@ -143,7 +153,7 @@ describe('test/loader/mixin/load_config.test.ts', () => { app = createApp('config-array'); await app.loader.loadPlugin(); await app.loader.loadConfig(); - assert.deepEqual(app.config.array, [ 1, 2 ]); + assert.deepEqual(app.config.array, [1, 2]); }); it('should generate configMeta', async () => { @@ -165,7 +175,10 @@ describe('test/loader/mixin/load_config.test.ts', () => { assert.equal(configMeta.date.toLowerCase(), configPath); assert.equal(configMeta.ooooo.toLowerCase(), configPath); assert.equal(configMeta.urllib.keepAlive.toLowerCase(), configPath); - assert.equal(configMeta.urllib.timeout.toLowerCase(), getFilepath('egg-esm/config/config.default.js')); + assert.equal( + configMeta.urllib.timeout.toLowerCase(), + getFilepath('egg-esm/config/config.default.js') + ); assert.equal(configMeta.urllib.foo.toLowerCase(), configPath); assert.equal(configMeta.urllib.n.toLowerCase(), configPath); assert.equal(configMeta.urllib.dd.toLowerCase(), configPath); @@ -183,7 +196,10 @@ describe('test/loader/mixin/load_config.test.ts', () => { assert.equal(configMeta.date, configPath); assert.equal(configMeta.ooooo, configPath); assert.equal(configMeta.urllib.keepAlive, configPath); - assert.equal(configMeta.urllib.timeout, getFilepath('egg-esm/config/config.default.js')); + assert.equal( + configMeta.urllib.timeout, + getFilepath('egg-esm/config/config.default.js') + ); assert.equal(configMeta.urllib.foo, configPath); assert.equal(configMeta.urllib.n, configPath); assert.equal(configMeta.urllib.dd, configPath); diff --git a/test/loader/mixin/load_controller.test.ts b/test/loader/mixin/load_controller.test.ts index 88855474..222aee6f 100644 --- a/test/loader/mixin/load_controller.test.ts +++ b/test/loader/mixin/load_controller.test.ts @@ -1,8 +1,10 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; import path from 'node:path'; + import { request } from '@eggjs/supertest'; -import is from 'is-type-of'; -import { Application, createApp, getFilepath } from '../../helper.js'; +import { isFunction, isAsyncFunction } from 'is-type-of'; + +import { createApp, getFilepath, type Application } from '../../helper.js'; describe('test/loader/mixin/load_controller.test.ts', () => { let app: Application; @@ -27,9 +29,18 @@ describe('test/loader/mixin/load_controller.test.ts', () => { describe('when controller is generator function', () => { it('should use it as middleware', () => { assert(app.controller.generatorFunction); - assert.equal(app.controller.generatorFunction.name, 'objectControllerMiddleware'); - const classFilePath = path.join(app.baseDir, 'app/controller/generator_function.js'); - assert.equal(app.controller.generatorFunction[app.loader.FileLoader.FULLPATH], classFilePath); + assert.equal( + app.controller.generatorFunction.name, + 'objectControllerMiddleware' + ); + const classFilePath = path.join( + app.baseDir, + 'app/controller/generator_function.js' + ); + assert.equal( + app.controller.generatorFunction[app.loader.FileLoader.FULLPATH], + classFilePath + ); return request(app.callback()) .get('/generator-function') @@ -50,10 +61,14 @@ describe('test/loader/mixin/load_controller.test.ts', () => { describe('when controller is object', () => { it('should define method which is function', () => { assert(app.controller.object.callFunction); - assert(app.controller.object.callFunction.name === 'objectControllerMiddleware'); + assert( + app.controller.object.callFunction.name === 'objectControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/object.js'); - assert(app.controller.object.callFunction[app.loader.FileLoader.FULLPATH] === - classFilePath + '#callFunction()'); + assert( + app.controller.object.callFunction[app.loader.FileLoader.FULLPATH] === + classFilePath + '#callFunction()' + ); return request(app.callback()) .get('/object-function') @@ -63,10 +78,17 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should define method which is generator function', () => { assert(app.controller.object.callGeneratorFunction); - assert(app.controller.object.callGeneratorFunction.name === 'objectControllerMiddleware'); + assert( + app.controller.object.callGeneratorFunction.name === + 'objectControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/object.js'); - assert(app.controller.object.callGeneratorFunction[app.loader.FileLoader.FULLPATH] === - classFilePath + '#callGeneratorFunction()'); + assert( + app.controller.object.callGeneratorFunction[ + app.loader.FileLoader.FULLPATH + ] === + classFilePath + '#callGeneratorFunction()' + ); return request(app.callback()) .get('/object-generator-function') @@ -76,10 +98,17 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should define method on subObject', () => { assert(app.controller.object.subObject.callGeneratorFunction); - assert(app.controller.object.subObject.callGeneratorFunction.name === 'objectControllerMiddleware'); + assert( + app.controller.object.subObject.callGeneratorFunction.name === + 'objectControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/object.js'); - assert(app.controller.object.subObject.callGeneratorFunction[app.loader.FileLoader.FULLPATH] === - classFilePath + '#subObject.callGeneratorFunction()'); + assert( + app.controller.object.subObject.callGeneratorFunction[ + app.loader.FileLoader.FULLPATH + ] === + classFilePath + '#subObject.callGeneratorFunction()' + ); return request(app.callback()) .get('/subObject-generator-function') @@ -88,11 +117,20 @@ describe('test/loader/mixin/load_controller.test.ts', () => { }); it('should define method on subObject.subSubObject', () => { - assert(app.controller.object.subObject.subSubObject.callGeneratorFunction); - assert(app.controller.object.subObject.subSubObject.callGeneratorFunction.name === 'objectControllerMiddleware'); + assert( + app.controller.object.subObject.subSubObject.callGeneratorFunction + ); + assert( + app.controller.object.subObject.subSubObject.callGeneratorFunction + .name === 'objectControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/object.js'); - assert(app.controller.object.subObject.subSubObject.callGeneratorFunction[app.loader.FileLoader.FULLPATH] === - classFilePath + '#subObject.subSubObject.callGeneratorFunction()'); + assert( + app.controller.object.subObject.subSubObject.callGeneratorFunction[ + app.loader.FileLoader.FULLPATH + ] === + classFilePath + '#subObject.subSubObject.callGeneratorFunction()' + ); return request(app.callback()) .get('/subSubObject-generator-function') @@ -102,10 +140,17 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should define method which is generator function with argument', () => { assert(app.controller.object.callGeneratorFunctionWithArg); - assert(app.controller.object.callGeneratorFunctionWithArg.name === 'objectControllerMiddleware'); + assert( + app.controller.object.callGeneratorFunctionWithArg.name === + 'objectControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/object.js'); - assert(app.controller.object.callGeneratorFunctionWithArg[app.loader.FileLoader.FULLPATH] === - classFilePath + '#callGeneratorFunctionWithArg()'); + assert( + app.controller.object.callGeneratorFunctionWithArg[ + app.loader.FileLoader.FULLPATH + ] === + classFilePath + '#callGeneratorFunctionWithArg()' + ); return request(app.callback()) .get('/object-generator-function-arg') @@ -115,10 +160,17 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should define method which is async function', () => { assert(app.controller.object.callAsyncFunction); - assert(app.controller.object.callAsyncFunction.name === 'objectControllerMiddleware'); + assert( + app.controller.object.callAsyncFunction.name === + 'objectControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/object.js'); - assert(app.controller.object.callAsyncFunction[app.loader.FileLoader.FULLPATH] === - classFilePath + '#callAsyncFunction()'); + assert( + app.controller.object.callAsyncFunction[ + app.loader.FileLoader.FULLPATH + ] === + classFilePath + '#callAsyncFunction()' + ); return request(app.callback()) .get('/object-async-function') @@ -128,10 +180,17 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should define method which is async function with argument', () => { assert(app.controller.object.callAsyncFunctionWithArg); - assert(app.controller.object.callAsyncFunctionWithArg.name === 'objectControllerMiddleware'); + assert( + app.controller.object.callAsyncFunctionWithArg.name === + 'objectControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/object.js'); - assert(app.controller.object.callAsyncFunctionWithArg[app.loader.FileLoader.FULLPATH] === - classFilePath + '#callAsyncFunctionWithArg()'); + assert( + app.controller.object.callAsyncFunctionWithArg[ + app.loader.FileLoader.FULLPATH + ] === + classFilePath + '#callAsyncFunctionWithArg()' + ); return request(app.callback()) .get('/object-async-function-arg') @@ -154,19 +213,21 @@ describe('test/loader/mixin/load_controller.test.ts', () => { .expect(200) .expect('create'); - await request(app.callback()) - .post('/resources-object/1') - .expect(404); + await request(app.callback()).post('/resources-object/1').expect(404); }); }); describe('when controller is class', () => { it('should define method which is function', () => { assert(app.controller.class.callFunction); - assert(app.controller.class.callFunction.name === 'classControllerMiddleware'); + assert( + app.controller.class.callFunction.name === 'classControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/class.js'); - assert(app.controller.class.callFunction[app.loader.FileLoader.FULLPATH] === - `${classFilePath}#HomeController.callFunction()`); + assert( + app.controller.class.callFunction[app.loader.FileLoader.FULLPATH] === + `${classFilePath}#HomeController.callFunction()` + ); return request(app.callback()) .get('/class-function') @@ -176,10 +237,16 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should define method which is generator function', () => { assert(app.controller.class.callGeneratorFunction); - assert(app.controller.class.callGeneratorFunction.name === 'classControllerMiddleware'); + assert( + app.controller.class.callGeneratorFunction.name === + 'classControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/class.js'); - assert(app.controller.class.callGeneratorFunction[app.loader.FileLoader.FULLPATH] === - `${classFilePath}#HomeController.callGeneratorFunction()`); + assert( + app.controller.class.callGeneratorFunction[ + app.loader.FileLoader.FULLPATH + ] === `${classFilePath}#HomeController.callGeneratorFunction()` + ); return request(app.callback()) .get('/class-generator-function') @@ -189,10 +256,16 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should define method which is generator function with ctx', () => { assert(app.controller.class.callGeneratorFunctionWithArg); - assert(app.controller.class.callGeneratorFunctionWithArg.name === 'classControllerMiddleware'); + assert( + app.controller.class.callGeneratorFunctionWithArg.name === + 'classControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/class.js'); - assert(app.controller.class.callGeneratorFunctionWithArg[app.loader.FileLoader.FULLPATH] === - `${classFilePath}#HomeController.callGeneratorFunctionWithArg()`); + assert( + app.controller.class.callGeneratorFunctionWithArg[ + app.loader.FileLoader.FULLPATH + ] === `${classFilePath}#HomeController.callGeneratorFunctionWithArg()` + ); return request(app.callback()) .get('/class-generator-function-arg') @@ -202,10 +275,16 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should define method which is async function', () => { assert(app.controller.class.callAsyncFunction); - assert(app.controller.class.callAsyncFunction.name === 'classControllerMiddleware'); + assert( + app.controller.class.callAsyncFunction.name === + 'classControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/class.js'); - assert(app.controller.class.callAsyncFunction[app.loader.FileLoader.FULLPATH] === - `${classFilePath}#HomeController.callAsyncFunction()`); + assert( + app.controller.class.callAsyncFunction[ + app.loader.FileLoader.FULLPATH + ] === `${classFilePath}#HomeController.callAsyncFunction()` + ); return request(app.callback()) .get('/class-async-function') @@ -215,10 +294,16 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should define method which is async function with ctx', () => { assert(app.controller.class.callAsyncFunctionWithArg); - assert(app.controller.class.callAsyncFunctionWithArg.name === 'classControllerMiddleware'); + assert( + app.controller.class.callAsyncFunctionWithArg.name === + 'classControllerMiddleware' + ); const classFilePath = path.join(app.baseDir, 'app/controller/class.js'); - assert(app.controller.class.callAsyncFunctionWithArg[app.loader.FileLoader.FULLPATH] === - `${classFilePath}#HomeController.callAsyncFunctionWithArg()`); + assert( + app.controller.class.callAsyncFunctionWithArg[ + app.loader.FileLoader.FULLPATH + ] === `${classFilePath}#HomeController.callAsyncFunctionWithArg()` + ); return request(app.callback()) .get('/class-async-function-arg') @@ -227,10 +312,19 @@ describe('test/loader/mixin/load_controller.test.ts', () => { }); it('should load class that is inherited from its super class', () => { - assert(app.controller.classInherited.callInheritedFunction.name === 'classControllerMiddleware'); - const classFilePath = path.join(app.baseDir, 'app/controller/class_inherited.js'); - assert(app.controller.classInherited.callInheritedFunction[app.loader.FileLoader.FULLPATH] === - `${classFilePath}#HomeController.callInheritedFunction()`); + assert( + app.controller.classInherited.callInheritedFunction.name === + 'classControllerMiddleware' + ); + const classFilePath = path.join( + app.baseDir, + 'app/controller/class_inherited.js' + ); + assert( + app.controller.classInherited.callInheritedFunction[ + app.loader.FileLoader.FULLPATH + ] === `${classFilePath}#HomeController.callInheritedFunction()` + ); return request(app.callback()) .get('/class-inherited-function') @@ -240,10 +334,19 @@ describe('test/loader/mixin/load_controller.test.ts', () => { it('should load inherited class without overriding its own function', () => { assert(app.controller.classInherited.callOverriddenFunction); - assert(app.controller.classInherited.callOverriddenFunction.name === 'classControllerMiddleware'); - const classFilePath = path.join(app.baseDir, 'app/controller/class_inherited.js'); - assert(app.controller.classInherited.callOverriddenFunction[app.loader.FileLoader.FULLPATH] === - `${classFilePath}#HomeController.callOverriddenFunction()`); + assert( + app.controller.classInherited.callOverriddenFunction.name === + 'classControllerMiddleware' + ); + const classFilePath = path.join( + app.baseDir, + 'app/controller/class_inherited.js' + ); + assert( + app.controller.classInherited.callOverriddenFunction[ + app.loader.FileLoader.FULLPATH + ] === `${classFilePath}#HomeController.callOverriddenFunction()` + ); return request(app.callback()) .get('/class-overridden-function') @@ -256,15 +359,25 @@ describe('test/loader/mixin/load_controller.test.ts', () => { }); it('should not override constructor', () => { - assert(/\[native code]/.test(app.controller.class.constructor.toString())); + assert( + /\[native code]/.test(app.controller.class.constructor.toString()) + ); }); it('should load class that is wrapped by function', () => { assert(app.controller.classWrapFunction.get); - assert(app.controller.classWrapFunction.get.name === 'classControllerMiddleware'); - const classFilePath = path.join(app.baseDir, 'app/controller/class_wrap_function.js'); - assert(app.controller.classWrapFunction.get[app.loader.FileLoader.FULLPATH] === - `${classFilePath}#HomeController.get()`); + assert( + app.controller.classWrapFunction.get.name === + 'classControllerMiddleware' + ); + const classFilePath = path.join( + app.baseDir, + 'app/controller/class_wrap_function.js' + ); + assert( + app.controller.classWrapFunction.get[app.loader.FileLoader.FULLPATH] === + `${classFilePath}#HomeController.get()` + ); return request(app.callback()) .get('/class-wrap-function') @@ -283,9 +396,7 @@ describe('test/loader/mixin/load_controller.test.ts', () => { .expect(200) .expect('create'); - await request(app.callback()) - .post('/resources-class/1') - .expect(404); + await request(app.callback()).post('/resources-class/1').expect(404); }); it('should get pathName from Controller instance', () => { @@ -299,7 +410,12 @@ describe('test/loader/mixin/load_controller.test.ts', () => { return request(app.callback()) .get('/class-fullpath') .expect(200) - .expect(path.join(getFilepath('controller-app'), 'app/controller/admin/config.js')); + .expect( + path.join( + getFilepath('controller-app'), + 'app/controller/admin/config.js' + ) + ); }); }); @@ -310,17 +426,23 @@ describe('test/loader/mixin/load_controller.test.ts', () => { await app.loader.loadAll(); throw new Error('should not run'); } catch (err: any) { - assert.match(err.message, /controller `next` should not use next as argument from file/); + assert.match( + err.message, + /controller `next` should not use next as argument from file/ + ); } }); }); describe('function attribute', () => { it('should keep function attribute ok', () => { - assert(is.function(app.controller.functionAttr.getAccountInfo)); - assert(is.asyncFunction(app.controller.functionAttr.getAccountInfo)); + assert(isFunction(app.controller.functionAttr.getAccountInfo)); + assert(isAsyncFunction(app.controller.functionAttr.getAccountInfo)); assert(app.controller.functionAttr.getAccountInfo.operationType); - assert(app.controller.functionAttr.foo && is.asyncFunction(app.controller.functionAttr.foo.bar)); + assert( + app.controller.functionAttr.foo && + isAsyncFunction(app.controller.functionAttr.foo.bar) + ); assert.deepEqual(app.controller.functionAttr.foo.bar.operationType, { value: 'account.foo.bar', name: 'account.foo.bar', @@ -379,9 +501,10 @@ describe('test/loader/mixin/load_controller.test.ts', () => { }); it('should support parameter', async () => { - assert.equal(app.config.controller!.supportParams, true); + assert(app.config.controller); + assert.equal(app.config.controller.supportParams, true); const ctx = { app }; - const args = [ 1, 2, 3 ]; + const args = [1, 2, 3]; let r = await app.controller.generatorFunction.call(ctx, ...args); assert.deepEqual(args, r); r = await app.controller.object.callFunction.call(ctx, ...args); diff --git a/test/loader/mixin/load_custom_app.test.ts b/test/loader/mixin/load_custom_app.test.ts index bd0df054..cc96cdb1 100644 --- a/test/loader/mixin/load_custom_app.test.ts +++ b/test/loader/mixin/load_custom_app.test.ts @@ -1,5 +1,6 @@ -import { strict as assert } from 'node:assert'; -import { Application, createApp } from '../../helper.js'; +import assert from 'node:assert/strict'; + +import { createApp, type Application } from '../../helper.js'; describe('test/loader/mixin/load_custom_app.test.ts', () => { describe('app.js as function', () => { @@ -18,7 +19,7 @@ describe('test/loader/mixin/load_custom_app.test.ts', () => { assert((app as any).app === 'app'); }); - it('should app.js of plugin before application\'s', () => { + it("should app.js of plugin before application's", () => { assert((app as any).dateB <= (app as any).date); assert((app as any).dateC <= (app as any).date); }); diff --git a/test/loader/mixin/load_custom_loader.test.ts b/test/loader/mixin/load_custom_loader.test.ts index c80d8ffd..1c7d778f 100644 --- a/test/loader/mixin/load_custom_loader.test.ts +++ b/test/loader/mixin/load_custom_loader.test.ts @@ -1,6 +1,8 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { request } from '@eggjs/supertest'; -import { Application, createApp } from '../../helper.js'; + +import { createApp, type Application } from '../../helper.js'; describe('test/loader/mixin/load_custom_loader.test.ts', () => { let app: Application; @@ -47,7 +49,6 @@ describe('test/loader/mixin/load_custom_loader.test.ts', () => { assert(name === 'pluginb'); }); - it('should loadConfig first', async () => { const app = createApp('custom-loader'); try { @@ -65,14 +66,15 @@ describe('test/loader/mixin/load_custom_loader.test.ts', () => { try { app.loader.config = { customLoader: { - custom: { - }, + custom: {}, }, } as any; await app.loader.loadCustomLoader(); throw new Error('should not run'); } catch (err: any) { - assert(err.message === 'directory is required for config.customLoader.custom'); + assert( + err.message === 'directory is required for config.customLoader.custom' + ); } finally { app.close(); } diff --git a/test/loader/mixin/load_extend.test.ts b/test/loader/mixin/load_extend.test.ts index 1d957c4e..26571095 100644 --- a/test/loader/mixin/load_extend.test.ts +++ b/test/loader/mixin/load_extend.test.ts @@ -1,7 +1,9 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { request } from '@eggjs/supertest'; import { mm } from 'mm'; -import { Application, createApp } from '../../helper.js'; + +import { createApp, type Application } from '../../helper.js'; describe('test/loader/mixin/load_extend.test.ts', () => { let app: Application; diff --git a/test/loader/mixin/load_extend_class.test.ts b/test/loader/mixin/load_extend_class.test.ts index 788acc20..57c4f161 100644 --- a/test/loader/mixin/load_extend_class.test.ts +++ b/test/loader/mixin/load_extend_class.test.ts @@ -1,7 +1,9 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { request } from '@eggjs/supertest'; import { mm } from 'mm'; -import { Application, createApp } from '../../helper.js'; + +import { createApp, type Application } from '../../helper.js'; describe('test/loader/mixin/load_extend_class.test.ts', () => { let app: Application; diff --git a/test/loader/mixin/load_helper_extend.test.ts b/test/loader/mixin/load_helper_extend.test.ts index 73fcfff7..b3e6664c 100644 --- a/test/loader/mixin/load_helper_extend.test.ts +++ b/test/loader/mixin/load_helper_extend.test.ts @@ -1,5 +1,6 @@ import { request } from '@eggjs/supertest'; -import { Application, createApp } from '../../helper.js'; + +import { createApp, type Application } from '../../helper.js'; describe('test/loader/mixin/load_helper_extend.test.ts', () => { describe('helper', () => { diff --git a/test/loader/mixin/load_middleware.test.ts b/test/loader/mixin/load_middleware.test.ts index 427e3d28..384265ac 100644 --- a/test/loader/mixin/load_middleware.test.ts +++ b/test/loader/mixin/load_middleware.test.ts @@ -1,7 +1,9 @@ import path from 'node:path'; -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { request } from '@eggjs/supertest'; -import { Application, createApp, getFilepath } from '../../helper.js'; + +import { createApp, getFilepath, type Application } from '../../helper.js'; describe('test/loader/mixin/load_middleware.test.ts', () => { let app: Application; @@ -38,29 +40,32 @@ describe('test/loader/mixin/load_middleware.test.ts', () => { names.push(mw._name); } try { - assert.deepEqual(names, [ 'status', 'static', 'custom', 'routerMiddleware' ]); + assert.deepEqual(names, [ + 'status', + 'static', + 'custom', + 'routerMiddleware', + ]); } catch { - assert.deepEqual(names, [ 'statusDebugWrapper', 'staticDebugWrapper', 'customDebugWrapper', 'routerMiddleware' ]); + assert.deepEqual(names, [ + 'statusDebugWrapper', + 'staticDebugWrapper', + 'customDebugWrapper', + 'routerMiddleware', + ]); } }); it('should override middlewares of plugin by framework', async () => { - await request(app.callback()) - .get('/status') - .expect('egg status'); + await request(app.callback()).get('/status').expect('egg status'); }); it('should override middlewares of plugin by application', async () => { - await request(app.callback()) - .get('/custom') - .expect('app custom'); + await request(app.callback()).get('/custom').expect('app custom'); }); it('should override middlewares of egg by application', async () => { - await request(app.callback()) - .get('/static') - .expect(200) - .expect('static'); + await request(app.callback()).get('/static').expect(200).expect('static'); }); it('should throw when middleware return no-generator', async () => { @@ -102,9 +107,7 @@ describe('test/loader/mixin/load_middleware.test.ts', () => { await app.loader.loadController(); await app.loader.loadRouter(); - await request(app.callback()) - .get('/status') - .expect(404); + await request(app.callback()).get('/status').expect(404); app.close(); }); @@ -117,13 +120,9 @@ describe('test/loader/mixin/load_middleware.test.ts', () => { await app.loader.loadController(); await app.loader.loadRouter(); - await request(app.callback()) - .get('/status') - .expect('egg status'); + await request(app.callback()).get('/status').expect('egg status'); - await request(app.callback()) - .post('/status') - .expect(404); + await request(app.callback()).post('/status').expect(404); app.close(); }); @@ -136,13 +135,9 @@ describe('test/loader/mixin/load_middleware.test.ts', () => { await app.loader.loadController(); await app.loader.loadRouter(); - await request(app.callback()) - .post('/status') - .expect('egg status'); + await request(app.callback()).post('/status').expect('egg status'); - await request(app.callback()) - .get('/status') - .expect(404); + await request(app.callback()).get('/status').expect(404); app.close(); }); @@ -155,9 +150,7 @@ describe('test/loader/mixin/load_middleware.test.ts', () => { await app.loader.loadController(); await app.loader.loadRouter(); - await request(app.callback()) - .get('/static') - .expect(404); + await request(app.callback()).get('/static').expect(404); app.close(); }); @@ -205,9 +198,7 @@ describe('test/loader/mixin/load_middleware.test.ts', () => { }); it('should support common functions', async () => { - await request(app.callback()) - .get('/common') - .expect('common'); + await request(app.callback()).get('/common').expect('common'); }); }); @@ -219,7 +210,9 @@ describe('test/loader/mixin/load_middleware.test.ts', () => { await app.loader.loadPlugin(); await app.loader.loadConfig(); await app.loader.loadCustomApp(); - const directory = app.loader.getLoadUnits().map(unit => path.join(unit.path, 'app/middleware')); + const directory = app.loader + .getLoadUnits() + .map(unit => path.join(unit.path, 'app/middleware')); directory.push(path.join(baseDir, 'app/other-middleware')); await app.loader.loadMiddleware({ directory, diff --git a/test/loader/mixin/load_plugin.test.ts b/test/loader/mixin/load_plugin.test.ts index df63d61d..5cbdb7c5 100644 --- a/test/loader/mixin/load_plugin.test.ts +++ b/test/loader/mixin/load_plugin.test.ts @@ -1,8 +1,10 @@ -import path from 'node:path'; import fs from 'node:fs'; -import { strict as assert } from 'node:assert'; +import path from 'node:path'; +import assert from 'node:assert/strict'; + import { mm } from 'mm'; -import { Application, createApp, getFilepath } from '../../helper.js'; + +import { createApp, getFilepath, type Application } from '../../helper.js'; import { EggCore, EggLoader } from '../../../src/index.js'; describe('test/loader/mixin/load_plugin.test.ts', () => { @@ -10,7 +12,9 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { afterEach(async () => { mm.restore(); - app && await app.close(); + if (app) { + await app.close(); + } app = undefined; }); @@ -62,29 +66,27 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { assert.deepEqual(loader.plugins.e, { enable: true, name: 'e', - dependencies: [ 'f' ], + dependencies: ['f'], optionalDependencies: [], env: [], path: path.join(baseDir, 'plugins/e'), from: path.join(baseDir, 'config/plugin.js'), }); - assert(loader.orderPlugins instanceof Array); + assert(Array.isArray(loader.orderPlugins)); }); it('should loadPlugin with order', async () => { app = createApp('plugin'); const loader = app.loader; const loaderOrders: string[] = []; - [ - 'loadEggPlugins', - 'loadAppPlugins', - 'loadCustomPlugins', - ].forEach(method => { - mm(loader, method, async () => { - loaderOrders.push(method); - return {}; - }); - }); + ['loadEggPlugins', 'loadAppPlugins', 'loadCustomPlugins'].forEach( + method => { + mm(loader, method, async () => { + loaderOrders.push(method); + return {}; + }); + } + ); await loader.loadPlugin(); assert.deepEqual(loaderOrders, [ @@ -104,7 +106,7 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { assert.deepEqual(loader.plugins.rds, { enable: true, name: 'rds', - dependencies: [ 'session' ], + dependencies: ['session'], optionalDependencies: [], env: [], package: 'rds', @@ -119,7 +121,9 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { return EggLoader; } get [Symbol.for('egg#eggPath')]() { - return getFilepath('plugin-pnpm/node_modules/.pnpm/framework@1.0.0/node_modules/framework'); + return getFilepath( + 'plugin-pnpm/node_modules/.pnpm/framework@1.0.0/node_modules/framework' + ); } } app = createApp('plugin-pnpm', { @@ -141,7 +145,9 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { return EggLoader; } get [Symbol.for('egg#eggPath')]() { - return getFilepath('plugin-pnpm-scope/node_modules/.pnpm/@eggjs+yadan@1.0.0/node_modules/@eggjs/yadan'); + return getFilepath( + 'plugin-pnpm-scope/node_modules/.pnpm/@eggjs+yadan@1.0.0/node_modules/@eggjs/yadan' + ); } } app = createApp('plugin-pnpm-scope', { @@ -187,7 +193,7 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { assert.deepEqual(loader.plugins.g, { enable: true, name: 'g', - dependencies: [ 'f' ], + dependencies: ['f'], optionalDependencies: [], env: [], path: path.join(baseDir, 'plugins/g'), @@ -199,8 +205,11 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { it('should warn when the name of plugin is not same', async () => { let message = ''; app = createApp('plugin'); - mm(app.console, 'warn', function(m: string) { - if (!m.startsWith('[@eggjs/core/egg_loader] eggPlugin is missing') && !message) { + mm(app.console, 'warn', (m: string) => { + if ( + !m.startsWith('[@eggjs/core/egg_loader] eggPlugin is missing') && + !message + ) { message = m; } }); @@ -208,13 +217,16 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { await loader.loadPlugin(); await loader.loadConfig(); - assert.equal(message, '[@eggjs/core/egg_loader] pluginName(e) is different from pluginConfigName(wrong-name)'); + assert.equal( + message, + '[@eggjs/core/egg_loader] pluginName(e) is different from pluginConfigName(wrong-name)' + ); }); it('should not warn when the config.strict is false', async () => { let message = ''; app = createApp('plugin-strict'); - mm(app.console, 'warn', function(m: string) { + mm(app.console, 'warn', (m: string) => { message = m; }); const loader = app.loader; @@ -226,7 +238,8 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { app = createApp('plugin-ts-src'); const loader = app.loader; await loader.loadPlugin(); - assert.match(loader.allPlugins.agg.path!, /src$/); + assert(loader.allPlugins.agg.path); + assert.match(loader.allPlugins.agg.path, /src$/); }); it('should loadConfig plugins with custom plugins config', async () => { @@ -237,7 +250,7 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { path: path.join(baseDir, 'node_modules/d'), }, d1: { - env: [ 'unittest' ], + env: ['unittest'], }, }; app = createApp('plugin', { plugins }); @@ -251,7 +264,7 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { package: 'd', dependencies: [], optionalDependencies: [], - env: [ 'unittest' ], + env: ['unittest'], path: path.join(baseDir, 'node_modules/d'), from: '', }); @@ -298,7 +311,9 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { it('should validate plugin.package', async () => { await assert.rejects(async () => { - app = createApp('plugin', { plugins: { foo: { package: '../' }, bar: { package: 'c:\\' } } }); + app = createApp('plugin', { + plugins: { foo: { package: '../' }, bar: { package: 'c:\\' } }, + }); const loader = app.loader; await loader.loadPlugin(); await loader.loadConfig(); @@ -343,19 +358,10 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { const loader = app.loader; await loader.loadPlugin(); await loader.loadConfig(); - assert.deepEqual(loader.orderPlugins.map(function(plugin) { - return plugin.name; - }), [ - 'session', - 'zzz', - 'package', - 'b', - 'c1', - 'f', - 'a', - 'd', - 'e', - ]); + assert.deepEqual( + loader.orderPlugins.map(plugin => plugin.name), + ['session', 'zzz', 'package', 'b', 'c1', 'f', 'a', 'd', 'e'] + ); }); it('should throw when plugin is recursive', async () => { @@ -386,7 +392,10 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { // - eagleeye required by [hsfclient] // - configclient required by [hsfclient] // - diamond required by [hsfclient] - assert.equal(msg, 'Following plugins will be enabled implicitly.\n - eagleeye required by [hsfclient]\n - configclient required by [hsfclient]\n - diamond required by [hsfclient]'); + assert.equal( + msg, + 'Following plugins will be enabled implicitly.\n - eagleeye required by [hsfclient]\n - configclient required by [hsfclient]\n - diamond required by [hsfclient]' + ); }); const loader = app.loader; await loader.loadPlugin(); @@ -415,7 +424,7 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { assert.equal(loader.plugins.d.enable, true); assert.equal(loader.plugins.c.enable, true); assert.equal(loader.plugins.e.enable, true); - assert.deepEqual(Object.keys(loader.plugins), [ 'b', 'e', 'c', 'a', 'd' ]); + assert.deepEqual(Object.keys(loader.plugins), ['b', 'e', 'c', 'a', 'd']); }); it('should enable when not match env', async () => { @@ -424,9 +433,7 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { await loader.loadPlugin(); await loader.loadConfig(); assert(!loader.plugins.testMe); - const plugins = loader.orderPlugins.map(function(plugin) { - return plugin.name; - }); + const plugins = loader.orderPlugins.map(plugin => plugin.name); assert(!plugins.includes('testMe')); }); @@ -440,9 +447,7 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { await loader1.loadConfig(); // unittest 环境不开启 - const keys1 = loader1.orderPlugins.map(function(plugin) { - return plugin.name; - }).join(','); + const keys1 = loader1.orderPlugins.map(plugin => plugin.name).join(','); assert(keys1.includes('b,c,d1,f,e')); assert(!loader1.plugins.a1); @@ -451,16 +456,14 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { const loader2 = app2.loader; await loader2.loadPlugin(); await loader2.loadConfig(); - const keys2 = loader2.orderPlugins.map(function(plugin) { - return plugin.name; - }).join(','); + const keys2 = loader2.orderPlugins.map(plugin => plugin.name).join(','); assert(keys2.includes('d1,a1,b,c,f,e')); assert.deepEqual(loader2.plugins.a1, { enable: true, name: 'a1', - dependencies: [ 'd1' ], + dependencies: ['d1'], optionalDependencies: [], - env: [ 'local', 'prod' ], + env: ['local', 'prod'], path: path.join(baseDir, 'node_modules/a1'), from: path.join(baseDir, 'config/plugin.js'), }); @@ -490,13 +493,22 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { await loader.loadPlugin(); await loader.loadConfig(); assert(!loader.plugins.session.package); - assert.equal(loader.plugins.session.path, getFilepath('plugin-path-package/session')); + assert.equal( + loader.plugins.session.path, + getFilepath('plugin-path-package/session') + ); assert(loader.plugins.hsfclient.package); - assert.equal(loader.plugins.hsfclient.path, getFilepath('plugin-path-package/node_modules/hsfclient')); + assert.equal( + loader.plugins.hsfclient.path, + getFilepath('plugin-path-package/node_modules/hsfclient') + ); }); it('should resolve the realpath of plugin path', async () => { - fs.rmSync(getFilepath('realpath/node_modules/a'), { force: true, recursive: true }); + fs.rmSync(getFilepath('realpath/node_modules/a'), { + force: true, + recursive: true, + }); fs.symlinkSync('../a', getFilepath('realpath/node_modules/a'), 'dir'); app = createApp('realpath'); const loader = app.loader; @@ -508,10 +520,10 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { it('should get the defining plugin path in every plugin', async () => { class Application extends EggCore { - get [ Symbol.for('egg#loader') ]() { + get [Symbol.for('egg#loader')]() { return EggLoader; } - get [ Symbol.for('egg#eggPath') ]() { + get [Symbol.for('egg#eggPath')]() { return getFilepath('plugin-from/framework'); } } @@ -520,8 +532,14 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { }); const loader = app.loader; await loader.loadPlugin(); - assert.equal(loader.plugins.a.from, getFilepath('plugin-from/config/plugin.js')); - assert.equal(loader.plugins.b.from, getFilepath('plugin-from/framework/config/plugin.js')); + assert.equal( + loader.plugins.a.from, + getFilepath('plugin-from/config/plugin.js') + ); + assert.equal( + loader.plugins.b.from, + getFilepath('plugin-from/framework/config/plugin.js') + ); }); it('should load plugin.unittest.js override default', async () => { @@ -555,30 +573,46 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { it('should warn when redefine plugin', async () => { app = createApp('load-plugin-config-override'); - mm(app.console, 'warn', function(msg: string, name: string, targetPlugin: object, from: string) { - assert.equal(msg, 'plugin %s has been defined that is %j, but you define again in %s'); - assert.equal(name, 'zzz'); - assert.deepEqual(targetPlugin, { - enable: true, - path: getFilepath('egg/plugins/zzz'), - name: 'zzz', - dependencies: [], - optionalDependencies: [], - env: [], - from: getFilepath('egg/config/plugin.js'), - }); - assert.equal(from, getFilepath('load-plugin-config-override/config/plugin.js')); - }); + mm( + app.console, + 'warn', + (msg: string, name: string, targetPlugin: object, from: string) => { + assert.equal( + msg, + 'plugin %s has been defined that is %j, but you define again in %s' + ); + assert.equal(name, 'zzz'); + assert.deepEqual(targetPlugin, { + enable: true, + path: getFilepath('egg/plugins/zzz'), + name: 'zzz', + dependencies: [], + optionalDependencies: [], + env: [], + from: getFilepath('egg/config/plugin.js'), + }); + assert.equal( + from, + getFilepath('load-plugin-config-override/config/plugin.js') + ); + } + ); const loader = app.loader; await loader.loadPlugin(); - assert.equal(loader.allPlugins.zzz.path, getFilepath('load-plugin-config-override/plugins/zzz')); + assert.equal( + loader.allPlugins.zzz.path, + getFilepath('load-plugin-config-override/plugins/zzz') + ); }); it('should support optionalDependencies', async () => { app = createApp('plugin-optional-dependencies'); const loader = app.loader; await loader.loadPlugin(); - assert.deepEqual(loader.orderPlugins.map(p => p.name), [ 'session', 'zzz', 'package', 'e', 'b', 'a', 'f' ]); + assert.deepEqual( + loader.orderPlugins.map(p => p.name), + ['session', 'zzz', 'package', 'e', 'b', 'a', 'f'] + ); }); it('should warn when redefine plugin', async () => { @@ -607,14 +641,10 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { }); const loader = app.loader; await loader.loadPlugin(); - assert.deepEqual(loader.orderPlugins.map(p => p.name), [ - 'zookeeper', - 'ddcs', - 'vip', - 'zoneclient', - 'rpc', - 'ldc', - ]); + assert.deepEqual( + loader.orderPlugins.map(p => p.name), + ['zookeeper', 'ddcs', 'vip', 'zoneclient', 'rpc', 'ldc'] + ); }); it('should parse implicitly enable dependencies', async () => { @@ -629,17 +659,14 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { }); const loader = app.loader; await loader.loadPlugin(); - assert.deepEqual(loader.orderPlugins.map(p => p.name), [ - 'zoneclient', - 'ldc', - 'rpcServer', - 'tracelog', - 'gateway', - ]); + assert.deepEqual( + loader.orderPlugins.map(p => p.name), + ['zoneclient', 'ldc', 'rpcServer', 'tracelog', 'gateway'] + ); assert.equal(loader.allPlugins.zoneclient.enable, true); assert.equal(loader.allPlugins.zoneclient.implicitEnable, true); - assert.deepEqual(loader.allPlugins.zoneclient.dependents, [ 'ldc' ]); + assert.deepEqual(loader.allPlugins.zoneclient.dependents, ['ldc']); }); it('should load plugin from scope', async () => { @@ -699,7 +726,9 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { return EggLoader; } get [Symbol.for('egg#eggPath')]() { - return getFilepath(path.join('plugin-duplicate', 'node_modules', '@scope', 'b')); + return getFilepath( + path.join('plugin-duplicate', 'node_modules', '@scope', 'b') + ); } } @@ -715,7 +744,7 @@ describe('test/loader/mixin/load_plugin.test.ts', () => { enable: true, name: 'a-duplicate', dependencies: [], - optionalDependencies: [ 'a' ], + optionalDependencies: ['a'], env: [], package: '@scope/a', path: path.join(baseDir, 'node_modules', '@scope', 'a'), diff --git a/test/loader/mixin/load_service.test.ts b/test/loader/mixin/load_service.test.ts index cbc0129d..61efc6f0 100644 --- a/test/loader/mixin/load_service.test.ts +++ b/test/loader/mixin/load_service.test.ts @@ -1,8 +1,10 @@ import path from 'node:path'; -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { request } from '@eggjs/supertest'; import { mm } from 'mm'; -import { Application, createApp, getFilepath } from '../../helper.js'; + +import { createApp, getFilepath, type Application } from '../../helper.js'; describe('test/loader/mixin/load_service.test.ts', () => { let app: Application; @@ -72,15 +74,9 @@ describe('test/loader/mixin/load_service.test.ts', () => { await app.loader.loadRouter(); await app.loader.loadMiddleware(); - await request(app.callback()) - .get('/same?t=1') - .expect('true') - .expect(200); + await request(app.callback()).get('/same?t=1').expect('true').expect(200); - await request(app.callback()) - .get('/same?t=2') - .expect('true') - .expect(200); + await request(app.callback()).get('/same?t=2').expect('true').expect(200); }); it('should extend app.Service', async () => { @@ -94,12 +90,8 @@ describe('test/loader/mixin/load_service.test.ts', () => { await app.loader.loadRouter(); await app.loader.loadMiddleware(); - await request(app.callback()) - .get('/user') - .expect(function(res) { - assert(res.body.user === '123mock'); - }) - .expect(200); + const res = await request(app.callback()).get('/user').expect(200); + assert.equal(res.body.user, '123mock'); }); describe('subdir', () => { diff --git a/test/singleton.test.ts b/test/singleton.test.ts index 3a42e57a..5edea785 100644 --- a/test/singleton.test.ts +++ b/test/singleton.test.ts @@ -1,5 +1,6 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; import { scheduler } from 'node:timers/promises'; + import { Singleton } from '../src/singleton.js'; class DataService { @@ -32,9 +33,7 @@ describe('test/singleton.test.ts', () => { it('should init with client', async () => { const name = 'dataService'; - const clients = [ - { foo: 'bar' }, - ]; + const clients = [{ foo: 'bar' }]; for (const client of clients) { const app: any = { config: { dataService: { client } } }; const singleton = new Singleton({ @@ -99,7 +98,7 @@ describe('test/singleton.test.ts', () => { dataService: { clients: { first: { foo: 'bar1' }, - second: { }, + second: {}, }, default: { foo: 'bar' }, }, @@ -115,11 +114,21 @@ describe('test/singleton.test.ts', () => { singleton.init(); assert(app.dataService instanceof Singleton); assert(app.dataService.get('first').config.foo === 'bar1'); - assert(app.dataService.getSingletonInstance('first').config.foo === 'bar1'); - assert(app.dataService.get('first'), app.dataService.getSingletonInstance('first')); + assert( + app.dataService.getSingletonInstance('first').config.foo === 'bar1' + ); + assert( + app.dataService.get('first'), + app.dataService.getSingletonInstance('first') + ); assert(app.dataService.get('second').config.foo === 'bar'); - assert(app.dataService.getSingletonInstance('second').config.foo === 'bar'); - assert(app.dataService.get('second'), app.dataService.getSingletonInstance('second')); + assert( + app.dataService.getSingletonInstance('second').config.foo === 'bar' + ); + assert( + app.dataService.get('second'), + app.dataService.getSingletonInstance('second') + ); assert(typeof app.dataService.createInstance === 'function'); }); @@ -169,7 +178,9 @@ describe('test/singleton.test.ts', () => { create, }); singleton.init(); - const dataService = await app.dataService.createInstanceAsync({ foo1: 'bar1' }); + const dataService = await app.dataService.createInstanceAsync({ + foo1: 'bar1', + }); assert(dataService instanceof DataService); assert(dataService.config.foo1 === 'bar1'); assert(dataService.config.foo === 'bar'); @@ -198,7 +209,9 @@ describe('test/singleton.test.ts', () => { }); singleton.init(); - const dataService = await app.dataService.createInstanceAsync({ foo1: 'bar1' }); + const dataService = await app.dataService.createInstanceAsync({ + foo1: 'bar1', + }); assert(dataService instanceof DataService); assert(dataService.config.foo1 === 'bar1'); assert(dataService.config.foo === 'bar'); @@ -206,6 +219,7 @@ describe('test/singleton.test.ts', () => { it('should work with no prototype and frozen', async () => { let warn = false; + // oxlint-disable-next-line unicorn/consistent-function-scoping function create() { const d = Object.create(null); Object.freeze(d); @@ -274,9 +288,7 @@ describe('test/singleton.test.ts', () => { it('should init with client', async () => { const name = 'dataService'; - const clients = [ - { foo: 'bar' }, - ]; + const clients = [{ foo: 'bar' }]; for (const client of clients) { const app: any = { config: { dataService: { client } } }; const singleton = new Singleton({ @@ -291,7 +303,6 @@ describe('test/singleton.test.ts', () => { } }); - it('should init with clients', async () => { const name = 'dataService'; @@ -331,7 +342,9 @@ describe('test/singleton.test.ts', () => { await singleton.init(); assert(app.dataService === singleton); assert(app.dataService instanceof Singleton); - app.dataService = await app.dataService.createInstanceAsync({ foo1: 'bar1' }); + app.dataService = await app.dataService.createInstanceAsync({ + foo1: 'bar1', + }); assert(app.dataService instanceof DataService); assert(app.dataService.config.foo1 === 'bar1'); assert(app.dataService.config.foo === 'bar'); diff --git a/test/utils/index.test.ts b/test/utils/index.test.ts index aaa0c1b8..40876720 100644 --- a/test/utils/index.test.ts +++ b/test/utils/index.test.ts @@ -1,6 +1,8 @@ import path from 'node:path'; -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { mm } from 'mm'; + import utils from '../../src/utils/index.js'; import { getFilepath } from '../helper.js'; @@ -48,29 +50,38 @@ describe('test/utils/index.test.ts', () => { }); it('should load es module with default', async () => { - const result = await utils.loadFile(path.join(baseDir, 'es-module-default.js')); + const result = await utils.loadFile( + path.join(baseDir, 'es-module-default.js') + ); assert(result.fn); }); it('should load es module with default = null', async () => { - const result = await utils.loadFile(path.join(baseDir, 'es-module-default-null.js')); + const result = await utils.loadFile( + path.join(baseDir, 'es-module-default-null.js') + ); assert.equal(result, null); }); it('should load es module with default = async function', async () => { - const result = await utils.loadFile(path.join(baseDir, 'es-module-default-async.js')); + const result = await utils.loadFile( + path.join(baseDir, 'es-module-default-async.js') + ); assert(typeof result().then === 'function'); }); it('should load es module with default = function returning a promise', async () => { - const result = await utils.loadFile(path.join(baseDir, 'es-module-default-promise.js')); + const result = await utils.loadFile( + path.join(baseDir, 'es-module-default-promise.js') + ); assert(typeof result().then === 'function'); }); it('should load no js file', async () => { - let result = (await utils.loadFile(path.join(baseDir, 'no-js.yml'))).toString(); + const buf = await utils.loadFile(path.join(baseDir, 'no-js.yml')); + let result = buf.toString(); if (process.platform === 'win32') { - result = result.replace(/\r\n/g, '\n'); + result = result.replaceAll(String.raw`\r\n`, '\n'); } assert.equal(result, '---\nmap:\n a: 1\n b: 2'); }); @@ -82,7 +93,9 @@ describe('test/utils/index.test.ts', () => { it('should load object', async () => { const result = await utils.loadFile(path.join(baseDir, 'object.js')); assert.equal(result.a, 1); - const result2 = await utils.loadFile(utils.resolvePath(path.join(baseDir, 'object'))); + const result2 = await utils.loadFile( + utils.resolvePath(path.join(baseDir, 'object')) + ); assert.equal(result2.a, 1); assert.equal(result2, result); }); @@ -90,7 +103,9 @@ describe('test/utils/index.test.ts', () => { it('should load object2.cjs', async () => { const result = await utils.loadFile(path.join(baseDir, 'object2.cjs')); assert.equal(result.a, 1); - const result2 = await utils.loadFile(utils.resolvePath(path.join(baseDir, 'object2.cjs'))); + const result2 = await utils.loadFile( + utils.resolvePath(path.join(baseDir, 'object2.cjs')) + ); assert.equal(result2.a, 1); assert.equal(result2, result); }); @@ -111,29 +126,38 @@ describe('test/utils/index.test.ts', () => { }); it('should load es module with default', async () => { - const result = await utils.loadFile(path.join(baseDir, 'es-module-default.js')); + const result = await utils.loadFile( + path.join(baseDir, 'es-module-default.js') + ); assert(result.fn); }); it('should load es module with default = null', async () => { - const result = await utils.loadFile(path.join(baseDir, 'es-module-default-null.js')); + const result = await utils.loadFile( + path.join(baseDir, 'es-module-default-null.js') + ); assert.equal(result, null); }); it('should load es module with default = async function', async () => { - const result = await utils.loadFile(path.join(baseDir, 'es-module-default-async.js')); + const result = await utils.loadFile( + path.join(baseDir, 'es-module-default-async.js') + ); assert(typeof result().then === 'function'); }); it('should load es module with default = function returning a promise', async () => { - const result = await utils.loadFile(path.join(baseDir, 'es-module-default-promise.js')); + const result = await utils.loadFile( + path.join(baseDir, 'es-module-default-promise.js') + ); assert(typeof result().then === 'function'); }); it('should load no js file', async () => { - let result = (await utils.loadFile(path.join(baseDir, 'no-js.yml'))).toString(); + const buf = await utils.loadFile(path.join(baseDir, 'no-js.yml')); + let result = buf.toString(); if (process.platform === 'win32') { - result = result.replace(/\r\n/g, '\n'); + result = result.replaceAll(String.raw`\r\n`, '\n'); } assert.equal(result, '---\nmap:\n a: 1\n b: 2'); }); diff --git a/test/utils/router.test.ts b/test/utils/router.test.ts index d28cd0c1..74ac9eb8 100644 --- a/test/utils/router.test.ts +++ b/test/utils/router.test.ts @@ -1,6 +1,8 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { request } from '@eggjs/supertest'; -import { Application, createApp } from '../helper.js'; + +import { createApp, type Application } from '../helper.js'; describe('test/utils/router.test.ts', () => { let app: Application; @@ -100,21 +102,15 @@ describe('test/utils/router.test.ts', () => { }); it('should POST /members', () => { - return request(app.callback()) - .post('/members') - .expect(404); + return request(app.callback()).post('/members').expect(404); }); it('should PUT /members/:id', () => { - return request(app.callback()) - .put('/members/1231') - .expect(404); + return request(app.callback()).put('/members/1231').expect(404); }); it('should GET /POSTS', () => { - return request(app.callback()) - .get('/POSTS') - .expect(404); + return request(app.callback()).get('/POSTS').expect(404); }); it('should GET /members/delete/:id', () => { @@ -132,9 +128,7 @@ describe('test/utils/router.test.ts', () => { }); it('should GET /packages/(.*)', () => { - return request(app.callback()) - .get('/packages/urllib') - .expect('urllib'); + return request(app.callback()).get('/packages/urllib').expect('urllib'); }); }); @@ -158,7 +152,7 @@ describe('test/utils/router.test.ts', () => { it('should execute by the correct order', () => { return request(app.callback()) .get('/mix') - .expect([ 'generator before', 'async', 'generator after' ]) + .expect(['generator before', 'async', 'generator after']) .expect(200); }); }); @@ -179,26 +173,55 @@ describe('test/utils/router.test.ts', () => { // no match params assert(app.router.url('edit_post', {}) === '/posts/:id/edit'); assert(app.router.url('noname') === ''); - assert(app.router.url('comment_index', { id: 1, a: 1 }) === '/comments/1?filter=&a=1'); + assert( + app.router.url('comment_index', { id: 1, a: 1 }) === + '/comments/1?filter=&a=1' + ); }); it('should work with unknow params', () => { - assert(app.router.url('posts', { name: 'foo', page: 2 }) === '/posts?name=foo&page=2'); - assert(app.router.url('posts', { name: 'foo&?', page: 2 }) === '/posts?name=foo%26%3F&page=2'); - assert(app.router.url('edit_post', { id: 10, page: 2 }) === '/posts/10/edit?page=2'); - assert(app.router.url('edit_post', { i: 2, id: 10 }) === '/posts/10/edit?i=2'); - assert(app.router.url('edit_post', { id: 10, page: 2, tags: [ 'chair', 'develop' ] }) === - '/posts/10/edit?page=2&tags=chair&tags=develop'); - assert(app.router.url('edit_post', { id: [ 10 ], page: [ 2 ], tags: [ 'chair', 'develop' ] }) === - '/posts/10/edit?page=2&tags=chair&tags=develop'); - assert(app.router.url('edit_post', { id: [ 10, 11 ], page: [ 2 ], tags: [ 'chair', 'develop' ] }) === - '/posts/10/edit?page=2&tags=chair&tags=develop'); + assert( + app.router.url('posts', { name: 'foo', page: 2 }) === + '/posts?name=foo&page=2' + ); + assert( + app.router.url('posts', { name: 'foo&?', page: 2 }) === + '/posts?name=foo%26%3F&page=2' + ); + assert( + app.router.url('edit_post', { id: 10, page: 2 }) === + '/posts/10/edit?page=2' + ); + assert( + app.router.url('edit_post', { i: 2, id: 10 }) === '/posts/10/edit?i=2' + ); + assert( + app.router.url('edit_post', { + id: 10, + page: 2, + tags: ['chair', 'develop'], + }) === '/posts/10/edit?page=2&tags=chair&tags=develop' + ); + assert( + app.router.url('edit_post', { + id: [10], + page: [2], + tags: ['chair', 'develop'], + }) === '/posts/10/edit?page=2&tags=chair&tags=develop' + ); + assert( + app.router.url('edit_post', { + id: [10, 11], + page: [2], + tags: ['chair', 'develop'], + }) === '/posts/10/edit?page=2&tags=chair&tags=develop' + ); }); it('should not support regular url', () => { assert.throws(() => { - app.router.url('packages', [ 'urllib' ] as any); - }, 'Can\'t get the url for regExp /^\/packages\/(.*)/ for by name \'posts\''); + app.router.url('packages', ['urllib'] as any); + }, "Can't get the url for regExp /^/packages/(.*)/ for by name 'posts'"); }); }); @@ -219,28 +242,28 @@ describe('test/utils/router.test.ts', () => { return request(app.callback()) .get('/middleware') .expect(200) - .expect([ 'generator', 'async', 'common' ]); + .expect(['generator', 'async', 'common']); }); it('should support all kinds of middlewares with name', () => { return request(app.callback()) .get('/named_middleware') .expect(200) - .expect([ 'generator', 'async', 'common' ]); + .expect(['generator', 'async', 'common']); }); it('should support all kinds of middlewares with register', () => { return request(app.callback()) .get('/register_middleware') .expect(200) - .expect([ 'generator', 'async', 'common' ]); + .expect(['generator', 'async', 'common']); }); it('should app.router support all kinds of middlewares', () => { return request(app.callback()) .get('/router_middleware') .expect(200) - .expect([ 'generator', 'async', 'common' ]); + .expect(['generator', 'async', 'common']); }); }); @@ -262,28 +285,22 @@ describe('test/utils/router.test.ts', () => { describe('controller mutli url', () => { it('should GET /url1', () => { - return request(app.callback()) - .get('/url1') - .expect(200) - .expect('index'); + return request(app.callback()).get('/url1').expect(200).expect('index'); }); it('should GET /url2', () => { - return request(app.callback()) - .get('/url2') - .expect(200) - .expect('index'); + return request(app.callback()).get('/url2').expect(200).expect('index'); }); it('use middlewares /urlm1', () => { return request(app.callback()) .get('/urlm1') .expect(200) - .expect([ 'generator', 'async', 'common' ]); + .expect(['generator', 'async', 'common']); }); it('use middlewares /urlm2', () => { return request(app.callback()) .get('/urlm2') .expect(200) - .expect([ 'generator', 'async', 'common' ]); + .expect(['generator', 'async', 'common']); }); }); @@ -302,7 +319,10 @@ describe('test/utils/router.test.ts', () => { app.get('/hello', 'not.exist.controller'); throw new Error('should not run here'); } catch (err: any) { - assert.match(err.message, /app\.controller\.not\.exist\.controller not exists/); + assert.match( + err.message, + /app\.controller\.not\.exist\.controller not exists/ + ); } }); @@ -320,7 +340,10 @@ describe('test/utils/router.test.ts', () => { app.router.resources('/test', 'not.exist.controller'); throw new Error('should not run here'); } catch (err: any) { - assert.match(err.message, /app\.controller\.not\.exist\.controller not exists/); + assert.match( + err.message, + /app\.controller\.not\.exist\.controller not exists/ + ); } }); }); @@ -335,10 +358,7 @@ describe('test/utils/router.test.ts', () => { after(() => app.close()); it('should always load router middleware at last', () => { - return request(app.callback()) - .get('/') - .expect(200) - .expect('foo'); + return request(app.callback()).get('/').expect(200).expect('foo'); }); }); }); diff --git a/test/utils/timing.test.ts b/test/utils/timing.test.ts index 12890f80..ba6c8dbb 100644 --- a/test/utils/timing.test.ts +++ b/test/utils/timing.test.ts @@ -1,4 +1,5 @@ -import { strict as assert } from 'node:assert'; +import assert from 'node:assert/strict'; + import { Timing } from '../../src/utils/timing.js'; describe('test/utils/timing.test.ts', () => { @@ -13,10 +14,14 @@ describe('test/utils/timing.test.ts', () => { assert.equal(json.length, 3); assert.equal(json[1].name, 'a'); - assert.equal(json[1].end! - json[1].start, json[1].duration); + assert(json[1].start); + assert(json[1].end); + assert.equal(json[1].end - json[1].start, json[1].duration); assert.equal(json[1].pid, process.pid); assert.equal(json[2].name, 'b'); - assert.equal(json[2].end! - json[2].start, json[2].duration); + assert(json[2].start); + assert(json[2].end); + assert.equal(json[2].end - json[2].start, json[2].duration); assert.equal(json[2].pid, process.pid); timing.start('c'); @@ -51,7 +56,7 @@ describe('test/utils/timing.test.ts', () => { assert.equal(timing.toJSON().length, 3); }); - it('should ignore end when name don\'t exist', () => { + it("should ignore end when name don't exist", () => { const timing = new Timing(); timing.end(); assert.equal(timing.toJSON().length, 1); @@ -98,7 +103,7 @@ describe('test/utils/timing.test.ts', () => { assert.equal(json2.length, 1); }); - it('should throw when end and name don\'t exists', () => { + it("should throw when end and name don't exists", () => { const timing = new Timing(); assert.throws(() => { timing.end('a'); @@ -107,7 +112,9 @@ describe('test/utils/timing.test.ts', () => { it('should init process start time', () => { const timing = new Timing(); - const processStart = timing.toJSON().find(item => item.name === 'Process Start'); + const processStart = timing + .toJSON() + .find(item => item.name === 'Process Start'); assert(processStart); assert(processStart.start); assert(processStart.end); From e6b2ade2812849d751f70ab49b12d5ec29e395d9 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Fri, 28 Mar 2025 22:06:42 +0800 Subject: [PATCH 07/10] f --- .github/workflows/nodejs.yml | 4 +- .github/workflows/release.yml | 2 +- .prettierignore | 1 + README.md | 44 +- benchmark/middleware/app/middleware/async.js | 2 +- benchmark/middleware/app/router.js | 2 +- benchmark/middleware/start.js | 16 +- src/egg.ts | 194 +++++-- src/lifecycle.ts | 82 ++- src/loader/context_loader.ts | 10 +- src/loader/egg_loader.ts | 506 +++++++++++++----- src/loader/file_loader.ts | 83 ++- src/singleton.ts | 82 ++- src/types.ts | 1 - src/utils/index.ts | 24 +- src/utils/sequencify.ts | 48 +- src/utils/timing.ts | 26 +- test/asyncLocalStorage.test.ts | 16 +- test/fixtures/agent/app/extend/agent.js | 2 +- test/fixtures/agent/package.json | 4 +- test/fixtures/app-before-close/app.js | 2 +- test/fixtures/app-ts/app.ts | 63 ++- test/fixtures/app-ts/tsconfig.json | 2 +- .../application/app/extend/application.js | 4 +- test/fixtures/application/package.json | 4 +- test/fixtures/beforestart-params-error/app.js | 2 +- test/fixtures/beforestart-timeout/app.js | 2 +- .../beforestart-with-timeout-env/app.js | 1 - test/fixtures/beforestart/app.js | 2 +- .../boot/app/plugin/boot-plugin/agent.js | 2 +- .../boot/app/plugin/boot-plugin/app.js | 2 +- .../plugin/a/config/config.default.js | 2 +- .../plugin/b/config/config.default.js | 2 +- test/fixtures/config/app/controller/foo.js | 6 +- test/fixtures/config/app/controller/util/a.js | 3 +- test/fixtures/config/app/services/foo.js | 6 +- test/fixtures/config/config/config.js | 4 +- .../app/depth/four/four/four/four.js | 2 +- test/fixtures/context-loader/app/depth/one.js | 2 +- .../app/depth/three/three/three.js | 2 +- .../context-loader/app/depth/two/two.js | 2 +- test/fixtures/context-loader/app/router.js | 16 +- .../context-loader/app/service/post.js | 12 +- .../context-loader/app/service/user.js | 14 +- .../context-loader/app/service1/user.js | 12 +- .../context-loader/app/service2/user.js | 12 +- .../context-loader/app/type/function-class.js | 5 +- .../context-loader/app/type/generator.js | 2 +- .../context-loader/app/type/object.js | 2 +- .../controller-app/app/controller/class.js | 1 - .../app/controller/class_inherited.js | 2 +- .../app/controller/function_attr.js | 4 +- .../app/controller/generator_function.js | 2 +- .../app/controller/generator_function_ctx.js | 2 +- .../controller-app/app/controller/object.js | 2 +- .../app/controller/resource_class.js | 1 - .../app/controller/resource_object.js | 2 +- test/fixtures/controller-app/app/router.js | 25 +- .../app/controller/home.js | 2 +- .../controller-params/app/controller/class.js | 1 - .../app/controller/generator_function.js | 2 +- .../custom-loader/app/repository/user.js | 1 - .../fixtures/custom-loader/app/util/sub/fn.js | 2 +- .../app/middleware/session.js | 2 +- .../custom_session_invaild/config/config.js | 6 +- .../dont-load-plugin/config/plugin.js | 4 +- .../fixtures/egg-esm/app/middleware/status.ts | 4 +- .../egg-esm/config/config.unittest.js | 2 +- test/fixtures/egg-esm/index.ts | 1 - .../egg-esm/plugins/hsfclient/package.json | 6 +- .../app/controller/test.ts | 2 +- .../app/extend/application.ts | 4 +- .../app/service/lord.js | 2 +- .../app/service/test.ts | 2 +- .../fixtures/egg-ts-js/app/controller/test.ts | 2 +- .../egg-ts-js/app/extend/application.ts | 4 +- test/fixtures/egg-ts-js/app/service/lord.js | 2 +- test/fixtures/egg-ts-js/app/service/test.ts | 2 +- test/fixtures/egg-ts/app/controller/home.ts | 4 +- test/fixtures/egg-ts/app/extend/agent.ts | 4 +- .../fixtures/egg-ts/app/extend/application.ts | 4 +- test/fixtures/egg-ts/app/extend/context.ts | 4 +- test/fixtures/egg-ts/app/extend/helper.ts | 4 +- test/fixtures/egg-ts/app/extend/request.ts | 4 +- test/fixtures/egg-ts/app/extend/response.ts | 4 +- test/fixtures/egg-ts/app/middleware/mid.ts | 4 +- test/fixtures/egg-ts/app/router.ts | 2 +- test/fixtures/egg-ts/app/service/Test.ts | 2 +- test/fixtures/egg-ts/config/config.default.ts | 4 +- test/fixtures/egg-ts/config/plugin.ts | 4 +- .../egg-ts/plugins/a/config/config.default.ts | 2 +- test/fixtures/egg/app/middleware/status.ts | 4 +- .../egg/plugins/hsfclient/package.json | 6 +- .../extend-with-class/app/controller/home.js | 4 +- .../app/extend/application.js | 4 +- .../extend-with-class/app/extend/context.js | 2 +- .../extend-with-class/app/extend/request.js | 2 +- .../extend-with-class/app/extend/response.js | 2 +- test/fixtures/extend-with-class/app/router.js | 2 +- test/fixtures/extend/app/controller/home.js | 2 +- test/fixtures/extend/app/controller/merge.js | 12 +- test/fixtures/extend/app/extend/context.js | 4 +- test/fixtures/extend/app/router.js | 7 +- test/fixtures/extend/config/plugin.js | 2 +- .../app/controller/user.js | 2 +- test/fixtures/framework-nosymbol/index.js | 1 - test/fixtures/framework-symbol/index.js | 2 - .../helloworld-ts/app/controller/foo.js | 18 +- .../helloworld-ts/app/controller/foo.ts | 3 +- test/fixtures/helloworld-ts/app/router.js | 12 +- .../helloworld-ts/config/config.default.js | 6 +- .../fixtures/helloworld-ts/test/index.test.ts | 14 +- test/fixtures/helloworld-ts/tsconfig.json | 4 +- test/fixtures/helper/app/controller/home.js | 6 +- test/fixtures/helper/app/extend/helper.js | 6 +- test/fixtures/helper/app/router.js | 2 +- .../config/plugin.custom.js | 2 +- .../load-plugin-by-env/config/plugin.js | 2 +- .../config/plugin.unittest.js | 2 +- .../config/plugin.default.js | 2 +- .../load-plugin-default/config/plugin.js | 2 +- .../config/plugin.unittest.js | 2 +- .../load_context_error/app/extend/context.js | 3 +- test/fixtures/load_dirs/babel/UserProxy.js | 65 ++- test/fixtures/load_dirs/dao/TestClass.js | 2 +- test/fixtures/load_dirs/dao/testFunction.js | 2 +- .../load_dirs/dao/testReturnFunction.js | 6 +- test/fixtures/load_dirs/es6_module/mod.js | 4 +- test/fixtures/load_dirs/filter/arr.js | 2 +- test/fixtures/load_dirs/filter/class.js | 2 +- test/fixtures/load_dirs/ignore/a.js | 2 +- test/fixtures/load_dirs/ignore/util/a.js | 3 +- .../fixtures/load_dirs/lowercase/SomeClass.js | 4 +- .../lowercase/SomeDir/SomeSubClass.js | 4 +- .../load_dirs/services/dir/service.js | 2 +- .../load_dirs/services/foo_service.js | 4 +- .../load_dirs/services/userProfile.js | 3 +- test/fixtures/load_dirs/ts_module/mod.ts | 2 +- test/fixtures/load_dirs/ts_module/mod3.ts | 2 +- test/fixtures/load_dirs/yml/config.yml | 2 +- test/fixtures/load_file/async.js | 4 +- .../load_file/es-module-default-async.js | 6 +- .../load_file/es-module-default-null.js | 4 +- .../load_file/es-module-default-promise.js | 6 +- test/fixtures/load_file/es-module-default.js | 6 +- test/fixtures/load_file/function.js | 2 +- test/fixtures/load_file/no-js.yml | 4 +- test/fixtures/load_file/promise_function.js | 2 +- .../loadfile-esm/es-module-default-async.js | 6 +- .../loadfile-esm/es-module-default-promise.js | 6 +- .../loadfile-esm/es-module-default.js | 2 +- test/fixtures/loadfile-esm/es-module.js | 2 +- test/fixtures/loadfile-esm/no-js.yml | 4 +- .../loadfile/es-module-default-async.js | 6 +- .../loadfile/es-module-default-null.js | 4 +- .../loadfile/es-module-default-promise.js | 6 +- test/fixtures/loadfile/es-module-default.js | 6 +- test/fixtures/loadfile/es-module.js | 4 +- test/fixtures/loadfile/no-js.yml | 4 +- .../middleware-aa/app/middleware/common.js | 6 +- .../middleware-aa/app/middleware/custom.js | 2 +- .../middleware-aa/app/middleware/match.js | 2 +- .../middleware-aa/app/middleware/router.js | 2 +- .../middleware-aa/app/middleware/static.js | 2 +- test/fixtures/middleware-aa/app/router.js | 2 +- test/fixtures/middleware-aa/config/config.js | 2 +- .../app/middleware/custom.js | 2 +- .../app/middleware/static.js | 4 +- .../middleware-app-disable/config/config.js | 2 +- .../app/middleware/custom.js | 2 +- .../app/middleware/static.js | 4 +- .../app/middleware/custom.js | 2 +- .../app/middleware/static.js | 4 +- .../middleware-match/app/middleware/custom.js | 2 +- .../middleware-match/app/middleware/static.js | 4 +- .../app/middleware/custom.js | 2 +- .../app/middleware/static.js | 4 +- .../middleware-override/config/plugin.js | 2 +- .../app/middleware/custom.js | 2 +- .../app/middleware/static.js | 4 +- .../middleware-redefined/config/config.js | 2 +- .../no-dep-plugin/plugins/a/package.json | 4 +- test/fixtures/notready/config/plugin.js | 2 +- .../framework/plugins/a/package.json | 5 +- .../framework/plugins/c/package.json | 4 +- .../framework/plugins/d/package.json | 4 +- .../plugin-dep-missing/config/plugin.js | 7 +- .../plugin-dep-recursive/config/plugin.js | 7 +- test/fixtures/plugin-dep/config/plugin.js | 13 +- .../plugin-duplicate/release/config/plugin.js | 2 +- .../plugin-framework/config/plugin.js | 2 +- test/fixtures/plugin-noexist/config/plugin.js | 2 +- test/fixtures/plugin/agent.js | 2 +- test/fixtures/plugin/app.js | 2 +- .../plugin/app/proxy/OnlyClassQuery.js | 2 +- .../plugin/app/proxy/UserInfoQuery.js | 4 +- test/fixtures/plugin/app/proxy/couponQuery.js | 4 +- test/fixtures/plugin/app/router.js | 6 +- test/fixtures/plugin/app/service/Foo4.js | 4 +- test/fixtures/plugin/app/service/foo.js | 4 +- .../plugin/app/service/fooDir/Foo5.js | 4 +- test/fixtures/plugin/config/plugin.js | 1 - test/fixtures/plugin/plugins/e/package.json | 4 +- test/fixtures/plugin/plugins/g/package.json | 4 +- .../preload-app-config/a/config/config.js | 4 +- .../preload-app-config/config/config.js | 4 +- .../preload-app-config/config/plugin.js | 2 +- .../proxy-override/app/proxy/queryProxy.js | 4 +- test/fixtures/proxy-override/config/plugin.js | 2 +- .../fixtures/redefine-plugin/config/plugin.js | 2 +- .../router-app/app/controller/async.js | 2 +- .../router-app/app/controller/comments.js | 6 +- .../router-app/app/controller/locals.js | 2 +- .../router-app/app/controller/members.js | 8 +- .../router-app/app/controller/middleware.js | 2 +- .../router-app/app/controller/package.js | 2 +- .../router-app/app/controller/posts.js | 14 +- .../router-app/app/middleware/async.js | 2 +- .../router-app/app/middleware/common.js | 4 +- .../router-app/app/middleware/generator.js | 4 +- .../app/middleware/generator_both.js | 4 +- test/fixtures/router-app/app/router.js | 29 +- .../router-app/app/views/locals/router.html | 2 +- test/fixtures/router-app/package.json | 2 +- test/fixtures/router-in-app/app.js | 2 +- test/fixtures/router-in-app/app/router.js | 2 +- .../router-in-app/config/config.default.js | 2 +- .../scope-env/config/plugin.en_prod.js | 2 +- .../service-override/config/plugin.js | 2 +- .../service-unique/app/controller/same.js | 2 +- .../services_loader_verify/app/service/foo.js | 8 +- .../config/config.default.ts | 2 +- .../certify-personal/mobile-hi/do_certify.js | 2 +- .../subdir-proxy/app/proxy/cif/user.js | 2 +- .../subdir-proxy/app/proxy/foo/bar.js | 2 +- .../subdir-proxy/app/proxy/foo/subdir/bar.js | 2 +- .../app/proxy/foo/subdir1/subdir11/bar.js | 2 +- .../app/proxy/foo/subdir2/sub2.js | 4 +- test/fixtures/subdir-proxy/app/proxy/ok.js | 4 +- test/fixtures/subdir-proxy/app/proxy/user.js | 4 +- test/fixtures/subdir-proxy/app/router.js | 4 +- .../subdir-services/app/controller/home.js | 5 +- .../subdir-services/app/service/ok.js | 2 +- .../subdir-services/app/service/old_style.js | 2 +- .../subdir-services/app/service/user.js | 2 +- test/fixtures/timing/agent.js | 2 +- test/fixtures/timing/index.js | 5 +- test/lifecycle.test.ts | 2 +- test/loader/mixin/load_custom_agent.test.ts | 2 +- test/support-typescript.test.ts | 3 +- 250 files changed, 1376 insertions(+), 771 deletions(-) diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 9ed9cf2b..ca21fa64 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -2,9 +2,9 @@ name: CI on: push: - branches: [ master ] + branches: [master] pull_request: - branches: [ master ] + branches: [master] jobs: Job: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a2bf04a7..4240f1cc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,7 +2,7 @@ name: Release on: push: - branches: [ master ] + branches: [master] jobs: release: diff --git a/.prettierignore b/.prettierignore index 9ffa84db..fff8eedf 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,2 +1,3 @@ CHANGELOG.md __snapshots__ +benchmark diff --git a/README.md b/README.md index cb61f61f..d0fdcc34 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ Then you can start with code below import { EggCore as Application } from '@eggjs/core'; const app = new Application({ - baseDir: '/path/to/app' + baseDir: '/path/to/app', }); app.ready(() => { app.listen(3000); @@ -140,13 +140,13 @@ Load app/service Retrieve application environment variable values via `serverEnv`. You can access directly by calling `this.serverEnv` after instantiation. -serverEnv | description ---- | --- -default | default environment -test | system integration testing environment -prod | production environment -local | local environment on your own computer -unittest | unit test environment +| serverEnv | description | +| --------- | -------------------------------------- | +| default | default environment | +| test | system integration testing environment | +| prod | production environment | +| local | local environment on your own computer | +| unittest | unit test environment | #### getEggPaths() @@ -163,7 +163,7 @@ This function will get add loadUnits follow the order: 2. framework 3. app -loadUnit has a path and a type. Type must be one of those values: *app*, *framework*, *plugin*. +loadUnit has a path and a type. Type must be one of those values: _app_, _framework_, _plugin_. ```js { @@ -174,7 +174,7 @@ loadUnit has a path and a type. Type must be one of those values: *app*, *framew #### getAppname() -To get application name from *package.json* +To get application name from _package.json_ #### appInfo @@ -228,18 +228,18 @@ await this.loadExtend('application', app); ### LoaderOptions -Param | Type | Description --------------- | -------------- | ------------------------ -directory | `String/Array` | directories to be loaded -target | `Object` | attach the target object from loaded files -match | `String/Array` | match the files when load, default to `**/*.js`(if process.env.EGG_TYPESCRIPT was true, default to `[ '**/*.(js|ts)', '!**/*.d.ts' ]`) -ignore | `String/Array` | ignore the files when load -initializer | `Function` | custom file exports, receive two parameters, first is the inject object(if not js file, will be content buffer), second is an `options` object that contain `path` -caseStyle | `String/Function` | set property's case when converting a filepath to property list. -override | `Boolean` | determine whether override the property when get the same name -call | `Boolean` | determine whether invoke when exports is function -inject | `Object` | an object that be the argument when invoke the function -filter | `Function` | a function that filter the exports which can be loaded +| Param | Type | Description | +| ----------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- | +| directory | `String/Array` | directories to be loaded | +| target | `Object` | attach the target object from loaded files | +| match | `String/Array` | match the files when load, default to `**/*.js`(if process.env.EGG_TYPESCRIPT was true, default to `[ '\*_/_.(js | ts)', '!\*_/_.d.ts' ]`) | +| ignore | `String/Array` | ignore the files when load | +| initializer | `Function` | custom file exports, receive two parameters, first is the inject object(if not js file, will be content buffer), second is an `options` object that contain `path` | +| caseStyle | `String/Function` | set property's case when converting a filepath to property list. | +| override | `Boolean` | determine whether override the property when get the same name | +| call | `Boolean` | determine whether invoke when exports is function | +| inject | `Object` | an object that be the argument when invoke the function | +| filter | `Function` | a function that filter the exports which can be loaded | ## Timing diff --git a/benchmark/middleware/app/middleware/async.js b/benchmark/middleware/app/middleware/async.js index 666fc468..0eac5eec 100644 --- a/benchmark/middleware/app/middleware/async.js +++ b/benchmark/middleware/app/middleware/async.js @@ -2,7 +2,7 @@ let index = 0; -module.exports = function exports() { +module.exports = function exports() { return async (ctx, next) => { await next(); ctx.body.push(`async middleware #${++index}`); diff --git a/benchmark/middleware/app/router.js b/benchmark/middleware/app/router.js index 04476415..7850952b 100644 --- a/benchmark/middleware/app/router.js +++ b/benchmark/middleware/app/router.js @@ -9,4 +9,4 @@ module.exports = app => { app.get('/', app.controller.home.index); app.get('/async', ...asyncMiddlewares, 'home.async'); -} +}; diff --git a/benchmark/middleware/start.js b/benchmark/middleware/start.js index 395b75f7..04531c66 100644 --- a/benchmark/middleware/start.js +++ b/benchmark/middleware/start.js @@ -7,10 +7,12 @@ const app = new EggApplication({ type: 'application', }); -app.loader.loadAll().then(() => { - app.listen(7001); - console.log('server started at 7001'); -}).catch(err => { - throw err; -}); - +app.loader + .loadAll() + .then(() => { + app.listen(7001); + console.log('server started at 7001'); + }) + .catch(err => { + throw err; + }); diff --git a/src/egg.ts b/src/egg.ts index 8529b2bf..81902ea5 100644 --- a/src/egg.ts +++ b/src/egg.ts @@ -3,13 +3,19 @@ import assert from 'node:assert'; import { debuglog } from 'node:util'; import { - Application as KoaApplication, Context as KoaContext, - Request as KoaRequest, Response as KoaResponse, + Application as KoaApplication, + Context as KoaContext, + Request as KoaRequest, + Response as KoaResponse, type MiddlewareFunc as KoaMiddlewareFunc, type Next, } from '@eggjs/koa'; import { EggConsoleLogger, type Logger } from 'egg-logger'; -import { EggRouter as Router, type RegisterOptions, type ResourcesController } from '@eggjs/router'; +import { + EggRouter as Router, + type RegisterOptions, + type ResourcesController, +} from '@eggjs/router'; import type { ReadyFunctionArg } from 'get-ready'; import { BaseContextClass } from './base_context_class.js'; @@ -19,7 +25,9 @@ import { EggLoader } from './loader/egg_loader.js'; import utils, { type Fun } from './utils/index.js'; import type { EggAppConfig } from './types.js'; import { - Singleton, type SingletonCreateMethod, type SingletonOptions, + Singleton, + type SingletonCreateMethod, + type SingletonOptions, } from './singleton.js'; const debug = debuglog('@eggjs/core/egg'); @@ -37,15 +45,10 @@ export interface EggCoreOptions { export type EggCoreInitOptions = Partial; // export @eggjs/koa classes -export { - KoaRequest, KoaResponse, KoaContext, KoaApplication, - Router, -}; +export { KoaRequest, KoaResponse, KoaContext, KoaApplication, Router }; // export @eggjs/koa types -export type { - Next, KoaMiddlewareFunc, -}; +export type { Next, KoaMiddlewareFunc }; // export @eggjs/core classes export class Request extends KoaRequest { @@ -95,7 +98,8 @@ export class Context extends KoaContext { } // export @eggjs/core types -export type MiddlewareFunc = KoaMiddlewareFunc; +export type MiddlewareFunc = + KoaMiddlewareFunc; export class EggCore extends KoaApplication { options: EggCoreOptions; @@ -111,13 +115,16 @@ export class EggCore extends KoaApplication { #router?: Router; /** auto inject on loadService() */ - + readonly serviceClasses: Record = {}; /** auto inject on loadController() */ - + readonly controller: Record = {}; /** auto inject on loadMiddleware() */ - readonly middlewares: Record MiddlewareFunc> = {}; + readonly middlewares: Record< + string, + (opt: unknown, app: EggCore) => MiddlewareFunc + > = {}; /** * @class @@ -130,10 +137,16 @@ export class EggCore extends KoaApplication { constructor(options: EggCoreInitOptions = {}) { options.baseDir = options.baseDir ?? process.cwd(); options.type = options.type ?? 'application'; - assert(typeof options.baseDir === 'string', 'options.baseDir required, and must be a string'); + assert( + typeof options.baseDir === 'string', + 'options.baseDir required, and must be a string' + ); // assert(fs.existsSync(options.baseDir), `Directory ${options.baseDir} not exists`); // assert(fs.statSync(options.baseDir).isDirectory(), `Directory ${options.baseDir} is not a directory`); - assert(options.type === 'application' || options.type === 'agent', 'options.type should be application or agent'); + assert( + options.type === 'application' || options.type === 'agent', + 'options.type should be application or agent' + ); super(); this.timing = new Timing(); @@ -206,7 +219,7 @@ export class EggCore extends KoaApplication { * @since 1.0.0 */ const Loader = this[EGG_LOADER]; - assert(Loader, 'Symbol.for(\'egg#loader\') is required'); + assert(Loader, "Symbol.for('egg#loader') is required"); this.loader = new Loader({ baseDir: options.baseDir, app: this, @@ -310,7 +323,7 @@ export class EggCore extends KoaApplication { * @since 1.0.0 */ get config(): EggAppConfig { - return this.loader ? this.loader.config : {} as EggAppConfig; + return this.loader ? this.loader.config : ({} as EggAppConfig); } /** @@ -327,7 +340,9 @@ export class EggCore extends KoaApplication { * @param {string} [name] scope name, default is empty string */ beforeStart(scope: Fun, name?: string) { - this.deprecate('`beforeStart` was deprecated, please use "Life Cycles" instead, see https://www.eggjs.org/advanced/loader#life-cycles'); + this.deprecate( + '`beforeStart` was deprecated, please use "Life Cycles" instead, see https://www.eggjs.org/advanced/loader#life-cycles' + ); this.lifecycle.registerBeforeStart(scope, name ?? ''); } @@ -370,7 +385,9 @@ export class EggCore extends KoaApplication { * mysql.ready(done); */ readyCallback(name: string, opts: object) { - this.deprecate('`readyCallback` was deprecated, please use "Life Cycles" instead, see https://www.eggjs.org/advanced/loader#life-cycles'); + this.deprecate( + '`readyCallback` was deprecated, please use "Life Cycles" instead, see https://www.eggjs.org/advanced/loader#life-cycles' + ); return this.lifecycle.legacyReadyCallback(name, opts); } @@ -387,7 +404,9 @@ export class EggCore extends KoaApplication { * @param {Function} fn - the function that can be generator function or async function. */ beforeClose(fn: Fun, name?: string) { - this.deprecate('`beforeClose` was deprecated, please use "Life Cycles" instead, see https://www.eggjs.org/advanced/loader#life-cycles'); + this.deprecate( + '`beforeClose` was deprecated, please use "Life Cycles" instead, see https://www.eggjs.org/advanced/loader#life-cycles' + ); this.lifecycle.registerBeforeClose(fn, name); } @@ -434,9 +453,16 @@ export class EggCore extends KoaApplication { // delegate all router method to application // 'head', 'options', 'get', 'put', 'patch', 'post', 'delete' // 'all', 'resources', 'register', 'redirect' - head(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - head(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - + head( + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + head( + name: string, + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + head(...args: any): EggCore { this.router.head.apply(this.router, args); return this; @@ -447,62 +473,124 @@ export class EggCore extends KoaApplication { // this.router.options.apply(this.router, args); // return this; // } - get(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - get(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - + get( + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + get( + name: string, + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + get(...args: any): EggCore { this.router.get.apply(this.router, args); return this; } - put(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - put(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - + put( + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + put( + name: string, + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + put(...args: any): EggCore { this.router.put.apply(this.router, args); return this; } - patch(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - patch(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - + patch( + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + patch( + name: string, + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + patch(...args: any): EggCore { this.router.patch.apply(this.router, args); return this; } - post(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - post(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - + post( + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + post( + name: string, + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + post(...args: any): EggCore { this.router.post.apply(this.router, args); return this; } - delete(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - delete(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - + delete( + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + delete( + name: string, + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + delete(...args: any): EggCore { this.router.delete.apply(this.router, args); return this; } - del(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - del(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - + del( + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + del( + name: string, + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + del(...args: any): EggCore { this.router.del.apply(this.router, args); return this; } - all(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - all(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): EggCore; - + all( + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + all( + name: string, + path: string | RegExp | (string | RegExp)[], + ...middlewares: (MiddlewareFunc | string)[] + ): EggCore; + all(...args: any): EggCore { this.router.all.apply(this.router, args); return this; } resources(prefix: string, controller: string | ResourcesController): EggCore; - resources(prefix: string, middleware: MiddlewareFunc, controller: string | ResourcesController): EggCore; - resources(name: string, prefix: string, controller: string | ResourcesController): EggCore; - resources(name: string, prefix: string, middleware: MiddlewareFunc, controller: string | ResourcesController): EggCore; - + resources( + prefix: string, + middleware: MiddlewareFunc, + controller: string | ResourcesController + ): EggCore; + resources( + name: string, + prefix: string, + controller: string | ResourcesController + ): EggCore; + resources( + name: string, + prefix: string, + middleware: MiddlewareFunc, + controller: string | ResourcesController + ): EggCore; + resources(...args: any): EggCore { this.router.resources.apply(this.router, args); return this; @@ -513,10 +601,12 @@ export class EggCore extends KoaApplication { return this; } - register(path: string | RegExp | (string | RegExp)[], + register( + path: string | RegExp | (string | RegExp)[], methods: string[], middleware: MiddlewareFunc | MiddlewareFunc[], - opts?: RegisterOptions) { + opts?: RegisterOptions + ) { this.router.register(path, methods, middleware, opts); return this; } diff --git a/src/lifecycle.ts b/src/lifecycle.ts index 6d228d4d..aeabcd88 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -55,7 +55,7 @@ export interface ILifecycleBoot { beforeClose?(): Promise; } -export type BootImplClass = new(...args: any[]) => T; +export type BootImplClass = new (...args: any[]) => T; export interface LifecycleOptions { baseDir: string; @@ -90,20 +90,29 @@ export class Lifecycle extends EventEmitter { this.timing.start(`${this.options.app.type} Start`); // get app timeout from env or use default timeout 10 second - const eggReadyTimeoutEnv = Number.parseInt(process.env.EGG_READY_TIMEOUT_ENV || '10000'); + const eggReadyTimeoutEnv = Number.parseInt( + process.env.EGG_READY_TIMEOUT_ENV || '10000' + ); assert( Number.isInteger(eggReadyTimeoutEnv), - `process.env.EGG_READY_TIMEOUT_ENV ${process.env.EGG_READY_TIMEOUT_ENV} should be able to parseInt.`); + `process.env.EGG_READY_TIMEOUT_ENV ${process.env.EGG_READY_TIMEOUT_ENV} should be able to parseInt.` + ); this.readyTimeout = eggReadyTimeoutEnv; this.#initReady(); - this - .on('ready_stat', data => { - this.logger.info('[@eggjs/core/lifecycle:ready_stat] end ready task %s, remain %j', data.id, data.remain); - }) - .on('ready_timeout', id => { - this.logger.warn('[@eggjs/core/lifecycle:ready_timeout] %s seconds later %s was still unable to finish.', this.readyTimeout / 1000, id); - }); + this.on('ready_stat', data => { + this.logger.info( + '[@eggjs/core/lifecycle:ready_stat] end ready task %s, remain %j', + data.id, + data.remain + ); + }).on('ready_timeout', id => { + this.logger.warn( + '[@eggjs/core/lifecycle:ready_timeout] %s seconds later %s was still unable to finish.', + this.readyTimeout / 1000, + id + ); + }); this.ready(err => { this.triggerDidReady(err); @@ -137,7 +146,9 @@ export class Lifecycle extends EventEmitter { const timingKeyPrefix = 'readyCallback'; const timing = this.timing; const cb = this.loadReady.readyCallback(name, opt); - const timingKey = `${timingKeyPrefix} in ` + utils.getResolvedFilename(name, this.app.baseDir); + const timingKey = + `${timingKeyPrefix} in ` + + utils.getResolvedFilename(name, this.app.baseDir); this.timing.start(timingKey); debug('register legacyReadyCallback'); return function legacyReadyCallback(...args: unknown[]) { @@ -148,12 +159,21 @@ export class Lifecycle extends EventEmitter { } addBootHook(bootHootOrBootClass: BootImplClass | ILifecycleBoot) { - assert(this.#init === false, 'do not add hook when lifecycle has been initialized'); + assert( + this.#init === false, + 'do not add hook when lifecycle has been initialized' + ); this.#bootHooks.push(bootHootOrBootClass); } - addFunctionAsBootHook(hook: (app: T) => void, fullPath?: string) { - assert(this.#init === false, 'do not add hook when lifecycle has been initialized'); + addFunctionAsBootHook( + hook: (app: T) => void, + fullPath?: string + ) { + assert( + this.#init === false, + 'do not add hook when lifecycle has been initialized' + ); // app.js is exported as a function // call this function in configDidLoad class Boot implements ILifecycleBoot { @@ -191,8 +211,7 @@ export class Lifecycle extends EventEmitter { } registerBeforeStart(scope: Fun, name: string) { - debug('%s add registerBeforeStart, name: %o', - this.options.app.type, name); + debug('%s add registerBeforeStart, name: %o', this.options.app.type, name); this.#registerReadyCallback({ scope, ready: this.loadReady, @@ -208,15 +227,22 @@ export class Lifecycle extends EventEmitter { fn.fullPath = fullPath; } this.#closeFunctionSet.add(fn); - debug('%s register beforeClose at %o, count: %d', - this.app.type, fullPath, this.#closeFunctionSet.size); + debug( + '%s register beforeClose at %o, count: %d', + this.app.type, + fullPath, + this.#closeFunctionSet.size + ); } async close() { // close in reverse order: first created, last closed const closeFns = Array.from(this.#closeFunctionSet); - debug('%s start trigger %d beforeClose functions', - this.app.type, closeFns.length); + debug( + '%s start trigger %d beforeClose functions', + this.app.type, + closeFns.length + ); for (const fn of closeFns.reverse()) { debug('%s trigger beforeClose at %o', this.app.type, fn.fullPath); await utils.callFn(fn); @@ -302,7 +328,11 @@ export class Lifecycle extends EventEmitter { try { await boot.didReady(err); } catch (err) { - debug('trigger didReady error at %o, error: %s', boot.fullPath, err); + debug( + 'trigger didReady error at %o, error: %s', + boot.fullPath, + err + ); this.emit('error', err); } } @@ -322,7 +352,11 @@ export class Lifecycle extends EventEmitter { try { await boot.serverDidReady(); } catch (err) { - debug('trigger serverDidReady error at %o, error: %s', boot.fullPath, err); + debug( + 'trigger serverDidReady error at %o, error: %s', + boot.fullPath, + err + ); this.emit('error', err); } } @@ -374,7 +408,9 @@ export class Lifecycle extends EventEmitter { // get filename from stack if scopeFullName is undefined const name = scopeFullName || utils.getCalleeFromStack(true, 4); - const timingKey = `${timingKeyPrefix} in ` + utils.getResolvedFilename(name, this.app.baseDir); + const timingKey = + `${timingKeyPrefix} in ` + + utils.getResolvedFilename(name, this.app.baseDir); this.timing.start(timingKey); diff --git a/src/loader/context_loader.ts b/src/loader/context_loader.ts index 9f7ea39f..c5a3577c 100644 --- a/src/loader/context_loader.ts +++ b/src/loader/context_loader.ts @@ -38,7 +38,8 @@ export class ClassLoader { } } -export interface ContextLoaderOptions extends Omit { +export interface ContextLoaderOptions + extends Omit { /** required inject */ inject: Record; /** property name defined to target */ @@ -86,7 +87,8 @@ export class ContextLoader extends FileLoader { if (!ctx[CLASS_LOADER]) { ctx[CLASS_LOADER] = new Map(); } - const classLoader: Map = ctx[CLASS_LOADER]; + const classLoader: Map = + ctx[CLASS_LOADER]; let instance = classLoader.get(property); if (!instance) { instance = getInstance(target, ctx); @@ -110,8 +112,8 @@ function getInstance(values: any, ctx: Context) { // it's just an object instance = Class; } - // Can't set property to primitive, so check again - // e.x. module.exports = 1; + // Can't set property to primitive, so check again + // e.x. module.exports = 1; } else if (isPrimitive(values)) { instance = values; } else { diff --git a/src/loader/egg_loader.ts b/src/loader/egg_loader.ts index f220f8ba..b2991a13 100644 --- a/src/loader/egg_loader.ts +++ b/src/loader/egg_loader.ts @@ -4,26 +4,38 @@ import assert from 'node:assert'; import { debuglog, inspect } from 'node:util'; import { homedir } from 'node-homedir'; -import { isAsyncFunction, isClass, isGeneratorFunction, isObject, isPromise } from 'is-type-of'; -import type { Logger } from 'egg-logger'; import { - getParamNames, readJSONSync, readJSON, exists, -} from 'utility'; + isAsyncFunction, + isClass, + isGeneratorFunction, + isObject, + isPromise, +} from 'is-type-of'; +import type { Logger } from 'egg-logger'; +import { getParamNames, readJSONSync, readJSON, exists } from 'utility'; import { extend } from 'extend2'; -import { Request, Response, Application, Context as KoaContext } from '@eggjs/koa'; +import { + Request, + Response, + Application, + Context as KoaContext, +} from '@eggjs/koa'; import { register as tsconfigPathsRegister } from 'tsconfig-paths'; import { isESM, isSupportTypeScript } from '@eggjs/utils'; import { pathMatching, type PathMatchingOptions } from 'egg-path-matching'; import { now, diff } from 'performance-ms'; -import { type FileLoaderOptions, CaseStyle, FULLPATH, FileLoader } from './file_loader.js'; +import { + type FileLoaderOptions, + CaseStyle, + FULLPATH, + FileLoader, +} from './file_loader.js'; import { type ContextLoaderOptions, ContextLoader } from './context_loader.js'; import utils, { type Fun } from '../utils/index.js'; import { sequencify } from '../utils/sequencify.js'; import { Timing } from '../utils/timing.js'; -import type { - Context, EggCore, MiddlewareFunc, -} from '../egg.js'; +import type { Context, EggCore, MiddlewareFunc } from '../egg.js'; import type { BaseContextClass } from '../base_context_class.js'; import type { EggAppConfig, EggAppInfo, EggPluginInfo } from '../types.js'; @@ -36,7 +48,6 @@ const originalPrototypes: Record = { application: Application.prototype, }; - export interface EggLoaderOptions { /** server env */ env: string; @@ -82,7 +93,10 @@ export class EggLoader { */ constructor(options: EggLoaderOptions) { this.options = options; - assert(fs.existsSync(this.options.baseDir), `${this.options.baseDir} not exists`); + assert( + fs.existsSync(this.options.baseDir), + `${this.options.baseDir} not exists` + ); assert(this.options.app, 'options.app is required'); assert(this.options.logger, 'options.logger is required'); @@ -97,7 +111,10 @@ export class EggLoader { // auto require('tsconfig-paths/register') on typescript app // support env.EGG_TYPESCRIPT = true or { "egg": { "typescript": true } } on package.json - if (process.env.EGG_TYPESCRIPT === 'true' || (this.pkg.egg && this.pkg.egg.typescript)) { + if ( + process.env.EGG_TYPESCRIPT === 'true' || + (this.pkg.egg && this.pkg.egg.typescript) + ) { // skip require tsconfig-paths if tsconfig.json not exists const tsConfigFile = path.join(this.options.baseDir, 'tsconfig.json'); if (fs.existsSync(tsConfigFile)) { @@ -106,7 +123,8 @@ export class EggLoader { } else { this.logger.info( '[@eggjs/core/egg_loader] skip register "tsconfig-paths" because tsconfig.json not exists at %s', - tsConfigFile); + tsConfigFile + ); } } @@ -342,7 +360,10 @@ export class EggLoader { // } continue; } - assert(typeof eggPath === 'string', 'Symbol.for(\'egg#eggPath\') should be string'); + assert( + typeof eggPath === 'string', + "Symbol.for('egg#eggPath') should be string" + ); assert(fs.existsSync(eggPath), `${eggPath} not exists`); const realpath = fs.realpathSync(eggPath); if (!eggPaths.includes(realpath)) { @@ -435,8 +456,12 @@ export class EggLoader { // disable the plugin that not match the serverEnv if (env && plugin.env.length > 0 && !plugin.env.includes(env)) { - this.logger.info('[@eggjs/core] Plugin %o is disabled by env unmatched, require env(%o) but got env is %o', - name, plugin.env, env); + this.logger.info( + '[@eggjs/core] Plugin %o is disabled by env unmatched, require env(%o) but got env is %o', + name, + plugin.env, + env + ); plugin.enable = false; continue; } @@ -448,7 +473,11 @@ export class EggLoader { } // retrieve the ordered plugins - this.orderPlugins = this.getOrderPlugins(plugins, enabledPluginNames, this.appPlugins); + this.orderPlugins = this.getOrderPlugins( + plugins, + enabledPluginNames, + this.appPlugins + ); const enablePlugins: Record = {}; for (const plugin of this.orderPlugins) { @@ -467,16 +496,26 @@ export class EggLoader { protected async loadAppPlugins() { // loader plugins from application - const appPlugins = await this.readPluginConfigs(path.join(this.options.baseDir, 'config/plugin.default')); - debug('Loaded app plugins: %j', Object.keys(appPlugins).map(k => `${k}:${appPlugins[k].enable}`)); + const appPlugins = await this.readPluginConfigs( + path.join(this.options.baseDir, 'config/plugin.default') + ); + debug( + 'Loaded app plugins: %j', + Object.keys(appPlugins).map(k => `${k}:${appPlugins[k].enable}`) + ); return appPlugins; } protected async loadEggPlugins() { // loader plugins from framework - const eggPluginConfigPaths = this.eggPaths.map(eggPath => path.join(eggPath, 'config/plugin.default')); + const eggPluginConfigPaths = this.eggPaths.map(eggPath => + path.join(eggPath, 'config/plugin.default') + ); const eggPlugins = await this.readPluginConfigs(eggPluginConfigPaths); - debug('Loaded egg plugins: %j', Object.keys(eggPlugins).map(k => `${k}:${eggPlugins[k].enable}`)); + debug( + 'Loaded egg plugins: %j', + Object.keys(eggPlugins).map(k => `${k}:${eggPlugins[k].enable}`) + ); return eggPlugins; } @@ -517,7 +556,7 @@ export class EggLoader { */ protected async readPluginConfigs(configPaths: string[] | string) { if (!Array.isArray(configPaths)) { - configPaths = [ configPaths ]; + configPaths = [configPaths]; } // Get all plugin configurations @@ -539,14 +578,19 @@ export class EggLoader { // let plugin.js compatible if (configPath.endsWith('plugin.default') && !filepath) { - filepath = this.resolveModule(configPath.replace(/plugin\.default$/, 'plugin')); + filepath = this.resolveModule( + configPath.replace(/plugin\.default$/, 'plugin') + ); } if (!filepath) { continue; } - const config = await utils.loadFile(filepath) as Record; + const config = (await utils.loadFile(filepath)) as Record< + string, + EggPluginInfo + >; for (const name in config) { this.#normalizePluginConfig(config, name, filepath); } @@ -556,7 +600,11 @@ export class EggLoader { return plugins; } - #normalizePluginConfig(plugins: Record, name: string, configPath: string) { + #normalizePluginConfig( + plugins: Record, + name: string, + configPath: string + ) { const plugin = plugins[name]; // plugin_name: false @@ -603,25 +651,32 @@ export class EggLoader { plugin.version = pkg.version; } // support commonjs and esm dist files - plugin.path = await this.#formatPluginPathFromPackageJSON(plugin.path as string, pkg); + plugin.path = await this.#formatPluginPathFromPackageJSON( + plugin.path as string, + pkg + ); } const logger = this.options.logger; if (!config) { - logger.warn(`[@eggjs/core/egg_loader] pkg.eggPlugin is missing in ${pluginPackage}`); + logger.warn( + `[@eggjs/core/egg_loader] pkg.eggPlugin is missing in ${pluginPackage}` + ); return; } if (config.name && config.strict !== false && config.name !== plugin.name) { // pluginName is configured in config/plugin.js // pluginConfigName is pkg.eggPlugin.name - logger.warn(`[@eggjs/core/egg_loader] pluginName(${plugin.name}) is different from pluginConfigName(${config.name})`); + logger.warn( + `[@eggjs/core/egg_loader] pluginName(${plugin.name}) is different from pluginConfigName(${config.name})` + ); } // dep compatible depCompatible(config); - for (const key of [ 'dependencies', 'optionalDependencies', 'env' ]) { + for (const key of ['dependencies', 'optionalDependencies', 'env']) { const values = config[key]; const existsValues = Reflect.get(plugin, key); if (Array.isArray(values) && !existsValues?.length) { @@ -630,8 +685,11 @@ export class EggLoader { } } - protected getOrderPlugins(allPlugins: Record, enabledPluginNames: string[], - appPlugins: Record) { + protected getOrderPlugins( + allPlugins: Record, + enabledPluginNames: string[], + appPlugins: Record + ) { // no plugins enabled if (enabledPluginNames.length === 0) { return []; @@ -643,7 +701,8 @@ export class EggLoader { // catch error when result.sequence is empty if (result.sequence.length === 0) { const err = new Error( - `sequencify plugins has problem, missing: [${result.missingTasks}], recursive: [${result.recursiveDependencies}]`); + `sequencify plugins has problem, missing: [${result.missingTasks}], recursive: [${result.recursiveDependencies}]` + ); // find plugins which is required by the missing plugin for (const missName of result.missingTasks) { const requires = []; @@ -677,7 +736,7 @@ export class EggLoader { } } - for (const [ name, dependents ] of Object.entries(requireMap)) { + for (const [name, dependents] of Object.entries(requireMap)) { // note:`dependents` will not includes `optionalDependencies` allPlugins[name].dependents = dependents; } @@ -690,17 +749,21 @@ export class EggLoader { let message = implicitEnabledPlugins .map(name => ` - ${name} required by [${requireMap[name]}]`) .join('\n'); - this.options.logger.info(`Following plugins will be enabled implicitly.\n${message}`); + this.options.logger.info( + `Following plugins will be enabled implicitly.\n${message}` + ); // should warn when the plugin is disabled by app const disabledPlugins = implicitEnabledPlugins.filter( - name => appPlugins[name] && appPlugins[name].enable === false); + name => appPlugins[name] && appPlugins[name].enable === false + ); if (disabledPlugins.length > 0) { message = disabledPlugins .map(name => ` - ${name} required by [${requireMap[name]}]`) .join('\n'); this.options.logger.warn( - `Following plugins will be enabled implicitly that is disabled by application.\n${message}`); + `Following plugins will be enabled implicitly that is disabled by application.\n${message}` + ); } } @@ -732,8 +795,10 @@ export class EggLoader { } if (plugin.package) { - assert(isValidatePackageName(plugin.package), - `plugin ${plugin.name} invalid, use 'path' instead of package: "${plugin.package}"`); + assert( + isValidatePackageName(plugin.package), + `plugin ${plugin.name} invalid, use 'path' instead of package: "${plugin.package}"` + ); } return this.#resolvePluginPath(plugin); } @@ -747,25 +812,33 @@ export class EggLoader { // 'node_modules/.pnpm/yadan@2.0.0/node_modules', <- this is the sibling directory // 'node_modules/.pnpm/egg@2.33.1/node_modules/egg/node_modules', // 'node_modules/.pnpm/egg@2.33.1/node_modules', <- this is the sibling directory - const pluginPkgFile = utils.resolvePath(`${name}/package.json`, { paths: [ ...this.lookupDirs ] }); + const pluginPkgFile = utils.resolvePath(`${name}/package.json`, { + paths: [...this.lookupDirs], + }); return path.dirname(pluginPkgFile); } catch (err) { debug('[resolvePluginPath] error: %o, plugin info: %o', err, plugin); - throw new Error(`Can not find plugin ${name} in "${[ ...this.lookupDirs ].join(', ')}"`, { - cause: err, - }); + throw new Error( + `Can not find plugin ${name} in "${[...this.lookupDirs].join(', ')}"`, + { + cause: err, + } + ); } } - async #formatPluginPathFromPackageJSON(pluginPath: string, pluginPkg: { - eggPlugin?: { - exports?: { - import?: string; - require?: string; - typescript?: string; + async #formatPluginPathFromPackageJSON( + pluginPath: string, + pluginPkg: { + eggPlugin?: { + exports?: { + import?: string; + require?: string; + typescript?: string; + }; }; - }; - }): Promise { + } + ): Promise { let realPluginPath = pluginPath; const exports = pluginPkg.eggPlugin?.exports; if (exports) { @@ -776,16 +849,26 @@ export class EggLoader { } else if (exports.require) { realPluginPath = path.join(pluginPath, exports.require); } - if (exports.typescript && isSupportTypeScript() && !(await exists(realPluginPath))) { + if ( + exports.typescript && + isSupportTypeScript() && + !(await exists(realPluginPath)) + ) { // if require/import path not exists, use typescript path for development stage realPluginPath = path.join(pluginPath, exports.typescript); - debug('[formatPluginPathFromPackageJSON] use typescript path %o', realPluginPath); + debug( + '[formatPluginPathFromPackageJSON] use typescript path %o', + realPluginPath + ); } } return realPluginPath; } - #extendPlugins(targets: Record, plugins: Record) { + #extendPlugins( + targets: Record, + plugins: Record + ) { if (!plugins) { return; } @@ -797,18 +880,26 @@ export class EggLoader { targets[name] = targetPlugin; } if (targetPlugin.package && targetPlugin.package === plugin.package) { - this.logger.warn('[@eggjs/core] plugin %s has been defined that is %j, but you define again in %s', - name, targetPlugin, plugin.from); + this.logger.warn( + '[@eggjs/core] plugin %s has been defined that is %j, but you define again in %s', + name, + targetPlugin, + plugin.from + ); } if (plugin.path || plugin.package) { delete targetPlugin.path; delete targetPlugin.package; } - for (const [ prop, value ] of Object.entries(plugin)) { + for (const [prop, value] of Object.entries(plugin)) { if (value === undefined) { continue; } - if (Reflect.get(targetPlugin, prop) && Array.isArray(value) && value.length === 0) { + if ( + Reflect.get(targetPlugin, prop) && + Array.isArray(value) && + value.length === 0 + ) { continue; } Reflect.set(targetPlugin, prop, value); @@ -851,11 +942,20 @@ export class EggLoader { for (const unit of this.getLoadUnits()) { const isApp = unit.type === 'app'; const config = await this.#loadConfig( - unit.path, filename, isApp ? undefined : appConfig, unit.type); + unit.path, + filename, + isApp ? undefined : appConfig, + unit.type + ); if (!config) { continue; } - debug('[loadConfig] Loaded config %s/%s, %j', unit.path, filename, config); + debug( + '[loadConfig] Loaded config %s/%s, %j', + unit.path, + filename, + config + ); extend(true, target, config); } } @@ -880,13 +980,15 @@ export class EggLoader { } async #preloadAppConfig() { - const names = [ - 'config.default', - `config.${this.serverEnv}`, - ]; + const names = ['config.default', `config.${this.serverEnv}`]; const target: Record = {}; for (const filename of names) { - const config = await this.#loadConfig(this.options.baseDir, filename, undefined, 'app'); + const config = await this.#loadConfig( + this.options.baseDir, + filename, + undefined, + 'app' + ); if (!config) { continue; } @@ -895,7 +997,12 @@ export class EggLoader { return target; } - async #loadConfig(dirpath: string, filename: string, extraInject: object | undefined, type: EggDirInfoType) { + async #loadConfig( + dirpath: string, + filename: string, + extraInject: object | undefined, + type: EggDirInfoType + ) { const isPlugin = type === 'plugin'; const isApp = type === 'app'; @@ -907,10 +1014,17 @@ export class EggLoader { if (!filepath) { return; } - const config: Record = await this.loadFile(filepath, this.appInfo, extraInject); + const config: Record = await this.loadFile( + filepath, + this.appInfo, + extraInject + ); if (!config) return; if (isPlugin || isApp) { - assert(!config.coreMiddleware, 'Can not define coreMiddleware in app or plugin'); + assert( + !config.coreMiddleware, + 'Can not define coreMiddleware in app or plugin' + ); } if (!isApp) { assert(!config.middleware, 'Can not define middleware in ' + filepath); @@ -928,7 +1042,10 @@ export class EggLoader { this.#setConfigMeta(envConfig, ''); return envConfig; } catch { - this.options.logger.warn('[egg-loader] process.env.EGG_APP_CONFIG is not invalid JSON: %s', envConfigStr); + this.options.logger.warn( + '[egg-loader] process.env.EGG_APP_CONFIG is not invalid JSON: %s', + envConfigStr + ); } } @@ -942,11 +1059,20 @@ export class EggLoader { for (const key of Object.keys(obj)) { const val = obj[key]; // ignore console - if (key === 'console' && val && typeof val.Console === 'function' && val.Console === console.Console) { + if ( + key === 'console' && + val && + typeof val.Console === 'function' && + val.Console === console.Console + ) { obj[key] = filepath; continue; } - if (val && Object.getPrototypeOf(val) === Object.prototype && Object.keys(val).length > 0) { + if ( + val && + Object.getPrototypeOf(val) === Object.prototype && + Object.keys(val).length > 0 + ) { this.#setConfig(val, filepath); continue; } @@ -1021,7 +1147,9 @@ export class EggLoader { * @private */ protected getExtendFilePaths(name: string): string[] { - return this.getLoadUnits().map(unit => path.join(unit.path, 'app/extend', name)); + return this.getLoadUnits().map(unit => + path.join(unit.path, 'app/extend', name) + ); } /** @@ -1036,7 +1164,8 @@ export class EggLoader { // All extend files const filepaths = this.getExtendFilePaths(name); // if use mm.env and serverEnv is not unittest - const needUnittest = 'EGG_MOCK_SERVER_ENV' in process.env && this.serverEnv !== 'unittest'; + const needUnittest = + 'EGG_MOCK_SERVER_ENV' in process.env && this.serverEnv !== 'unittest'; const length = filepaths.length; for (let i = 0; i < length; i++) { const filepath = filepaths[i]; @@ -1055,9 +1184,13 @@ export class EggLoader { continue; } if (filepath.endsWith('/index.js')) { - this.app.deprecate(`app/extend/${name}/index.js is deprecated, use app/extend/${name}.js instead`); + this.app.deprecate( + `app/extend/${name}/index.js is deprecated, use app/extend/${name}.js instead` + ); } else if (filepath.endsWith('/index.ts')) { - this.app.deprecate(`app/extend/${name}/index.ts is deprecated, use app/extend/${name}.ts instead`); + this.app.deprecate( + `app/extend/${name}/index.ts is deprecated, use app/extend/${name}.ts instead` + ); } let ext = await this.requireFile(filepath); @@ -1071,18 +1204,31 @@ export class EggLoader { for (const property of properties) { if (mergeRecord.has(property)) { - debug('Property: "%s" already exists in "%s",it will be redefined by "%s"', - property, mergeRecord.get(property), filepath); + debug( + 'Property: "%s" already exists in "%s",it will be redefined by "%s"', + property, + mergeRecord.get(property), + filepath + ); } // Copy descriptor - let descriptor = Object.getOwnPropertyDescriptor(ext, property) as PropertyDescriptor; - let originalDescriptor = Object.getOwnPropertyDescriptor(proto, property); + let descriptor = Object.getOwnPropertyDescriptor( + ext, + property + ) as PropertyDescriptor; + let originalDescriptor = Object.getOwnPropertyDescriptor( + proto, + property + ); if (!originalDescriptor) { // try to get descriptor from originalPrototypes const originalProto = originalPrototypes[name]; if (originalProto) { - originalDescriptor = Object.getOwnPropertyDescriptor(originalProto, property); + originalDescriptor = Object.getOwnPropertyDescriptor( + originalProto, + property + ); } } if (originalDescriptor) { @@ -1171,7 +1317,10 @@ export class EggLoader { this.lifecycle.addFunctionAsBootHook(bootHook, bootFilePath); debug('[loadBootHook] add bootHookFunction from %o', bootFilePath); } else { - this.options.logger.warn('[@eggjs/core/egg_loader] %s must exports a boot class', bootFilePath); + this.options.logger.warn( + '[@eggjs/core/egg_loader] %s must exports a boot class', + bootFilePath + ); } } // init boots @@ -1190,7 +1339,9 @@ export class EggLoader { async loadService(options?: Partial) { this.timing.start('Load Service'); // 载入到 app.serviceClasses - const servicePaths = this.getLoadUnits().map(unit => path.join(unit.path, 'app/service')); + const servicePaths = this.getLoadUnits().map(unit => + path.join(unit.path, 'app/service') + ); options = { call: true, caseStyle: CaseStyle.lower, @@ -1199,7 +1350,11 @@ export class EggLoader { ...options, }; debug('[loadService] options: %o', options); - await this.loadToContext(servicePaths, 'service', options as ContextLoaderOptions); + await this.loadToContext( + servicePaths, + 'service', + options as ContextLoaderOptions + ); this.timing.end('Load Service'); } /** end Service loader */ @@ -1229,7 +1384,9 @@ export class EggLoader { const app = this.app; // load middleware to app.middleware - const middlewarePaths = this.getLoadUnits().map(unit => path.join(unit.path, 'app/middleware')); + const middlewarePaths = this.getLoadUnits().map(unit => + path.join(unit.path, 'app/middleware') + ); opt = { call: false, override: true, @@ -1237,7 +1394,11 @@ export class EggLoader { directory: middlewarePaths, ...opt, }; - await this.loadToApp(middlewarePaths, 'middlewares', opt as FileLoaderOptions); + await this.loadToApp( + middlewarePaths, + 'middlewares', + opt as FileLoaderOptions + ); for (const name in app.middlewares) { Object.defineProperty(app.middleware, name, { @@ -1249,11 +1410,19 @@ export class EggLoader { }); } - this.options.logger.info('Use coreMiddleware order: %j', this.config.coreMiddleware); - this.options.logger.info('Use appMiddleware order: %j', this.config.appMiddleware); + this.options.logger.info( + 'Use coreMiddleware order: %j', + this.config.coreMiddleware + ); + this.options.logger.info( + 'Use appMiddleware order: %j', + this.config.appMiddleware + ); // use middleware ordered by app.config.coreMiddleware and app.config.appMiddleware - const middlewareNames = this.config.coreMiddleware.concat(this.config.appMiddleware); + const middlewareNames = this.config.coreMiddleware.concat( + this.config.appMiddleware + ); debug('[loadMiddleware] middlewareNames: %j', middlewareNames); const middlewaresMap = new Map(); for (const name of middlewareNames) { @@ -1267,10 +1436,15 @@ export class EggLoader { middlewaresMap.set(name, true); const options = this.config[name] || {}; let mw: MiddlewareFunc | null = createMiddleware(options, app); - assert(typeof mw === 'function', `Middleware ${name} must be a function, but actual is ${inspect(mw)}`); + assert( + typeof mw === 'function', + `Middleware ${name} must be a function, but actual is ${inspect(mw)}` + ); if (isGeneratorFunction(mw)) { const fullpath = Reflect.get(createMiddleware, FULLPATH); - throw new TypeError(`Support for generators was removed, middleware: ${name}, fullpath: ${fullpath}`); + throw new TypeError( + `Support for generators was removed, middleware: ${name}, fullpath: ${fullpath}` + ); } mw._name = name; // middlewares support options.enable, options.ignore and options.match @@ -1281,14 +1455,27 @@ export class EggLoader { mw = debugMiddlewareWrapper(mw); } app.use(mw); - debug('[loadMiddleware] Use middleware: %s with options: %j', name, options); - this.options.logger.info('[@eggjs/core/egg_loader] Use middleware: %s', name); + debug( + '[loadMiddleware] Use middleware: %s with options: %j', + name, + options + ); + this.options.logger.info( + '[@eggjs/core/egg_loader] Use middleware: %s', + name + ); } else { - this.options.logger.info('[@eggjs/core/egg_loader] Disable middleware: %s', name); + this.options.logger.info( + '[@eggjs/core/egg_loader] Disable middleware: %s', + name + ); } } - this.options.logger.info('[@eggjs/core/egg_loader] Loaded middleware from %j', middlewarePaths); + this.options.logger.info( + '[@eggjs/core/egg_loader] Loaded middleware from %j', + middlewarePaths + ); this.timing.end('Load Middleware'); // add router middleware, make sure router is the last middleware @@ -1318,13 +1505,21 @@ export class EggLoader { // } // ``` if (isGeneratorFunction(obj)) { - throw new TypeError(`Support for generators was removed, fullpath: ${opt.path}`); + throw new TypeError( + `Support for generators was removed, fullpath: ${opt.path}` + ); } - if (!isClass(obj) && !isAsyncFunction(obj) && typeof obj === 'function') { + if ( + !isClass(obj) && + !isAsyncFunction(obj) && + typeof obj === 'function' + ) { obj = obj(this.app); debug('[loadController] after init(app) => %o, meta: %j', obj, opt); if (isGeneratorFunction(obj)) { - throw new TypeError(`Support for generators was removed, fullpath: ${opt.path}`); + throw new TypeError( + `Support for generators was removed, fullpath: ${opt.path}` + ); } } if (isClass(obj)) { @@ -1336,15 +1531,24 @@ export class EggLoader { return wrapObject(obj, opt.path); } if (isAsyncFunction(obj)) { - return wrapObject({ 'module.exports': obj }, opt.path)['module.exports']; + return wrapObject({ 'module.exports': obj }, opt.path)[ + 'module.exports' + ]; } return obj; }, ...opt, }; - await this.loadToApp(controllerBase, 'controller', opt as FileLoaderOptions); + await this.loadToApp( + controllerBase, + 'controller', + opt as FileLoaderOptions + ); debug('[loadController] app.controller => %o', this.app.controller); - this.options.logger.info('[@eggjs/core/egg_loader] Controller loaded: %s', controllerBase); + this.options.logger.info( + '[@eggjs/core/egg_loader] Controller loaded: %s', + controllerBase + ); this.timing.end('Load Controller'); } /** end Controller loader */ @@ -1371,20 +1575,32 @@ export class EggLoader { const loaderConfig = { ...customLoader[property], }; - assert(loaderConfig.directory, `directory is required for config.customLoader.${property}`); + assert( + loaderConfig.directory, + `directory is required for config.customLoader.${property}` + ); let directory: string | string[]; if (loaderConfig.loadunit === true) { - directory = this.getLoadUnits().map(unit => path.join(unit.path, loaderConfig.directory)); + directory = this.getLoadUnits().map(unit => + path.join(unit.path, loaderConfig.directory) + ); } else { directory = path.join(this.appInfo.baseDir, loaderConfig.directory); } const inject = loaderConfig.inject || 'app'; - debug('[loadCustomLoader] loaderConfig: %o, inject: %o, directory: %o', - loaderConfig, inject, directory); + debug( + '[loadCustomLoader] loaderConfig: %o, inject: %o, directory: %o', + loaderConfig, + inject, + directory + ); switch (inject) { case 'ctx': { - assert(!(property in this.app.context), `customLoader should not override ctx.${property}`); + assert( + !(property in this.app.context), + `customLoader should not override ctx.${property}` + ); const options = { caseStyle: CaseStyle.lower, fieldClass: `${property}Classes`, @@ -1395,7 +1611,10 @@ export class EggLoader { break; } case 'app': { - assert(!(property in this.app), `customLoader should not override app.${property}`); + assert( + !(property in this.app), + `customLoader should not override app.${property}` + ); const options = { caseStyle: CaseStyle.lower, initializer: (Clazz: unknown) => { @@ -1425,7 +1644,7 @@ export class EggLoader { * @example * ```js * app.loader.loadFile(path.join(app.options.baseDir, 'config/router.js')); - * ``` + * ``` * @since 1.0.0 */ async loadFile(filepath: string, ...inject: unknown[]) { @@ -1436,7 +1655,7 @@ export class EggLoader { // function(arg1, args, ...) {} if (inject.length === 0) { - inject = [ this.app ]; + inject = [this.app]; } let mod = await this.requireFile(fullpath); if (typeof mod === 'function' && !isClass(mod)) { @@ -1516,8 +1735,11 @@ export class EggLoader { * @param {Object} options - see {@link FileLoader} * @since 1.0.0 */ - async loadToApp(directory: string | string[], property: string | symbol, - options?: Omit) { + async loadToApp( + directory: string | string[], + property: string | symbol, + options?: Omit + ) { const target = {}; Reflect.set(this.app, property, target); const loadOptions: FileLoaderOptions = { @@ -1540,8 +1762,11 @@ export class EggLoader { * @param {Object} options - see {@link ContextLoader} * @since 1.0.0 */ - async loadToContext(directory: string | string[], property: string | symbol, - options?: Omit) { + async loadToContext( + directory: string | string[], + property: string | symbol, + options?: Omit + ) { const loadOptions: ContextLoaderOptions = { ...options, directory: options?.directory || directory, @@ -1572,7 +1797,7 @@ export class EggLoader { } getTypeFiles(filename: string) { - const files = [ `${filename}.default` ]; + const files = [`${filename}.default`]; if (this.serverScope) files.push(`${filename}.${this.serverScope}`); if (this.serverEnv === 'default') return files; files.push(`${filename}.${this.serverEnv}`); @@ -1598,7 +1823,10 @@ export class EggLoader { } function depCompatible(plugin: EggPluginInfo & { dep?: string[] }) { - if (plugin.dep && !(Array.isArray(plugin.dependencies) && plugin.dependencies.length > 0)) { + if ( + plugin.dep && + !(Array.isArray(plugin.dependencies) && plugin.dependencies.length > 0) + ) { plugin.dependencies = plugin.dep; delete plugin.dep; } @@ -1613,8 +1841,10 @@ function isValidatePackageName(name: string) { } // support pathMatching on middleware -function wrapMiddleware(mw: MiddlewareFunc, - options: PathMatchingOptions & { enable?: boolean }): MiddlewareFunc | null { +function wrapMiddleware( + mw: MiddlewareFunc, + options: PathMatchingOptions & { enable?: boolean } +): MiddlewareFunc | null { // support options.enable if (options.enable === false) { return null; @@ -1637,17 +1867,31 @@ function wrapMiddleware(mw: MiddlewareFunc, function debugMiddlewareWrapper(mw: MiddlewareFunc): MiddlewareFunc { const fn: MiddlewareFunc = async (ctx, next) => { const startTime = now(); - debug('[debugMiddlewareWrapper] [%s %s] enter middleware: %s', ctx.method, ctx.url, mw._name); + debug( + '[debugMiddlewareWrapper] [%s %s] enter middleware: %s', + ctx.method, + ctx.url, + mw._name + ); await mw(ctx, next); const rt = diff(startTime); - debug('[debugMiddlewareWrapper] [%s %s] after middleware: %s [%sms]', ctx.method, ctx.url, mw._name, rt); + debug( + '[debugMiddlewareWrapper] [%s %s] after middleware: %s [%sms]', + ctx.method, + ctx.url, + mw._name, + rt + ); }; fn._name = `${mw._name}DebugWrapper`; return fn; } // wrap the controller class, yield a object with middlewares -function wrapControllerClass(Controller: typeof BaseContextClass, fullPath: string) { +function wrapControllerClass( + Controller: typeof BaseContextClass, + fullPath: string +) { let proto = Controller.prototype; const ret: Record = {}; // tracing the prototype chain @@ -1666,7 +1910,8 @@ function wrapControllerClass(Controller: typeof BaseContextClass, fullPath: stri const controllerMethodName = `${Controller.name}.${key}`; if (isGeneratorFunction(d.value)) { throw new TypeError( - `Support for generators was removed, controller \`${controllerMethodName}\`, fullpath: ${fullPath}`); + `Support for generators was removed, controller \`${controllerMethodName}\`, fullpath: ${fullPath}` + ); } ret[key] = controllerMethodToMiddleware(Controller, key); ret[key][FULLPATH] = `${fullPath}#${controllerMethodName}()`; @@ -1677,11 +1922,14 @@ function wrapControllerClass(Controller: typeof BaseContextClass, fullPath: stri return ret; } -function controllerMethodToMiddleware(Controller: typeof BaseContextClass, key: string) { +function controllerMethodToMiddleware( + Controller: typeof BaseContextClass, + key: string +) { return function classControllerMiddleware(this: Context, ...args: unknown[]) { const controller = new Controller(this); if (!this.app.config.controller?.supportParams) { - args = [ this ]; + args = [this]; } // @ts-expect-error key exists return controller[key](...args); @@ -1689,7 +1937,11 @@ function controllerMethodToMiddleware(Controller: typeof BaseContextClass, key: } // wrap the method of the object, method can receive ctx as it's first argument -function wrapObject(obj: Record, fullPath: string, prefix?: string) { +function wrapObject( + obj: Record, + fullPath: string, + prefix?: string +) { const keys = Object.keys(obj); const ret: Record = {}; prefix = prefix ?? ''; @@ -1697,12 +1949,16 @@ function wrapObject(obj: Record, fullPath: string, prefix?: string) const controllerMethodName = `${prefix}${key}`; const item = obj[key]; if (isGeneratorFunction(item)) { - throw new TypeError(`Support for generators was removed, controller \`${controllerMethodName}\`, fullpath: ${fullPath}`); + throw new TypeError( + `Support for generators was removed, controller \`${controllerMethodName}\`, fullpath: ${fullPath}` + ); } if (typeof item === 'function') { const names = getParamNames(item); if (names[0] === 'next') { - throw new Error(`controller \`${controllerMethodName}\` should not use next as argument from file ${fullPath}`); + throw new Error( + `controller \`${controllerMethodName}\` should not use next as argument from file ${fullPath}` + ); } ret[key] = objectFunctionToMiddleware(item); ret[key][FULLPATH] = `${fullPath}#${controllerMethodName}()`; @@ -1717,7 +1973,7 @@ function wrapObject(obj: Record, fullPath: string, prefix?: string) function objectFunctionToMiddleware(func: Fun) { async function objectControllerMiddleware(this: Context, ...args: unknown[]) { if (!this.app.config.controller?.supportParams) { - args = [ this ]; + args = [this]; } return await func.apply(this, args); } diff --git a/src/loader/file_loader.ts b/src/loader/file_loader.ts index fa0be021..8139a905 100644 --- a/src/loader/file_loader.ts +++ b/src/loader/file_loader.ts @@ -4,7 +4,12 @@ import { debuglog } from 'node:util'; import path from 'node:path'; import globby from 'globby'; -import { isClass, isGeneratorFunction, isAsyncFunction, isPrimitive } from 'is-type-of'; +import { + isClass, + isGeneratorFunction, + isAsyncFunction, + isPrimitive, +} from 'is-type-of'; import { isSupportTypeScript } from '@eggjs/utils'; import utils, { type Fun } from '../utils/index.js'; @@ -21,14 +26,17 @@ export enum CaseStyle { } export type CaseStyleFunction = (filepath: string) => string[]; -export type FileLoaderInitializer = (exports: unknown, options: { path: string; pathName: string }) => unknown; +export type FileLoaderInitializer = ( + exports: unknown, + options: { path: string; pathName: string } +) => unknown; export type FileLoaderFilter = (exports: unknown) => boolean; export interface FileLoaderOptions { /** directories to be loaded */ directory: string | string[]; /** attach the target object from loaded files */ - + target: Record; /** match the files when load, support glob, default to all js files */ match?: string | string[]; @@ -41,7 +49,7 @@ export interface FileLoaderOptions { /** determine whether override the property when get the same name */ override?: boolean; /** an object that be the argument when invoke the function */ - + inject?: Record; /** a function that filter the exports which can be loaded */ filter?: FileLoaderFilter; @@ -69,7 +77,8 @@ export class FileLoader { return EXPORTS; } - readonly options: FileLoaderOptions & Required>; + readonly options: FileLoaderOptions & + Required>; /** * @class @@ -121,7 +130,9 @@ export class FileLoader { const properties = item.properties.slice(0, index + 1).join('.'); if (index === item.properties.length - 1) { if (property in target && !this.options.override) { - throw new Error(`can't overwrite property '${properties}' from ${target[property][FULLPATH]} by ${item.fullpath}`); + throw new Error( + `can't overwrite property '${properties}' from ${target[property][FULLPATH]} by ${item.fullpath}` + ); } obj = item.exports; if (obj && !isPrimitive(obj)) { @@ -168,31 +179,37 @@ export class FileLoader { protected async parse(): Promise { let files = this.options.match; if (files) { - files = Array.isArray(files) ? files : [ files ]; + files = Array.isArray(files) ? files : [files]; } else { files = isSupportTypeScript() - ? [ '**/*.(js|ts)', '!**/*.d.ts' ] - : [ '**/*.js' ]; + ? ['**/*.(js|ts)', '!**/*.d.ts'] + : ['**/*.js']; } let ignore = this.options.ignore; if (ignore) { - ignore = Array.isArray(ignore) ? ignore : [ ignore ]; + ignore = Array.isArray(ignore) ? ignore : [ignore]; ignore = ignore.filter(f => !!f).map(f => '!' + f); files = files.concat(ignore); } let directories = this.options.directory; if (!Array.isArray(directories)) { - directories = [ directories ]; + directories = [directories]; } - const filter = typeof this.options.filter === 'function' ? this.options.filter : null; + const filter = + typeof this.options.filter === 'function' ? this.options.filter : null; const items: FileLoaderParseItem[] = []; debug('[parse] parsing directories: %j', directories); for (const directory of directories) { const filepaths = globby.sync(files, { cwd: directory }); - debug('[parse] globby files: %o, cwd: %o => %o', files, directory, filepaths); + debug( + '[parse] globby files: %o, cwd: %o => %o', + files, + directory, + filepaths + ); for (const filepath of filepaths) { const fullpath = path.join(directory, filepath); if (!fs.statSync(fullpath).isFile()) continue; @@ -207,12 +224,17 @@ export class FileLoader { // app/service/foo/bar.js => [ 'foo', 'bar' ] const properties = getProperties(filepath, this.options.caseStyle); // app/service/foo/bar.js => service.foo.bar - const pathName = directory.split(/[/\\]/).slice(-1) + '.' + properties.join('.'); + const pathName = + directory.split(/[/\\]/).slice(-1) + '.' + properties.join('.'); // get exports from the file const exports = await getExports(fullpath, this.options, pathName); // ignore exports when it's null or false returned by filter function - if (exports === null || exports === undefined || (filter && filter(exports) === false)) { + if ( + exports === null || + exports === undefined || + (filter && filter(exports) === false) + ) { continue; } @@ -223,7 +245,12 @@ export class FileLoader { } items.push({ fullpath, properties, exports }); - debug('[parse] parse %s, properties %j, exports %o', fullpath, properties, exports); + debug( + '[parse] parse %s, properties %j, exports %o', + fullpath, + properties, + exports + ); } } @@ -233,11 +260,17 @@ export class FileLoader { // convert file path to an array of properties // a/b/c.js => ['a', 'b', 'c'] -function getProperties(filepath: string, caseStyle: CaseStyle | CaseStyleFunction) { +function getProperties( + filepath: string, + caseStyle: CaseStyle | CaseStyleFunction +) { // if caseStyle is function, return the result of function if (typeof caseStyle === 'function') { const result = caseStyle(filepath); - assert(Array.isArray(result), `caseStyle expect an array, but got ${JSON.stringify(result)}`); + assert( + Array.isArray(result), + `caseStyle expect an array, but got ${JSON.stringify(result)}` + ); return result; } // use default camelize @@ -246,7 +279,11 @@ function getProperties(filepath: string, caseStyle: CaseStyle | CaseStyleFunctio // Get exports from filepath // If exports is null/undefined, it will be ignored -async function getExports(fullpath: string, options: FileLoaderOptions, pathName: string) { +async function getExports( + fullpath: string, + options: FileLoaderOptions, + pathName: string +) { let exports = await utils.loadFile(fullpath); // process exports as you like if (options.initializer) { @@ -255,7 +292,9 @@ async function getExports(fullpath: string, options: FileLoaderOptions, pathName } if (isGeneratorFunction(exports)) { - throw new TypeError(`Support for generators was removed, fullpath: ${fullpath}`); + throw new TypeError( + `Support for generators was removed, fullpath: ${fullpath}` + ); } // return exports when it's a class or async function @@ -296,7 +335,9 @@ function defaultCamelize(filepath: string, caseStyle: CaseStyle) { // FooBar.js > FooBar // FooBar.js > FooBar // FooBar.js > fooBar (if lowercaseFirst is true) - property = property.replaceAll(/[_-][a-z]/ig, s => s.slice(1).toUpperCase()); + property = property.replaceAll(/[_-][a-z]/gi, s => + s.slice(1).toUpperCase() + ); let first = property[0]; if (caseStyle === CaseStyle.lower) { first = first.toLowerCase(); diff --git a/src/singleton.ts b/src/singleton.ts index ebbf1f36..3e81eb7a 100644 --- a/src/singleton.ts +++ b/src/singleton.ts @@ -2,8 +2,11 @@ import assert from 'node:assert'; import { isAsyncFunction } from 'is-type-of'; import type { EggCore } from './egg.js'; -export type SingletonCreateMethod = - (config: Record, app: EggCore, clientName: string) => unknown | Promise; +export type SingletonCreateMethod = ( + config: Record, + app: EggCore, + clientName: string +) => unknown | Promise; export interface SingletonOptions { name: string; @@ -19,10 +22,22 @@ export class Singleton { readonly options: Record; constructor(options: SingletonOptions) { - assert(options.name, '[@eggjs/core/singleton] Singleton#constructor options.name is required'); - assert(options.app, '[@eggjs/core/singleton] Singleton#constructor options.app is required'); - assert(options.create, '[@eggjs/core/singleton] Singleton#constructor options.create is required'); - assert(!(options.name in options.app), `[@eggjs/core/singleton] ${options.name} is already exists in app`); + assert( + options.name, + '[@eggjs/core/singleton] Singleton#constructor options.name is required' + ); + assert( + options.app, + '[@eggjs/core/singleton] Singleton#constructor options.app is required' + ); + assert( + options.create, + '[@eggjs/core/singleton] Singleton#constructor options.create is required' + ); + assert( + !(options.name in options.app), + `[@eggjs/core/singleton] ${options.name} is already exists in app` + ); this.app = options.app; this.name = options.name; this.create = options.create; @@ -35,8 +50,10 @@ export class Singleton { initSync() { const options = this.options; - assert(!(options.client && options.clients), - `[@eggjs/core/singleton] ${this.name} can not set options.client and options.clients both`); + assert( + !(options.client && options.clients), + `[@eggjs/core/singleton] ${this.name} can not set options.client and options.clients both` + ); // alias app[name] as client, but still support createInstance method if (options.client) { @@ -62,12 +79,17 @@ export class Singleton { async initAsync() { const options = this.options; - assert(!(options.client && options.clients), - `[@eggjs/core/singleton] ${this.name} can not set options.client and options.clients both`); + assert( + !(options.client && options.clients), + `[@eggjs/core/singleton] ${this.name} can not set options.client and options.clients both` + ); // alias app[name] as client, but still support createInstance method if (options.client) { - const client = await this.createInstanceAsync(options.client, options.name); + const client = await this.createInstanceAsync( + options.client, + options.name + ); this.#setClientToApp(client); this.#extendDynamicMethods(client); return; @@ -75,10 +97,13 @@ export class Singleton { // multi client, use app[name].getInstance(id) if (options.clients) { - await Promise.all(Object.keys(options.clients).map((id: string) => { - return this.createInstanceAsync(options.clients[id], id) - .then(client => this.clients.set(id, client)); - })); + await Promise.all( + Object.keys(options.clients).map((id: string) => { + return this.createInstanceAsync(options.clients[id], id).then( + client => this.clients.set(id, client) + ); + }) + ); this.#setClientToApp(this); return; } @@ -107,14 +132,20 @@ export class Singleton { createInstance(config: Record, clientName: string) { // async creator only support createInstanceAsync - assert(!isAsyncFunction(this.create), - `[@eggjs/core/singleton] ${this.name} only support asynchronous creation, please use createInstanceAsync`); + assert( + !isAsyncFunction(this.create), + `[@eggjs/core/singleton] ${this.name} only support asynchronous creation, please use createInstanceAsync` + ); // options.default will be merge in to options.clients[id] config = { ...this.options.default, ...config, }; - return (this.create as SingletonCreateMethod)(config, this.app, clientName) as T; + return (this.create as SingletonCreateMethod)( + config, + this.app, + clientName + ) as T; } async createInstanceAsync(config: Record, clientName: string) { @@ -123,12 +154,18 @@ export class Singleton { ...this.options.default, ...config, }; - return await this.create(config, this.app, clientName) as T; + return (await this.create(config, this.app, clientName)) as T; } #extendDynamicMethods(client: any) { - assert(!client.createInstance, '[@eggjs/core/singleton] singleton instance should not have createInstance method'); - assert(!client.createInstanceAsync, '[@eggjs/core/singleton] singleton instance should not have createInstanceAsync method'); + assert( + !client.createInstance, + '[@eggjs/core/singleton] singleton instance should not have createInstance method' + ); + assert( + !client.createInstanceAsync, + '[@eggjs/core/singleton] singleton instance should not have createInstanceAsync method' + ); try { let extendable = client; @@ -142,7 +179,8 @@ export class Singleton { } catch (err) { this.app.coreLogger.warn( '[@eggjs/core/singleton] %s dynamic create is disabled because of client is un-extendable', - this.name); + this.name + ); this.app.coreLogger.warn(err); } } diff --git a/src/types.ts b/src/types.ts index fbf03d08..e9cccc83 100644 --- a/src/types.ts +++ b/src/types.ts @@ -46,7 +46,6 @@ export interface CustomLoaderConfigItem { loadunit?: boolean; } - export interface EggAppConfig extends Record { coreMiddleware: string[]; middleware: string[]; diff --git a/src/utils/index.ts b/src/utils/index.ts index 1ba8e088..78d8cb87 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -11,14 +11,14 @@ const debug = debuglog('@eggjs/core/utils'); export type Fun = (...args: unknown[]) => unknown; // Guard against poorly mocked module constructors. -const Module = typeof module !== 'undefined' && module.constructor.length > 1 - ? module.constructor - /* istanbul ignore next */ - : BuiltinModule; - +const Module = + typeof module !== 'undefined' && module.constructor.length > 1 + ? module.constructor + : /* istanbul ignore next */ + BuiltinModule; const extensions = (Module as any)._extensions; -const extensionNames = Object.keys(extensions).concat([ '.cjs', '.mjs' ]); +const extensionNames = Object.keys(extensions).concat(['.cjs', '.mjs']); debug('Module extensions: %j', extensionNames); function getCalleeFromStack(withLine?: boolean, stackIndex?: number) { @@ -30,7 +30,7 @@ function getCalleeFromStack(withLine?: boolean, stackIndex?: number) { Error.stackTraceLimit = 5; // capture the stack - + const obj: any = {}; Error.captureStackTrace(obj); let callSite = obj.stack[stackIndex]; @@ -61,7 +61,9 @@ export default { console.trace('[@eggjs/core/deprecated] %s', message); } else { console.log('[@eggjs/core/deprecated] %s', message); - console.log('[@eggjs/core/deprecated] set NODE_DEBUG=@eggjs/core/utils can show call stack'); + console.log( + '[@eggjs/core/deprecated] set NODE_DEBUG=@eggjs/core/utils can show call stack' + ); } }, @@ -92,7 +94,9 @@ export default { console.trace(e); throw e; } - const err = new Error(`[@eggjs/core] load file: ${filepath}, error: ${e.message}`); + const err = new Error( + `[@eggjs/core] load file: ${filepath}, error: ${e.message}` + ); err.cause = e; debug('[loadFile] handle %s error: %s', filepath, e); throw err; @@ -103,7 +107,7 @@ export default { return importResolve(filepath, options); }, - methods: [ 'head', 'options', 'get', 'put', 'patch', 'post', 'delete' ], + methods: ['head', 'options', 'get', 'put', 'patch', 'post', 'delete'], async callFn(fn: Fun, args?: unknown[], ctx?: unknown) { args = args || []; diff --git a/src/utils/sequencify.ts b/src/utils/sequencify.ts index 571df9cd..7149b558 100644 --- a/src/utils/sequencify.ts +++ b/src/utils/sequencify.ts @@ -12,11 +12,17 @@ export interface SequencifyTask { optionalDependencies: string[]; } -// oxlint-disable-next-line max-params -function sequence(tasks: Record, - names: string[], result: SequencifyResult, - missing: string[], recursive: string[], - nest: string[], optional: boolean, parent: string) { +function sequence( + // oxlint-disable-next-line max-params + tasks: Record, + names: string[], + result: SequencifyResult, + missing: string[], + recursive: string[], + nest: string[], + optional: boolean, + parent: string +) { for (const name of names) { if (result.requires[name]) { continue; @@ -31,13 +37,34 @@ function sequence(tasks: Record, nest.push(name); recursive.push(...nest.slice(0)); nest.pop(); - } else if (node.dependencies.length > 0 || node.optionalDependencies.length > 0) { + } else if ( + node.dependencies.length > 0 || + node.optionalDependencies.length > 0 + ) { nest.push(name); if (node.dependencies.length > 0) { - sequence(tasks, node.dependencies, result, missing, recursive, nest, optional, name); + sequence( + tasks, + node.dependencies, + result, + missing, + recursive, + nest, + optional, + name + ); } if (node.optionalDependencies.length > 0) { - sequence(tasks, node.optionalDependencies, result, missing, recursive, nest, true, name); + sequence( + tasks, + node.optionalDependencies, + result, + missing, + recursive, + nest, + true, + name + ); } nest.pop(); } @@ -53,7 +80,10 @@ function sequence(tasks: Record, // tasks: object with keys as task names // names: array of task names -export function sequencify(tasks: Record, names: string[]) { +export function sequencify( + tasks: Record, + names: string[] +) { const result: SequencifyResult = { sequence: [], requires: {}, diff --git a/src/utils/timing.ts b/src/utils/timing.ts index 82d6a2ca..0f1f43dc 100644 --- a/src/utils/timing.ts +++ b/src/utils/timing.ts @@ -27,10 +27,16 @@ export class Timing { init() { // process start time - this.start('Process Start', Date.now() - Math.floor(process.uptime() * 1000)); + this.start( + 'Process Start', + Date.now() - Math.floor(process.uptime() * 1000) + ); this.end('Process Start'); - if ('scriptStartTime' in process && typeof process.scriptStartTime === 'number') { + if ( + 'scriptStartTime' in process && + typeof process.scriptStartTime === 'number' + ) { // js script start execute time this.start('Script Start', process.scriptStartTime); this.end('Script Start'); @@ -89,14 +95,18 @@ export class Timing { itemToString(timelineEnd: number, item: TimingItem, times: number) { const isEnd = typeof item.duration === 'number'; - const duration = isEnd ? item.duration as number : timelineEnd - item.start; + const duration = isEnd + ? (item.duration as number) + : timelineEnd - item.start; const offset = item.start - this.#startTime; const status = `${duration}ms${isEnd ? '' : ' NOT_END'}`; const timespan = Math.floor(Number((offset * times).toFixed(6))); let timeline = Math.floor(Number((duration * times).toFixed(6))); timeline = timeline > 0 ? timeline : 1; // make sure there is at least one unit const message = `#${item.index} ${item.name}`; - return ' '.repeat(timespan) + '▇'.repeat(timeline) + ` [${status}] - ${message}`; + return ( + ' '.repeat(timespan) + '▇'.repeat(timeline) + ` [${status}] - ${message}` + ); } toString(prefix = 'egg start timeline:', width = 50) { @@ -107,6 +117,12 @@ export class Timing { times = width / timelineDuration; } // follow https://github.com/node-modules/time-profile/blob/master/lib/profiler.js#L88 - return prefix + EOL + this.#list.map(item => this.itemToString(timelineEnd, item, times)).join(EOL); + return ( + prefix + + EOL + + this.#list + .map(item => this.itemToString(timelineEnd, item, times)) + .join(EOL) + ); } } diff --git a/test/asyncLocalStorage.test.ts b/test/asyncLocalStorage.test.ts index 60b0e40d..3d02df5e 100644 --- a/test/asyncLocalStorage.test.ts +++ b/test/asyncLocalStorage.test.ts @@ -17,12 +17,10 @@ describe('test/asyncLocalStorage.test.ts', () => { it('should start app with asyncLocalStorage = true by default', async () => { assert.equal(app.currentContext, undefined); - const res1 = await request(app.callback()) - .get('/status'); + const res1 = await request(app.callback()).get('/status'); assert.equal(res1.status, 200); assert.equal(res1.text, 'egg status'); - const res = await request(app.callback()) - .get('/'); + const res = await request(app.callback()).get('/'); assert.equal(res.status, 200); // console.log(res.body); assert.equal(res.body.sessionId, 'mock-session-id-123'); @@ -33,8 +31,14 @@ describe('test/asyncLocalStorage.test.ts', () => { it('should access als on global', async () => { assert(Reflect.get(global, Symbol.for('gals#asyncLocalStorage'))); assert(Reflect.get(global, kGALS)); - assert(Reflect.get(global, Symbol.for('gals#asyncLocalStorage')) instanceof AsyncLocalStorage); - assert.equal(app.ctxStorage, Reflect.get(global, Symbol.for('gals#asyncLocalStorage'))); + assert( + Reflect.get(global, Symbol.for('gals#asyncLocalStorage')) instanceof + AsyncLocalStorage + ); + assert.equal( + app.ctxStorage, + Reflect.get(global, Symbol.for('gals#asyncLocalStorage')) + ); assert.equal(app.ctxStorage, getAsyncLocalStorage()); }); }); diff --git a/test/fixtures/agent/app/extend/agent.js b/test/fixtures/agent/app/extend/agent.js index a28324eb..bca2eea4 100644 --- a/test/fixtures/agent/app/extend/agent.js +++ b/test/fixtures/agent/app/extend/agent.js @@ -2,5 +2,5 @@ module.exports = { foo: 'agent bar', - bar: 'foo' + bar: 'foo', }; diff --git a/test/fixtures/agent/package.json b/test/fixtures/agent/package.json index a96f0007..7323e7c1 100644 --- a/test/fixtures/agent/package.json +++ b/test/fixtures/agent/package.json @@ -1,3 +1,3 @@ { - "name": "application" -} \ No newline at end of file + "name": "application" +} diff --git a/test/fixtures/app-before-close/app.js b/test/fixtures/app-before-close/app.js index aa28a0bf..a035bd8e 100644 --- a/test/fixtures/app-before-close/app.js +++ b/test/fixtures/app-before-close/app.js @@ -12,7 +12,7 @@ module.exports = app => { app.closeGeneratorFn = true; app.closeOrderArray.push('closeGeneratorFn'); }); - app.beforeClose(function() { + app.beforeClose(function () { app.closeOrderArray.push('closeAsyncFn'); return new Promise(resolve => { app.closeAsyncFn = true; diff --git a/test/fixtures/app-ts/app.ts b/test/fixtures/app-ts/app.ts index 6025e838..eddb1851 100644 --- a/test/fixtures/app-ts/app.ts +++ b/test/fixtures/app-ts/app.ts @@ -2,7 +2,13 @@ import * as assert from 'assert'; import * as path from 'path'; const EGG_LOADER = Symbol.for('egg#loader'); const EGG_PATH = Symbol.for('egg#eggPath'); -import { BaseContextClass, EggCore, EggCoreOptions, EggLoader, EggLoaderOptions } from '../../..'; +import { + BaseContextClass, + EggCore, + EggCoreOptions, + EggLoader, + EggLoaderOptions, +} from '../../..'; // normal const app = new EggCore<{ env: string }>(); @@ -41,17 +47,25 @@ new BaseContextClass({ app: {} }); // ready & close (async function test() { - const app2 = new EggCore({ baseDir: path.resolve(__dirname, '../app-getter/') }); + const app2 = new EggCore({ + baseDir: path.resolve(__dirname, '../app-getter/'), + }); assert(app2.type === 'application'); assert(app2.name === 'app-getter'); assert(app2.plugins === app.loader.plugins); app2.beforeClose(() => {}); app2.beforeStart(() => {}); - const result = await app2.toAsyncFunction<{ env: number; }>(function*() { return yield { env: 1 } })(); + const result = await app2.toAsyncFunction<{ env: number }>(function* () { + return yield { env: 1 }; + })(); assert(result.env === 1); await app2.toPromise([ - function*() { yield {} }, - function*() { yield {} } + function* () { + yield {}; + }, + function* () { + yield {}; + }, ]); await app2.ready(); await app2.close(); @@ -83,9 +97,9 @@ class MyLoader extends EggLoader { this.loadHelperExtend(); this.loadCustomAgent(); this.loadService(); - this.loadController({ ignore: [ '**/node_module' ] }); + this.loadController({ ignore: ['**/node_module'] }); this.loadRouter(); - this.loadMiddleware({ ignore: [ '**/node_module' ] }); + this.loadMiddleware({ ignore: ['**/node_module'] }); } } const app3 = new MyEgg({ baseDir: path.resolve(__dirname, '../app-getter/') }); @@ -94,7 +108,6 @@ assert(app3.config === app3.loader.config); assert(app3.deprecate); app3.deprecate('is deprecate'); - // loadTo const app4 = { context: {} } as any; const baseDir = path.join(__dirname, '../load_to_app'); @@ -119,10 +132,15 @@ const loader2 = new EggLoader({ }); loader2.loadToApp('dao', 'dao', { match: '**/test*.js', caseStyle: 'lower' }); assert(app5.dao); -loader2.loadToContext('dao', 'dao', { caseStyle: 'lower', ignore: [ 'testFunction.js', 'testReturnFunction.js' ] }); +loader2.loadToContext('dao', 'dao', { + caseStyle: 'lower', + ignore: ['testFunction.js', 'testReturnFunction.js'], +}); assert(app5.context.dao); assert(loader2.loadFile(path.resolve(baseDir2, './dao/testFunction'))); -assert(loader2.loadFile(path.resolve(baseDir2, './dao/testFunction'), { abc: 123 })); +assert( + loader2.loadFile(path.resolve(baseDir2, './dao/testFunction'), { abc: 123 }) +); // file loader const FileLoader = loader.FileLoader; @@ -130,9 +148,11 @@ const app6 = {} as any; new FileLoader({ directory: path.join(__dirname, '../load_dirs'), target: app6, - match: [ 'dao/*' ], + match: ['dao/*'], caseStyle: 'upper', - filter(obj) { return !!obj; }, + filter(obj) { + return !!obj; + }, initializer(obj, options) { assert(options.path); assert(options.pathName); @@ -153,9 +173,11 @@ class CustomFileLoader extends FileLoader { new CustomFileLoader({ directory: path.join(__dirname, '../load_dirs'), target: app9, - match: [ 'dao/*' ], + match: ['dao/*'], caseStyle: 'upper', - filter(obj) { return !!obj; }, + filter(obj) { + return !!obj; + }, initializer(obj, options) { assert(options.path); assert(options.pathName); @@ -171,9 +193,11 @@ new ContextLoader({ property: 'kick', fieldClass: 'ass', inject: app7, - match: [ 'dao/*' ], + match: ['dao/*'], caseStyle: 'upper', - filter(obj) { return !!obj; }, + filter(obj) { + return !!obj; + }, initializer(obj, options) { assert(options.path); assert(options.pathName); @@ -185,7 +209,6 @@ assert(app7.ass.Dao.TestFunction); assert(app7.context.kick.Dao.TestClass); assert(app7.context.kick.Dao.TestFunction); - // custom context loader const app8 = { context: {} } as any; class CustomContextLoader extends ContextLoader { @@ -199,9 +222,11 @@ new CustomContextLoader({ property: 'kick', fieldClass: 'ass', inject: app8, - match: [ 'dao/*' ], + match: ['dao/*'], caseStyle: 'upper', - filter(obj) { return !!obj; }, + filter(obj) { + return !!obj; + }, initializer(obj, options) { assert(options.path); assert(options.pathName); diff --git a/test/fixtures/app-ts/tsconfig.json b/test/fixtures/app-ts/tsconfig.json index df4c7e6e..0843d6c5 100644 --- a/test/fixtures/app-ts/tsconfig.json +++ b/test/fixtures/app-ts/tsconfig.json @@ -5,4 +5,4 @@ "module": "commonjs", "strict": true } -} \ No newline at end of file +} diff --git a/test/fixtures/application/app/extend/application.js b/test/fixtures/application/app/extend/application.js index 8cd0f95d..d91f93a0 100644 --- a/test/fixtures/application/app/extend/application.js +++ b/test/fixtures/application/app/extend/application.js @@ -2,5 +2,5 @@ module.exports = { foo: 'app bar', - bar: 'foo' -}; \ No newline at end of file + bar: 'foo', +}; diff --git a/test/fixtures/application/package.json b/test/fixtures/application/package.json index a96f0007..7323e7c1 100644 --- a/test/fixtures/application/package.json +++ b/test/fixtures/application/package.json @@ -1,3 +1,3 @@ { - "name": "application" -} \ No newline at end of file + "name": "application" +} diff --git a/test/fixtures/beforestart-params-error/app.js b/test/fixtures/beforestart-params-error/app.js index e8342c93..579fe6c1 100644 --- a/test/fixtures/beforestart-params-error/app.js +++ b/test/fixtures/beforestart-params-error/app.js @@ -1,3 +1,3 @@ -module.exports = function(app) { +module.exports = function (app) { app.beforeStart(); }; diff --git a/test/fixtures/beforestart-timeout/app.js b/test/fixtures/beforestart-timeout/app.js index 579546a5..d230b244 100644 --- a/test/fixtures/beforestart-timeout/app.js +++ b/test/fixtures/beforestart-timeout/app.js @@ -1,6 +1,6 @@ const { scheduler } = require('node:timers/promises'); -module.exports = function(app) { +module.exports = function (app) { app.beforeStart(async () => { await scheduler.wait(11000); }); diff --git a/test/fixtures/beforestart-with-timeout-env/app.js b/test/fixtures/beforestart-with-timeout-env/app.js index 8fb2588c..49d1d19d 100644 --- a/test/fixtures/beforestart-with-timeout-env/app.js +++ b/test/fixtures/beforestart-with-timeout-env/app.js @@ -7,4 +7,3 @@ module.exports = function (app) { }); app.beforeStartFunction = false; }; - diff --git a/test/fixtures/beforestart/app.js b/test/fixtures/beforestart/app.js index acfc50d0..62e781cc 100644 --- a/test/fixtures/beforestart/app.js +++ b/test/fixtures/beforestart/app.js @@ -1,7 +1,7 @@ const { scheduler } = require('node:timers/promises'); module.exports = function (app) { - app.beforeStart(function() { + app.beforeStart(function () { app.beforeStartFunction = true; }); app.beforeStart(async function () { diff --git a/test/fixtures/boot/app/plugin/boot-plugin/agent.js b/test/fixtures/boot/app/plugin/boot-plugin/agent.js index 116a6763..8ec67a38 100644 --- a/test/fixtures/boot/app/plugin/boot-plugin/agent.js +++ b/test/fixtures/boot/app/plugin/boot-plugin/agent.js @@ -7,7 +7,7 @@ module.exports = agent => { agent.bootLog.push('beforeStart'); }); - agent.ready(()=> { + agent.ready(() => { agent.bootLog.push('ready'); }); }; diff --git a/test/fixtures/boot/app/plugin/boot-plugin/app.js b/test/fixtures/boot/app/plugin/boot-plugin/app.js index aaead4fc..942ad27e 100644 --- a/test/fixtures/boot/app/plugin/boot-plugin/app.js +++ b/test/fixtures/boot/app/plugin/boot-plugin/app.js @@ -10,7 +10,7 @@ module.exports = app => { app.bootLog.push('beforeStart'); }); - app.ready(()=> { + app.ready(() => { app.bootLog.push('ready'); }); }; diff --git a/test/fixtures/config-array/plugin/a/config/config.default.js b/test/fixtures/config-array/plugin/a/config/config.default.js index fb4cceed..ac017010 100644 --- a/test/fixtures/config-array/plugin/a/config/config.default.js +++ b/test/fixtures/config-array/plugin/a/config/config.default.js @@ -1,3 +1,3 @@ 'use strict'; -exports.array = [ 1, 2, 3 ]; +exports.array = [1, 2, 3]; diff --git a/test/fixtures/config-array/plugin/b/config/config.default.js b/test/fixtures/config-array/plugin/b/config/config.default.js index bc86f0dc..62b1bd4b 100644 --- a/test/fixtures/config-array/plugin/b/config/config.default.js +++ b/test/fixtures/config-array/plugin/b/config/config.default.js @@ -1,3 +1,3 @@ 'use strict'; -exports.array = [ 1, 2 ]; +exports.array = [1, 2]; diff --git a/test/fixtures/config/app/controller/foo.js b/test/fixtures/config/app/controller/foo.js index fed4d750..eae4c759 100644 --- a/test/fixtures/config/app/controller/foo.js +++ b/test/fixtures/config/app/controller/foo.js @@ -1,11 +1,11 @@ 'use strict'; var util = require('./util/a'); -module.exports = function() { +module.exports = function () { return { - a: function*() { + a: function* () { util.b(); this.body = 'hello'; - } + }, }; }; diff --git a/test/fixtures/config/app/controller/util/a.js b/test/fixtures/config/app/controller/util/a.js index f2b6d0b5..35437f1b 100644 --- a/test/fixtures/config/app/controller/util/a.js +++ b/test/fixtures/config/app/controller/util/a.js @@ -1,5 +1,4 @@ module.exports = { a: 1, - b: function() { - } + b: function () {}, }; diff --git a/test/fixtures/config/app/services/foo.js b/test/fixtures/config/app/services/foo.js index bf69a7cd..90a31f66 100644 --- a/test/fixtures/config/app/services/foo.js +++ b/test/fixtures/config/app/services/foo.js @@ -1,10 +1,10 @@ 'use strict'; var util = require('./util/bar'); -module.exports = function() { +module.exports = function () { return { - bar: function*(ctx) { + bar: function* (ctx) { console.log(ctx); - } + }, }; }; diff --git a/test/fixtures/config/config/config.js b/test/fixtures/config/config/config.js index b31a6ff3..1dbd59ff 100644 --- a/test/fixtures/config/config/config.js +++ b/test/fixtures/config/config/config.js @@ -2,7 +2,7 @@ exports.loader = { service: { ignore: 'util/**' }, - controller: { ignore: 'util/**' } + controller: { ignore: 'util/**' }, }; exports.name = 'config-test'; @@ -10,5 +10,5 @@ exports.name = 'config-test'; exports.test = 1; exports.urllib = { - keepAlive: false + keepAlive: false, }; diff --git a/test/fixtures/context-loader/app/depth/four/four/four/four.js b/test/fixtures/context-loader/app/depth/four/four/four/four.js index 40814179..103f71eb 100644 --- a/test/fixtures/context-loader/app/depth/four/four/four/four.js +++ b/test/fixtures/context-loader/app/depth/four/four/four/four.js @@ -8,4 +8,4 @@ module.exports = class Four { get() { return this.ctx.name + ':four'; } -} +}; diff --git a/test/fixtures/context-loader/app/depth/one.js b/test/fixtures/context-loader/app/depth/one.js index 156d8c5e..1b3b4bd5 100644 --- a/test/fixtures/context-loader/app/depth/one.js +++ b/test/fixtures/context-loader/app/depth/one.js @@ -8,4 +8,4 @@ module.exports = class One { get() { return this.ctx.name + ':one'; } -} +}; diff --git a/test/fixtures/context-loader/app/depth/three/three/three.js b/test/fixtures/context-loader/app/depth/three/three/three.js index 59403649..c8697283 100644 --- a/test/fixtures/context-loader/app/depth/three/three/three.js +++ b/test/fixtures/context-loader/app/depth/three/three/three.js @@ -8,4 +8,4 @@ module.exports = class Three { get() { return this.ctx.name + ':three'; } -} +}; diff --git a/test/fixtures/context-loader/app/depth/two/two.js b/test/fixtures/context-loader/app/depth/two/two.js index 963e220c..8500f1ee 100644 --- a/test/fixtures/context-loader/app/depth/two/two.js +++ b/test/fixtures/context-loader/app/depth/two/two.js @@ -8,4 +8,4 @@ module.exports = class Two { get() { return this.ctx.name + ':two'; } -} +}; diff --git a/test/fixtures/context-loader/app/router.js b/test/fixtures/context-loader/app/router.js index 39ae70a3..59e8dc09 100644 --- a/test/fixtures/context-loader/app/router.js +++ b/test/fixtures/context-loader/app/router.js @@ -1,14 +1,14 @@ module.exports = app => { - app.get('/depth', async function() { + app.get('/depth', async function () { this.body = { one: this.depth.one.get(), two: this.depth.two.two.get(), three: this.depth.three.three.three.get(), four: this.depth.four.four.four.four.get(), - } + }; }); - app.get('/type', async function() { + app.get('/type', async function () { this.body = { class: this.type.class.get(), functionClass: this.type.functionClass.get(), @@ -19,22 +19,22 @@ module.exports = app => { }; }); - app.get('/service', async function() { + app.get('/service', async function () { this.body = { service1: this.service1.user.userInfo, service2: this.service2.user.userInfo, }; }); - app.get('/pathname', async function() { + app.get('/pathname', async function () { this.body = await this.pathname.a.b.c.getPathname(); }); - app.get('/config', async function() { + app.get('/config', async function () { this.body = await this.pathname.a.b.c.getName(); }); - app.get('/BaseContextClass/service', async function() { + app.get('/BaseContextClass/service', async function () { this.body = this.service.user.info; - }) + }); }; diff --git a/test/fixtures/context-loader/app/service/post.js b/test/fixtures/context-loader/app/service/post.js index 11d8284b..1ac233e7 100644 --- a/test/fixtures/context-loader/app/service/post.js +++ b/test/fixtures/context-loader/app/service/post.js @@ -1,8 +1,8 @@ 'use strict'; -module.exports = app => class UserService1 extends app.Service { - - get postInfo() { - return 'post'; - } -}; +module.exports = app => + class UserService1 extends app.Service { + get postInfo() { + return 'post'; + } + }; diff --git a/test/fixtures/context-loader/app/service/user.js b/test/fixtures/context-loader/app/service/user.js index 28a62c09..f9b29e52 100644 --- a/test/fixtures/context-loader/app/service/user.js +++ b/test/fixtures/context-loader/app/service/user.js @@ -1,9 +1,9 @@ 'use strict'; -module.exports = app => class UserService1 extends app.Service { - - get info() { - const post = this.service.post.postInfo; - return `user:${post}`; - } -}; +module.exports = app => + class UserService1 extends app.Service { + get info() { + const post = this.service.post.postInfo; + return `user:${post}`; + } + }; diff --git a/test/fixtures/context-loader/app/service1/user.js b/test/fixtures/context-loader/app/service1/user.js index 191f0618..1ecf144b 100644 --- a/test/fixtures/context-loader/app/service1/user.js +++ b/test/fixtures/context-loader/app/service1/user.js @@ -1,8 +1,8 @@ 'use strict'; -module.exports = app => class UserService1 extends app.Service { - - get userInfo() { - return 'service1'; - } -}; +module.exports = app => + class UserService1 extends app.Service { + get userInfo() { + return 'service1'; + } + }; diff --git a/test/fixtures/context-loader/app/service2/user.js b/test/fixtures/context-loader/app/service2/user.js index bd233d33..e883384b 100644 --- a/test/fixtures/context-loader/app/service2/user.js +++ b/test/fixtures/context-loader/app/service2/user.js @@ -1,8 +1,8 @@ 'use strict'; -module.exports = app => class UserService2 extends app.Service { - - get userInfo() { - return 'service2'; - } -}; +module.exports = app => + class UserService2 extends app.Service { + get userInfo() { + return 'service2'; + } + }; diff --git a/test/fixtures/context-loader/app/type/function-class.js b/test/fixtures/context-loader/app/type/function-class.js index 83c90567..e5671290 100644 --- a/test/fixtures/context-loader/app/type/function-class.js +++ b/test/fixtures/context-loader/app/type/function-class.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = app => ( +module.exports = app => class Service { constructor(ctx) { this.ctx = ctx; @@ -8,5 +8,4 @@ module.exports = app => ( get() { return this.ctx.name + ':' + app.config.name; } - } -); + }; diff --git a/test/fixtures/context-loader/app/type/generator.js b/test/fixtures/context-loader/app/type/generator.js index 466f7219..dda18c42 100644 --- a/test/fixtures/context-loader/app/type/generator.js +++ b/test/fixtures/context-loader/app/type/generator.js @@ -1,3 +1,3 @@ -module.exports = async function() { +module.exports = async function () { return 'generator'; }; diff --git a/test/fixtures/context-loader/app/type/object.js b/test/fixtures/context-loader/app/type/object.js index 833fe60d..43775072 100644 --- a/test/fixtures/context-loader/app/type/object.js +++ b/test/fixtures/context-loader/app/type/object.js @@ -3,5 +3,5 @@ module.exports = { get() { return 'object.get'; - } + }, }; diff --git a/test/fixtures/controller-app/app/controller/class.js b/test/fixtures/controller-app/app/controller/class.js index bcd2868d..786ce964 100644 --- a/test/fixtures/controller-app/app/controller/class.js +++ b/test/fixtures/controller-app/app/controller/class.js @@ -1,5 +1,4 @@ module.exports = class HomeController { - constructor(ctx) { this.ctx = ctx; } diff --git a/test/fixtures/controller-app/app/controller/class_inherited.js b/test/fixtures/controller-app/app/controller/class_inherited.js index a01875e6..e0f18dbf 100644 --- a/test/fixtures/controller-app/app/controller/class_inherited.js +++ b/test/fixtures/controller-app/app/controller/class_inherited.js @@ -18,4 +18,4 @@ module.exports = class HomeController extends BaseController { callOverriddenFunction() { this.ctx.body = 'own'; } -}; \ No newline at end of file +}; diff --git a/test/fixtures/controller-app/app/controller/function_attr.js b/test/fixtures/controller-app/app/controller/function_attr.js index c6879022..54aaa416 100644 --- a/test/fixtures/controller-app/app/controller/function_attr.js +++ b/test/fixtures/controller-app/app/controller/function_attr.js @@ -1,6 +1,6 @@ 'use strict'; -exports.getAccountInfo = async function() { +exports.getAccountInfo = async function () { const [name] = this.request.body || []; if (!name) { throw Error('please provide name'); @@ -11,7 +11,7 @@ exports.getAccountInfo = async function() { exports.getAccountInfo.operationType = true; exports.foo = { - bar: async function() { + bar: async function () { return 'account.foo.bar() is called!'; }, }; diff --git a/test/fixtures/controller-app/app/controller/generator_function.js b/test/fixtures/controller-app/app/controller/generator_function.js index 0fa485f6..f66beac0 100644 --- a/test/fixtures/controller-app/app/controller/generator_function.js +++ b/test/fixtures/controller-app/app/controller/generator_function.js @@ -1,3 +1,3 @@ -module.exports = async function() { +module.exports = async function () { this.body = 'done'; }; diff --git a/test/fixtures/controller-app/app/controller/generator_function_ctx.js b/test/fixtures/controller-app/app/controller/generator_function_ctx.js index 8d8dd863..a4bd37f3 100644 --- a/test/fixtures/controller-app/app/controller/generator_function_ctx.js +++ b/test/fixtures/controller-app/app/controller/generator_function_ctx.js @@ -1,5 +1,5 @@ 'use strict'; -module.exports = async function(ctx) { +module.exports = async function (ctx) { ctx.body = 'done'; }; diff --git a/test/fixtures/controller-app/app/controller/object.js b/test/fixtures/controller-app/app/controller/object.js index 29dd3c32..1b8fe434 100644 --- a/test/fixtures/controller-app/app/controller/object.js +++ b/test/fixtures/controller-app/app/controller/object.js @@ -32,5 +32,5 @@ module.exports = { get nofunction() { return 'done'; - } + }, }; diff --git a/test/fixtures/controller-app/app/controller/resource_class.js b/test/fixtures/controller-app/app/controller/resource_class.js index af067e19..b3ff1cee 100644 --- a/test/fixtures/controller-app/app/controller/resource_class.js +++ b/test/fixtures/controller-app/app/controller/resource_class.js @@ -2,7 +2,6 @@ module.exports = app => { return class Resource extends app.Controller { - async index(ctx) { ctx.body = 'index'; } diff --git a/test/fixtures/controller-app/app/controller/resource_object.js b/test/fixtures/controller-app/app/controller/resource_object.js index 02da039a..87f0946e 100644 --- a/test/fixtures/controller-app/app/controller/resource_object.js +++ b/test/fixtures/controller-app/app/controller/resource_object.js @@ -1,6 +1,6 @@ 'use strict'; -exports.index = async function() { +exports.index = async function () { this.body = 'index'; }; diff --git a/test/fixtures/controller-app/app/router.js b/test/fixtures/controller-app/app/router.js index 3ce48f2f..fb135d46 100644 --- a/test/fixtures/controller-app/app/router.js +++ b/test/fixtures/controller-app/app/router.js @@ -7,20 +7,35 @@ module.exports = app => { app.get('/object-function', 'object.callFunction'); app.get('/object-generator-function', 'object.callGeneratorFunction'); - app.get('/subObject-generator-function', 'object.subObject.callGeneratorFunction'); - app.get('/subSubObject-generator-function', 'object.subObject.subSubObject.callGeneratorFunction'); - app.get('/object-generator-function-arg', 'object.callGeneratorFunctionWithArg'); + app.get( + '/subObject-generator-function', + 'object.subObject.callGeneratorFunction' + ); + app.get( + '/subSubObject-generator-function', + 'object.subObject.subSubObject.callGeneratorFunction' + ); + app.get( + '/object-generator-function-arg', + 'object.callGeneratorFunctionWithArg' + ); app.get('/object-async-function', 'object.callAsyncFunction'); app.get('/object-async-function-arg', 'object.callAsyncFunctionWithArg'); app.get('/class-function', 'class.callFunction'); app.get('/class-generator-function', 'class.callGeneratorFunction'); - app.get('/class-generator-function-arg', 'class.callGeneratorFunctionWithArg'); + app.get( + '/class-generator-function-arg', + 'class.callGeneratorFunctionWithArg' + ); app.get('/class-async-function', 'class.callAsyncFunction'); app.get('/class-async-function-arg', 'class.callAsyncFunctionWithArg'); app.get('/class-inherited-function', 'classInherited.callInheritedFunction'); - app.get('/class-overridden-function', 'classInherited.callOverriddenFunction'); + app.get( + '/class-overridden-function', + 'classInherited.callOverriddenFunction' + ); app.get('/class-wrap-function', 'classWrapFunction.get'); app.get('/class-pathname', 'admin.config.getName'); diff --git a/test/fixtures/controller-next-argument/app/controller/home.js b/test/fixtures/controller-next-argument/app/controller/home.js index 5bdd668f..1bfda25c 100644 --- a/test/fixtures/controller-next-argument/app/controller/home.js +++ b/test/fixtures/controller-next-argument/app/controller/home.js @@ -1,6 +1,6 @@ 'use strict'; -exports.next = async function(next) { +exports.next = async function (next) { await next(); this.body = 'done'; }; diff --git a/test/fixtures/controller-params/app/controller/class.js b/test/fixtures/controller-params/app/controller/class.js index 99d07fe9..a289fd4b 100644 --- a/test/fixtures/controller-params/app/controller/class.js +++ b/test/fixtures/controller-params/app/controller/class.js @@ -1,7 +1,6 @@ 'use strict'; module.exports = class HomeController { - constructor(ctx) { this.ctx = ctx; } diff --git a/test/fixtures/controller-params/app/controller/generator_function.js b/test/fixtures/controller-params/app/controller/generator_function.js index 7f4d7f88..296cf1c3 100644 --- a/test/fixtures/controller-params/app/controller/generator_function.js +++ b/test/fixtures/controller-params/app/controller/generator_function.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = async function(...args) { +module.exports = async function (...args) { this.body = 'done'; return args; }; diff --git a/test/fixtures/custom-loader/app/repository/user.js b/test/fixtures/custom-loader/app/repository/user.js index 3b432f37..40013504 100644 --- a/test/fixtures/custom-loader/app/repository/user.js +++ b/test/fixtures/custom-loader/app/repository/user.js @@ -8,7 +8,6 @@ class UserRepository { async get() { return this.ctx.params.name; } - } module.exports = UserRepository; diff --git a/test/fixtures/custom-loader/app/util/sub/fn.js b/test/fixtures/custom-loader/app/util/sub/fn.js index b65b2df2..ef19299a 100644 --- a/test/fixtures/custom-loader/app/util/sub/fn.js +++ b/test/fixtures/custom-loader/app/util/sub/fn.js @@ -5,5 +5,5 @@ module.exports = app => { echo() { return `echo ${app.config.pkgName}`; }, - } + }; }; diff --git a/test/fixtures/custom_session_invaild/app/middleware/session.js b/test/fixtures/custom_session_invaild/app/middleware/session.js index 98b160d6..97ddb348 100644 --- a/test/fixtures/custom_session_invaild/app/middleware/session.js +++ b/test/fixtures/custom_session_invaild/app/middleware/session.js @@ -1,5 +1,5 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return {}; }; diff --git a/test/fixtures/custom_session_invaild/config/config.js b/test/fixtures/custom_session_invaild/config/config.js index f818471f..7ae79a0d 100644 --- a/test/fixtures/custom_session_invaild/config/config.js +++ b/test/fixtures/custom_session_invaild/config/config.js @@ -1,7 +1,5 @@ -exports.middleware = [ - 'session' -]; +exports.middleware = ['session']; exports.hsf = { - enable: false + enable: false, }; diff --git a/test/fixtures/dont-load-plugin/config/plugin.js b/test/fixtures/dont-load-plugin/config/plugin.js index 96eb8951..a06d160d 100644 --- a/test/fixtures/dont-load-plugin/config/plugin.js +++ b/test/fixtures/dont-load-plugin/config/plugin.js @@ -3,10 +3,10 @@ const path = require('path'); exports.testMe = { enable: true, env: ['local'], - path: path.join(__dirname, '../../../plugins/test-me') + path: path.join(__dirname, '../../../plugins/test-me'), }; exports.testMeAli = { enable: true, - path: path.join(__dirname, '../../../plugins/test-me-ali') + path: path.join(__dirname, '../../../plugins/test-me-ali'), }; diff --git a/test/fixtures/egg-esm/app/middleware/status.ts b/test/fixtures/egg-esm/app/middleware/status.ts index 74e29b77..93cbfd7b 100644 --- a/test/fixtures/egg-esm/app/middleware/status.ts +++ b/test/fixtures/egg-esm/app/middleware/status.ts @@ -1,4 +1,4 @@ -export default function() { +export default function () { return (ctx: any, next: any) => { ctx.traceId = `trace:${Date.now()}`; if (ctx.path === '/status') { @@ -8,4 +8,4 @@ export default function() { return next(); }; -}; +} diff --git a/test/fixtures/egg-esm/config/config.unittest.js b/test/fixtures/egg-esm/config/config.unittest.js index cef3da6f..6ce6f505 100644 --- a/test/fixtures/egg-esm/config/config.unittest.js +++ b/test/fixtures/egg-esm/config/config.unittest.js @@ -1,3 +1,3 @@ export default { egg: 'egg-unittest', -} +}; diff --git a/test/fixtures/egg-esm/index.ts b/test/fixtures/egg-esm/index.ts index a47efb03..e485f5cf 100644 --- a/test/fixtures/egg-esm/index.ts +++ b/test/fixtures/egg-esm/index.ts @@ -40,4 +40,3 @@ export class Application extends EggCore { } export { EggCoreInitOptions } from '../../../src/index.js'; - \ No newline at end of file diff --git a/test/fixtures/egg-esm/plugins/hsfclient/package.json b/test/fixtures/egg-esm/plugins/hsfclient/package.json index 3ec1b600..3e8b3a11 100644 --- a/test/fixtures/egg-esm/plugins/hsfclient/package.json +++ b/test/fixtures/egg-esm/plugins/hsfclient/package.json @@ -1,6 +1,10 @@ { "eggPlugin": { "name": "hsfclient", - "dep": ["eagleeye", "configclient", "diamond"] + "dep": [ + "eagleeye", + "configclient", + "diamond" + ] } } diff --git a/test/fixtures/egg-ts-js-tsconfig-paths/app/controller/test.ts b/test/fixtures/egg-ts-js-tsconfig-paths/app/controller/test.ts index e868e3f7..29ffa5f0 100644 --- a/test/fixtures/egg-ts-js-tsconfig-paths/app/controller/test.ts +++ b/test/fixtures/egg-ts-js-tsconfig-paths/app/controller/test.ts @@ -1,3 +1,3 @@ module.exports = async ctx => { ctx.body = 'ok'; -} \ No newline at end of file +}; diff --git a/test/fixtures/egg-ts-js-tsconfig-paths/app/extend/application.ts b/test/fixtures/egg-ts-js-tsconfig-paths/app/extend/application.ts index a867bb33..b6d5e550 100644 --- a/test/fixtures/egg-ts-js-tsconfig-paths/app/extend/application.ts +++ b/test/fixtures/egg-ts-js-tsconfig-paths/app/extend/application.ts @@ -1,3 +1,3 @@ module.exports = { - appExtend: 'hello' -} \ No newline at end of file + appExtend: 'hello', +}; diff --git a/test/fixtures/egg-ts-js-tsconfig-paths/app/service/lord.js b/test/fixtures/egg-ts-js-tsconfig-paths/app/service/lord.js index c9d1df43..ff6df944 100644 --- a/test/fixtures/egg-ts-js-tsconfig-paths/app/service/lord.js +++ b/test/fixtures/egg-ts-js-tsconfig-paths/app/service/lord.js @@ -2,4 +2,4 @@ module.exports = class LordService { jsService() { return 'from js service'; } -} \ No newline at end of file +}; diff --git a/test/fixtures/egg-ts-js-tsconfig-paths/app/service/test.ts b/test/fixtures/egg-ts-js-tsconfig-paths/app/service/test.ts index 96ac64eb..f97ba1b2 100644 --- a/test/fixtures/egg-ts-js-tsconfig-paths/app/service/test.ts +++ b/test/fixtures/egg-ts-js-tsconfig-paths/app/service/test.ts @@ -2,4 +2,4 @@ module.exports = class TestService { tsService() { return 'from ts service'; } -} \ No newline at end of file +}; diff --git a/test/fixtures/egg-ts-js/app/controller/test.ts b/test/fixtures/egg-ts-js/app/controller/test.ts index ac8f74b0..6e273497 100644 --- a/test/fixtures/egg-ts-js/app/controller/test.ts +++ b/test/fixtures/egg-ts-js/app/controller/test.ts @@ -1,3 +1,3 @@ module.exports = async (ctx: any) => { ctx.body = 'ok'; -} +}; diff --git a/test/fixtures/egg-ts-js/app/extend/application.ts b/test/fixtures/egg-ts-js/app/extend/application.ts index a867bb33..b6d5e550 100644 --- a/test/fixtures/egg-ts-js/app/extend/application.ts +++ b/test/fixtures/egg-ts-js/app/extend/application.ts @@ -1,3 +1,3 @@ module.exports = { - appExtend: 'hello' -} \ No newline at end of file + appExtend: 'hello', +}; diff --git a/test/fixtures/egg-ts-js/app/service/lord.js b/test/fixtures/egg-ts-js/app/service/lord.js index c9d1df43..ff6df944 100644 --- a/test/fixtures/egg-ts-js/app/service/lord.js +++ b/test/fixtures/egg-ts-js/app/service/lord.js @@ -2,4 +2,4 @@ module.exports = class LordService { jsService() { return 'from js service'; } -} \ No newline at end of file +}; diff --git a/test/fixtures/egg-ts-js/app/service/test.ts b/test/fixtures/egg-ts-js/app/service/test.ts index 96ac64eb..f97ba1b2 100644 --- a/test/fixtures/egg-ts-js/app/service/test.ts +++ b/test/fixtures/egg-ts-js/app/service/test.ts @@ -2,4 +2,4 @@ module.exports = class TestService { tsService() { return 'from ts service'; } -} \ No newline at end of file +}; diff --git a/test/fixtures/egg-ts/app/controller/home.ts b/test/fixtures/egg-ts/app/controller/home.ts index 6cfecb56..d2aea1b2 100644 --- a/test/fixtures/egg-ts/app/controller/home.ts +++ b/test/fixtures/egg-ts/app/controller/home.ts @@ -13,6 +13,6 @@ module.exports = async (ctx: any) => { ctx.app.config.test, ctx.app.config.testFromA, ctx.mid, - serviceText + serviceText, ].join(','); -} +}; diff --git a/test/fixtures/egg-ts/app/extend/agent.ts b/test/fixtures/egg-ts/app/extend/agent.ts index 48f7a077..76125a9e 100644 --- a/test/fixtures/egg-ts/app/extend/agent.ts +++ b/test/fixtures/egg-ts/app/extend/agent.ts @@ -1,5 +1,5 @@ module.exports = { agentShow() { return 'from extend agent'; - } -} \ No newline at end of file + }, +}; diff --git a/test/fixtures/egg-ts/app/extend/application.ts b/test/fixtures/egg-ts/app/extend/application.ts index f08d3b3f..058e6c29 100644 --- a/test/fixtures/egg-ts/app/extend/application.ts +++ b/test/fixtures/egg-ts/app/extend/application.ts @@ -1,5 +1,5 @@ module.exports = { applicationShow() { return 'from extend application'; - } -} \ No newline at end of file + }, +}; diff --git a/test/fixtures/egg-ts/app/extend/context.ts b/test/fixtures/egg-ts/app/extend/context.ts index 99624e1e..8885fe79 100644 --- a/test/fixtures/egg-ts/app/extend/context.ts +++ b/test/fixtures/egg-ts/app/extend/context.ts @@ -1,5 +1,5 @@ module.exports = { contextShow() { return 'from extend context'; - } -} \ No newline at end of file + }, +}; diff --git a/test/fixtures/egg-ts/app/extend/helper.ts b/test/fixtures/egg-ts/app/extend/helper.ts index 1f7209d6..25ad2ce2 100644 --- a/test/fixtures/egg-ts/app/extend/helper.ts +++ b/test/fixtures/egg-ts/app/extend/helper.ts @@ -1,5 +1,5 @@ module.exports = { helperShow() { return 'from extend helper'; - } -} \ No newline at end of file + }, +}; diff --git a/test/fixtures/egg-ts/app/extend/request.ts b/test/fixtures/egg-ts/app/extend/request.ts index 5672f9bc..09edeaad 100644 --- a/test/fixtures/egg-ts/app/extend/request.ts +++ b/test/fixtures/egg-ts/app/extend/request.ts @@ -1,5 +1,5 @@ module.exports = { requestShow() { return 'from extend request'; - } -} \ No newline at end of file + }, +}; diff --git a/test/fixtures/egg-ts/app/extend/response.ts b/test/fixtures/egg-ts/app/extend/response.ts index 21a270d8..babd7236 100644 --- a/test/fixtures/egg-ts/app/extend/response.ts +++ b/test/fixtures/egg-ts/app/extend/response.ts @@ -1,5 +1,5 @@ module.exports = { responseShow() { return 'from extend response'; - } -} \ No newline at end of file + }, +}; diff --git a/test/fixtures/egg-ts/app/middleware/mid.ts b/test/fixtures/egg-ts/app/middleware/mid.ts index e967cbee..e94004d4 100644 --- a/test/fixtures/egg-ts/app/middleware/mid.ts +++ b/test/fixtures/egg-ts/app/middleware/mid.ts @@ -2,5 +2,5 @@ export default () => { return async (ctx: any, next: any) => { ctx.mid = 'from middleware'; await next(); - } -} + }; +}; diff --git a/test/fixtures/egg-ts/app/router.ts b/test/fixtures/egg-ts/app/router.ts index d90bdec9..a11969ad 100644 --- a/test/fixtures/egg-ts/app/router.ts +++ b/test/fixtures/egg-ts/app/router.ts @@ -1,4 +1,4 @@ module.exports = (app: any) => { const { router, controller } = app; router.get('/', controller.home); -} +}; diff --git a/test/fixtures/egg-ts/app/service/Test.ts b/test/fixtures/egg-ts/app/service/Test.ts index 8da345f7..a33d21fd 100644 --- a/test/fixtures/egg-ts/app/service/Test.ts +++ b/test/fixtures/egg-ts/app/service/Test.ts @@ -2,4 +2,4 @@ module.exports = class TestService { getTest() { return 'from service'; } -} \ No newline at end of file +}; diff --git a/test/fixtures/egg-ts/config/config.default.ts b/test/fixtures/egg-ts/config/config.default.ts index bc4c4552..bfcb391a 100644 --- a/test/fixtures/egg-ts/config/config.default.ts +++ b/test/fixtures/egg-ts/config/config.default.ts @@ -1,6 +1,6 @@ module.exports = () => { return { - middleware: [ 'mid' ], + middleware: ['mid'], test: 'from config.default', }; -} \ No newline at end of file +}; diff --git a/test/fixtures/egg-ts/config/plugin.ts b/test/fixtures/egg-ts/config/plugin.ts index 917b0963..60cc4e67 100644 --- a/test/fixtures/egg-ts/config/plugin.ts +++ b/test/fixtures/egg-ts/config/plugin.ts @@ -3,5 +3,5 @@ const path = require('path'); module.exports = { a: { path: path.resolve(__dirname, '../plugins/a'), - } -} \ No newline at end of file + }, +}; diff --git a/test/fixtures/egg-ts/plugins/a/config/config.default.ts b/test/fixtures/egg-ts/plugins/a/config/config.default.ts index 6878f7f3..06fd68c2 100644 --- a/test/fixtures/egg-ts/plugins/a/config/config.default.ts +++ b/test/fixtures/egg-ts/plugins/a/config/config.default.ts @@ -2,4 +2,4 @@ module.exports = () => { return { testFromA: 'from plugins', }; -} +}; diff --git a/test/fixtures/egg/app/middleware/status.ts b/test/fixtures/egg/app/middleware/status.ts index 74e29b77..93cbfd7b 100644 --- a/test/fixtures/egg/app/middleware/status.ts +++ b/test/fixtures/egg/app/middleware/status.ts @@ -1,4 +1,4 @@ -export default function() { +export default function () { return (ctx: any, next: any) => { ctx.traceId = `trace:${Date.now()}`; if (ctx.path === '/status') { @@ -8,4 +8,4 @@ export default function() { return next(); }; -}; +} diff --git a/test/fixtures/egg/plugins/hsfclient/package.json b/test/fixtures/egg/plugins/hsfclient/package.json index 3ec1b600..3e8b3a11 100644 --- a/test/fixtures/egg/plugins/hsfclient/package.json +++ b/test/fixtures/egg/plugins/hsfclient/package.json @@ -1,6 +1,10 @@ { "eggPlugin": { "name": "hsfclient", - "dep": ["eagleeye", "configclient", "diamond"] + "dep": [ + "eagleeye", + "configclient", + "diamond" + ] } } diff --git a/test/fixtures/extend-with-class/app/controller/home.js b/test/fixtures/extend-with-class/app/controller/home.js index 68be9621..8911834c 100644 --- a/test/fixtures/extend-with-class/app/controller/home.js +++ b/test/fixtures/extend-with-class/app/controller/home.js @@ -1,4 +1,4 @@ -export default async function() { +export default async function () { const status = Number(this.query.status || 200); this.status = status; this.etag = '2.2.2.2'; @@ -10,4 +10,4 @@ export default async function() { status: this.status, etag: this.etag, }; -}; +} diff --git a/test/fixtures/extend-with-class/app/extend/application.js b/test/fixtures/extend-with-class/app/extend/application.js index f8e99e20..6f3eabf5 100644 --- a/test/fixtures/extend-with-class/app/extend/application.js +++ b/test/fixtures/extend-with-class/app/extend/application.js @@ -1,7 +1,7 @@ -import { EggCore } from '../../../../../src/index.js' +import { EggCore } from '../../../../../src/index.js'; export default class Application extends EggCore { get appApplication() { return 'app application'; } -}; +} diff --git a/test/fixtures/extend-with-class/app/extend/context.js b/test/fixtures/extend-with-class/app/extend/context.js index 4abeccd0..1ef81c58 100644 --- a/test/fixtures/extend-with-class/app/extend/context.js +++ b/test/fixtures/extend-with-class/app/extend/context.js @@ -1,4 +1,4 @@ -import { Context } from '../../../../../src/index.js' +import { Context } from '../../../../../src/index.js'; export default class MyContext extends Context { get appContext() { diff --git a/test/fixtures/extend-with-class/app/extend/request.js b/test/fixtures/extend-with-class/app/extend/request.js index 1ed931b0..0ff3160e 100644 --- a/test/fixtures/extend-with-class/app/extend/request.js +++ b/test/fixtures/extend-with-class/app/extend/request.js @@ -1,4 +1,4 @@ -import { Request } from '../../../../../src/index.js' +import { Request } from '../../../../../src/index.js'; export default class AppRequest extends Request { get appRequest() { diff --git a/test/fixtures/extend-with-class/app/extend/response.js b/test/fixtures/extend-with-class/app/extend/response.js index e380911d..e0259b8b 100644 --- a/test/fixtures/extend-with-class/app/extend/response.js +++ b/test/fixtures/extend-with-class/app/extend/response.js @@ -1,4 +1,4 @@ -import { Response } from '../../../../../src/index.js' +import { Response } from '../../../../../src/index.js'; export default class AppResponse extends Response { get appResponse() { diff --git a/test/fixtures/extend-with-class/app/router.js b/test/fixtures/extend-with-class/app/router.js index f98396bc..eba09909 100644 --- a/test/fixtures/extend-with-class/app/router.js +++ b/test/fixtures/extend-with-class/app/router.js @@ -1,3 +1,3 @@ -export default (app) => { +export default app => { app.get('/', app.controller.home); }; diff --git a/test/fixtures/extend/app/controller/home.js b/test/fixtures/extend/app/controller/home.js index b01802cc..2e63991d 100644 --- a/test/fixtures/extend/app/controller/home.js +++ b/test/fixtures/extend/app/controller/home.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = async function() { +module.exports = async function () { const status = Number(this.query.status || 200); this.status = status; this.etag = '2.2.2.2'; diff --git a/test/fixtures/extend/app/controller/merge.js b/test/fixtures/extend/app/controller/merge.js index 15ef4192..6ac056bf 100644 --- a/test/fixtures/extend/app/controller/merge.js +++ b/test/fixtures/extend/app/controller/merge.js @@ -1,17 +1,17 @@ -exports.appOverrideChair = async function() { +exports.appOverrideChair = async function () { this.body = { - value: this.ajax() + value: this.ajax(), }; }; -exports.pluginOverrideChair = async function() { +exports.pluginOverrideChair = async function () { this.body = { - value: this.ip + value: this.ip, }; }; -exports.appOverridePlugin = async function() { +exports.appOverridePlugin = async function () { this.body = { - value: this.response.overridePlugin + value: this.response.overridePlugin, }; }; diff --git a/test/fixtures/extend/app/extend/context.js b/test/fixtures/extend/app/extend/context.js index 45d0a389..1bfb88e7 100644 --- a/test/fixtures/extend/app/extend/context.js +++ b/test/fixtures/extend/app/extend/context.js @@ -5,7 +5,7 @@ module.exports = { return 'app context'; }, - ajax: function() { + ajax: function () { return 'app ajax patch'; - } + }, }; diff --git a/test/fixtures/extend/app/router.js b/test/fixtures/extend/app/router.js index 549ce787..794cf99b 100644 --- a/test/fixtures/extend/app/router.js +++ b/test/fixtures/extend/app/router.js @@ -1,9 +1,12 @@ 'use strict'; -module.exports = function(app) { +module.exports = function (app) { app.get('/', app.controller.home); app.get('/merge/app_override_chair', app.controller.merge.appOverrideChair); app.get('/merge/app_override_plugin', app.controller.merge.appOverridePlugin); - app.get('/merge/plugin_override_chair', app.controller.merge.pluginOverrideChair); + app.get( + '/merge/plugin_override_chair', + app.controller.merge.pluginOverrideChair + ); }; diff --git a/test/fixtures/extend/config/plugin.js b/test/fixtures/extend/config/plugin.js index a32c0ebc..b6f8ae62 100644 --- a/test/fixtures/extend/config/plugin.js +++ b/test/fixtures/extend/config/plugin.js @@ -3,5 +3,5 @@ module.exports = { a: false, - b: true + b: true, }; diff --git a/test/fixtures/extends-app-service/app/controller/user.js b/test/fixtures/extends-app-service/app/controller/user.js index 287c7e1e..b83457d6 100644 --- a/test/fixtures/extends-app-service/app/controller/user.js +++ b/test/fixtures/extends-app-service/app/controller/user.js @@ -1,4 +1,4 @@ -module.exports = async function() { +module.exports = async function () { this.body = { user: await this.service.user.get('123'), }; diff --git a/test/fixtures/framework-nosymbol/index.js b/test/fixtures/framework-nosymbol/index.js index 2b3a5d72..392a3182 100644 --- a/test/fixtures/framework-nosymbol/index.js +++ b/test/fixtures/framework-nosymbol/index.js @@ -2,7 +2,6 @@ const EggApplication = require('../egg').Application; - class Application extends EggApplication { get a() {} } diff --git a/test/fixtures/framework-symbol/index.js b/test/fixtures/framework-symbol/index.js index 07fd003d..0b9fc334 100644 --- a/test/fixtures/framework-symbol/index.js +++ b/test/fixtures/framework-symbol/index.js @@ -3,7 +3,6 @@ const Application = require('framework2'); class Framework extends Application { - constructor(options) { super(options); } @@ -11,7 +10,6 @@ class Framework extends Application { get [Symbol.for('egg#eggPath')]() { return __dirname; } - } module.exports = Framework; diff --git a/test/fixtures/helloworld-ts/app/controller/foo.js b/test/fixtures/helloworld-ts/app/controller/foo.js index 6fef5713..152098b5 100644 --- a/test/fixtures/helloworld-ts/app/controller/foo.js +++ b/test/fixtures/helloworld-ts/app/controller/foo.js @@ -1,13 +1,13 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); class FooController { - async render() { - const ctx = this.ctx; - ctx.status = 400; - ctx.body = { - foo: 'bar', - }; - } + async render() { + const ctx = this.ctx; + ctx.status = 400; + ctx.body = { + foo: 'bar', + }; + } } exports.default = FooController; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiZm9vLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsNkJBQWlDO0FBRWpDLE1BQXFCLGFBQWMsU0FBUSxnQkFBVTtJQUNuRCxLQUFLLENBQUMsTUFBTTtRQUNWLE1BQU0sR0FBRyxHQUFHLElBQUksQ0FBQyxHQUFHLENBQUM7UUFDckIsR0FBRyxDQUFDLE1BQU0sR0FBRyxHQUFHLENBQUM7UUFDakIsR0FBRyxDQUFDLElBQUksR0FBRztZQUNULEdBQUcsRUFBRSxLQUFLO1NBQ1gsQ0FBQztJQUNKLENBQUM7Q0FDRjtBQVJELGdDQVFDIn0= diff --git a/test/fixtures/helloworld-ts/app/controller/foo.ts b/test/fixtures/helloworld-ts/app/controller/foo.ts index 818ca61a..fff79e38 100644 --- a/test/fixtures/helloworld-ts/app/controller/foo.ts +++ b/test/fixtures/helloworld-ts/app/controller/foo.ts @@ -1,4 +1,3 @@ export default class FooController { - async render() { - } + async render() {} } diff --git a/test/fixtures/helloworld-ts/app/router.js b/test/fixtures/helloworld-ts/app/router.js index 0aa3b9db..9d5743ee 100644 --- a/test/fixtures/helloworld-ts/app/router.js +++ b/test/fixtures/helloworld-ts/app/router.js @@ -1,7 +1,7 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = (app) => { - app.router.get('/', async (ctx) => { - ctx.body = 'Hello World'; - }); +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); +exports.default = app => { + app.router.get('/', async ctx => { + ctx.body = 'Hello World'; + }); }; diff --git a/test/fixtures/helloworld-ts/config/config.default.js b/test/fixtures/helloworld-ts/config/config.default.js index 592d7186..e20094d6 100644 --- a/test/fixtures/helloworld-ts/config/config.default.js +++ b/test/fixtures/helloworld-ts/config/config.default.js @@ -1,5 +1,5 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); +'use strict'; +Object.defineProperty(exports, '__esModule', { value: true }); exports.default = { - keys: 'my secret keys', + keys: 'my secret keys', }; diff --git a/test/fixtures/helloworld-ts/test/index.test.ts b/test/fixtures/helloworld-ts/test/index.test.ts index 5252564d..762c748c 100644 --- a/test/fixtures/helloworld-ts/test/index.test.ts +++ b/test/fixtures/helloworld-ts/test/index.test.ts @@ -2,18 +2,12 @@ import { app } from '@eggjs/mock/bootstrap'; describe('example helloworld test', () => { it('should GET / 200', () => { - return app.httpRequest() - .get('/') - .expect(200) - .expect('Hello World'); + return app.httpRequest().get('/').expect(200).expect('Hello World'); }); it('should GET /foo', async () => { - await app.httpRequest() - .get('/foo') - .expect(400) - .expect({ - foo: 'bar', - }); + await app.httpRequest().get('/foo').expect(400).expect({ + foo: 'bar', + }); }); }); diff --git a/test/fixtures/helloworld-ts/tsconfig.json b/test/fixtures/helloworld-ts/tsconfig.json index 480e95d5..87a8b4ab 100644 --- a/test/fixtures/helloworld-ts/tsconfig.json +++ b/test/fixtures/helloworld-ts/tsconfig.json @@ -8,7 +8,5 @@ "moduleResolution": "NodeNext", "declaration": false }, - "exclude": [ - "test" - ] + "exclude": ["test"] } diff --git a/test/fixtures/helper/app/controller/home.js b/test/fixtures/helper/app/controller/home.js index 2c4f2525..efde820e 100644 --- a/test/fixtures/helper/app/controller/home.js +++ b/test/fixtures/helper/app/controller/home.js @@ -1,4 +1,4 @@ -module.exports = async function() { +module.exports = async function () { try { this.body = ` app: ${this.helper.exists(this.helper.app)} @@ -7,7 +7,7 @@ module.exports = async function() { override: ${this.helper.override()} not exists on locals: ${this.helper.exists(this.notExistsApp)} `; - } catch(e) { + } catch (e) { console.log(e); } -} +}; diff --git a/test/fixtures/helper/app/extend/helper.js b/test/fixtures/helper/app/extend/helper.js index d6dcb653..a469a5c7 100644 --- a/test/fixtures/helper/app/extend/helper.js +++ b/test/fixtures/helper/app/extend/helper.js @@ -1,11 +1,11 @@ -exports.app = function() { +exports.app = function () { return 'app'; }; -exports.override = function() { +exports.override = function () { return 'app'; }; -exports.exists = function(obj) { +exports.exists = function (obj) { return obj !== undefined; }; diff --git a/test/fixtures/helper/app/router.js b/test/fixtures/helper/app/router.js index 0791f319..e599cfb4 100644 --- a/test/fixtures/helper/app/router.js +++ b/test/fixtures/helper/app/router.js @@ -1,3 +1,3 @@ -module.exports = function(app) { +module.exports = function (app) { app.get('/', app.controller.home); }; diff --git a/test/fixtures/load-plugin-by-env/config/plugin.custom.js b/test/fixtures/load-plugin-by-env/config/plugin.custom.js index 46419f0a..3a87d119 100644 --- a/test/fixtures/load-plugin-by-env/config/plugin.custom.js +++ b/test/fixtures/load-plugin-by-env/config/plugin.custom.js @@ -5,4 +5,4 @@ const path = require('path'); exports.c = { enable: true, path: path.join(__dirname, '../plugins/c'), -} +}; diff --git a/test/fixtures/load-plugin-by-env/config/plugin.js b/test/fixtures/load-plugin-by-env/config/plugin.js index ef9b5024..5cf8a060 100644 --- a/test/fixtures/load-plugin-by-env/config/plugin.js +++ b/test/fixtures/load-plugin-by-env/config/plugin.js @@ -5,4 +5,4 @@ const path = require('path'); exports.a = { enable: true, path: path.join(__dirname, '../plugins/a'), -} +}; diff --git a/test/fixtures/load-plugin-by-env/config/plugin.unittest.js b/test/fixtures/load-plugin-by-env/config/plugin.unittest.js index 1fefc15b..1ca4c71b 100644 --- a/test/fixtures/load-plugin-by-env/config/plugin.unittest.js +++ b/test/fixtures/load-plugin-by-env/config/plugin.unittest.js @@ -7,4 +7,4 @@ exports.a = false; exports.b = { enable: true, path: path.join(__dirname, '../plugins/b'), -} +}; diff --git a/test/fixtures/load-plugin-default/config/plugin.default.js b/test/fixtures/load-plugin-default/config/plugin.default.js index 46419f0a..3a87d119 100644 --- a/test/fixtures/load-plugin-default/config/plugin.default.js +++ b/test/fixtures/load-plugin-default/config/plugin.default.js @@ -5,4 +5,4 @@ const path = require('path'); exports.c = { enable: true, path: path.join(__dirname, '../plugins/c'), -} +}; diff --git a/test/fixtures/load-plugin-default/config/plugin.js b/test/fixtures/load-plugin-default/config/plugin.js index ef9b5024..5cf8a060 100644 --- a/test/fixtures/load-plugin-default/config/plugin.js +++ b/test/fixtures/load-plugin-default/config/plugin.js @@ -5,4 +5,4 @@ const path = require('path'); exports.a = { enable: true, path: path.join(__dirname, '../plugins/a'), -} +}; diff --git a/test/fixtures/load-plugin-default/config/plugin.unittest.js b/test/fixtures/load-plugin-default/config/plugin.unittest.js index 0197bd53..b016c089 100644 --- a/test/fixtures/load-plugin-default/config/plugin.unittest.js +++ b/test/fixtures/load-plugin-default/config/plugin.unittest.js @@ -5,4 +5,4 @@ const path = require('path'); exports.b = { enable: true, path: path.join(__dirname, '../plugins/b'), -} +}; diff --git a/test/fixtures/load_context_error/app/extend/context.js b/test/fixtures/load_context_error/app/extend/context.js index 017454f1..d0116e6b 100644 --- a/test/fixtures/load_context_error/app/extend/context.js +++ b/test/fixtures/load_context_error/app/extend/context.js @@ -1,6 +1,5 @@ 'use strict'; require('this is a pen'); -exports.customCon = function * () { +exports.customCon = function* () { this.body = 'test'; }; - diff --git a/test/fixtures/load_dirs/babel/UserProxy.js b/test/fixtures/load_dirs/babel/UserProxy.js index 43d20a85..290f8a21 100644 --- a/test/fixtures/load_dirs/babel/UserProxy.js +++ b/test/fixtures/load_dirs/babel/UserProxy.js @@ -2,31 +2,70 @@ var _temporalUndefined = {}; -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); +var _createClass = (function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ('value' in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; +})(); var UserProxy = _temporalUndefined; -function _temporalAssertDefined(val, name, undef) { if (val === undef) { throw new ReferenceError(name + ' is not defined - temporal dead zone'); } return true; } +function _temporalAssertDefined(val, name, undef) { + if (val === undef) { + throw new ReferenceError(name + ' is not defined - temporal dead zone'); + } + return true; +} -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError('Cannot call a class as a function'); + } +} UserProxy = (function () { function UserProxy() { - _classCallCheck(this, _temporalAssertDefined(UserProxy, 'UserProxy', _temporalUndefined) && UserProxy); + _classCallCheck( + this, + _temporalAssertDefined(UserProxy, 'UserProxy', _temporalUndefined) && + UserProxy + ); this.user = { - name: 'xiaochen.gaoxc' + name: 'xiaochen.gaoxc', }; } - _createClass(_temporalAssertDefined(UserProxy, 'UserProxy', _temporalUndefined) && UserProxy, [{ - key: 'getUser', - value: function getUser() { - return this.user; - } - }]); + _createClass( + _temporalAssertDefined(UserProxy, 'UserProxy', _temporalUndefined) && + UserProxy, + [ + { + key: 'getUser', + value: function getUser() { + return this.user; + }, + }, + ] + ); - return _temporalAssertDefined(UserProxy, 'UserProxy', _temporalUndefined) && UserProxy; + return ( + _temporalAssertDefined(UserProxy, 'UserProxy', _temporalUndefined) && + UserProxy + ); })(); -module.exports = _temporalAssertDefined(UserProxy, 'UserProxy', _temporalUndefined) && UserProxy; \ No newline at end of file +module.exports = + _temporalAssertDefined(UserProxy, 'UserProxy', _temporalUndefined) && + UserProxy; diff --git a/test/fixtures/load_dirs/dao/TestClass.js b/test/fixtures/load_dirs/dao/TestClass.js index e097d78c..9d813919 100644 --- a/test/fixtures/load_dirs/dao/TestClass.js +++ b/test/fixtures/load_dirs/dao/TestClass.js @@ -8,4 +8,4 @@ module.exports = class TestClass { this.app = app; this.path = fullpath; } -} +}; diff --git a/test/fixtures/load_dirs/dao/testFunction.js b/test/fixtures/load_dirs/dao/testFunction.js index 57d482dc..e4142f8b 100644 --- a/test/fixtures/load_dirs/dao/testFunction.js +++ b/test/fixtures/load_dirs/dao/testFunction.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function(obj) { +module.exports = function (obj) { return { user: { name: 'kai.fangk', diff --git a/test/fixtures/load_dirs/dao/testReturnFunction.js b/test/fixtures/load_dirs/dao/testReturnFunction.js index 980f4967..a7393ebe 100644 --- a/test/fixtures/load_dirs/dao/testReturnFunction.js +++ b/test/fixtures/load_dirs/dao/testReturnFunction.js @@ -1,11 +1,11 @@ 'use strict'; -module.exports = function(obj) { - return function() { +module.exports = function (obj) { + return function () { return { user: { name: 'kai.fangk', }, - } + }; }; }; diff --git a/test/fixtures/load_dirs/es6_module/mod.js b/test/fixtures/load_dirs/es6_module/mod.js index fc64c89c..6e5c71a4 100644 --- a/test/fixtures/load_dirs/es6_module/mod.js +++ b/test/fixtures/load_dirs/es6_module/mod.js @@ -1,6 +1,6 @@ 'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = function() { +Object.defineProperty(exports, '__esModule', { value: true }); +exports.default = function () { return { a: 1 }; }; diff --git a/test/fixtures/load_dirs/filter/arr.js b/test/fixtures/load_dirs/filter/arr.js index 6f2c8d3e..aacbf518 100644 --- a/test/fixtures/load_dirs/filter/arr.js +++ b/test/fixtures/load_dirs/filter/arr.js @@ -1,3 +1,3 @@ 'use strict'; -module.exports = [ '1' ]; +module.exports = ['1']; diff --git a/test/fixtures/load_dirs/filter/class.js b/test/fixtures/load_dirs/filter/class.js index f611b053..8ddfa781 100644 --- a/test/fixtures/load_dirs/filter/class.js +++ b/test/fixtures/load_dirs/filter/class.js @@ -1,3 +1,3 @@ 'use strict'; -module.exports = class User {} +module.exports = class User {}; diff --git a/test/fixtures/load_dirs/ignore/a.js b/test/fixtures/load_dirs/ignore/a.js index d3ccb9a4..dcbd51f9 100644 --- a/test/fixtures/load_dirs/ignore/a.js +++ b/test/fixtures/load_dirs/ignore/a.js @@ -1,3 +1,3 @@ -module.exports = function() { +module.exports = function () { return { a: 1 }; }; diff --git a/test/fixtures/load_dirs/ignore/util/a.js b/test/fixtures/load_dirs/ignore/util/a.js index aa55c2a1..8711334c 100644 --- a/test/fixtures/load_dirs/ignore/util/a.js +++ b/test/fixtures/load_dirs/ignore/util/a.js @@ -1,4 +1,3 @@ module.exports = { - method1: function() { - } + method1: function () {}, }; diff --git a/test/fixtures/load_dirs/lowercase/SomeClass.js b/test/fixtures/load_dirs/lowercase/SomeClass.js index 3dcf1151..4a53e6b8 100644 --- a/test/fixtures/load_dirs/lowercase/SomeClass.js +++ b/test/fixtures/load_dirs/lowercase/SomeClass.js @@ -1,5 +1,5 @@ exports.getByName = function (name, callback) { setTimeout(function () { - callback(null, {name: name}); + callback(null, { name: name }); }, 1); -}; \ No newline at end of file +}; diff --git a/test/fixtures/load_dirs/lowercase/SomeDir/SomeSubClass.js b/test/fixtures/load_dirs/lowercase/SomeDir/SomeSubClass.js index 3dcf1151..4a53e6b8 100644 --- a/test/fixtures/load_dirs/lowercase/SomeDir/SomeSubClass.js +++ b/test/fixtures/load_dirs/lowercase/SomeDir/SomeSubClass.js @@ -1,5 +1,5 @@ exports.getByName = function (name, callback) { setTimeout(function () { - callback(null, {name: name}); + callback(null, { name: name }); }, 1); -}; \ No newline at end of file +}; diff --git a/test/fixtures/load_dirs/services/dir/service.js b/test/fixtures/load_dirs/services/dir/service.js index a56b9112..c626bf5a 100644 --- a/test/fixtures/load_dirs/services/dir/service.js +++ b/test/fixtures/load_dirs/services/dir/service.js @@ -1,6 +1,6 @@ module.exports = function (app) { return { load: true, - app: app + app: app, }; }; diff --git a/test/fixtures/load_dirs/services/foo_service.js b/test/fixtures/load_dirs/services/foo_service.js index fcfdfc09..0743fcca 100644 --- a/test/fixtures/load_dirs/services/foo_service.js +++ b/test/fixtures/load_dirs/services/foo_service.js @@ -1,5 +1,5 @@ -module.exports = function(obj) { +module.exports = function (obj) { return { - a: 1 + a: 1, }; }; diff --git a/test/fixtures/load_dirs/services/userProfile.js b/test/fixtures/load_dirs/services/userProfile.js index 39c4fc32..d95388eb 100644 --- a/test/fixtures/load_dirs/services/userProfile.js +++ b/test/fixtures/load_dirs/services/userProfile.js @@ -14,9 +14,8 @@ * Module dependencies. */ - exports.getByName = function (name, callback) { setTimeout(function () { - callback(null, {name: name}); + callback(null, { name: name }); }, 1); }; diff --git a/test/fixtures/load_dirs/ts_module/mod.ts b/test/fixtures/load_dirs/ts_module/mod.ts index e58598cb..e9b7e0e5 100644 --- a/test/fixtures/load_dirs/ts_module/mod.ts +++ b/test/fixtures/load_dirs/ts_module/mod.ts @@ -1,3 +1,3 @@ -export default function() { +export default function () { return { a: 1 }; } diff --git a/test/fixtures/load_dirs/ts_module/mod3.ts b/test/fixtures/load_dirs/ts_module/mod3.ts index 7790b3c4..9bb7301f 100644 --- a/test/fixtures/load_dirs/ts_module/mod3.ts +++ b/test/fixtures/load_dirs/ts_module/mod3.ts @@ -1,4 +1,4 @@ export default { ok: true, foo: 'bar', -} +}; diff --git a/test/fixtures/load_dirs/yml/config.yml b/test/fixtures/load_dirs/yml/config.yml index e40ed4fe..e7ab8da9 100644 --- a/test/fixtures/load_dirs/yml/config.yml +++ b/test/fixtures/load_dirs/yml/config.yml @@ -1,4 +1,4 @@ --- map: a: 1 - b: 2 \ No newline at end of file + b: 2 diff --git a/test/fixtures/load_file/async.js b/test/fixtures/load_file/async.js index 1e36c648..7c9fd787 100644 --- a/test/fixtures/load_file/async.js +++ b/test/fixtures/load_file/async.js @@ -1,5 +1,5 @@ -"use strict"; +'use strict'; module.exports = async () => { - return { clients: "Test Config" }; + return { clients: 'Test Config' }; }; diff --git a/test/fixtures/load_file/es-module-default-async.js b/test/fixtures/load_file/es-module-default-async.js index 4c3109c3..5bfea8bd 100644 --- a/test/fixtures/load_file/es-module-default-async.js +++ b/test/fixtures/load_file/es-module-default-async.js @@ -1,5 +1,5 @@ -"use strict"; +'use strict'; exports.__esModule = true; -exports["default"] = async function () { - return { clients: "Test Config" }; +exports['default'] = async function () { + return { clients: 'Test Config' }; }; diff --git a/test/fixtures/load_file/es-module-default-null.js b/test/fixtures/load_file/es-module-default-null.js index fb3c8922..4be65cae 100644 --- a/test/fixtures/load_file/es-module-default-null.js +++ b/test/fixtures/load_file/es-module-default-null.js @@ -1,3 +1,3 @@ -"use strict"; +'use strict'; exports.__esModule = true; -exports["default"] = null; +exports['default'] = null; diff --git a/test/fixtures/load_file/es-module-default-promise.js b/test/fixtures/load_file/es-module-default-promise.js index ed59b0e4..ff7fff75 100644 --- a/test/fixtures/load_file/es-module-default-promise.js +++ b/test/fixtures/load_file/es-module-default-promise.js @@ -1,5 +1,5 @@ -"use strict"; +'use strict'; exports.__esModule = true; -exports["default"] = function () { - return Promise.resolve({ clients: "Test Config" }); +exports['default'] = function () { + return Promise.resolve({ clients: 'Test Config' }); }; diff --git a/test/fixtures/load_file/es-module-default.js b/test/fixtures/load_file/es-module-default.js index 665cac36..13560177 100644 --- a/test/fixtures/load_file/es-module-default.js +++ b/test/fixtures/load_file/es-module-default.js @@ -1,5 +1,5 @@ -"use strict"; +'use strict'; exports.__esModule = true; -exports["default"] = { - fn() {} +exports['default'] = { + fn() {}, }; diff --git a/test/fixtures/load_file/function.js b/test/fixtures/load_file/function.js index b1157b9a..9dac194b 100644 --- a/test/fixtures/load_file/function.js +++ b/test/fixtures/load_file/function.js @@ -1,3 +1,3 @@ 'use strict'; -module.exports = (a, b) => [ a, b ]; +module.exports = (a, b) => [a, b]; diff --git a/test/fixtures/load_file/no-js.yml b/test/fixtures/load_file/no-js.yml index 8b1abc10..e7ab8da9 100644 --- a/test/fixtures/load_file/no-js.yml +++ b/test/fixtures/load_file/no-js.yml @@ -1,4 +1,4 @@ --- map: - a: 1 - b: 2 \ No newline at end of file + a: 1 + b: 2 diff --git a/test/fixtures/load_file/promise_function.js b/test/fixtures/load_file/promise_function.js index 4811525c..b253e2ec 100644 --- a/test/fixtures/load_file/promise_function.js +++ b/test/fixtures/load_file/promise_function.js @@ -1,3 +1,3 @@ module.exports = function () { - return Promise.resolve({ clients: "Test Config" }); + return Promise.resolve({ clients: 'Test Config' }); }; diff --git a/test/fixtures/loadfile-esm/es-module-default-async.js b/test/fixtures/loadfile-esm/es-module-default-async.js index 22b2d681..a29f3f83 100644 --- a/test/fixtures/loadfile-esm/es-module-default-async.js +++ b/test/fixtures/loadfile-esm/es-module-default-async.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; export default async function () { - return { clients: "Test Config" }; -}; + return { clients: 'Test Config' }; +} diff --git a/test/fixtures/loadfile-esm/es-module-default-promise.js b/test/fixtures/loadfile-esm/es-module-default-promise.js index 46338176..9aeb5cb4 100644 --- a/test/fixtures/loadfile-esm/es-module-default-promise.js +++ b/test/fixtures/loadfile-esm/es-module-default-promise.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; export default function () { - return Promise.resolve({ clients: "Test Config" }); -}; + return Promise.resolve({ clients: 'Test Config' }); +} diff --git a/test/fixtures/loadfile-esm/es-module-default.js b/test/fixtures/loadfile-esm/es-module-default.js index 9f8871b0..1ded1c48 100644 --- a/test/fixtures/loadfile-esm/es-module-default.js +++ b/test/fixtures/loadfile-esm/es-module-default.js @@ -1,3 +1,3 @@ export default { - fn() {} + fn() {}, }; diff --git a/test/fixtures/loadfile-esm/es-module.js b/test/fixtures/loadfile-esm/es-module.js index 7a0ec15c..f83b81a8 100644 --- a/test/fixtures/loadfile-esm/es-module.js +++ b/test/fixtures/loadfile-esm/es-module.js @@ -1,3 +1,3 @@ export function fn() { - console.log(fn); + console.log(fn); } diff --git a/test/fixtures/loadfile-esm/no-js.yml b/test/fixtures/loadfile-esm/no-js.yml index 8b1abc10..e7ab8da9 100644 --- a/test/fixtures/loadfile-esm/no-js.yml +++ b/test/fixtures/loadfile-esm/no-js.yml @@ -1,4 +1,4 @@ --- map: - a: 1 - b: 2 \ No newline at end of file + a: 1 + b: 2 diff --git a/test/fixtures/loadfile/es-module-default-async.js b/test/fixtures/loadfile/es-module-default-async.js index 4c3109c3..5bfea8bd 100644 --- a/test/fixtures/loadfile/es-module-default-async.js +++ b/test/fixtures/loadfile/es-module-default-async.js @@ -1,5 +1,5 @@ -"use strict"; +'use strict'; exports.__esModule = true; -exports["default"] = async function () { - return { clients: "Test Config" }; +exports['default'] = async function () { + return { clients: 'Test Config' }; }; diff --git a/test/fixtures/loadfile/es-module-default-null.js b/test/fixtures/loadfile/es-module-default-null.js index fb3c8922..4be65cae 100644 --- a/test/fixtures/loadfile/es-module-default-null.js +++ b/test/fixtures/loadfile/es-module-default-null.js @@ -1,3 +1,3 @@ -"use strict"; +'use strict'; exports.__esModule = true; -exports["default"] = null; +exports['default'] = null; diff --git a/test/fixtures/loadfile/es-module-default-promise.js b/test/fixtures/loadfile/es-module-default-promise.js index ed59b0e4..ff7fff75 100644 --- a/test/fixtures/loadfile/es-module-default-promise.js +++ b/test/fixtures/loadfile/es-module-default-promise.js @@ -1,5 +1,5 @@ -"use strict"; +'use strict'; exports.__esModule = true; -exports["default"] = function () { - return Promise.resolve({ clients: "Test Config" }); +exports['default'] = function () { + return Promise.resolve({ clients: 'Test Config' }); }; diff --git a/test/fixtures/loadfile/es-module-default.js b/test/fixtures/loadfile/es-module-default.js index 665cac36..13560177 100644 --- a/test/fixtures/loadfile/es-module-default.js +++ b/test/fixtures/loadfile/es-module-default.js @@ -1,5 +1,5 @@ -"use strict"; +'use strict'; exports.__esModule = true; -exports["default"] = { - fn() {} +exports['default'] = { + fn() {}, }; diff --git a/test/fixtures/loadfile/es-module.js b/test/fixtures/loadfile/es-module.js index 0b65d6a4..3ff1db43 100644 --- a/test/fixtures/loadfile/es-module.js +++ b/test/fixtures/loadfile/es-module.js @@ -1,6 +1,6 @@ -"use strict"; +'use strict'; exports.__esModule = true; function fn() { - console.log(fn); + console.log(fn); } exports.fn = fn; diff --git a/test/fixtures/loadfile/no-js.yml b/test/fixtures/loadfile/no-js.yml index 8b1abc10..e7ab8da9 100644 --- a/test/fixtures/loadfile/no-js.yml +++ b/test/fixtures/loadfile/no-js.yml @@ -1,4 +1,4 @@ --- map: - a: 1 - b: 2 \ No newline at end of file + a: 1 + b: 2 diff --git a/test/fixtures/middleware-aa/app/middleware/common.js b/test/fixtures/middleware-aa/app/middleware/common.js index 42686683..eed40d94 100644 --- a/test/fixtures/middleware-aa/app/middleware/common.js +++ b/test/fixtures/middleware-aa/app/middleware/common.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return function(ctx, next) { - return next().then(() => ctx.body = 'common'); +module.exports = function () { + return function (ctx, next) { + return next().then(() => (ctx.body = 'common')); }; }; diff --git a/test/fixtures/middleware-aa/app/middleware/custom.js b/test/fixtures/middleware-aa/app/middleware/custom.js index 34aeeaa8..9ae67fe2 100644 --- a/test/fixtures/middleware-aa/app/middleware/custom.js +++ b/test/fixtures/middleware-aa/app/middleware/custom.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return async (ctx, next) => { ctx.set('custom', 'custom'); await next(); diff --git a/test/fixtures/middleware-aa/app/middleware/match.js b/test/fixtures/middleware-aa/app/middleware/match.js index 1b948b82..297c1440 100644 --- a/test/fixtures/middleware-aa/app/middleware/match.js +++ b/test/fixtures/middleware-aa/app/middleware/match.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return async (ctx, next) => { ctx.set('match', 'match'); await next(); diff --git a/test/fixtures/middleware-aa/app/middleware/router.js b/test/fixtures/middleware-aa/app/middleware/router.js index 18b216bc..365dcd1a 100644 --- a/test/fixtures/middleware-aa/app/middleware/router.js +++ b/test/fixtures/middleware-aa/app/middleware/router.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return async (ctx, next) => { ctx.set('router', 'router'); await next(); diff --git a/test/fixtures/middleware-aa/app/middleware/static.js b/test/fixtures/middleware-aa/app/middleware/static.js index 56e96765..95614a08 100644 --- a/test/fixtures/middleware-aa/app/middleware/static.js +++ b/test/fixtures/middleware-aa/app/middleware/static.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return async (ctx, next) => { if (ctx.path === '/static') { ctx.set('static', 'static'); diff --git a/test/fixtures/middleware-aa/app/router.js b/test/fixtures/middleware-aa/app/router.js index b16d3e60..5bd370b8 100644 --- a/test/fixtures/middleware-aa/app/router.js +++ b/test/fixtures/middleware-aa/app/router.js @@ -10,4 +10,4 @@ module.exports = app => { function controller() { this.body = 'hello'; -}; +} diff --git a/test/fixtures/middleware-aa/config/config.js b/test/fixtures/middleware-aa/config/config.js index 2c15b545..318f05d7 100644 --- a/test/fixtures/middleware-aa/config/config.js +++ b/test/fixtures/middleware-aa/config/config.js @@ -1,4 +1,4 @@ -exports.middleware = [ 'static', 'match', 'common' ]; +exports.middleware = ['static', 'match', 'common']; exports.match = { match: '/match', diff --git a/test/fixtures/middleware-app-disable/app/middleware/custom.js b/test/fixtures/middleware-app-disable/app/middleware/custom.js index 904873e3..ce0e795a 100644 --- a/test/fixtures/middleware-app-disable/app/middleware/custom.js +++ b/test/fixtures/middleware-app-disable/app/middleware/custom.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return async function appCustom(ctx) { ctx.body = 'app custom'; }; diff --git a/test/fixtures/middleware-app-disable/app/middleware/static.js b/test/fixtures/middleware-app-disable/app/middleware/static.js index 4fcfa78c..ca785f57 100644 --- a/test/fixtures/middleware-app-disable/app/middleware/static.js +++ b/test/fixtures/middleware-app-disable/app/middleware/static.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return async function(ctx, next) { +module.exports = function () { + return async function (ctx, next) { if (ctx.path === '/static') { ctx.body = 'static'; return; diff --git a/test/fixtures/middleware-app-disable/config/config.js b/test/fixtures/middleware-app-disable/config/config.js index dfd6bded..11e426a1 100644 --- a/test/fixtures/middleware-app-disable/config/config.js +++ b/test/fixtures/middleware-app-disable/config/config.js @@ -1,4 +1,4 @@ -exports.middleware = [ 'static' ]; +exports.middleware = ['static']; exports.static = { enable: false, diff --git a/test/fixtures/middleware-disable/app/middleware/custom.js b/test/fixtures/middleware-disable/app/middleware/custom.js index 054e0ff7..02dcf601 100644 --- a/test/fixtures/middleware-disable/app/middleware/custom.js +++ b/test/fixtures/middleware-disable/app/middleware/custom.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return function* appCustom() { this.body = 'app custom'; }; diff --git a/test/fixtures/middleware-disable/app/middleware/static.js b/test/fixtures/middleware-disable/app/middleware/static.js index 1827d88a..422a57d8 100644 --- a/test/fixtures/middleware-disable/app/middleware/static.js +++ b/test/fixtures/middleware-disable/app/middleware/static.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return function*(next) { +module.exports = function () { + return function* (next) { if (this.path === '/static') { this.body = 'static'; return; diff --git a/test/fixtures/middleware-ignore/app/middleware/custom.js b/test/fixtures/middleware-ignore/app/middleware/custom.js index 054e0ff7..02dcf601 100644 --- a/test/fixtures/middleware-ignore/app/middleware/custom.js +++ b/test/fixtures/middleware-ignore/app/middleware/custom.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return function* appCustom() { this.body = 'app custom'; }; diff --git a/test/fixtures/middleware-ignore/app/middleware/static.js b/test/fixtures/middleware-ignore/app/middleware/static.js index 1827d88a..422a57d8 100644 --- a/test/fixtures/middleware-ignore/app/middleware/static.js +++ b/test/fixtures/middleware-ignore/app/middleware/static.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return function*(next) { +module.exports = function () { + return function* (next) { if (this.path === '/static') { this.body = 'static'; return; diff --git a/test/fixtures/middleware-match/app/middleware/custom.js b/test/fixtures/middleware-match/app/middleware/custom.js index 054e0ff7..02dcf601 100644 --- a/test/fixtures/middleware-match/app/middleware/custom.js +++ b/test/fixtures/middleware-match/app/middleware/custom.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return function* appCustom() { this.body = 'app custom'; }; diff --git a/test/fixtures/middleware-match/app/middleware/static.js b/test/fixtures/middleware-match/app/middleware/static.js index 1827d88a..422a57d8 100644 --- a/test/fixtures/middleware-match/app/middleware/static.js +++ b/test/fixtures/middleware-match/app/middleware/static.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return function*(next) { +module.exports = function () { + return function* (next) { if (this.path === '/static') { this.body = 'static'; return; diff --git a/test/fixtures/middleware-override/app/middleware/custom.js b/test/fixtures/middleware-override/app/middleware/custom.js index 904873e3..ce0e795a 100644 --- a/test/fixtures/middleware-override/app/middleware/custom.js +++ b/test/fixtures/middleware-override/app/middleware/custom.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return async function appCustom(ctx) { ctx.body = 'app custom'; }; diff --git a/test/fixtures/middleware-override/app/middleware/static.js b/test/fixtures/middleware-override/app/middleware/static.js index 4fcfa78c..ca785f57 100644 --- a/test/fixtures/middleware-override/app/middleware/static.js +++ b/test/fixtures/middleware-override/app/middleware/static.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return async function(ctx, next) { +module.exports = function () { + return async function (ctx, next) { if (ctx.path === '/static') { ctx.body = 'static'; return; diff --git a/test/fixtures/middleware-override/config/plugin.js b/test/fixtures/middleware-override/config/plugin.js index 057c0570..fd815544 100644 --- a/test/fixtures/middleware-override/config/plugin.js +++ b/test/fixtures/middleware-override/config/plugin.js @@ -6,6 +6,6 @@ module.exports = { // 标准写法 b: { - enable: true + enable: true, }, }; diff --git a/test/fixtures/middleware-redefined/app/middleware/custom.js b/test/fixtures/middleware-redefined/app/middleware/custom.js index 054e0ff7..02dcf601 100644 --- a/test/fixtures/middleware-redefined/app/middleware/custom.js +++ b/test/fixtures/middleware-redefined/app/middleware/custom.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return function* appCustom() { this.body = 'app custom'; }; diff --git a/test/fixtures/middleware-redefined/app/middleware/static.js b/test/fixtures/middleware-redefined/app/middleware/static.js index 1827d88a..422a57d8 100644 --- a/test/fixtures/middleware-redefined/app/middleware/static.js +++ b/test/fixtures/middleware-redefined/app/middleware/static.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return function*(next) { +module.exports = function () { + return function* (next) { if (this.path === '/static') { this.body = 'static'; return; diff --git a/test/fixtures/middleware-redefined/config/config.js b/test/fixtures/middleware-redefined/config/config.js index 9c8071e9..b4acd027 100644 --- a/test/fixtures/middleware-redefined/config/config.js +++ b/test/fixtures/middleware-redefined/config/config.js @@ -1 +1 @@ -exports.middleware = [ 'status' ]; +exports.middleware = ['status']; diff --git a/test/fixtures/no-dep-plugin/plugins/a/package.json b/test/fixtures/no-dep-plugin/plugins/a/package.json index 0bb3ef84..c5298997 100644 --- a/test/fixtures/no-dep-plugin/plugins/a/package.json +++ b/test/fixtures/no-dep-plugin/plugins/a/package.json @@ -2,6 +2,8 @@ "name": "a", "eggPlugin": { "name": "customA", - "dep": [ "customB" ] + "dep": [ + "customB" + ] } } diff --git a/test/fixtures/notready/config/plugin.js b/test/fixtures/notready/config/plugin.js index 020bcd85..42f84bb3 100644 --- a/test/fixtures/notready/config/plugin.js +++ b/test/fixtures/notready/config/plugin.js @@ -5,4 +5,4 @@ const path = require('path'); exports.a = { enable: true, path: path.join(__dirname, '../a'), -} +}; diff --git a/test/fixtures/plugin-dep-disable/framework/plugins/a/package.json b/test/fixtures/plugin-dep-disable/framework/plugins/a/package.json index e42a7d6b..684f8bae 100644 --- a/test/fixtures/plugin-dep-disable/framework/plugins/a/package.json +++ b/test/fixtures/plugin-dep-disable/framework/plugins/a/package.json @@ -2,6 +2,9 @@ "name": "a", "eggPlugin": { "name": "a", - "dep": ["b", "c"] + "dep": [ + "b", + "c" + ] } } diff --git a/test/fixtures/plugin-dep-disable/framework/plugins/c/package.json b/test/fixtures/plugin-dep-disable/framework/plugins/c/package.json index d8f4d99a..ecb0779a 100644 --- a/test/fixtures/plugin-dep-disable/framework/plugins/c/package.json +++ b/test/fixtures/plugin-dep-disable/framework/plugins/c/package.json @@ -2,6 +2,8 @@ "name": "c", "eggPlugin": { "name": "c", - "dep": [ "e" ] + "dep": [ + "e" + ] } } diff --git a/test/fixtures/plugin-dep-disable/framework/plugins/d/package.json b/test/fixtures/plugin-dep-disable/framework/plugins/d/package.json index 807c96f5..e9ecd837 100644 --- a/test/fixtures/plugin-dep-disable/framework/plugins/d/package.json +++ b/test/fixtures/plugin-dep-disable/framework/plugins/d/package.json @@ -2,6 +2,8 @@ "name": "d", "eggPlugin": { "name": "d", - "dep": ["b"] + "dep": [ + "b" + ] } } diff --git a/test/fixtures/plugin-dep-missing/config/plugin.js b/test/fixtures/plugin-dep-missing/config/plugin.js index 40cfd4b9..2d5e3ab2 100644 --- a/test/fixtures/plugin-dep-missing/config/plugin.js +++ b/test/fixtures/plugin-dep-missing/config/plugin.js @@ -4,19 +4,18 @@ module.exports = { a: { enable: true, dep: ['b'], - path: path.join(__dirname, '../plugins/a') + path: path.join(__dirname, '../plugins/a'), }, b: { enable: true, dep: ['c'], - path: path.join(__dirname, '../plugins/b') + path: path.join(__dirname, '../plugins/b'), }, c: { enable: true, dep: ['a1'], - path: path.join(__dirname, '../plugins/c') + path: path.join(__dirname, '../plugins/c'), }, - }; diff --git a/test/fixtures/plugin-dep-recursive/config/plugin.js b/test/fixtures/plugin-dep-recursive/config/plugin.js index b9d10e08..8d178e98 100644 --- a/test/fixtures/plugin-dep-recursive/config/plugin.js +++ b/test/fixtures/plugin-dep-recursive/config/plugin.js @@ -4,19 +4,18 @@ module.exports = { a: { enable: true, dep: ['b'], - path: path.join(__dirname, '../plugins/a') + path: path.join(__dirname, '../plugins/a'), }, b: { enable: true, dep: ['c'], - path: path.join(__dirname, '../plugins/b') + path: path.join(__dirname, '../plugins/b'), }, c: { enable: true, dep: ['a'], - path: path.join(__dirname, '../plugins/c') + path: path.join(__dirname, '../plugins/c'), }, - }; diff --git a/test/fixtures/plugin-dep/config/plugin.js b/test/fixtures/plugin-dep/config/plugin.js index 11f6e8e1..c208d332 100644 --- a/test/fixtures/plugin-dep/config/plugin.js +++ b/test/fixtures/plugin-dep/config/plugin.js @@ -4,36 +4,35 @@ module.exports = { a: { enable: true, dep: ['b', 'f'], - path: path.join(__dirname, '../plugins/a') + path: path.join(__dirname, '../plugins/a'), }, b: { enable: true, - path: path.join(__dirname, '../plugins/b') + path: path.join(__dirname, '../plugins/b'), }, c1: { enable: true, dep: ['b'], - path: path.join(__dirname, '../plugins/c') + path: path.join(__dirname, '../plugins/c'), }, d: { enable: true, dep: ['a'], - path: path.join(__dirname, '../plugins/d') + path: path.join(__dirname, '../plugins/d'), }, e: { enable: true, dep: ['f'], - path: path.join(__dirname, '../plugins/e') + path: path.join(__dirname, '../plugins/e'), }, f: { enable: true, dep: ['c1'], - path: path.join(__dirname, '../plugins/f') + path: path.join(__dirname, '../plugins/f'), }, - }; diff --git a/test/fixtures/plugin-duplicate/release/config/plugin.js b/test/fixtures/plugin-duplicate/release/config/plugin.js index 24e8017d..5069882d 100644 --- a/test/fixtures/plugin-duplicate/release/config/plugin.js +++ b/test/fixtures/plugin-duplicate/release/config/plugin.js @@ -5,7 +5,7 @@ module.exports = { enable: true, package: '@scope/b', }, - "a-duplicate": { + 'a-duplicate': { enable: true, package: '@scope/a', }, diff --git a/test/fixtures/plugin-framework/config/plugin.js b/test/fixtures/plugin-framework/config/plugin.js index 0f5bd3fa..eb395eb6 100644 --- a/test/fixtures/plugin-framework/config/plugin.js +++ b/test/fixtures/plugin-framework/config/plugin.js @@ -1,3 +1,3 @@ 'use strict'; -exports.hsfclient = true; \ No newline at end of file +exports.hsfclient = true; diff --git a/test/fixtures/plugin-noexist/config/plugin.js b/test/fixtures/plugin-noexist/config/plugin.js index 48cc6667..85da92c8 100644 --- a/test/fixtures/plugin-noexist/config/plugin.js +++ b/test/fixtures/plugin-noexist/config/plugin.js @@ -2,5 +2,5 @@ module.exports = { // plugin 不存在报错 - noexist: true + noexist: true, }; diff --git a/test/fixtures/plugin/agent.js b/test/fixtures/plugin/agent.js index 1ca468bf..69557d01 100644 --- a/test/fixtures/plugin/agent.js +++ b/test/fixtures/plugin/agent.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function(agent) { +module.exports = function (agent) { agent.date = Date.now(); agent.agent = 'agent'; }; diff --git a/test/fixtures/plugin/app.js b/test/fixtures/plugin/app.js index b8e2c3ab..78ec3b3c 100644 --- a/test/fixtures/plugin/app.js +++ b/test/fixtures/plugin/app.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function(app) { +module.exports = function (app) { app.date = Date.now(); app.app = 'app'; }; diff --git a/test/fixtures/plugin/app/proxy/OnlyClassQuery.js b/test/fixtures/plugin/app/proxy/OnlyClassQuery.js index 8cd65ebb..d5cf4d2f 100644 --- a/test/fixtures/plugin/app/proxy/OnlyClassQuery.js +++ b/test/fixtures/plugin/app/proxy/OnlyClassQuery.js @@ -7,7 +7,7 @@ class OnlyCLassQuery extends Proxy { super(ctx); } - * query() { + *query() { return { foo: 'clz', }; diff --git a/test/fixtures/plugin/app/proxy/UserInfoQuery.js b/test/fixtures/plugin/app/proxy/UserInfoQuery.js index f6ae6116..09fe6d9a 100644 --- a/test/fixtures/plugin/app/proxy/UserInfoQuery.js +++ b/test/fixtures/plugin/app/proxy/UserInfoQuery.js @@ -1,12 +1,12 @@ 'use strict'; -module.exports = function(app) { +module.exports = function (app) { class UserInfoQuery extends app.Proxy { constructor(ctx) { super(ctx); } - * query() { + *query() { return { foo: 'bar', }; diff --git a/test/fixtures/plugin/app/proxy/couponQuery.js b/test/fixtures/plugin/app/proxy/couponQuery.js index 133654c1..53742f82 100644 --- a/test/fixtures/plugin/app/proxy/couponQuery.js +++ b/test/fixtures/plugin/app/proxy/couponQuery.js @@ -1,12 +1,12 @@ 'use strict'; -module.exports = function(app) { +module.exports = function (app) { class CouponQuery extends app.Proxy { constructor(ctx) { super(ctx); } - * query() { + *query() { return { coupon: 100, }; diff --git a/test/fixtures/plugin/app/router.js b/test/fixtures/plugin/app/router.js index a66cdc86..a1ab5edc 100644 --- a/test/fixtures/plugin/app/router.js +++ b/test/fixtures/plugin/app/router.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function(app) { - app.get('/', async function() { +module.exports = function (app) { + app.get('/', async function () { const foo2 = await this.service.foo2(); const foo3 = await this.service.foo3.foo3(); this.body = { @@ -14,7 +14,7 @@ module.exports = function(app) { }; }); - app.get('/proxy', async function() { + app.get('/proxy', async function () { this.body = { coupon: await this.proxy.couponQuery.query(), userInfo: await this.proxy.userInfoQuery.query(), diff --git a/test/fixtures/plugin/app/service/Foo4.js b/test/fixtures/plugin/app/service/Foo4.js index c3a72478..52c96313 100644 --- a/test/fixtures/plugin/app/service/Foo4.js +++ b/test/fixtures/plugin/app/service/Foo4.js @@ -1,9 +1,7 @@ 'use strict'; module.exports = function (app) { - class Foo4 extends app.Service { - - } + class Foo4 extends app.Service {} return Foo4; }; diff --git a/test/fixtures/plugin/app/service/foo.js b/test/fixtures/plugin/app/service/foo.js index 90a8ac76..26b5cfd7 100644 --- a/test/fixtures/plugin/app/service/foo.js +++ b/test/fixtures/plugin/app/service/foo.js @@ -1,9 +1,7 @@ 'use strict'; module.exports = function (app) { - class Foo extends app.Service { - - } + class Foo extends app.Service {} return Foo; }; diff --git a/test/fixtures/plugin/app/service/fooDir/Foo5.js b/test/fixtures/plugin/app/service/fooDir/Foo5.js index 378e7c78..1db6e385 100644 --- a/test/fixtures/plugin/app/service/fooDir/Foo5.js +++ b/test/fixtures/plugin/app/service/fooDir/Foo5.js @@ -1,9 +1,7 @@ 'use strict'; module.exports = function (app) { - class Foo5 extends app.Service { - - } + class Foo5 extends app.Service {} return Foo5; }; diff --git a/test/fixtures/plugin/config/plugin.js b/test/fixtures/plugin/config/plugin.js index 2b6d29b3..c6757578 100644 --- a/test/fixtures/plugin/config/plugin.js +++ b/test/fixtures/plugin/config/plugin.js @@ -39,5 +39,4 @@ module.exports = { dep: ['session'], package: 'rds', }, - }; diff --git a/test/fixtures/plugin/plugins/e/package.json b/test/fixtures/plugin/plugins/e/package.json index 9bfa531e..be3b3d5f 100644 --- a/test/fixtures/plugin/plugins/e/package.json +++ b/test/fixtures/plugin/plugins/e/package.json @@ -1,6 +1,8 @@ { "eggPlugin": { "name": "wrong-name", - "dep": [ "f" ] + "dep": [ + "f" + ] } } diff --git a/test/fixtures/plugin/plugins/g/package.json b/test/fixtures/plugin/plugins/g/package.json index 61e61bf6..c36f0ecf 100644 --- a/test/fixtures/plugin/plugins/g/package.json +++ b/test/fixtures/plugin/plugins/g/package.json @@ -1,7 +1,9 @@ { "eggPlugin": { "name": "g", - "dep": [ "f" ] + "dep": [ + "f" + ] }, "version": "1.0.0" } diff --git a/test/fixtures/preload-app-config/a/config/config.js b/test/fixtures/preload-app-config/a/config/config.js index 9b1bdece..663e0006 100644 --- a/test/fixtures/preload-app-config/a/config/config.js +++ b/test/fixtures/preload-app-config/a/config/config.js @@ -1,11 +1,11 @@ 'use strict'; -module.exports = function(antx, appConfig) { +module.exports = function (antx, appConfig) { appConfig.app.sub.val = 2; return { plugin: { sub: appConfig.app.sub, val: appConfig.app.val, }, - } + }; }; diff --git a/test/fixtures/preload-app-config/config/config.js b/test/fixtures/preload-app-config/config/config.js index 463c3ff3..558d0a9d 100644 --- a/test/fixtures/preload-app-config/config/config.js +++ b/test/fixtures/preload-app-config/config/config.js @@ -1,10 +1,10 @@ 'use strict'; -module.exports = function(antx, appConfig) { +module.exports = function (antx, appConfig) { return { app: { sub: { - val: 1 + val: 1, }, val: 2, }, diff --git a/test/fixtures/preload-app-config/config/plugin.js b/test/fixtures/preload-app-config/config/plugin.js index fd992b33..8ce5339c 100644 --- a/test/fixtures/preload-app-config/config/plugin.js +++ b/test/fixtures/preload-app-config/config/plugin.js @@ -6,5 +6,5 @@ module.exports = { a: { enable: true, path: path.join(__dirname, '../a'), - } + }, }; diff --git a/test/fixtures/proxy-override/app/proxy/queryProxy.js b/test/fixtures/proxy-override/app/proxy/queryProxy.js index fad2fe3d..7d545bec 100644 --- a/test/fixtures/proxy-override/app/proxy/queryProxy.js +++ b/test/fixtures/proxy-override/app/proxy/queryProxy.js @@ -1,12 +1,12 @@ 'use strict'; -module.exports = function(app) { +module.exports = function (app) { class QueryProxy extends app.Proxy { constructor(ctx) { super(ctx); } - * query() { + *query() { return { foo: 'bar', }; diff --git a/test/fixtures/proxy-override/config/plugin.js b/test/fixtures/proxy-override/config/plugin.js index ba571c7d..bed44742 100644 --- a/test/fixtures/proxy-override/config/plugin.js +++ b/test/fixtures/proxy-override/config/plugin.js @@ -1,5 +1,5 @@ 'use strict'; module.exports = { - a: true + a: true, }; diff --git a/test/fixtures/redefine-plugin/config/plugin.js b/test/fixtures/redefine-plugin/config/plugin.js index 9e83d181..b3d8904f 100644 --- a/test/fixtures/redefine-plugin/config/plugin.js +++ b/test/fixtures/redefine-plugin/config/plugin.js @@ -4,5 +4,5 @@ module.exports = { package: { enable: true, package: 'package', - } + }, }; diff --git a/test/fixtures/router-app/app/controller/async.js b/test/fixtures/router-app/app/controller/async.js index 68692fa7..9a98a3a7 100644 --- a/test/fixtures/router-app/app/controller/async.js +++ b/test/fixtures/router-app/app/controller/async.js @@ -5,5 +5,5 @@ module.exports = app => { async index() { this.ctx.body.push('async'); } - } + }; }; diff --git a/test/fixtures/router-app/app/controller/comments.js b/test/fixtures/router-app/app/controller/comments.js index 40f87620..29d86c09 100644 --- a/test/fixtures/router-app/app/controller/comments.js +++ b/test/fixtures/router-app/app/controller/comments.js @@ -2,14 +2,14 @@ // 测试 app.resources 遇到 controller 没有足够的 action 的场景 -exports.index = async function() { +exports.index = async function () { this.body = 'index'; }; -exports.new = async function() { +exports.new = async function () { this.body = 'new'; }; -exports.show = async function() { +exports.show = async function () { this.body = 'show - ' + this.params.id; }; diff --git a/test/fixtures/router-app/app/controller/locals.js b/test/fixtures/router-app/app/controller/locals.js index d78ff887..5dca17a8 100644 --- a/test/fixtures/router-app/app/controller/locals.js +++ b/test/fixtures/router-app/app/controller/locals.js @@ -1,5 +1,5 @@ 'use strict'; -exports.router = async function() { +exports.router = async function () { await this.render('locals/router.html'); }; diff --git a/test/fixtures/router-app/app/controller/members.js b/test/fixtures/router-app/app/controller/members.js index 38176474..dafc0113 100644 --- a/test/fixtures/router-app/app/controller/members.js +++ b/test/fixtures/router-app/app/controller/members.js @@ -2,18 +2,18 @@ // 测试 app.resources 遇到 controller 没有足够的 action 的场景 -exports.index = async function() { +exports.index = async function () { this.body = 'index'; }; -exports.new = async function() { +exports.new = async function () { this.body = 'new'; }; -exports.show = async function() { +exports.show = async function () { this.body = 'show - ' + this.params.id; }; -exports.delete = async function() { +exports.delete = async function () { this.body = `delete - ${this.params.id}`; }; diff --git a/test/fixtures/router-app/app/controller/middleware.js b/test/fixtures/router-app/app/controller/middleware.js index b5bdd9fd..a85b2da1 100644 --- a/test/fixtures/router-app/app/controller/middleware.js +++ b/test/fixtures/router-app/app/controller/middleware.js @@ -1,5 +1,5 @@ 'use strict'; -module.exports = async function() { +module.exports = async function () { this.body = []; }; diff --git a/test/fixtures/router-app/app/controller/package.js b/test/fixtures/router-app/app/controller/package.js index bec81585..8ade6d88 100644 --- a/test/fixtures/router-app/app/controller/package.js +++ b/test/fixtures/router-app/app/controller/package.js @@ -1,5 +1,5 @@ 'use strict'; -exports.get = async function() { +exports.get = async function () { this.body = this.params[0]; }; diff --git a/test/fixtures/router-app/app/controller/posts.js b/test/fixtures/router-app/app/controller/posts.js index 746609ac..09ad2580 100644 --- a/test/fixtures/router-app/app/controller/posts.js +++ b/test/fixtures/router-app/app/controller/posts.js @@ -1,29 +1,29 @@ 'use strict'; -exports.index = async function() { +exports.index = async function () { this.body = 'index'; }; -exports.new = async function() { +exports.new = async function () { this.body = 'new'; }; -exports.create = async function() { +exports.create = async function () { this.body = 'create'; }; -exports.show = async function() { +exports.show = async function () { this.body = 'show - ' + this.params.id; }; -exports.edit = async function() { +exports.edit = async function () { this.body = 'edit - ' + this.params.id; }; -exports.update = async function() { +exports.update = async function () { this.body = 'update - ' + this.params.id; }; -exports.destroy = async function() { +exports.destroy = async function () { this.body = 'destroy - ' + this.params.id; }; diff --git a/test/fixtures/router-app/app/middleware/async.js b/test/fixtures/router-app/app/middleware/async.js index fe2af8e5..97d8b591 100644 --- a/test/fixtures/router-app/app/middleware/async.js +++ b/test/fixtures/router-app/app/middleware/async.js @@ -1,6 +1,6 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return async (ctx, next) => { await next(); ctx.body.push('async'); diff --git a/test/fixtures/router-app/app/middleware/common.js b/test/fixtures/router-app/app/middleware/common.js index 0a53e7d0..af44d6c2 100644 --- a/test/fixtures/router-app/app/middleware/common.js +++ b/test/fixtures/router-app/app/middleware/common.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return function(ctx, next) { +module.exports = function () { + return function (ctx, next) { return next().then(() => { ctx.body.push('common'); }); diff --git a/test/fixtures/router-app/app/middleware/generator.js b/test/fixtures/router-app/app/middleware/generator.js index b6889ebc..aa1476fb 100644 --- a/test/fixtures/router-app/app/middleware/generator.js +++ b/test/fixtures/router-app/app/middleware/generator.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return async function(ctx, next) { +module.exports = function () { + return async function (ctx, next) { await next(); ctx.body.push('generator'); }; diff --git a/test/fixtures/router-app/app/middleware/generator_both.js b/test/fixtures/router-app/app/middleware/generator_both.js index 718393d3..38479960 100644 --- a/test/fixtures/router-app/app/middleware/generator_both.js +++ b/test/fixtures/router-app/app/middleware/generator_both.js @@ -1,7 +1,7 @@ 'use strict'; -module.exports = function() { - return async function(ctx, next) { +module.exports = function () { + return async function (ctx, next) { ctx.body = []; ctx.body.push('generator before'); await next(); diff --git a/test/fixtures/router-app/app/router.js b/test/fixtures/router-app/app/router.js index f80a3e06..f7e2a000 100644 --- a/test/fixtures/router-app/app/router.js +++ b/test/fixtures/router-app/app/router.js @@ -12,13 +12,28 @@ module.exports = function (app) { .resources('posts', '/posts', 'posts') .resources('members', '/members', app.controller.members) .resources('/comments', app.controller.comments) - .get('comment_index', '/comments/:id?filter=', app.controller.comments.index) + .get( + 'comment_index', + '/comments/:id?filter=', + app.controller.comments.index + ) .get('params', '/params/:a/:b', app.controller.locals.router) .get('/middleware', common, asyncMw, generator, 'middleware') - .get('middleware', '/named_middleware', common, asyncMw, generator, 'middleware') - .get('/mix', generatorBoth , 'async.index') - .register('/comments', [ 'post' ] , app.controller.comments.new) - .register('/register_middleware', [ 'get' ], [ common, asyncMw, generator, 'middleware' ]) + .get( + 'middleware', + '/named_middleware', + common, + asyncMw, + generator, + 'middleware' + ) + .get('/mix', generatorBoth, 'async.index') + .register('/comments', ['post'], app.controller.comments.new) + .register( + '/register_middleware', + ['get'], + [common, asyncMw, generator, 'middleware'] + ) .redirect('/redirect', '/middleware', 302); app.router @@ -27,6 +42,6 @@ module.exports = function (app) { app.get('packages', /^\/packages\/(.*)/, 'package.get'); - app.get([ '/url1', '/url2' ], 'members.index') - app.get([ '/urlm1', '/urlm2' ], common, asyncMw, generator, 'middleware') + app.get(['/url1', '/url2'], 'members.index'); + app.get(['/urlm1', '/urlm2'], common, asyncMw, generator, 'middleware'); }; diff --git a/test/fixtures/router-app/app/views/locals/router.html b/test/fixtures/router-app/app/views/locals/router.html index 0006527d..acdbfe2b 100644 --- a/test/fixtures/router-app/app/views/locals/router.html +++ b/test/fixtures/router-app/app/views/locals/router.html @@ -1 +1 @@ -posts: /posts \ No newline at end of file +posts: /posts diff --git a/test/fixtures/router-app/package.json b/test/fixtures/router-app/package.json index 874899c0..71fab1a3 100644 --- a/test/fixtures/router-app/package.json +++ b/test/fixtures/router-app/package.json @@ -1,3 +1,3 @@ { "name": "router-app" -} \ No newline at end of file +} diff --git a/test/fixtures/router-in-app/app.js b/test/fixtures/router-in-app/app.js index ac7d5f92..0ed0ea73 100644 --- a/test/fixtures/router-in-app/app.js +++ b/test/fixtures/router-in-app/app.js @@ -2,4 +2,4 @@ module.exports = app => { app.router; -} +}; diff --git a/test/fixtures/router-in-app/app/router.js b/test/fixtures/router-in-app/app/router.js index 273d94ac..0436cfaf 100644 --- a/test/fixtures/router-in-app/app/router.js +++ b/test/fixtures/router-in-app/app/router.js @@ -4,4 +4,4 @@ module.exports = app => { app.get('/', ctx => { ctx.body = ctx.foo; }); -} +}; diff --git a/test/fixtures/router-in-app/config/config.default.js b/test/fixtures/router-in-app/config/config.default.js index b3a59cfb..02644ce1 100644 --- a/test/fixtures/router-in-app/config/config.default.js +++ b/test/fixtures/router-in-app/config/config.default.js @@ -1,3 +1,3 @@ 'use strict'; -exports.middleware = [ 'foo' ]; +exports.middleware = ['foo']; diff --git a/test/fixtures/scope-env/config/plugin.en_prod.js b/test/fixtures/scope-env/config/plugin.en_prod.js index d315e6ff..a9b46f76 100644 --- a/test/fixtures/scope-env/config/plugin.en_prod.js +++ b/test/fixtures/scope-env/config/plugin.en_prod.js @@ -5,5 +5,5 @@ module.exports = { d: { enable: true, package: 'd', - } + }, }; diff --git a/test/fixtures/service-override/config/plugin.js b/test/fixtures/service-override/config/plugin.js index ba571c7d..bed44742 100644 --- a/test/fixtures/service-override/config/plugin.js +++ b/test/fixtures/service-override/config/plugin.js @@ -1,5 +1,5 @@ 'use strict'; module.exports = { - a: true + a: true, }; diff --git a/test/fixtures/service-unique/app/controller/same.js b/test/fixtures/service-unique/app/controller/same.js index 465fcb7d..349c56b6 100644 --- a/test/fixtures/service-unique/app/controller/same.js +++ b/test/fixtures/service-unique/app/controller/same.js @@ -1,4 +1,4 @@ -module.exports = async function() { +module.exports = async function () { const ctx = this.service.ctx.get(); this.body = String(ctx === this); }; diff --git a/test/fixtures/services_loader_verify/app/service/foo.js b/test/fixtures/services_loader_verify/app/service/foo.js index 03116bd2..9bee3f7d 100644 --- a/test/fixtures/services_loader_verify/app/service/foo.js +++ b/test/fixtures/services_loader_verify/app/service/foo.js @@ -1,17 +1,17 @@ 'use strict'; -module.exports = function() { +module.exports = function () { return { *bar(ctx) { console.log(ctx); }, - * bar1(ctx) { + *bar1(ctx) { console.log(ctx); }, - aa: function*(ctx) { + aa: function* (ctx) { console.log(ctx); - } + }, }; }; diff --git a/test/fixtures/session-cache-app/config/config.default.ts b/test/fixtures/session-cache-app/config/config.default.ts index 94c3ffd6..5532a6a7 100644 --- a/test/fixtures/session-cache-app/config/config.default.ts +++ b/test/fixtures/session-cache-app/config/config.default.ts @@ -1,3 +1,3 @@ export default { foo: 'bar', -} +}; diff --git a/test/fixtures/subdir-proxy/app/proxy/certify-personal/mobile-hi/do_certify.js b/test/fixtures/subdir-proxy/app/proxy/certify-personal/mobile-hi/do_certify.js index 2e43c29d..6d33a7b0 100644 --- a/test/fixtures/subdir-proxy/app/proxy/certify-personal/mobile-hi/do_certify.js +++ b/test/fixtures/subdir-proxy/app/proxy/certify-personal/mobile-hi/do_certify.js @@ -6,7 +6,7 @@ module.exports = function (app) { super(ctx); } - * exec(cmd) { + *exec(cmd) { return { cmd: cmd, method: this.ctx.method, diff --git a/test/fixtures/subdir-proxy/app/proxy/cif/user.js b/test/fixtures/subdir-proxy/app/proxy/cif/user.js index 15572080..5c2aa526 100644 --- a/test/fixtures/subdir-proxy/app/proxy/cif/user.js +++ b/test/fixtures/subdir-proxy/app/proxy/cif/user.js @@ -6,7 +6,7 @@ module.exports = function (app) { super(ctx); } - * get(uid) { + *get(uid) { return { uid: uid, cif: true, diff --git a/test/fixtures/subdir-proxy/app/proxy/foo/bar.js b/test/fixtures/subdir-proxy/app/proxy/foo/bar.js index fbd0293a..a25e0a1d 100644 --- a/test/fixtures/subdir-proxy/app/proxy/foo/bar.js +++ b/test/fixtures/subdir-proxy/app/proxy/foo/bar.js @@ -6,7 +6,7 @@ module.exports = function (app) { super(ctx); } - * get(name) { + *get(name) { return { name: name, bar: 'bar1', diff --git a/test/fixtures/subdir-proxy/app/proxy/foo/subdir/bar.js b/test/fixtures/subdir-proxy/app/proxy/foo/subdir/bar.js index 7280d019..ee2d8298 100644 --- a/test/fixtures/subdir-proxy/app/proxy/foo/subdir/bar.js +++ b/test/fixtures/subdir-proxy/app/proxy/foo/subdir/bar.js @@ -6,7 +6,7 @@ module.exports = function (app) { super(ctx); } - * get(name) { + *get(name) { return { name: name, bar: 'bar2', diff --git a/test/fixtures/subdir-proxy/app/proxy/foo/subdir1/subdir11/bar.js b/test/fixtures/subdir-proxy/app/proxy/foo/subdir1/subdir11/bar.js index a0c7bd14..238b99d8 100644 --- a/test/fixtures/subdir-proxy/app/proxy/foo/subdir1/subdir11/bar.js +++ b/test/fixtures/subdir-proxy/app/proxy/foo/subdir1/subdir11/bar.js @@ -6,7 +6,7 @@ module.exports = function (app) { super(ctx); } - * get(name) { + *get(name) { return { name: name, bar: 'bar111', diff --git a/test/fixtures/subdir-proxy/app/proxy/foo/subdir2/sub2.js b/test/fixtures/subdir-proxy/app/proxy/foo/subdir2/sub2.js index 682fb361..dfff60e5 100644 --- a/test/fixtures/subdir-proxy/app/proxy/foo/subdir2/sub2.js +++ b/test/fixtures/subdir-proxy/app/proxy/foo/subdir2/sub2.js @@ -6,11 +6,11 @@ module.exports = app => { super(ctx); } - * get(name) { + *get(name) { return { name: name, bar: 'bar3', }; } - } + }; }; diff --git a/test/fixtures/subdir-proxy/app/proxy/ok.js b/test/fixtures/subdir-proxy/app/proxy/ok.js index b88ea9b3..d1f105e4 100644 --- a/test/fixtures/subdir-proxy/app/proxy/ok.js +++ b/test/fixtures/subdir-proxy/app/proxy/ok.js @@ -6,10 +6,10 @@ module.exports = app => { super(ctx); } - * get() { + *get() { return { ok: true, }; } - } + }; }; diff --git a/test/fixtures/subdir-proxy/app/proxy/user.js b/test/fixtures/subdir-proxy/app/proxy/user.js index 1959b8ca..16934dbf 100644 --- a/test/fixtures/subdir-proxy/app/proxy/user.js +++ b/test/fixtures/subdir-proxy/app/proxy/user.js @@ -6,9 +6,9 @@ module.exports = function (app) { super(ctx); } - * get(uid) { + *get(uid) { return { - uid: uid + uid: uid, }; } } diff --git a/test/fixtures/subdir-proxy/app/router.js b/test/fixtures/subdir-proxy/app/router.js index ce1e3339..da4cabb6 100644 --- a/test/fixtures/subdir-proxy/app/router.js +++ b/test/fixtures/subdir-proxy/app/router.js @@ -1,5 +1,5 @@ module.exports = function (app) { - app.get('/', function*() { + app.get('/', function* () { this.body = { user: yield this.proxy.user.get('123'), cif: yield this.proxy.cif.user.get('123cif'), @@ -13,4 +13,4 @@ module.exports = function (app) { oldStyle: yield this.proxy.oldStyle.url(this), }; }); -} +}; diff --git a/test/fixtures/subdir-services/app/controller/home.js b/test/fixtures/subdir-services/app/controller/home.js index f592d168..f63fb5e2 100644 --- a/test/fixtures/subdir-services/app/controller/home.js +++ b/test/fixtures/subdir-services/app/controller/home.js @@ -1,4 +1,4 @@ -module.exports = async function() { +module.exports = async function () { this.body = { user: await this.service.user.get('123'), cif: await this.service.cif.user.get('123cif'), @@ -8,7 +8,8 @@ module.exports = async function() { subdir11bar: await this.service.foo.subdir1.subdir11.bar.get(), ok: await this.service.ok.get(), cmd: await this.service.certifyPersonal.mobileHi.doCertify.exec('hihi'), - serviceIsSame: this.service.certifyPersonal === this.service.certifyPersonal, + serviceIsSame: + this.service.certifyPersonal === this.service.certifyPersonal, oldStyle: await this.service.oldStyle.url(this), }; }; diff --git a/test/fixtures/subdir-services/app/service/ok.js b/test/fixtures/subdir-services/app/service/ok.js index 7c6071ea..63693507 100644 --- a/test/fixtures/subdir-services/app/service/ok.js +++ b/test/fixtures/subdir-services/app/service/ok.js @@ -11,5 +11,5 @@ module.exports = app => { ok: true, }; } - } + }; }; diff --git a/test/fixtures/subdir-services/app/service/old_style.js b/test/fixtures/subdir-services/app/service/old_style.js index 5f95e564..12e62557 100644 --- a/test/fixtures/subdir-services/app/service/old_style.js +++ b/test/fixtures/subdir-services/app/service/old_style.js @@ -1,3 +1,3 @@ -exports.url = async (ctx) => { +exports.url = async ctx => { return ctx.url; }; diff --git a/test/fixtures/subdir-services/app/service/user.js b/test/fixtures/subdir-services/app/service/user.js index 49a5fe78..b1a65bd0 100644 --- a/test/fixtures/subdir-services/app/service/user.js +++ b/test/fixtures/subdir-services/app/service/user.js @@ -8,7 +8,7 @@ module.exports = function (app) { async get(uid) { return { - uid: uid + uid: uid, }; } } diff --git a/test/fixtures/timing/agent.js b/test/fixtures/timing/agent.js index 54172be6..fc4840d9 100644 --- a/test/fixtures/timing/agent.js +++ b/test/fixtures/timing/agent.js @@ -7,5 +7,5 @@ module.exports = agent => { agent.beforeStart(function* () { block(); - }) + }); }; diff --git a/test/fixtures/timing/index.js b/test/fixtures/timing/index.js index 15b7f642..d3455566 100644 --- a/test/fixtures/timing/index.js +++ b/test/fixtures/timing/index.js @@ -22,6 +22,9 @@ class Application extends EggApplication { const app = utils.createApp('application', { Application }); app.loader.loadAll(); app.ready(err => { - fs.writeFileSync(path.join(__dirname, 'timing.json'), JSON.stringify(app.timing.toJSON())); + fs.writeFileSync( + path.join(__dirname, 'timing.json'), + JSON.stringify(app.timing.toJSON()) + ); process.exit(err ? 1 : 0); }); diff --git a/test/lifecycle.test.ts b/test/lifecycle.test.ts index 9436ee32..17701e15 100644 --- a/test/lifecycle.test.ts +++ b/test/lifecycle.test.ts @@ -20,7 +20,7 @@ describe('test/lifecycle.test.ts', () => { configDidLoad() { console.log('test'); } - }, + } ); }, /do not add hook when lifecycle has been initialized/); diff --git a/test/loader/mixin/load_custom_agent.test.ts b/test/loader/mixin/load_custom_agent.test.ts index 96f83744..32f1dd91 100644 --- a/test/loader/mixin/load_custom_agent.test.ts +++ b/test/loader/mixin/load_custom_agent.test.ts @@ -17,7 +17,7 @@ describe('test/loader/mixin/load_custom_agent.test.ts', () => { assert(agent.agent === 'agent'); }); - it('should agent.js of plugin before application\'s', () => { + it("should agent.js of plugin before application's", () => { assert(agent.dateB <= agent.date); assert(agent.dateC <= agent.date); }); diff --git a/test/support-typescript.test.ts b/test/support-typescript.test.ts index 1833a574..fd3d1c6d 100644 --- a/test/support-typescript.test.ts +++ b/test/support-typescript.test.ts @@ -14,8 +14,7 @@ describe('test/support-typescript.test.ts', () => { }); it('should ignore *.js when *.ts same file exists', async () => { - const res = await request(app.callback()) - .get('/'); + const res = await request(app.callback()).get('/'); assert.equal(res.status, 200); assert.equal(res.text, 'Hello World'); }); From 2f119021ff26135997eb83868f93ea668cfb671a Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Fri, 28 Mar 2025 22:07:08 +0800 Subject: [PATCH 08/10] f --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d0fdcc34..47f418a9 100644 --- a/README.md +++ b/README.md @@ -232,7 +232,7 @@ await this.loadExtend('application', app); | ----------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- | | directory | `String/Array` | directories to be loaded | | target | `Object` | attach the target object from loaded files | -| match | `String/Array` | match the files when load, default to `**/*.js`(if process.env.EGG_TYPESCRIPT was true, default to `[ '\*_/_.(js | ts)', '!\*_/_.d.ts' ]`) | +| match | `String/Array` | match the files when load, default to `**/*.js`(if process.env.EGG\*TYPESCRIPT was true, default to `[ '\*\*/\_.(js | ts)', '!\*_/_.d.ts' ]`) | | ignore | `String/Array` | ignore the files when load | | initializer | `Function` | custom file exports, receive two parameters, first is the inject object(if not js file, will be content buffer), second is an `options` object that contain `path` | | caseStyle | `String/Function` | set property's case when converting a filepath to property list. | From e5669a19b6c7902941d5af6363616908fe3eb118 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Fri, 28 Mar 2025 22:11:31 +0800 Subject: [PATCH 09/10] f --- test/loader/load_file.test.ts | 2 +- test/utils/index.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/loader/load_file.test.ts b/test/loader/load_file.test.ts index 306a2c35..3e47a086 100644 --- a/test/loader/load_file.test.ts +++ b/test/loader/load_file.test.ts @@ -41,7 +41,7 @@ describe('test/loader/load_file.test.ts', () => { if (process.platform === 'win32') { result = result.replaceAll(String.raw`\r\n`, '\n'); } - assert.equal(result, '---\nmap:\n a: 1\n b: 2'); + assert.equal(result, '---\nmap:\n a: 1\n b: 2\n'); }); it('should load cjs module file which returns function returning a promise', async () => { diff --git a/test/utils/index.test.ts b/test/utils/index.test.ts index 40876720..89c01930 100644 --- a/test/utils/index.test.ts +++ b/test/utils/index.test.ts @@ -83,7 +83,7 @@ describe('test/utils/index.test.ts', () => { if (process.platform === 'win32') { result = result.replaceAll(String.raw`\r\n`, '\n'); } - assert.equal(result, '---\nmap:\n a: 1\n b: 2'); + assert.equal(result, '---\nmap:\n a: 1\n b: 2\n'); }); }); @@ -159,7 +159,7 @@ describe('test/utils/index.test.ts', () => { if (process.platform === 'win32') { result = result.replaceAll(String.raw`\r\n`, '\n'); } - assert.equal(result, '---\nmap:\n a: 1\n b: 2'); + assert.equal(result, '---\nmap:\n a: 1\n b: 2\n'); }); }); }); From 673bcda03a54e77b07ca8c10ac978a7e40373627 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Fri, 28 Mar 2025 22:18:34 +0800 Subject: [PATCH 10/10] f --- test/egg.test.ts | 9 +++------ test/loader/load_file.test.ts | 2 +- test/utils/index.test.ts | 4 ++-- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/test/egg.test.ts b/test/egg.test.ts index b2ae3ee3..f968327d 100644 --- a/test/egg.test.ts +++ b/test/egg.test.ts @@ -783,14 +783,11 @@ describe('test/egg.test.ts', () => { error = e; } assert.strictEqual(error.message, 'didLoad error'); - assert.deepStrictEqual((app as any).bootLog, ['configDidLoad']); + assert.deepEqual((app as any).bootLog, ['configDidLoad']); await sleep(10); - assert.deepStrictEqual((app as any).bootLog, [ - 'configDidLoad', - 'didReady', - ]); + assert.deepEqual((app as any).bootLog, ['configDidLoad', 'didReady']); await app.close(); - assert.deepStrictEqual((app as any).bootLog, [ + assert.deepEqual((app as any).bootLog, [ 'configDidLoad', 'didReady', 'beforeClose', diff --git a/test/loader/load_file.test.ts b/test/loader/load_file.test.ts index 3e47a086..d35db6ed 100644 --- a/test/loader/load_file.test.ts +++ b/test/loader/load_file.test.ts @@ -39,7 +39,7 @@ describe('test/loader/load_file.test.ts', () => { const buf = await app.loader.loadFile(getFilepath('load_file/no-js.yml')); let result = buf.toString(); if (process.platform === 'win32') { - result = result.replaceAll(String.raw`\r\n`, '\n'); + result = result.replaceAll('\r\n', '\n'); } assert.equal(result, '---\nmap:\n a: 1\n b: 2\n'); }); diff --git a/test/utils/index.test.ts b/test/utils/index.test.ts index 89c01930..5f286883 100644 --- a/test/utils/index.test.ts +++ b/test/utils/index.test.ts @@ -81,7 +81,7 @@ describe('test/utils/index.test.ts', () => { const buf = await utils.loadFile(path.join(baseDir, 'no-js.yml')); let result = buf.toString(); if (process.platform === 'win32') { - result = result.replaceAll(String.raw`\r\n`, '\n'); + result = result.replaceAll('\r\n', '\n'); } assert.equal(result, '---\nmap:\n a: 1\n b: 2\n'); }); @@ -157,7 +157,7 @@ describe('test/utils/index.test.ts', () => { const buf = await utils.loadFile(path.join(baseDir, 'no-js.yml')); let result = buf.toString(); if (process.platform === 'win32') { - result = result.replaceAll(String.raw`\r\n`, '\n'); + result = result.replaceAll('\r\n', '\n'); } assert.equal(result, '---\nmap:\n a: 1\n b: 2\n'); });