From e5a26794fc1fcbbc6210b8083e885af3d4d185f4 Mon Sep 17 00:00:00 2001 From: D-Sketon <2055272094@qq.com> Date: Thu, 9 Nov 2023 15:16:45 +0800 Subject: [PATCH] refactor: refactor types --- lib/box/file.ts | 8 ++++---- lib/hexo/load_config.ts | 4 ++-- lib/hexo/load_database.ts | 2 +- lib/hexo/load_plugins.ts | 4 ++-- lib/hexo/load_theme_config.ts | 5 +++-- lib/hexo/locals.ts | 6 +++--- lib/hexo/multi_config_path.ts | 4 ++-- lib/hexo/register_models.ts | 2 +- lib/hexo/render.ts | 25 +++++++++++++------------ lib/hexo/router.ts | 20 ++++++++++---------- lib/hexo/scaffold.ts | 21 +++++++++++++++------ lib/hexo/update_package.ts | 5 +++-- lib/hexo/validate_config.ts | 2 +- lib/plugins/renderer/json.ts | 2 +- lib/plugins/renderer/nunjucks.ts | 10 +++++----- lib/plugins/renderer/plain.ts | 2 +- lib/plugins/renderer/yaml.ts | 4 ++-- lib/theme/index.ts | 20 ++++++++++++-------- lib/theme/processors/view.ts | 2 +- lib/theme/view.ts | 11 ++++++----- package.json | 1 + 21 files changed, 89 insertions(+), 71 deletions(-) diff --git a/lib/box/file.ts b/lib/box/file.ts index 99bb509ddd..30d71cdddf 100644 --- a/lib/box/file.ts +++ b/lib/box/file.ts @@ -19,12 +19,12 @@ class File { this.type = type; } - read(options?: ReadFileOptions): Promise { - return readFile(this.source, options); + read(options?: ReadFileOptions): Promise { + return readFile(this.source, options) as Promise; } - readSync(options?: ReadFileOptions): string | Buffer { - return readFileSync(this.source, options); + readSync(options?: ReadFileOptions): string { + return readFileSync(this.source, options) as string; } stat(): Promise { diff --git a/lib/hexo/load_config.ts b/lib/hexo/load_config.ts index 489f4e03ff..49ed3ba3ef 100644 --- a/lib/hexo/load_config.ts +++ b/lib/hexo/load_config.ts @@ -8,7 +8,7 @@ import { deepMerge } from 'hexo-util'; import validateConfig from './validate_config'; import type Hexo from './index'; -export = async (ctx: Hexo) => { +export = async (ctx: Hexo): Promise => { if (!ctx.env.init) return; const baseDir = ctx.base_dir; @@ -66,7 +66,7 @@ export = async (ctx: Hexo) => { }; -async function findConfigPath(path: string) { +async function findConfigPath(path: string): Promise { const { dir, name } = parse(path); const files = await readdir(dir); diff --git a/lib/hexo/load_database.ts b/lib/hexo/load_database.ts index f0ac5decb0..f816a6f0ea 100644 --- a/lib/hexo/load_database.ts +++ b/lib/hexo/load_database.ts @@ -2,7 +2,7 @@ import { exists, unlink } from 'hexo-fs'; import Promise from 'bluebird'; import type Hexo from './index'; -export = (ctx: Hexo) => { +export = (ctx: Hexo): Promise => { if (ctx._dbLoaded) return Promise.resolve(); const db = ctx.database; diff --git a/lib/hexo/load_plugins.ts b/lib/hexo/load_plugins.ts index 289474f00f..49802f9292 100644 --- a/lib/hexo/load_plugins.ts +++ b/lib/hexo/load_plugins.ts @@ -4,13 +4,13 @@ import Promise from 'bluebird'; import { magenta } from 'picocolors'; import type Hexo from './index'; -export = (ctx: Hexo) => { +export = (ctx: Hexo): Promise => { if (!ctx.env.init || ctx.env.safe) return; return loadModules(ctx).then(() => loadScripts(ctx)); }; -function loadModuleList(ctx: Hexo, basedir: string) { +function loadModuleList(ctx: Hexo, basedir: string): Promise { const packagePath = join(basedir, 'package.json'); // Make sure package.json exists diff --git a/lib/hexo/load_theme_config.ts b/lib/hexo/load_theme_config.ts index 54c700960a..11056504aa 100644 --- a/lib/hexo/load_theme_config.ts +++ b/lib/hexo/load_theme_config.ts @@ -4,8 +4,9 @@ import { exists, readdir } from 'hexo-fs'; import { magenta } from 'picocolors'; import { deepMerge } from 'hexo-util'; import type Hexo from './index'; +import type Promise from 'bluebird'; -export = (ctx: Hexo) => { +export = (ctx: Hexo): Promise => { if (!ctx.env.init) return; if (!ctx.config.theme) return; @@ -31,7 +32,7 @@ export = (ctx: Hexo) => { }); }; -function findConfigPath(path: string) { +function findConfigPath(path: string): Promise { const { dir, name } = parse(path); return readdir(dir).then(files => { diff --git a/lib/hexo/locals.ts b/lib/hexo/locals.ts index 7153cb0a48..ef3b51eb27 100644 --- a/lib/hexo/locals.ts +++ b/lib/hexo/locals.ts @@ -20,7 +20,7 @@ class Locals { }); } - set(name: string, value: any) { + set(name: string, value: any): this { if (typeof name !== 'string') throw new TypeError('name must be a string!'); if (value == null) throw new TypeError('value is required!'); @@ -32,7 +32,7 @@ class Locals { return this; } - remove(name: string) { + remove(name: string): this { if (typeof name !== 'string') throw new TypeError('name must be a string!'); this.getters[name] = null; @@ -41,7 +41,7 @@ class Locals { return this; } - invalidate() { + invalidate(): this { this.cache.flush(); return this; diff --git a/lib/hexo/multi_config_path.ts b/lib/hexo/multi_config_path.ts index 978c04fca0..f17e332532 100644 --- a/lib/hexo/multi_config_path.ts +++ b/lib/hexo/multi_config_path.ts @@ -4,7 +4,7 @@ import yml from 'js-yaml'; import { deepMerge } from 'hexo-util'; import type Hexo from './index'; -export = (ctx: Hexo) => function multiConfigPath(base: string, configPaths: string, outputDir: string) { +export = (ctx: Hexo) => function multiConfigPath(base: string, configPaths: string, outputDir: string): string { const { log } = ctx; const defaultPath = join(base, '_config.yml'); @@ -43,7 +43,7 @@ export = (ctx: Hexo) => function multiConfigPath(base: string, configPaths: stri } // files read synchronously to ensure proper overwrite order - const file = readFileSync(configPath); + const file = readFileSync(configPath) as string; const ext = extname(paths[i]).toLowerCase(); if (ext === '.yml') { diff --git a/lib/hexo/register_models.ts b/lib/hexo/register_models.ts index 88a73e6081..f6bb39b3ae 100644 --- a/lib/hexo/register_models.ts +++ b/lib/hexo/register_models.ts @@ -1,7 +1,7 @@ import * as models from '../models'; import type Hexo from './index'; -export = (ctx: Hexo) => { +export = (ctx: Hexo): void => { const db = ctx.database; const keys = Object.keys(models); diff --git a/lib/hexo/render.ts b/lib/hexo/render.ts index 4d1ebda922..7a0240c567 100644 --- a/lib/hexo/render.ts +++ b/lib/hexo/render.ts @@ -3,16 +3,17 @@ import Promise from 'bluebird'; import { readFile, readFileSync } from 'hexo-fs'; import type Hexo from './index'; import type { Renderer } from '../extend'; -import type { StoreFunctionData } from '../extend/renderer'; +import type { StoreFunction, StoreFunctionData, StoreSyncFunction } from '../extend/renderer'; +import { NodeJSLikeCallback } from '../types'; -const getExtname = (str: string) => { +const getExtname = (str: string): string => { if (typeof str !== 'string') return ''; const ext = extname(str); return ext.startsWith('.') ? ext.slice(1) : ext; }; -const toString = (result, options) => { +const toString = (result: any, options: StoreFunctionData) => { if (!Object.prototype.hasOwnProperty.call(options, 'toString') || typeof result === 'string') return result; if (typeof options.toString === 'function') { @@ -35,27 +36,27 @@ class Render { this.renderer = ctx.extend.renderer; } - isRenderable(path: string) { + isRenderable(path: string): boolean { return this.renderer.isRenderable(path); } - isRenderableSync(path: string) { + isRenderableSync(path: string): boolean { return this.renderer.isRenderableSync(path); } - getOutput(path: string) { + getOutput(path: string): string { return this.renderer.getOutput(path); } - getRenderer(ext: string, sync?: boolean) { + getRenderer(ext: string, sync?: boolean): StoreSyncFunction | StoreFunction { return this.renderer.get(ext, sync); } - getRendererSync(ext: string) { + getRendererSync(ext: string): StoreSyncFunction | StoreFunction { return this.getRenderer(ext, true); } - render(data: StoreFunctionData, options?: { highlight?: boolean; }, callback?: undefined) { + render(data: StoreFunctionData, options?: { highlight?: boolean; }, callback?: NodeJSLikeCallback): Promise { if (!callback && typeof options === 'function') { callback = options; options = {}; @@ -64,7 +65,7 @@ class Render { const ctx = this.context; let ext = ''; - let promise; + let promise: Promise; if (!data) return Promise.reject(new TypeError('No input file or string!')); @@ -76,7 +77,7 @@ class Render { promise = readFile(data.path); } - return promise.then(text => { + return promise.then((text: string) => { data.text = text; ext = data.engine || getExtname(data.path); if (!ext || !this.isRenderable(ext)) return text; @@ -99,7 +100,7 @@ class Render { }).asCallback(callback); } - renderSync(data: StoreFunctionData, options = {}) { + renderSync(data: StoreFunctionData, options = {}): any { if (!data) throw new TypeError('No input file or string!'); const ctx = this.context; diff --git a/lib/hexo/router.ts b/lib/hexo/router.ts index 33edb61478..8d9965e483 100644 --- a/lib/hexo/router.ts +++ b/lib/hexo/router.ts @@ -17,7 +17,7 @@ declare module 'stream' { class RouteStream extends Readable { public _data: any; public _ended: boolean; - public modified: any; + public modified: boolean; constructor(data: Data) { super({ objectMode: true }); @@ -28,7 +28,7 @@ class RouteStream extends Readable { } // Assume we only accept Buffer, plain object, or string - _toBuffer(data) { + _toBuffer(data: Buffer | object | string): Buffer | null { if (data instanceof Buffer) { return data; } @@ -41,7 +41,7 @@ class RouteStream extends Readable { return null; } - _read() { + _read(): boolean { const data = this._data; if (typeof data !== 'function') { @@ -84,7 +84,7 @@ class RouteStream extends Readable { } } -const _format = (path: string) => { +const _format = (path: string): string => { path = path || ''; if (typeof path !== 'string') throw new TypeError('path must be a string!'); @@ -113,16 +113,16 @@ class Router extends EventEmitter { this.routes = {}; } - list() { + list(): string[] { const { routes } = this; return Object.keys(routes).filter(key => routes[key]); } - format(path: string) { + format(path: string): string { return _format(path); } - get(path: string) { + get(path: string): RouteStream { if (typeof path !== 'string') throw new TypeError('path must be a string!'); const data = this.routes[this.format(path)]; @@ -131,14 +131,14 @@ class Router extends EventEmitter { return new RouteStream(data); } - isModified(path: string) { + isModified(path: string): boolean { if (typeof path !== 'string') throw new TypeError('path must be a string!'); const data = this.routes[this.format(path)]; return data ? data.modified : false; } - set(path: string, data: any) { + set(path: string, data: any): this { if (typeof path !== 'string') throw new TypeError('path must be a string!'); if (data == null) throw new TypeError('data is required!'); @@ -173,7 +173,7 @@ class Router extends EventEmitter { return this; } - remove(path: string) { + remove(path: string): this { if (typeof path !== 'string') throw new TypeError('path must be a string!'); path = this.format(path); diff --git a/lib/hexo/scaffold.ts b/lib/hexo/scaffold.ts index 0f167413f9..9f44137114 100644 --- a/lib/hexo/scaffold.ts +++ b/lib/hexo/scaffold.ts @@ -2,11 +2,14 @@ import { extname, join } from 'path'; import { exists, listDir, readFile, unlink, writeFile } from 'hexo-fs'; import type Hexo from './index'; import type { NodeJSLikeCallback } from '../types'; +import type Promise from 'bluebird'; class Scaffold { public context: Hexo; public scaffoldDir: string; - public defaults: any; + public defaults: { + normal: string + }; constructor(context: Hexo) { this.context = context; @@ -23,7 +26,10 @@ class Scaffold { }; } - _listDir() { + _listDir(): Promise<{ + name: string; + path: string; + }[]> { const { scaffoldDir } = this; return exists(scaffoldDir).then(exist => { @@ -38,11 +44,14 @@ class Scaffold { })); } - _getScaffold(name: string) { + _getScaffold(name: string): Promise<{ + name: string; + path: string; + }> { return this._listDir().then(list => list.find(item => item.name === name)); } - get(name: string, callback?: NodeJSLikeCallback) { + get(name: string, callback?: NodeJSLikeCallback): Promise { return this._getScaffold(name).then(item => { if (item) { return readFile(item.path); @@ -52,7 +61,7 @@ class Scaffold { }).asCallback(callback); } - set(name: string, content: any, callback: NodeJSLikeCallback) { + set(name: string, content: any, callback: NodeJSLikeCallback): Promise { const { scaffoldDir } = this; return this._getScaffold(name).then(item => { @@ -63,7 +72,7 @@ class Scaffold { }).asCallback(callback); } - remove(name: string, callback: NodeJSLikeCallback) { + remove(name: string, callback: NodeJSLikeCallback): Promise { return this._getScaffold(name).then(item => { if (!item) return; diff --git a/lib/hexo/update_package.ts b/lib/hexo/update_package.ts index 4b8f3593bd..7913a67f67 100644 --- a/lib/hexo/update_package.ts +++ b/lib/hexo/update_package.ts @@ -1,8 +1,9 @@ import { join } from 'path'; import { writeFile, exists, readFile } from 'hexo-fs'; import type Hexo from './index'; +import type Promise from 'bluebird'; -export = (ctx: Hexo) => { +export = (ctx: Hexo): Promise => { const pkgPath = join(ctx.base_dir, 'package.json'); return readPkg(pkgPath).then(pkg => { @@ -19,7 +20,7 @@ export = (ctx: Hexo) => { }); }; -function readPkg(path: string) { +function readPkg(path: string): Promise { return exists(path).then(exist => { if (!exist) return; diff --git a/lib/hexo/validate_config.ts b/lib/hexo/validate_config.ts index 66af8ceeba..c7ca6477bd 100644 --- a/lib/hexo/validate_config.ts +++ b/lib/hexo/validate_config.ts @@ -1,6 +1,6 @@ import type Hexo from './index'; -export = (ctx: Hexo) => { +export = (ctx: Hexo): void => { const { config, log } = ctx; log.info('Validating config'); diff --git a/lib/plugins/renderer/json.ts b/lib/plugins/renderer/json.ts index c5d02377f9..e4833402c3 100644 --- a/lib/plugins/renderer/json.ts +++ b/lib/plugins/renderer/json.ts @@ -1,6 +1,6 @@ import type { StoreFunctionData } from '../../extend/renderer'; -function jsonRenderer(data: StoreFunctionData) { +function jsonRenderer(data: StoreFunctionData): any { return JSON.parse(data.text); } diff --git a/lib/plugins/renderer/nunjucks.ts b/lib/plugins/renderer/nunjucks.ts index ccb0281346..1b854f1ebc 100644 --- a/lib/plugins/renderer/nunjucks.ts +++ b/lib/plugins/renderer/nunjucks.ts @@ -22,7 +22,7 @@ function toArray(value) { return []; } -function safeJsonStringify(json, spacer = undefined) { +function safeJsonStringify(json: any, spacer = undefined): string { if (typeof json !== 'undefined' && json !== null) { return JSON.stringify(json, null, spacer); } @@ -37,12 +37,12 @@ const nunjucksCfg = { lstripBlocks: false }; -const nunjucksAddFilter = (env: Environment) => { +const nunjucksAddFilter = (env: Environment): void => { env.addFilter('toarray', toArray); env.addFilter('safedump', safeJsonStringify); }; -function njkCompile(data: StoreFunctionData) { +function njkCompile(data: StoreFunctionData): nunjucks.Template { let env: Environment; if (data.path) { env = nunjucks.configure(dirname(data.path), nunjucksCfg); @@ -56,11 +56,11 @@ function njkCompile(data: StoreFunctionData) { return nunjucks.compile(text as string, env, data.path); } -function njkRenderer(data: StoreFunctionData, locals: object) { +function njkRenderer(data: StoreFunctionData, locals: object): string { return njkCompile(data).render(locals); } -njkRenderer.compile = (data: StoreFunctionData) => { +njkRenderer.compile = (data: StoreFunctionData): (locals: any) => string => { // Need a closure to keep the compiled template. return locals => njkCompile(data).render(locals); }; diff --git a/lib/plugins/renderer/plain.ts b/lib/plugins/renderer/plain.ts index 99c35a1c1c..f537106a8d 100644 --- a/lib/plugins/renderer/plain.ts +++ b/lib/plugins/renderer/plain.ts @@ -1,6 +1,6 @@ import type { StoreFunctionData } from '../../extend/renderer'; -function plainRenderer(data: StoreFunctionData) { +function plainRenderer(data: StoreFunctionData): string { return data.text; } diff --git a/lib/plugins/renderer/yaml.ts b/lib/plugins/renderer/yaml.ts index fd460d14a0..ceef7f7a15 100644 --- a/lib/plugins/renderer/yaml.ts +++ b/lib/plugins/renderer/yaml.ts @@ -3,7 +3,7 @@ import { escape } from 'hexo-front-matter'; import logger from 'hexo-log'; import type { StoreFunctionData } from '../../extend/renderer'; -let schema = {}; +let schema: yaml.Schema; // FIXME: workaround for https://github.com/hexojs/hexo/issues/4917 try { schema = yaml.DEFAULT_SCHEMA.extend(require('js-yaml-js-types').all); @@ -15,7 +15,7 @@ try { } } -function yamlHelper(data: StoreFunctionData) { +function yamlHelper(data: StoreFunctionData): any { return yaml.load(escape(data.text), { schema }); } diff --git a/lib/theme/index.ts b/lib/theme/index.ts index aff5a74711..41c83d6bfe 100644 --- a/lib/theme/index.ts +++ b/lib/theme/index.ts @@ -7,15 +7,19 @@ import { i18n } from './processors/i18n'; import { source } from './processors/source'; import { view } from './processors/view'; import type Hexo from '../hexo'; +import type { Pattern } from 'hexo-util'; class Theme extends Box { - public config: any; - public views: any; + public config: object; + public views: Record>; public i18n: I18n; - public View: any; - public processors: any[]; + public View: typeof View; + public processors: { + pattern: Pattern; + process: (...args: any[]) => any; + }[]; - constructor(ctx: Hexo, options?) { + constructor(ctx: Hexo, options?: object) { super(ctx, ctx.theme_dir, options); this.config = {}; @@ -48,7 +52,7 @@ class Theme extends Box { _View.prototype._helper = ctx.extend.helper; } - getView(path: string) { + getView(path: string): View { // Replace backslashes on Windows path = path.replace(/\\/g, '/'); @@ -65,7 +69,7 @@ class Theme extends Box { return views[Object.keys(views)[0]]; } - setView(path: string, data) { + setView(path: string, data: string): void { const ext = extname(path); const name = path.substring(0, path.length - ext.length); this.views[name] = this.views[name] || {}; @@ -74,7 +78,7 @@ class Theme extends Box { views[ext] = new this.View(path, data); } - removeView(path: string) { + removeView(path: string): void { const ext = extname(path); const name = path.substring(0, path.length - ext.length); const views = this.views[name]; diff --git a/lib/theme/processors/view.ts b/lib/theme/processors/view.ts index c127d02e7c..89d5205423 100644 --- a/lib/theme/processors/view.ts +++ b/lib/theme/processors/view.ts @@ -2,7 +2,7 @@ import { Pattern } from 'hexo-util'; import type { _File } from '../../box'; import type Theme from '..'; -function process(file: _File) { +function process(file: _File): Promise { const { path } = file.params; if (file.type === 'delete') { diff --git a/lib/theme/view.ts b/lib/theme/view.ts index e96d2f0538..c693a3ded5 100644 --- a/lib/theme/view.ts +++ b/lib/theme/view.ts @@ -4,6 +4,7 @@ import Promise from 'bluebird'; import type Theme from '.'; import type Render from '../hexo/render'; import type { NodeJSLikeCallback } from '../types'; +import type { Helper } from '../extend'; const assignIn = (target: any, ...sources: any[]) => { const length = sources.length; @@ -30,10 +31,10 @@ class View { public data: any; public _compiled: any; public _compiledSync: any; - public _helper: any; + public _helper: Helper; public _render: Render; - constructor(path: string, data) { + constructor(path: string, data: string) { this.path = path; this.source = join(this._theme.base, 'layout', path); this.data = typeof data === 'string' ? yfm(data) : data; @@ -42,7 +43,7 @@ class View { } render(callback: NodeJSLikeCallback): Promise; - render(options: Options, callback: NodeJSLikeCallback): Promise; + render(options: Options, callback?: NodeJSLikeCallback): Promise; render(options: Options | NodeJSLikeCallback = {}, callback?: NodeJSLikeCallback): Promise { if (!callback && typeof options === 'function') { callback = options; @@ -107,7 +108,7 @@ class View { return locals; } - _resolveLayout(name: string) { + _resolveLayout(name: string): View { // Relative path const layoutPath = join(dirname(this.path), name); let layoutView = this._theme.getView(layoutPath); @@ -119,7 +120,7 @@ class View { if (layoutView && layoutView.source !== this.source) return layoutView; } - _precompile() { + _precompile(): void { const render = this._render; const ctx = render.context; const ext = extname(this.path); diff --git a/package.json b/package.json index 9eefc8dfec..a92319e548 100644 --- a/package.json +++ b/package.json @@ -68,6 +68,7 @@ "devDependencies": { "@types/abbrev": "^1.1.3", "@types/bluebird": "^3.5.37", + "@types/js-yaml": "^4.0.9", "@types/node": "^18.11.8", "@types/nunjucks": "^3.2.2", "@types/text-table": "^0.2.4",