Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: refactor: refactor types #5483

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions lib/box/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,38 @@ import { readFile, readFileSync, stat, statSync, type ReadFileOptions } from 'he
import type fs from 'fs';

class File {

/**
* Full path of the file
*/
public source: string;

/**
* Relative path to the box of the file
*/
public path: string;

/**
* The information from path matching.
*/
public params: any;
public type: string;

/**
* File type. The value can be create, update, skip, delete.
*/
// eslint-disable-next-line no-use-before-define
public type: typeof File.TYPE_CREATE | typeof File.TYPE_UPDATE | typeof File.TYPE_SKIP | typeof File.TYPE_DELETE;
static TYPE_CREATE: 'create';
static TYPE_UPDATE: 'update';
static TYPE_SKIP: 'skip';
static TYPE_DELETE: 'delete';

constructor({ source, path, params, type }) {
constructor({ source, path, params, type }: {
source: string;
path: string;
params: any;
type: typeof File.TYPE_CREATE | typeof File.TYPE_UPDATE | typeof File.TYPE_SKIP | typeof File.TYPE_DELETE;
SukkaW marked this conversation as resolved.
Show resolved Hide resolved
}) {
this.source = source;
this.path = path;
this.params = params;
Expand Down
19 changes: 10 additions & 9 deletions lib/box/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { EventEmitter } from 'events';
import { isMatch, makeRe } from 'micromatch';
import type Hexo from '../hexo';
import type { NodeJSLikeCallback } from '../types';
import type fs from 'fs';

const defaultPattern = new Pattern(() => ({}));

Expand Down Expand Up @@ -101,7 +102,7 @@ class Box extends EventEmitter {

_readDir(base: string, prefix = ''): BlueBirdPromise<any> {
const { context: ctx } = this;
const results = [];
const results: string[] = [];
return readDirWalker(ctx, base, results, this.ignore, prefix)
.return(results)
.map(path => this._checkFileStatus(path))
Expand Down Expand Up @@ -266,30 +267,30 @@ function toRegExp(ctx: Hexo, arg: string): RegExp | null {
return result;
}

function isIgnoreMatch(path: string, ignore: string | any[]): boolean {
function isIgnoreMatch(path: string, ignore: string | string[]): boolean {
return path && ignore && ignore.length && isMatch(path, ignore);
}

function readDirWalker(ctx: Hexo, base: string, results: any[], ignore: any, prefix: string): BlueBirdPromise<any> {
function readDirWalker(ctx: Hexo, base: string, results: string[], ignore: string | string[], prefix: string): BlueBirdPromise<any> {
if (isIgnoreMatch(base, ignore)) return BlueBirdPromise.resolve();

return BlueBirdPromise.map(readdir(base).catch(err => {
ctx.log.error({ err }, 'Failed to read directory: %s', base);
if (err && err.code === 'ENOENT') return [];
throw err;
}), async path => {
const fullpath = join(base, path);
const stats = await stat(fullpath).catch(err => {
ctx.log.error({ err }, 'Failed to stat file: %s', fullpath);
}), async (path: string) => {
const fullPath = join(base, path);
const stats: fs.Stats = await stat(fullPath).catch(err => {
ctx.log.error({ err }, 'Failed to stat file: %s', fullPath);
if (err && err.code === 'ENOENT') return null;
throw err;
});
const prefixPath = `${prefix}${path}`;
if (stats) {
if (stats.isDirectory()) {
return readDirWalker(ctx, fullpath, results, ignore, `${prefixPath}/`);
return readDirWalker(ctx, fullPath, results, ignore, `${prefixPath}/`);
}
if (!isIgnoreMatch(fullpath, ignore)) {
if (!isIgnoreMatch(fullPath, ignore)) {
results.push(prefixPath);
}
}
Expand Down
3 changes: 3 additions & 0 deletions lib/extend/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ interface Alias {
[abbreviation: string]: string
}

/**
* The console forms the bridge between Hexo and its users. It registers and describes the available console commands.
*/
class Console {
public store: Store;
public alias: Alias;
Expand Down
3 changes: 3 additions & 0 deletions lib/extend/deployer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ interface Store {
[key: string]: StoreFunction
}

/**
* A deployer helps users quickly deploy their site to a remote server without complicated commands.
*/
class Deployer {
public store: Store;

Expand Down
4 changes: 4 additions & 0 deletions lib/extend/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ interface Store {
[key: string]: StoreFunction[]
}

/**
* A filter is used to modify some specified data. Hexo passes data to filters in sequence and the filters then modify the data one after the other.
* This concept was borrowed from WordPress.
*/
class Filter {
public store: Store;

Expand Down
3 changes: 3 additions & 0 deletions lib/extend/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ interface Store {
[key: string]: StoreFunction
}

/**
* A generator builds routes based on processed files.
*/
class Generator {
public id: number;
public store: Store;
Expand Down
4 changes: 3 additions & 1 deletion lib/extend/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ interface Store {
[key: string]: StoreFunction
}


/**
* A helper makes it easy to quickly add snippets to your templates. We recommend using helpers instead of templates when you’re dealing with more complicated code.
*/
class Helper {
public store: Store;

Expand Down
4 changes: 4 additions & 0 deletions lib/extend/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ type Store = {
};
};

/**
* An injector is used to add static code snippet to the `<head>` or/and `<body>` of generated HTML files.
* Hexo run injector before `after_render:html` filter is executed.
*/
class Injector {
public store: Store;
public cache: any;
Expand Down
3 changes: 3 additions & 0 deletions lib/extend/migrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ interface Store {
[key: string]: StoreFunction
}

/**
* A migrator helps users migrate from other systems to Hexo.
*/
class Migrator {
public store: Store;

Expand Down
4 changes: 4 additions & 0 deletions lib/extend/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ type Store = {
}[];

type patternType = Exclude<ConstructorParameters<typeof Pattern>[0], ((str: string) => string)>;

/**
* A processor is used to process source files in the `source` folder.
*/
class Processor {
public store: Store;

Expand Down
3 changes: 3 additions & 0 deletions lib/extend/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ interface Store {
[key: string]: StoreFunction;
}

/**
* A renderer is used to render content.
*/
class Renderer {
public store: Store;
public storeSync: SyncStore;
Expand Down
3 changes: 3 additions & 0 deletions lib/extend/tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
return node;
}

run(context, args, body, callback) {

Check warning on line 62 in lib/extend/tag.ts

View workflow job for this annotation

GitHub Actions / linter

'body' is defined but never used

Check warning on line 62 in lib/extend/tag.ts

View workflow job for this annotation

GitHub Actions / linter

'callback' is defined but never used
return this._run(context, args, '');
}

Expand All @@ -80,14 +80,14 @@
return new nodes.CallExtension(this, 'run', node, [body]);
}

_parseBody(parser, nodes, lexer) {

Check warning on line 83 in lib/extend/tag.ts

View workflow job for this annotation

GitHub Actions / linter

'nodes' is defined but never used

Check warning on line 83 in lib/extend/tag.ts

View workflow job for this annotation

GitHub Actions / linter

'lexer' is defined but never used
const body = parser.parseUntilBlocks(`end${this.tags[0]}`);

parser.advanceAfterBlockEnd();
return body;
}

run(context, args, body, callback) {

Check warning on line 90 in lib/extend/tag.ts

View workflow job for this annotation

GitHub Actions / linter

'callback' is defined but never used
return this._run(context, args, trimBody(body));
}
}
Expand Down Expand Up @@ -200,6 +200,9 @@
ends?: boolean;
}

/**
* A tag allows users to quickly and easily insert snippets into their posts.
*/
class Tag {
public env: Environment;
public source: string;
Expand Down
6 changes: 3 additions & 3 deletions lib/hexo/default_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export = {
category_dir: 'categories',
code_dir: 'downloads/code',
i18n_dir: ':lang',
skip_render: [],
skip_render: [] as string[],
// Writing
new_post_name: ':title.md',
default_layout: 'post',
Expand All @@ -44,7 +44,7 @@ export = {
line_number: true,
tab_replace: '',
wrap: true,
exclude_languages: [],
exclude_languages: [] as string[],
language_attr: false,
hljs: false,
line_threshold: 0,
Expand All @@ -55,7 +55,7 @@ export = {
preprocess: true,
line_number: true,
tab_replace: '',
exclude_languages: [],
exclude_languages: [] as string[],
strip_indent: true
},
use_filename_as_post_title: false,
Expand Down
58 changes: 57 additions & 1 deletion lib/hexo/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,37 @@ function debounce(func: () => void, wait: number): () => void {
}

interface Args {

/**
* Enable debug mode. Display debug messages in the terminal and save debug.log in the root directory.
*/
debug?: boolean;

/**
* Enable safe mode. Don’t load any plugins.
*/
safe?: boolean;

/**
* Enable silent mode. Don’t display any messages in the terminal.
*/
silent?: boolean;

/**
* Enable to add drafts to the posts list.
*/
draft?: boolean;

/**
* Enable to add drafts to the posts list.
*/
drafts?: boolean;
_?: string[];
output?: string;

/**
* Specify the path of the configuration file.
*/
config?: string;
[key: string]: any;
}
Expand Down Expand Up @@ -407,6 +431,11 @@ class Hexo extends EventEmitter {
});
}

/**
* Load configuration and plugins.
* @returns {Promise}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use TypeScript definition only, the JSDoc types can be omitted.

* @link https://hexo.io/api#Initialize
*/
init(): Promise<void> {
this.log.debug('Hexo version: %s', magenta(this.version));
this.log.debug('Working directory: %s', magenta(tildify(this.base_dir)));
Expand Down Expand Up @@ -434,6 +463,14 @@ class Hexo extends EventEmitter {
});
}

/**
* Call any console command explicitly.
* @param name
* @param args
* @param callback
* @returns {Promise}
* @link https://hexo.io/api#Execute-Commands
*/
call(name: string, callback?: NodeJSLikeCallback<any>): Promise<any>;
call(name: string, args: object, callback?: NodeJSLikeCallback<any>): Promise<any>;
call(name: string, args?: object | NodeJSLikeCallback<any>, callback?: NodeJSLikeCallback<any>): Promise<any> {
Expand Down Expand Up @@ -500,6 +537,12 @@ class Hexo extends EventEmitter {
return args.draft || args.drafts || this.config.render_drafts;
}

/**
* Load all files in the source folder as well as the theme data.
* @param callback
* @returns {Promise}
* @link https://hexo.io/api#Load-Files
*/
load(callback?: NodeJSLikeCallback<any>): Promise<any> {
return loadDatabase(this).then(() => {
this.log.info('Start processing');
Expand All @@ -514,6 +557,13 @@ class Hexo extends EventEmitter {
}).asCallback(callback);
}

/**
* Load all files in the source folder as well as the theme data.
* Start watching for file changes continuously.
* @param callback
* @returns {Promise}
* @link https://hexo.io/api#Load-Files
*/
watch(callback?: NodeJSLikeCallback<any>): Promise<any> {
let useCache = false;
const { cache } = Object.assign({
Expand Down Expand Up @@ -622,7 +672,7 @@ class Hexo extends EventEmitter {
// add Route
const path = route.format(generatorResult.path);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// @ts-expect-error
const { data, layout } = generatorResult;

if (!layout) {
Expand Down Expand Up @@ -666,6 +716,12 @@ class Hexo extends EventEmitter {
});
}

/**
* Exit gracefully and finish up important things such as saving the database.
* @param err
* @returns {Promise}
* @link https://hexo.io/api/#Exit
*/
exit(err?: any): Promise<void> {
if (err) {
this.log.fatal(
Expand Down
3 changes: 2 additions & 1 deletion lib/models/asset.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import warehouse from 'warehouse';
import { join } from 'path';
import type Hexo from '../hexo';
import type { AssetSchema } from '../types';

export = (ctx: Hexo) => {
const Asset = new warehouse.Schema({
Expand All @@ -10,7 +11,7 @@ export = (ctx: Hexo) => {
renderable: {type: Boolean, default: true}
});

Asset.virtual('source').get(function() {
Asset.virtual('source').get(function(this: AssetSchema) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's improve the warehouse's virtual type to infer this here.

return join(ctx.base_dir, this._id);
});

Expand Down
Loading
Loading