vite-plugin-mock-data 8.0.0 → 8.0.1
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/dist/index.js +38 -58
- package/package.json +5 -7
- package/dist/index.mjs +0 -268
package/dist/index.js
CHANGED
|
@@ -1,50 +1,30 @@
|
|
|
1
|
+
import { isObject } from "is-what-type";
|
|
2
|
+
import { banner, logFactory, toAbsolutePath } from "vp-runtime-helper";
|
|
3
|
+
import { join, parse } from "node:path";
|
|
4
|
+
import getRouter from "find-my-way";
|
|
5
|
+
import sirv from "sirv";
|
|
6
|
+
import { send, transformWithOxc } from "vite";
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { unlink, writeFile } from "node:fs/promises";
|
|
9
|
+
import { createRequire } from "node:module";
|
|
10
|
+
import { glob } from "tinyglobby";
|
|
1
11
|
//#region \0rolldown/runtime.js
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __copyProps = (to, from, except, desc) => {
|
|
9
|
-
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
-
key = keys[i];
|
|
11
|
-
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
-
get: ((k) => from[k]).bind(null, key),
|
|
13
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
19
|
-
value: mod,
|
|
20
|
-
enumerable: true
|
|
21
|
-
}) : target, mod));
|
|
12
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
|
|
13
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
14
|
+
throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
|
|
15
|
+
});
|
|
22
16
|
//#endregion
|
|
23
|
-
let is_what_type = require("is-what-type");
|
|
24
|
-
let vp_runtime_helper = require("vp-runtime-helper");
|
|
25
|
-
let node_path = require("node:path");
|
|
26
|
-
let find_my_way = require("find-my-way");
|
|
27
|
-
find_my_way = __toESM(find_my_way);
|
|
28
|
-
let sirv = require("sirv");
|
|
29
|
-
sirv = __toESM(sirv);
|
|
30
|
-
let vite = require("vite");
|
|
31
|
-
let node_fs = require("node:fs");
|
|
32
|
-
let node_fs_promises = require("node:fs/promises");
|
|
33
|
-
let node_module = require("node:module");
|
|
34
|
-
let tinyglobby = require("tinyglobby");
|
|
35
17
|
//#region package.json
|
|
36
18
|
var name = "vite-plugin-mock-data";
|
|
37
19
|
var package_default = {
|
|
38
20
|
name,
|
|
39
|
-
version: "8.0.
|
|
21
|
+
version: "8.0.1",
|
|
40
22
|
description: "Provides a simple way to mock data.",
|
|
41
|
-
|
|
42
|
-
module: "./dist/index.mjs",
|
|
23
|
+
type: "module",
|
|
43
24
|
types: "./dist/index.d.ts",
|
|
44
25
|
exports: { ".": {
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"require": "./dist/index.js"
|
|
26
|
+
"import": "./dist/index.js",
|
|
27
|
+
"types": "./dist/index.d.ts"
|
|
48
28
|
} },
|
|
49
29
|
engines: {
|
|
50
30
|
"node": "^20.19.0 || >=22.12.0",
|
|
@@ -116,7 +96,7 @@ function readJsonBody(req) {
|
|
|
116
96
|
}
|
|
117
97
|
function sendResult(req, res, ret, defaultHeaders) {
|
|
118
98
|
if (res.headersSent || ret === void 0) return;
|
|
119
|
-
|
|
99
|
+
send(req, res, typeof ret !== "string" ? JSON.stringify(ret) : ret, isObject(ret) ? "json" : "html", { headers: defaultHeaders });
|
|
120
100
|
}
|
|
121
101
|
function sirvOptions(headers) {
|
|
122
102
|
return {
|
|
@@ -133,7 +113,7 @@ function sirvOptions(headers) {
|
|
|
133
113
|
};
|
|
134
114
|
}
|
|
135
115
|
function configureServer(server, routerOpts, routes, cwd) {
|
|
136
|
-
const router = (
|
|
116
|
+
const router = getRouter(routerOpts);
|
|
137
117
|
if (Array.isArray(routes)) routes.forEach((route) => {
|
|
138
118
|
Object.keys(route).forEach((xpath) => {
|
|
139
119
|
let [methods, pathname] = xpath.split(" ");
|
|
@@ -143,11 +123,11 @@ function configureServer(server, routerOpts, routes, cwd) {
|
|
|
143
123
|
}
|
|
144
124
|
methods = methods.toUpperCase();
|
|
145
125
|
let routeConfig = route[xpath];
|
|
146
|
-
if (!
|
|
126
|
+
if (!isObject(routeConfig)) routeConfig = { handler: routeConfig };
|
|
147
127
|
let handler;
|
|
148
128
|
if (typeof routeConfig.file === "string") handler = (req, res) => {
|
|
149
|
-
const parsedPath =
|
|
150
|
-
const serve =
|
|
129
|
+
const parsedPath = parse(toAbsolutePath(routeConfig.file, cwd));
|
|
130
|
+
const serve = sirv(parsedPath.dir, sirvOptions(server.config.server.headers));
|
|
151
131
|
req.url = `/${parsedPath.base}`;
|
|
152
132
|
serve(req, res);
|
|
153
133
|
};
|
|
@@ -155,7 +135,7 @@ function configureServer(server, routerOpts, routes, cwd) {
|
|
|
155
135
|
const ret = routeConfig.handler;
|
|
156
136
|
const retType = typeof ret;
|
|
157
137
|
handler = (req, res) => {
|
|
158
|
-
|
|
138
|
+
send(req, res, retType !== "string" ? JSON.stringify(ret) : ret, isObject(ret) ? "json" : "html", { headers: server.config.server.headers });
|
|
159
139
|
};
|
|
160
140
|
} else {
|
|
161
141
|
const userHandler = routeConfig.handler;
|
|
@@ -204,19 +184,19 @@ function configureServer(server, routerOpts, routes, cwd) {
|
|
|
204
184
|
//#endregion
|
|
205
185
|
//#region src/logger.ts
|
|
206
186
|
var PLUGIN_NAME = name;
|
|
207
|
-
var logger =
|
|
187
|
+
var logger = logFactory.getLogger(PLUGIN_NAME);
|
|
208
188
|
//#endregion
|
|
209
189
|
//#region src/loadRoutes.ts
|
|
210
|
-
var _require = typeof
|
|
190
|
+
var _require = typeof __require === "function" ? __require : createRequire(import.meta.url);
|
|
211
191
|
async function getRoute(filename) {
|
|
212
192
|
logger.debug("Load mock file:", filename);
|
|
213
|
-
let { ext, dir, name } =
|
|
193
|
+
let { ext, dir, name } = parse(filename);
|
|
214
194
|
const isTs = ext === ".ts" || ext === ".mts";
|
|
215
195
|
if (isTs) {
|
|
216
|
-
const { code } = await
|
|
217
|
-
filename =
|
|
196
|
+
const { code } = await transformWithOxc(readFileSync(filename, "utf-8"), filename);
|
|
197
|
+
filename = join(dir, `${name}-${PLUGIN_NAME}.mjs`);
|
|
218
198
|
ext = ".mjs";
|
|
219
|
-
await
|
|
199
|
+
await writeFile(filename, code);
|
|
220
200
|
}
|
|
221
201
|
let config;
|
|
222
202
|
switch (ext) {
|
|
@@ -225,14 +205,14 @@ async function getRoute(filename) {
|
|
|
225
205
|
break;
|
|
226
206
|
case ".mjs":
|
|
227
207
|
config = (await import(filename)).default;
|
|
228
|
-
if (isTs) await
|
|
208
|
+
if (isTs) await unlink(filename);
|
|
229
209
|
break;
|
|
230
|
-
case ".json": config = JSON.parse(
|
|
210
|
+
case ".json": config = JSON.parse(readFileSync(filename, "utf-8"));
|
|
231
211
|
}
|
|
232
212
|
return config;
|
|
233
213
|
}
|
|
234
214
|
async function loadRoutes(dir, routes) {
|
|
235
|
-
const paths = await
|
|
215
|
+
const paths = await glob(`${dir}/**/*.{js,mjs,json,ts,mts}`, { absolute: true });
|
|
236
216
|
const configs = await Promise.all(paths.map(getRoute));
|
|
237
217
|
for (const config of configs) if (config) routes.push(config);
|
|
238
218
|
}
|
|
@@ -259,7 +239,7 @@ async function loadRoutes(dir, routes) {
|
|
|
259
239
|
* @returns a vite plugin
|
|
260
240
|
*/
|
|
261
241
|
function pluginMockDate(opts) {
|
|
262
|
-
if (opts.enableBanner)
|
|
242
|
+
if (opts.enableBanner) banner(package_default.name);
|
|
263
243
|
const { isAfter, routerOptions, routes, logLevel, cwd = process.cwd() } = opts;
|
|
264
244
|
if (logLevel) logger.level = logLevel;
|
|
265
245
|
const allRoutes = [];
|
|
@@ -268,13 +248,13 @@ function pluginMockDate(opts) {
|
|
|
268
248
|
async configureServer(server) {
|
|
269
249
|
if (typeof routes === "string") {
|
|
270
250
|
logger.debug("Load routes from", routes);
|
|
271
|
-
await loadRoutes(
|
|
251
|
+
await loadRoutes(toAbsolutePath(routes, cwd), allRoutes);
|
|
272
252
|
} else if (Array.isArray(routes)) for (const route of routes) {
|
|
273
253
|
logger.debug("Load routes from", route);
|
|
274
|
-
if (typeof route === "string") await loadRoutes(
|
|
254
|
+
if (typeof route === "string") await loadRoutes(toAbsolutePath(route, cwd), allRoutes);
|
|
275
255
|
else allRoutes.push(route);
|
|
276
256
|
}
|
|
277
|
-
else if (
|
|
257
|
+
else if (isObject(routes)) {
|
|
278
258
|
logger.debug("Load routes from", routes);
|
|
279
259
|
allRoutes.push(routes);
|
|
280
260
|
}
|
|
@@ -283,4 +263,4 @@ function pluginMockDate(opts) {
|
|
|
283
263
|
};
|
|
284
264
|
}
|
|
285
265
|
//#endregion
|
|
286
|
-
|
|
266
|
+
export { pluginMockDate as default };
|
package/package.json
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-plugin-mock-data",
|
|
3
|
-
"version": "8.0.
|
|
3
|
+
"version": "8.0.1",
|
|
4
4
|
"description": "Provides a simple way to mock data.",
|
|
5
|
-
"
|
|
6
|
-
"module": "./dist/index.mjs",
|
|
5
|
+
"type": "module",
|
|
7
6
|
"types": "./dist/index.d.ts",
|
|
8
7
|
"exports": {
|
|
9
8
|
".": {
|
|
10
|
-
"
|
|
11
|
-
"
|
|
12
|
-
"require": "./dist/index.js"
|
|
9
|
+
"import": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts"
|
|
13
11
|
}
|
|
14
12
|
},
|
|
15
13
|
"engines": {
|
|
@@ -41,7 +39,7 @@
|
|
|
41
39
|
"devDependencies": {
|
|
42
40
|
"vite": "^8.0.0",
|
|
43
41
|
"vite-plugin-dts": "^5.0.3",
|
|
44
|
-
"vite-plugin-external": "^8.0.
|
|
42
|
+
"vite-plugin-external": "^8.0.2"
|
|
45
43
|
},
|
|
46
44
|
"files": [
|
|
47
45
|
"dist"
|
package/dist/index.mjs
DELETED
|
@@ -1,268 +0,0 @@
|
|
|
1
|
-
import { isObject } from "is-what-type";
|
|
2
|
-
import { banner, logFactory, toAbsolutePath } from "vp-runtime-helper";
|
|
3
|
-
import { join, parse } from "node:path";
|
|
4
|
-
import getRouter from "find-my-way";
|
|
5
|
-
import sirv from "sirv";
|
|
6
|
-
import { send, transformWithOxc } from "vite";
|
|
7
|
-
import { readFileSync } from "node:fs";
|
|
8
|
-
import { unlink, writeFile } from "node:fs/promises";
|
|
9
|
-
import { createRequire } from "node:module";
|
|
10
|
-
import { glob } from "tinyglobby";
|
|
11
|
-
//#region \0rolldown/runtime.js
|
|
12
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
|
|
13
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
14
|
-
throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
|
|
15
|
-
});
|
|
16
|
-
//#endregion
|
|
17
|
-
//#region package.json
|
|
18
|
-
var name = "vite-plugin-mock-data";
|
|
19
|
-
var package_default = {
|
|
20
|
-
name,
|
|
21
|
-
version: "8.0.0",
|
|
22
|
-
description: "Provides a simple way to mock data.",
|
|
23
|
-
main: "./dist/index.js",
|
|
24
|
-
module: "./dist/index.mjs",
|
|
25
|
-
types: "./dist/index.d.ts",
|
|
26
|
-
exports: { ".": {
|
|
27
|
-
"types": "./dist/index.d.ts",
|
|
28
|
-
"import": "./dist/index.mjs",
|
|
29
|
-
"require": "./dist/index.js"
|
|
30
|
-
} },
|
|
31
|
-
engines: {
|
|
32
|
-
"node": "^20.19.0 || >=22.12.0",
|
|
33
|
-
"vite": ">=8.0.0"
|
|
34
|
-
},
|
|
35
|
-
scripts: {
|
|
36
|
-
"build": "vite build",
|
|
37
|
-
"watch": "vite build --watch",
|
|
38
|
-
"prepublishOnly": "npm run build",
|
|
39
|
-
"release": "pnpm publish --no-git-checks",
|
|
40
|
-
"test": "vitest run",
|
|
41
|
-
"test:watch": "vitest"
|
|
42
|
-
},
|
|
43
|
-
repository: {
|
|
44
|
-
"type": "git",
|
|
45
|
-
"url": "git+https://github.com/fengxinming/vite-plugins.git",
|
|
46
|
-
"directory": "plugins/vite-plugin-mock-data"
|
|
47
|
-
},
|
|
48
|
-
keywords: ["vite-plugin", "vite-plugin-mock-data"],
|
|
49
|
-
author: "Jesse Feng <fxm0016@126.com>",
|
|
50
|
-
license: "MIT",
|
|
51
|
-
bugs: { "url": "https://github.com/fengxinming/vite-plugins/issues" },
|
|
52
|
-
homepage: "https://fengxinming.github.io/vite-plugins/plugins/vite-plugin-mock-data/quick-start",
|
|
53
|
-
dependencies: {
|
|
54
|
-
"find-my-way": "^9.2.0",
|
|
55
|
-
"is-what-type": "^1.1.4",
|
|
56
|
-
"sirv": "^3.0.1",
|
|
57
|
-
"tinyglobby": "^0.2.12",
|
|
58
|
-
"vp-runtime-helper": "workspace:^"
|
|
59
|
-
},
|
|
60
|
-
devDependencies: {
|
|
61
|
-
"vite": "^8.0.0",
|
|
62
|
-
"vite-plugin-dts": "^5.0.3",
|
|
63
|
-
"vite-plugin-external": "workspace:^"
|
|
64
|
-
},
|
|
65
|
-
files: ["dist"]
|
|
66
|
-
};
|
|
67
|
-
//#endregion
|
|
68
|
-
//#region src/configureServer.ts
|
|
69
|
-
/**
|
|
70
|
-
* Simple request body parser for JSON / urlencoded payloads.
|
|
71
|
-
* Populates `req.body` so that route handlers can read it directly,
|
|
72
|
-
* matching the documented handler signature `(req) => req.body`.
|
|
73
|
-
*/
|
|
74
|
-
function readJsonBody(req) {
|
|
75
|
-
return new Promise((resolve, reject) => {
|
|
76
|
-
const chunks = [];
|
|
77
|
-
req.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
|
|
78
|
-
req.on("end", () => {
|
|
79
|
-
const raw = Buffer.concat(chunks).toString("utf8");
|
|
80
|
-
if (!raw) {
|
|
81
|
-
resolve(void 0);
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
const type = (req.headers["content-type"] || "").toLowerCase();
|
|
85
|
-
try {
|
|
86
|
-
if (type.includes("application/json")) resolve(JSON.parse(raw));
|
|
87
|
-
else if (type.includes("application/x-www-form-urlencoded")) {
|
|
88
|
-
const out = {};
|
|
89
|
-
for (const [k, v] of new URLSearchParams(raw)) out[k] = v;
|
|
90
|
-
resolve(out);
|
|
91
|
-
} else resolve(raw);
|
|
92
|
-
} catch (e) {
|
|
93
|
-
reject(e);
|
|
94
|
-
}
|
|
95
|
-
});
|
|
96
|
-
req.on("error", reject);
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
function sendResult(req, res, ret, defaultHeaders) {
|
|
100
|
-
if (res.headersSent || ret === void 0) return;
|
|
101
|
-
send(req, res, typeof ret !== "string" ? JSON.stringify(ret) : ret, isObject(ret) ? "json" : "html", { headers: defaultHeaders });
|
|
102
|
-
}
|
|
103
|
-
function sirvOptions(headers) {
|
|
104
|
-
return {
|
|
105
|
-
dev: true,
|
|
106
|
-
etag: true,
|
|
107
|
-
extensions: [],
|
|
108
|
-
setHeaders(res, pathname) {
|
|
109
|
-
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
110
|
-
if (/\.[tj]sx?$/.test(pathname)) res.setHeader("Content-Type", "application/javascript");
|
|
111
|
-
if (headers) Object.entries(headers).forEach(([key, val]) => {
|
|
112
|
-
if (val) res.setHeader(key, val);
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
function configureServer(server, routerOpts, routes, cwd) {
|
|
118
|
-
const router = getRouter(routerOpts);
|
|
119
|
-
if (Array.isArray(routes)) routes.forEach((route) => {
|
|
120
|
-
Object.keys(route).forEach((xpath) => {
|
|
121
|
-
let [methods, pathname] = xpath.split(" ");
|
|
122
|
-
if (!pathname) {
|
|
123
|
-
pathname = methods;
|
|
124
|
-
methods = "GET";
|
|
125
|
-
}
|
|
126
|
-
methods = methods.toUpperCase();
|
|
127
|
-
let routeConfig = route[xpath];
|
|
128
|
-
if (!isObject(routeConfig)) routeConfig = { handler: routeConfig };
|
|
129
|
-
let handler;
|
|
130
|
-
if (typeof routeConfig.file === "string") handler = (req, res) => {
|
|
131
|
-
const parsedPath = parse(toAbsolutePath(routeConfig.file, cwd));
|
|
132
|
-
const serve = sirv(parsedPath.dir, sirvOptions(server.config.server.headers));
|
|
133
|
-
req.url = `/${parsedPath.base}`;
|
|
134
|
-
serve(req, res);
|
|
135
|
-
};
|
|
136
|
-
else if (typeof routeConfig.handler !== "function") {
|
|
137
|
-
const ret = routeConfig.handler;
|
|
138
|
-
const retType = typeof ret;
|
|
139
|
-
handler = (req, res) => {
|
|
140
|
-
send(req, res, retType !== "string" ? JSON.stringify(ret) : ret, isObject(ret) ? "json" : "html", { headers: server.config.server.headers });
|
|
141
|
-
};
|
|
142
|
-
} else {
|
|
143
|
-
const userHandler = routeConfig.handler;
|
|
144
|
-
const needsBody = methods.toUpperCase().split("/").some((m) => [
|
|
145
|
-
"POST",
|
|
146
|
-
"PUT",
|
|
147
|
-
"PATCH",
|
|
148
|
-
"DELETE"
|
|
149
|
-
].includes(m));
|
|
150
|
-
handler = async (req, res, params) => {
|
|
151
|
-
req.params = params ?? {};
|
|
152
|
-
try {
|
|
153
|
-
if (needsBody) req.body = await readJsonBody(req);
|
|
154
|
-
} catch (e) {
|
|
155
|
-
res.statusCode = 400;
|
|
156
|
-
res.setHeader("Content-Type", "application/json");
|
|
157
|
-
res.end(JSON.stringify({
|
|
158
|
-
error: "Invalid request body",
|
|
159
|
-
detail: String(e)
|
|
160
|
-
}));
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
try {
|
|
164
|
-
sendResult(req, res, await userHandler(req, res), server.config.server.headers);
|
|
165
|
-
} catch (e) {
|
|
166
|
-
server.config.logger.error(`[mock-data] handler error on ${methods} ${pathname}: ${e}`);
|
|
167
|
-
if (!res.headersSent) {
|
|
168
|
-
res.statusCode = 500;
|
|
169
|
-
res.setHeader("Content-Type", "application/json");
|
|
170
|
-
res.end(JSON.stringify({
|
|
171
|
-
error: "Mock handler error",
|
|
172
|
-
detail: String(e)
|
|
173
|
-
}));
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
if (handler) router.on(methods.split("/"), pathname, {}, handler, routeConfig.store);
|
|
179
|
-
});
|
|
180
|
-
});
|
|
181
|
-
server.middlewares.use((req, res, next) => {
|
|
182
|
-
router.defaultRoute = () => next();
|
|
183
|
-
router.lookup(req, res);
|
|
184
|
-
});
|
|
185
|
-
}
|
|
186
|
-
//#endregion
|
|
187
|
-
//#region src/logger.ts
|
|
188
|
-
var PLUGIN_NAME = name;
|
|
189
|
-
var logger = logFactory.getLogger(PLUGIN_NAME);
|
|
190
|
-
//#endregion
|
|
191
|
-
//#region src/loadRoutes.ts
|
|
192
|
-
var _require = typeof __require === "function" ? __require : createRequire(import.meta.url);
|
|
193
|
-
async function getRoute(filename) {
|
|
194
|
-
logger.debug("Load mock file:", filename);
|
|
195
|
-
let { ext, dir, name } = parse(filename);
|
|
196
|
-
const isTs = ext === ".ts" || ext === ".mts";
|
|
197
|
-
if (isTs) {
|
|
198
|
-
const { code } = await transformWithOxc(readFileSync(filename, "utf-8"), filename);
|
|
199
|
-
filename = join(dir, `${name}-${PLUGIN_NAME}.mjs`);
|
|
200
|
-
ext = ".mjs";
|
|
201
|
-
await writeFile(filename, code);
|
|
202
|
-
}
|
|
203
|
-
let config;
|
|
204
|
-
switch (ext) {
|
|
205
|
-
case ".js":
|
|
206
|
-
config = _require(filename);
|
|
207
|
-
break;
|
|
208
|
-
case ".mjs":
|
|
209
|
-
config = (await import(filename)).default;
|
|
210
|
-
if (isTs) await unlink(filename);
|
|
211
|
-
break;
|
|
212
|
-
case ".json": config = JSON.parse(readFileSync(filename, "utf-8"));
|
|
213
|
-
}
|
|
214
|
-
return config;
|
|
215
|
-
}
|
|
216
|
-
async function loadRoutes(dir, routes) {
|
|
217
|
-
const paths = await glob(`${dir}/**/*.{js,mjs,json,ts,mts}`, { absolute: true });
|
|
218
|
-
const configs = await Promise.all(paths.map(getRoute));
|
|
219
|
-
for (const config of configs) if (config) routes.push(config);
|
|
220
|
-
}
|
|
221
|
-
//#endregion
|
|
222
|
-
//#region src/index.ts
|
|
223
|
-
/**
|
|
224
|
-
* Provides a simple way to mock data.
|
|
225
|
-
*
|
|
226
|
-
* @example
|
|
227
|
-
* ```js
|
|
228
|
-
* import { defineConfig } from 'vite';
|
|
229
|
-
* import pluginMockDate from 'vite-plugin-mock-data';
|
|
230
|
-
*
|
|
231
|
-
* export default defineConfig({
|
|
232
|
-
* plugins: [
|
|
233
|
-
* pluginMockDate({
|
|
234
|
-
* routes: './mock'
|
|
235
|
-
* })
|
|
236
|
-
* ]
|
|
237
|
-
* });
|
|
238
|
-
* ```
|
|
239
|
-
*
|
|
240
|
-
* @param opts Options
|
|
241
|
-
* @returns a vite plugin
|
|
242
|
-
*/
|
|
243
|
-
function pluginMockDate(opts) {
|
|
244
|
-
if (opts.enableBanner) banner(package_default.name);
|
|
245
|
-
const { isAfter, routerOptions, routes, logLevel, cwd = process.cwd() } = opts;
|
|
246
|
-
if (logLevel) logger.level = logLevel;
|
|
247
|
-
const allRoutes = [];
|
|
248
|
-
return {
|
|
249
|
-
name: PLUGIN_NAME,
|
|
250
|
-
async configureServer(server) {
|
|
251
|
-
if (typeof routes === "string") {
|
|
252
|
-
logger.debug("Load routes from", routes);
|
|
253
|
-
await loadRoutes(toAbsolutePath(routes, cwd), allRoutes);
|
|
254
|
-
} else if (Array.isArray(routes)) for (const route of routes) {
|
|
255
|
-
logger.debug("Load routes from", route);
|
|
256
|
-
if (typeof route === "string") await loadRoutes(toAbsolutePath(route, cwd), allRoutes);
|
|
257
|
-
else allRoutes.push(route);
|
|
258
|
-
}
|
|
259
|
-
else if (isObject(routes)) {
|
|
260
|
-
logger.debug("Load routes from", routes);
|
|
261
|
-
allRoutes.push(routes);
|
|
262
|
-
}
|
|
263
|
-
return isAfter ? () => configureServer(server, routerOptions, allRoutes, cwd) : configureServer(server, routerOptions, allRoutes, cwd);
|
|
264
|
-
}
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
//#endregion
|
|
268
|
-
export { pluginMockDate as default };
|