vite-plugin-mock-data 6.0.1 โ 6.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -186
- package/dist/configureServer.d.ts +7 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +80 -57
- package/dist/index.mjs +79 -56
- package/dist/loadRoutes.d.ts +2 -0
- package/dist/logger.d.ts +3 -0
- package/dist/typings.d.ts +16 -5
- package/package.json +18 -9
package/README.md
CHANGED
|
@@ -13,196 +13,21 @@
|
|
|
13
13
|
npm install vite-plugin-mock-data --save-dev
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
##
|
|
16
|
+
## Documentation
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
import { Config as SirvConfig, HTTPVersion, RouteOptions, Handler } from 'find-my-way';
|
|
18
|
+
For detailed usage instructions and API references, please visit the official documentation:
|
|
20
19
|
|
|
21
|
-
|
|
22
|
-
file?: string;
|
|
23
|
-
handler?: any | Handler<HTTPVersion.V1>;
|
|
24
|
-
options?: RouteOptions;
|
|
25
|
-
store?: any;
|
|
26
|
-
}
|
|
20
|
+
๐ [View Full Documentation](https://fengxinming.github.io/vite-plugins/plugins/vite-plugin-mock-data/quick-start)
|
|
27
21
|
|
|
28
|
-
|
|
29
|
-
[route: string]: string | Handler<HTTPVersion.V1> | HandleRoute;
|
|
30
|
-
}
|
|
22
|
+
## Contributing
|
|
31
23
|
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* The directory to serve files from.
|
|
35
|
-
* @default `process.cwd()`
|
|
36
|
-
*/
|
|
37
|
-
cwd?: string;
|
|
24
|
+
We welcome contributions from the community! If you find a bug or want to suggest an improvement, feel free to open an issue or submit a pull request.
|
|
38
25
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
isAfter?: boolean;
|
|
26
|
+
### How to Contribute
|
|
27
|
+
1. Fork the repository.
|
|
28
|
+
2. Create a new branch for your changes.
|
|
29
|
+
3. Submit a pull request with a clear description of your changes.
|
|
44
30
|
|
|
45
|
-
|
|
46
|
-
* Specify the directory to define mock assets.
|
|
47
|
-
*/
|
|
48
|
-
assets?: string;
|
|
31
|
+
## License
|
|
49
32
|
|
|
50
|
-
|
|
51
|
-
* Initial options of `find-my-way`. see more at https://github.com/delvedor/find-my-way#findmywayoptions
|
|
52
|
-
*/
|
|
53
|
-
routerOptions?: SirvConfig<HTTPVersion.V1> | SirvConfig<HTTPVersion.V2>;
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Initial list of mock routes that should be added to the dev server
|
|
57
|
-
* or specify the directory to define mock routes that should be added to the dev server.
|
|
58
|
-
*/
|
|
59
|
-
routes?: RouteConfig | Array<RouteConfig | string> | string;
|
|
60
|
-
}
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
* `cwd` - Default: `process.cwd()`.
|
|
64
|
-
* `isAfter` - If `true`, these mock routes is matched after internal middlewares are installed.
|
|
65
|
-
* `assets` - Specify the directory to define mock assets.
|
|
66
|
-
* `routerOptions` - [Initial options of `find-my-way`](https://github.com/delvedor/find-my-way#findmywayoptions)
|
|
67
|
-
* `routes`
|
|
68
|
-
* `RouteConfig | Array<RouteConfig | string>` - Initial list of mock routes that should be added to the dev server.
|
|
69
|
-
* `string` - Specify the directory to define mock routes that should be added to the dev server.
|
|
70
|
-
|
|
71
|
-
## Usage
|
|
72
|
-
|
|
73
|
-
### Specify the directory to define mock assets
|
|
74
|
-
|
|
75
|
-
```js
|
|
76
|
-
import { defineConfig } from 'vite';
|
|
77
|
-
import mockData from 'vite-plugin-mock-data';
|
|
78
|
-
|
|
79
|
-
export default defineConfig({
|
|
80
|
-
plugins: [
|
|
81
|
-
mockData({
|
|
82
|
-
assets: './mockAssets'
|
|
83
|
-
})
|
|
84
|
-
]
|
|
85
|
-
});
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
```txt
|
|
89
|
-
.
|
|
90
|
-
โโโ mockAssets
|
|
91
|
-
โ โโโ test.zip
|
|
92
|
-
โ โโโ test.json
|
|
93
|
-
```
|
|
94
|
-
|
|
95
|
-
```js
|
|
96
|
-
fetch('/test.json')
|
|
97
|
-
.then(res => res.json())
|
|
98
|
-
.then((json) => {
|
|
99
|
-
console.log(json);
|
|
100
|
-
});
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
```html
|
|
104
|
-
<a class="download" href="./test.zip">Download</a>
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
### add mock routes to the dev server
|
|
108
|
-
|
|
109
|
-
```js
|
|
110
|
-
import { defineConfig } from 'vite';
|
|
111
|
-
import mockData from 'vite-plugin-mock-data';
|
|
112
|
-
|
|
113
|
-
export default defineConfig({
|
|
114
|
-
plugins: [
|
|
115
|
-
mockData({
|
|
116
|
-
routes: {
|
|
117
|
-
'/hello': 'hello',
|
|
118
|
-
'/hello2'(req, res) {
|
|
119
|
-
res.statusCode = 200;
|
|
120
|
-
res.setHeader('Content-Type', 'text/html');
|
|
121
|
-
res.end('hello2');
|
|
122
|
-
},
|
|
123
|
-
'/hello3': {
|
|
124
|
-
handler(req, res) {
|
|
125
|
-
res.statusCode = 200;
|
|
126
|
-
res.setHeader('Content-Type', 'text/html');
|
|
127
|
-
res.end('hello3');
|
|
128
|
-
}
|
|
129
|
-
},
|
|
130
|
-
'/json': {
|
|
131
|
-
handler: { hello: 1 }
|
|
132
|
-
},
|
|
133
|
-
'/package.json': {
|
|
134
|
-
file: './package.json'
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
})
|
|
138
|
-
]
|
|
139
|
-
});
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
```js
|
|
143
|
-
fetch('/package.json')
|
|
144
|
-
.then(res => res.json())
|
|
145
|
-
.then((json) => {
|
|
146
|
-
console.log(json);
|
|
147
|
-
});
|
|
148
|
-
```
|
|
149
|
-
|
|
150
|
-
### Specify the directory to add mock routes to the dev server
|
|
151
|
-
|
|
152
|
-
```js
|
|
153
|
-
import { defineConfig } from 'vite';
|
|
154
|
-
import mockData from 'vite-plugin-mock-data';
|
|
155
|
-
|
|
156
|
-
export default defineConfig({
|
|
157
|
-
plugins: [
|
|
158
|
-
mockData({
|
|
159
|
-
routes: './mock'
|
|
160
|
-
})
|
|
161
|
-
]
|
|
162
|
-
});
|
|
163
|
-
```
|
|
164
|
-
|
|
165
|
-
```txt
|
|
166
|
-
.
|
|
167
|
-
โโโ mock
|
|
168
|
-
โ โโโ test.js
|
|
169
|
-
```
|
|
170
|
-
|
|
171
|
-
```js
|
|
172
|
-
module.exports = {
|
|
173
|
-
'/hello': 'hello',
|
|
174
|
-
'/hello2'(req, res) {
|
|
175
|
-
res.statusCode = 200;
|
|
176
|
-
res.setHeader('Content-Type', 'text/html');
|
|
177
|
-
res.end('hello2');
|
|
178
|
-
},
|
|
179
|
-
'/hello3': {
|
|
180
|
-
handler(req, res) {
|
|
181
|
-
res.statusCode = 200;
|
|
182
|
-
res.setHeader('Content-Type', 'text/html');
|
|
183
|
-
res.end('hello3');
|
|
184
|
-
}
|
|
185
|
-
},
|
|
186
|
-
'/json': {
|
|
187
|
-
handler: { hello: 1 }
|
|
188
|
-
},
|
|
189
|
-
'/package.json': {
|
|
190
|
-
file: './package.json'
|
|
191
|
-
}
|
|
192
|
-
};
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
```js
|
|
196
|
-
fetch('/package.json')
|
|
197
|
-
.then(res => res.json())
|
|
198
|
-
.then((json) => {
|
|
199
|
-
console.log(json);
|
|
200
|
-
});
|
|
201
|
-
```
|
|
202
|
-
|
|
203
|
-
## Examples
|
|
204
|
-
|
|
205
|
-
* [See vite3 demo](../../examples/vite3-demo)
|
|
206
|
-
* [See vite4 demo](../../examples/vite4-demo)
|
|
207
|
-
* [See vite5 demo](../../examples/vite5-demo)
|
|
208
|
-
* [See vite6 demo](../../examples/vite6-demo)
|
|
33
|
+
This project is licensed under the [MIT License](../../LICENSE).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { OutgoingHttpHeaders } from 'node:http';
|
|
2
|
+
import { Config as SirvConfig, HTTPVersion } from 'find-my-way';
|
|
3
|
+
import { type Options as SirvOptions } from 'sirv';
|
|
4
|
+
import { ViteDevServer } from 'vite';
|
|
5
|
+
import { RouteConfig } from './typings';
|
|
6
|
+
export declare function sirvOptions(headers?: OutgoingHttpHeaders): SirvOptions;
|
|
7
|
+
export declare function configureServer(server: ViteDevServer, routerOpts: SirvConfig<HTTPVersion.V1> | SirvConfig<HTTPVersion.V2> | undefined, routes: RouteConfig[], cwd: string): void;
|
package/dist/index.d.ts
CHANGED
|
@@ -7,11 +7,11 @@ export * from './typings';
|
|
|
7
7
|
* @example
|
|
8
8
|
* ```js
|
|
9
9
|
* import { defineConfig } from 'vite';
|
|
10
|
-
* import
|
|
10
|
+
* import pluginMockDate from 'vite-plugin-mock-data';
|
|
11
11
|
*
|
|
12
12
|
* export default defineConfig({
|
|
13
13
|
* plugins: [
|
|
14
|
-
*
|
|
14
|
+
* pluginMockDate({
|
|
15
15
|
* routes: './mock'
|
|
16
16
|
* })
|
|
17
17
|
* ]
|
|
@@ -21,4 +21,4 @@ export * from './typings';
|
|
|
21
21
|
* @param opts Options
|
|
22
22
|
* @returns a vite plugin
|
|
23
23
|
*/
|
|
24
|
-
export default function
|
|
24
|
+
export default function pluginMockDate(opts: Options): Plugin;
|
package/dist/index.js
CHANGED
|
@@ -1,43 +1,21 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
const isWhatType = require("is-what-type");
|
|
3
|
+
const vpRuntimeHelper = require("vp-runtime-helper");
|
|
2
4
|
const node_path = require("node:path");
|
|
3
|
-
const node_module = require("node:module");
|
|
4
|
-
const node_fs = require("node:fs");
|
|
5
|
-
const tinyglobby = require("tinyglobby");
|
|
6
5
|
const getRouter = require("find-my-way");
|
|
7
6
|
const sirv = require("sirv");
|
|
8
7
|
const vite = require("vite");
|
|
8
|
+
const node_fs = require("node:fs");
|
|
9
|
+
const promises = require("node:fs/promises");
|
|
10
|
+
const node_module = require("node:module");
|
|
11
|
+
const tinyglobby = require("tinyglobby");
|
|
12
|
+
const baseLogFactory = require("base-log-factory");
|
|
13
|
+
const blfColorfulAppender = require("blf-colorful-appender");
|
|
9
14
|
var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
return node_path.isAbsolute(pth) ? pth : node_path.posix.join(cwd || process.cwd(), pth);
|
|
15
|
-
}
|
|
16
|
-
async function getRoute(filename) {
|
|
17
|
-
let config;
|
|
18
|
-
switch (node_path.extname(filename)) {
|
|
19
|
-
case ".js":
|
|
20
|
-
config = node_module.createRequire(typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.js", document.baseURI).href)(filename);
|
|
21
|
-
break;
|
|
22
|
-
case ".mjs":
|
|
23
|
-
config = (await import(filename)).default;
|
|
24
|
-
break;
|
|
25
|
-
case ".json":
|
|
26
|
-
config = JSON.parse(node_fs.readFileSync(filename, "utf-8"));
|
|
27
|
-
break;
|
|
28
|
-
}
|
|
29
|
-
return config;
|
|
30
|
-
}
|
|
31
|
-
async function loadRoutes(dir, routes) {
|
|
32
|
-
const paths = await tinyglobby.glob(`${dir}/**/*.{js,mjs,json}`, { absolute: true });
|
|
33
|
-
const configs = await Promise.all(paths.map(getRoute));
|
|
34
|
-
configs.reduce((prev, cur) => {
|
|
35
|
-
if (cur) {
|
|
36
|
-
prev.push(cur);
|
|
37
|
-
}
|
|
38
|
-
return prev;
|
|
39
|
-
}, routes);
|
|
40
|
-
}
|
|
15
|
+
const name = "vite-plugin-mock-data";
|
|
16
|
+
const pkg = {
|
|
17
|
+
name
|
|
18
|
+
};
|
|
41
19
|
function sirvOptions(headers) {
|
|
42
20
|
return {
|
|
43
21
|
dev: true,
|
|
@@ -58,7 +36,7 @@ function sirvOptions(headers) {
|
|
|
58
36
|
}
|
|
59
37
|
};
|
|
60
38
|
}
|
|
61
|
-
function configureServer(server, routerOpts, routes,
|
|
39
|
+
function configureServer(server, routerOpts, routes, cwd) {
|
|
62
40
|
const router = getRouter(routerOpts);
|
|
63
41
|
if (Array.isArray(routes)) {
|
|
64
42
|
routes.forEach((route) => {
|
|
@@ -68,23 +46,24 @@ function configureServer(server, routerOpts, routes, serve, cwd) {
|
|
|
68
46
|
pathname = methods;
|
|
69
47
|
methods = "GET";
|
|
70
48
|
}
|
|
49
|
+
methods = methods.toUpperCase();
|
|
71
50
|
let routeConfig = route[xpath];
|
|
72
|
-
if (!isObject(routeConfig)) {
|
|
51
|
+
if (!isWhatType.isObject(routeConfig)) {
|
|
73
52
|
routeConfig = { handler: routeConfig };
|
|
74
53
|
}
|
|
75
54
|
let handler;
|
|
76
55
|
if (typeof routeConfig.file === "string") {
|
|
77
56
|
handler = (req, res) => {
|
|
78
|
-
const parsedPath = node_path.parse(
|
|
79
|
-
const
|
|
57
|
+
const parsedPath = node_path.parse(vpRuntimeHelper.toAbsolutePath(routeConfig.file, cwd));
|
|
58
|
+
const serve = sirv(parsedPath.dir, sirvOptions(server.config.server.headers));
|
|
80
59
|
req.url = `/${parsedPath.base}`;
|
|
81
|
-
|
|
60
|
+
serve(req, res);
|
|
82
61
|
};
|
|
83
62
|
} else if (typeof routeConfig.handler !== "function") {
|
|
84
63
|
const ret = routeConfig.handler;
|
|
85
64
|
const retType = typeof ret;
|
|
86
65
|
handler = (req, res) => {
|
|
87
|
-
vite.send(req, res, retType !== "string" ? JSON.stringify(ret) : ret, isObject(ret) ? "json" : "html", {
|
|
66
|
+
vite.send(req, res, retType !== "string" ? JSON.stringify(ret) : ret, isWhatType.isObject(ret) ? "json" : "html", {
|
|
88
67
|
headers: server.config.server.headers
|
|
89
68
|
});
|
|
90
69
|
};
|
|
@@ -97,41 +76,85 @@ function configureServer(server, routerOpts, routes, serve, cwd) {
|
|
|
97
76
|
});
|
|
98
77
|
});
|
|
99
78
|
}
|
|
100
|
-
if (serve) {
|
|
101
|
-
server.middlewares.use(serve);
|
|
102
|
-
}
|
|
103
79
|
server.middlewares.use((req, res, next) => {
|
|
104
80
|
router.defaultRoute = () => next();
|
|
105
81
|
router.lookup(req, res);
|
|
106
82
|
});
|
|
107
83
|
}
|
|
108
|
-
|
|
109
|
-
|
|
84
|
+
const PLUGIN_NAME = pkg.name;
|
|
85
|
+
const logger = new baseLogFactory.Logger(PLUGIN_NAME, {
|
|
86
|
+
level: baseLogFactory.Level.WARN,
|
|
87
|
+
appenders: [
|
|
88
|
+
new blfColorfulAppender.ColorfulAppender()
|
|
89
|
+
]
|
|
90
|
+
});
|
|
91
|
+
async function getRoute(filename) {
|
|
92
|
+
logger.debug("Load mock file:", filename);
|
|
93
|
+
let { ext, dir, name: name2 } = node_path.parse(filename);
|
|
94
|
+
const isTs = ext === ".ts" || ext === ".mts";
|
|
95
|
+
if (isTs) {
|
|
96
|
+
const { code } = await vite.transformWithEsbuild(node_fs.readFileSync(filename, "utf-8"), filename, {
|
|
97
|
+
loader: "ts",
|
|
98
|
+
target: "esnext"
|
|
99
|
+
});
|
|
100
|
+
filename = node_path.join(dir, `${name2}-${PLUGIN_NAME}.mjs`);
|
|
101
|
+
ext = ".mjs";
|
|
102
|
+
await promises.writeFile(filename, code);
|
|
103
|
+
}
|
|
104
|
+
let config;
|
|
105
|
+
switch (ext) {
|
|
106
|
+
case ".js":
|
|
107
|
+
config = node_module.createRequire(typeof document === "undefined" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.js", document.baseURI).href)(filename);
|
|
108
|
+
break;
|
|
109
|
+
case ".mjs":
|
|
110
|
+
config = (await import(filename)).default;
|
|
111
|
+
if (isTs) {
|
|
112
|
+
await promises.unlink(filename);
|
|
113
|
+
}
|
|
114
|
+
break;
|
|
115
|
+
case ".json":
|
|
116
|
+
config = JSON.parse(node_fs.readFileSync(filename, "utf-8"));
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
return config;
|
|
120
|
+
}
|
|
121
|
+
async function loadRoutes(dir, routes) {
|
|
122
|
+
const paths = await tinyglobby.glob(`${dir}/**/*.{js,mjs,json,ts,mts}`, { absolute: true });
|
|
123
|
+
const configs = await Promise.all(paths.map(getRoute));
|
|
124
|
+
for (const config of configs) {
|
|
125
|
+
if (config) {
|
|
126
|
+
routes.push(config);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function pluginMockDate(opts) {
|
|
131
|
+
vpRuntimeHelper.banner(pkg.name);
|
|
132
|
+
const { isAfter, routerOptions, routes, logLevel, cwd = process.cwd() } = opts;
|
|
133
|
+
if (logLevel) {
|
|
134
|
+
logger.level = logLevel;
|
|
135
|
+
}
|
|
110
136
|
const allRoutes = [];
|
|
111
137
|
return {
|
|
112
|
-
name:
|
|
138
|
+
name: PLUGIN_NAME,
|
|
113
139
|
async configureServer(server) {
|
|
114
140
|
if (typeof routes === "string") {
|
|
115
|
-
|
|
141
|
+
logger.debug("Load routes from", routes);
|
|
142
|
+
await loadRoutes(vpRuntimeHelper.toAbsolutePath(routes, cwd), allRoutes);
|
|
116
143
|
} else if (Array.isArray(routes)) {
|
|
117
144
|
for (const route of routes) {
|
|
145
|
+
logger.debug("Load routes from", route);
|
|
118
146
|
if (typeof route === "string") {
|
|
119
|
-
await loadRoutes(
|
|
147
|
+
await loadRoutes(vpRuntimeHelper.toAbsolutePath(route, cwd), allRoutes);
|
|
120
148
|
} else {
|
|
121
149
|
allRoutes.push(route);
|
|
122
150
|
}
|
|
123
151
|
}
|
|
124
|
-
} else if (isObject(routes)) {
|
|
152
|
+
} else if (isWhatType.isObject(routes)) {
|
|
153
|
+
logger.debug("Load routes from", routes);
|
|
125
154
|
allRoutes.push(routes);
|
|
126
155
|
}
|
|
127
|
-
|
|
128
|
-
if (assets) {
|
|
129
|
-
serve = sirv(toAbsolute(assets, cwd), sirvOptions(server.config.server.headers));
|
|
130
|
-
}
|
|
131
|
-
if (allRoutes && allRoutes.length > 0) {
|
|
132
|
-
return isAfter ? () => configureServer(server, routerOptions, allRoutes, serve, cwd) : configureServer(server, routerOptions, allRoutes, serve, cwd);
|
|
133
|
-
}
|
|
156
|
+
return isAfter ? () => configureServer(server, routerOptions, allRoutes, cwd) : configureServer(server, routerOptions, allRoutes, cwd);
|
|
134
157
|
}
|
|
135
158
|
};
|
|
136
159
|
}
|
|
137
|
-
module.exports =
|
|
160
|
+
module.exports = pluginMockDate;
|
package/dist/index.mjs
CHANGED
|
@@ -1,41 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { glob } from "tinyglobby";
|
|
1
|
+
import { isObject } from "is-what-type";
|
|
2
|
+
import { toAbsolutePath, banner } from "vp-runtime-helper";
|
|
3
|
+
import { parse, join } from "node:path";
|
|
5
4
|
import getRouter from "find-my-way";
|
|
6
5
|
import sirv from "sirv";
|
|
7
|
-
import { send } from "vite";
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
config = createRequire(import.meta.url)(filename);
|
|
19
|
-
break;
|
|
20
|
-
case ".mjs":
|
|
21
|
-
config = (await import(filename)).default;
|
|
22
|
-
break;
|
|
23
|
-
case ".json":
|
|
24
|
-
config = JSON.parse(readFileSync(filename, "utf-8"));
|
|
25
|
-
break;
|
|
26
|
-
}
|
|
27
|
-
return config;
|
|
28
|
-
}
|
|
29
|
-
async function loadRoutes(dir, routes) {
|
|
30
|
-
const paths = await glob(`${dir}/**/*.{js,mjs,json}`, { absolute: true });
|
|
31
|
-
const configs = await Promise.all(paths.map(getRoute));
|
|
32
|
-
configs.reduce((prev, cur) => {
|
|
33
|
-
if (cur) {
|
|
34
|
-
prev.push(cur);
|
|
35
|
-
}
|
|
36
|
-
return prev;
|
|
37
|
-
}, routes);
|
|
38
|
-
}
|
|
6
|
+
import { send, transformWithEsbuild } from "vite";
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { writeFile, unlink } from "node:fs/promises";
|
|
9
|
+
import { createRequire } from "node:module";
|
|
10
|
+
import { glob } from "tinyglobby";
|
|
11
|
+
import { Logger, Level } from "base-log-factory";
|
|
12
|
+
import { ColorfulAppender } from "blf-colorful-appender";
|
|
13
|
+
const name = "vite-plugin-mock-data";
|
|
14
|
+
const pkg = {
|
|
15
|
+
name
|
|
16
|
+
};
|
|
39
17
|
function sirvOptions(headers) {
|
|
40
18
|
return {
|
|
41
19
|
dev: true,
|
|
@@ -56,7 +34,7 @@ function sirvOptions(headers) {
|
|
|
56
34
|
}
|
|
57
35
|
};
|
|
58
36
|
}
|
|
59
|
-
function configureServer(server, routerOpts, routes,
|
|
37
|
+
function configureServer(server, routerOpts, routes, cwd) {
|
|
60
38
|
const router = getRouter(routerOpts);
|
|
61
39
|
if (Array.isArray(routes)) {
|
|
62
40
|
routes.forEach((route) => {
|
|
@@ -66,6 +44,7 @@ function configureServer(server, routerOpts, routes, serve, cwd) {
|
|
|
66
44
|
pathname = methods;
|
|
67
45
|
methods = "GET";
|
|
68
46
|
}
|
|
47
|
+
methods = methods.toUpperCase();
|
|
69
48
|
let routeConfig = route[xpath];
|
|
70
49
|
if (!isObject(routeConfig)) {
|
|
71
50
|
routeConfig = { handler: routeConfig };
|
|
@@ -73,10 +52,10 @@ function configureServer(server, routerOpts, routes, serve, cwd) {
|
|
|
73
52
|
let handler;
|
|
74
53
|
if (typeof routeConfig.file === "string") {
|
|
75
54
|
handler = (req, res) => {
|
|
76
|
-
const parsedPath = parse(
|
|
77
|
-
const
|
|
55
|
+
const parsedPath = parse(toAbsolutePath(routeConfig.file, cwd));
|
|
56
|
+
const serve = sirv(parsedPath.dir, sirvOptions(server.config.server.headers));
|
|
78
57
|
req.url = `/${parsedPath.base}`;
|
|
79
|
-
|
|
58
|
+
serve(req, res);
|
|
80
59
|
};
|
|
81
60
|
} else if (typeof routeConfig.handler !== "function") {
|
|
82
61
|
const ret = routeConfig.handler;
|
|
@@ -95,43 +74,87 @@ function configureServer(server, routerOpts, routes, serve, cwd) {
|
|
|
95
74
|
});
|
|
96
75
|
});
|
|
97
76
|
}
|
|
98
|
-
if (serve) {
|
|
99
|
-
server.middlewares.use(serve);
|
|
100
|
-
}
|
|
101
77
|
server.middlewares.use((req, res, next) => {
|
|
102
78
|
router.defaultRoute = () => next();
|
|
103
79
|
router.lookup(req, res);
|
|
104
80
|
});
|
|
105
81
|
}
|
|
106
|
-
|
|
107
|
-
|
|
82
|
+
const PLUGIN_NAME = pkg.name;
|
|
83
|
+
const logger = new Logger(PLUGIN_NAME, {
|
|
84
|
+
level: Level.WARN,
|
|
85
|
+
appenders: [
|
|
86
|
+
new ColorfulAppender()
|
|
87
|
+
]
|
|
88
|
+
});
|
|
89
|
+
async function getRoute(filename) {
|
|
90
|
+
logger.debug("Load mock file:", filename);
|
|
91
|
+
let { ext, dir, name: name2 } = parse(filename);
|
|
92
|
+
const isTs = ext === ".ts" || ext === ".mts";
|
|
93
|
+
if (isTs) {
|
|
94
|
+
const { code } = await transformWithEsbuild(readFileSync(filename, "utf-8"), filename, {
|
|
95
|
+
loader: "ts",
|
|
96
|
+
target: "esnext"
|
|
97
|
+
});
|
|
98
|
+
filename = join(dir, `${name2}-${PLUGIN_NAME}.mjs`);
|
|
99
|
+
ext = ".mjs";
|
|
100
|
+
await writeFile(filename, code);
|
|
101
|
+
}
|
|
102
|
+
let config;
|
|
103
|
+
switch (ext) {
|
|
104
|
+
case ".js":
|
|
105
|
+
config = createRequire(import.meta.url)(filename);
|
|
106
|
+
break;
|
|
107
|
+
case ".mjs":
|
|
108
|
+
config = (await import(filename)).default;
|
|
109
|
+
if (isTs) {
|
|
110
|
+
await unlink(filename);
|
|
111
|
+
}
|
|
112
|
+
break;
|
|
113
|
+
case ".json":
|
|
114
|
+
config = JSON.parse(readFileSync(filename, "utf-8"));
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
return config;
|
|
118
|
+
}
|
|
119
|
+
async function loadRoutes(dir, routes) {
|
|
120
|
+
const paths = await glob(`${dir}/**/*.{js,mjs,json,ts,mts}`, { absolute: true });
|
|
121
|
+
const configs = await Promise.all(paths.map(getRoute));
|
|
122
|
+
for (const config of configs) {
|
|
123
|
+
if (config) {
|
|
124
|
+
routes.push(config);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function pluginMockDate(opts) {
|
|
129
|
+
banner(pkg.name);
|
|
130
|
+
const { isAfter, routerOptions, routes, logLevel, cwd = process.cwd() } = opts;
|
|
131
|
+
if (logLevel) {
|
|
132
|
+
logger.level = logLevel;
|
|
133
|
+
}
|
|
108
134
|
const allRoutes = [];
|
|
109
135
|
return {
|
|
110
|
-
name:
|
|
136
|
+
name: PLUGIN_NAME,
|
|
111
137
|
async configureServer(server) {
|
|
112
138
|
if (typeof routes === "string") {
|
|
113
|
-
|
|
139
|
+
logger.debug("Load routes from", routes);
|
|
140
|
+
await loadRoutes(toAbsolutePath(routes, cwd), allRoutes);
|
|
114
141
|
} else if (Array.isArray(routes)) {
|
|
115
142
|
for (const route of routes) {
|
|
143
|
+
logger.debug("Load routes from", route);
|
|
116
144
|
if (typeof route === "string") {
|
|
117
|
-
await loadRoutes(
|
|
145
|
+
await loadRoutes(toAbsolutePath(route, cwd), allRoutes);
|
|
118
146
|
} else {
|
|
119
147
|
allRoutes.push(route);
|
|
120
148
|
}
|
|
121
149
|
}
|
|
122
150
|
} else if (isObject(routes)) {
|
|
151
|
+
logger.debug("Load routes from", routes);
|
|
123
152
|
allRoutes.push(routes);
|
|
124
153
|
}
|
|
125
|
-
|
|
126
|
-
if (assets) {
|
|
127
|
-
serve = sirv(toAbsolute(assets, cwd), sirvOptions(server.config.server.headers));
|
|
128
|
-
}
|
|
129
|
-
if (allRoutes && allRoutes.length > 0) {
|
|
130
|
-
return isAfter ? () => configureServer(server, routerOptions, allRoutes, serve, cwd) : configureServer(server, routerOptions, allRoutes, serve, cwd);
|
|
131
|
-
}
|
|
154
|
+
return isAfter ? () => configureServer(server, routerOptions, allRoutes, cwd) : configureServer(server, routerOptions, allRoutes, cwd);
|
|
132
155
|
}
|
|
133
156
|
};
|
|
134
157
|
}
|
|
135
158
|
export {
|
|
136
|
-
|
|
159
|
+
pluginMockDate as default
|
|
137
160
|
};
|
package/dist/logger.d.ts
ADDED
package/dist/typings.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { LogLevel } from 'base-log-factory';
|
|
2
|
+
import { Config as SirvConfig, Handler, HTTPVersion, RouteOptions } from 'find-my-way';
|
|
2
3
|
export interface HandleRoute {
|
|
3
4
|
file?: string;
|
|
4
5
|
handler?: any | Handler<HTTPVersion.V1>;
|
|
@@ -14,15 +15,25 @@ export interface Options {
|
|
|
14
15
|
* @default `process.cwd()`
|
|
15
16
|
*/
|
|
16
17
|
cwd?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Cache directory for compiled files.
|
|
20
|
+
*
|
|
21
|
+
* ็จไบๅญๆพ ts ่ขซ็ผ่ฏๅๅญๆพ็ๆไปถ็ฎๅฝใ
|
|
22
|
+
*
|
|
23
|
+
* @default `${cwd}/node_modules/.vite_mock_data`
|
|
24
|
+
*/
|
|
25
|
+
cacheDir?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Log level
|
|
28
|
+
*
|
|
29
|
+
* ่พๅบๆฅๅฟ็ญ็บง
|
|
30
|
+
*/
|
|
31
|
+
logLevel?: LogLevel;
|
|
17
32
|
/**
|
|
18
33
|
* If `true`, these mock routes is matched after internal middlewares are installed.
|
|
19
34
|
* @default `false`
|
|
20
35
|
*/
|
|
21
36
|
isAfter?: boolean;
|
|
22
|
-
/**
|
|
23
|
-
* Specify the directory to define mock assets.
|
|
24
|
-
*/
|
|
25
|
-
assets?: string;
|
|
26
37
|
/**
|
|
27
38
|
* Initial options of `find-my-way`. see more at https://github.com/delvedor/find-my-way#findmywayoptions
|
|
28
39
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-plugin-mock-data",
|
|
3
|
-
"version": "6.0.
|
|
3
|
+
"version": "6.0.2",
|
|
4
4
|
"description": "Provides a simple way to mock data.",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -16,11 +16,6 @@
|
|
|
16
16
|
"node": ">=14.18.0",
|
|
17
17
|
"vite": ">=3.1.0"
|
|
18
18
|
},
|
|
19
|
-
"scripts": {
|
|
20
|
-
"release": "npm publish",
|
|
21
|
-
"build:lib": "vite build",
|
|
22
|
-
"watch": "vite build --watch"
|
|
23
|
-
},
|
|
24
19
|
"repository": {
|
|
25
20
|
"type": "git",
|
|
26
21
|
"url": "git+https://github.com/fengxinming/vite-plugins.git",
|
|
@@ -35,13 +30,27 @@
|
|
|
35
30
|
"bugs": {
|
|
36
31
|
"url": "https://github.com/fengxinming/vite-plugins/issues"
|
|
37
32
|
},
|
|
38
|
-
"homepage": "https://github.
|
|
33
|
+
"homepage": "https://fengxinming.github.io/vite-plugins/plugins/vite-plugin-mock-data/quick-start",
|
|
39
34
|
"dependencies": {
|
|
35
|
+
"base-log-factory": "^2.0.9",
|
|
36
|
+
"blf-colorful-appender": "^1.0.2",
|
|
40
37
|
"find-my-way": "^9.2.0",
|
|
38
|
+
"is-what-type": "^1.0.0",
|
|
41
39
|
"sirv": "^3.0.1",
|
|
42
|
-
"tinyglobby": "^0.2.12"
|
|
40
|
+
"tinyglobby": "^0.2.12",
|
|
41
|
+
"vp-runtime-helper": "^1.0.3"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@rollup/plugin-typescript": "^12.1.2",
|
|
45
|
+
"@types/fs-extra": "^11.0.4",
|
|
46
|
+
"vite": "^6.1.0"
|
|
43
47
|
},
|
|
44
48
|
"files": [
|
|
45
49
|
"dist"
|
|
46
|
-
]
|
|
50
|
+
],
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build:lib": "vite build",
|
|
53
|
+
"watch": "vite build --watch",
|
|
54
|
+
"release": "pnpm publish --no-git-checks"
|
|
55
|
+
}
|
|
47
56
|
}
|