Skip to content

Commit

Permalink
refactor: config
Browse files Browse the repository at this point in the history
  • Loading branch information
sorrycc committed Nov 14, 2024
1 parent 3faadb0 commit f0f2f81
Show file tree
Hide file tree
Showing 10 changed files with 172 additions and 104 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ $ pnpm release:create-tnf
We use [Prettier](https://prettier.io/) to format the code, please run `pnpm format` to format the code. And we also have some other rules:
- Do not use specifiers for `fs` and `path` modules.
- Do use `pathe` instead of `path` module.
- Do use `pathe` instead of `path` module for windows compatibility.
```ts
// bad
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Tnf, ~~the north face~~, the next framework. Tnf is focused on simple, performan
- Conventional global style with `src/global.{less,css}`.
- Less, CSS Modules support built-in.
- Tailwind CSS support built-in.
- [ ] Framework unplugin which is compatible with umi and other frameworks.
- Framework unified plugin system which is compatible with umi and other frameworks.
- [ ] Security built-in. Including doctor rules which is used in Ant Group.
- [ ] Support SSR, API routes and server functions.
- [ ] AI based generator and other features.
Expand Down
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import assert from 'assert';
import path from 'pathe';
import yargsParser from 'yargs-parser';
import { loadConfig } from './config';
import { loadConfig } from './config/config';
import { FRAMEWORK_NAME, MIN_NODE_VERSION } from './constants';
import { checkVersion, setNoDeprecation, setNodeTitle } from './fishkit/node';
import { PluginManager } from './plugin/plugin_manager';
Expand Down
98 changes: 0 additions & 98 deletions src/config.ts

This file was deleted.

50 changes: 50 additions & 0 deletions src/config/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {
loadConfig as loadC12Config,
watchConfig as watchC12Config,
} from 'c12';
import { CONFIG_FILE } from '../constants';
import type { Config } from './types';
import { ConfigSchema } from './types';

interface ConfigOpts {
cwd: string;
defaults?: Partial<Config>;
overrides?: Partial<Config>;
}

export async function loadConfig(opts: ConfigOpts): Promise<Config> {
const { config: rawConfig } = await loadC12Config(createLoadConfigOpts(opts));
const result = ConfigSchema.safeParse(rawConfig);
if (!result.success) {
throw new Error(`Invalid configuration: ${result.error.message}`);
}
return result.data;
}

export function watchConfig(opts: ConfigOpts) {
return watchC12Config({
...createLoadConfigOpts(opts),
onWatch(event) {
console.log(event);
},
onUpdate({ oldConfig, newConfig, getDiff }) {
const result = ConfigSchema.safeParse(newConfig);
if (!result.success) {
console.error(`Invalid configuration: ${result.error.message}`);
return;
}
console.log('onUpdate', oldConfig, result.data, getDiff());
},
});
}

function createLoadConfigOpts({ cwd, defaults, overrides }: ConfigOpts) {
return {
cwd,
configFile: CONFIG_FILE,
rcFile: false as const,
globalRc: false as const,
defaults,
overrides,
};
}
50 changes: 50 additions & 0 deletions src/config/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { z } from 'zod';
import { PluginSchema } from '../plugin/types';

export const ConfigSchema = z.object({
externals: z.record(z.string()).optional(),
devServer: z
.object({
port: z.number().optional(),
https: z
.object({
hosts: z.array(z.string()).optional(),
})
.optional(),
ip: z.string().optional(),
host: z.string().optional(),
})
.optional(),
less: z
.object({
modifyVars: z.any().optional(),
globalVars: z.any().optional(),
math: z.any().optional(),
sourceMap: z.any(),
plugins: z.array(z.any()).optional(),
})
.optional(),
plugins: z.array(PluginSchema).optional(),
router: z
.object({
defaultPreload: z.enum(['intent', 'render', 'viewport']).optional(),
defaultPreloadDelay: z.number().optional(),
devtool: z
.union([
z.object({
options: z.object({
initialIsOpen: z.boolean().optional(),
position: z
.enum(['bottom-left', 'bottom-right', 'top-left', 'top-right'])
.optional(),
}),
}),
z.literal(false),
])
.optional(),
})
.optional(),
tailwindcss: z.boolean().optional(),
});

export type Config = z.infer<typeof ConfigSchema>;
2 changes: 1 addition & 1 deletion src/fishkit/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import proxy from 'express-http-proxy';
import { getPort } from 'get-port-please';
import http from 'http';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { type Config } from '../config';
import type { Config } from '../config/types';
import { DEFAULT_PORT } from '../constants';
import { createHttpsServer } from './https';

Expand Down
1 change: 0 additions & 1 deletion src/generate/generate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type yargsParser from 'yargs-parser';
import type { Context } from '../types';
import { generatePage } from './generate_page';

Expand Down
67 changes: 67 additions & 0 deletions src/plugin_manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import type { Plugin } from './plugin/types';

type PluginKey = keyof Plugin;

enum HookType {
First = 'first',
Series = 'series',
Parallel = 'parallel',
}

export class PluginManager {
#plugins: Plugin[] = [];
constructor(rawPlugins: Plugin[]) {
this.#plugins = [
...rawPlugins.filter((p) => p.enforce === 'pre'),
...rawPlugins.filter((p) => !p.enforce),
...rawPlugins.filter((p) => p.enforce === 'post'),
];
}

async apply({
hook,
args,
type = HookType.Series,
}: {
hook: PluginKey;
args: any;
type: HookType;
}) {
const plugins = this.#plugins.filter((p) => !!p[hook]);

if (type === HookType.First) {
for (const plugin of plugins) {
const hookFn = plugin[hook];
if (typeof hookFn === 'function') {
const result = await hookFn(args);
if (result != null) {
return result;
}
}
}
return null;
}

if (type === HookType.Parallel) {
const results = await Promise.all(
plugins.map((p) => {
const hookFn = p[hook];
if (typeof hookFn === 'function') {
return hookFn(args);
}
return null;
}),
);
return results.filter((r) => r != null);
}

let result = args;
for (const plugin of plugins) {
const hookFn = plugin[hook];
if (typeof hookFn === 'function') {
result = await hookFn(result);
}
}
return result;
}
}
2 changes: 1 addition & 1 deletion src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type yargsParser from 'yargs-parser';
import type { Config } from '../config';
import type { Config } from '../config/types';
import type { PluginManager } from '../plugin/plugin_manager';
import type { Plugin } from '../plugin/types';

Expand Down

0 comments on commit f0f2f81

Please sign in to comment.