mokup 2.3.0 → 2.3.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.
@@ -1,1790 +0,0 @@
1
- import { promises, existsSync } from 'node:fs';
2
- import { resolve, isAbsolute, join, normalize, extname, relative, dirname, basename } from '@mokup/shared/pathe';
3
- import { createRequire } from 'node:module';
4
- import { resolveRouteGroup, formatRouteFile, resolveGroupRoot, resolveGroups } from '@mokup/shared/playground-grouping';
5
- import { m as methodSet, t as toViteImportPath, b as buildManifestData, a as methodSuffixSet, c as configExtensions, s as supportedExtensions } from './mokup.Iqw32OxC.mjs';
6
- import { Buffer } from 'node:buffer';
7
- import { Hono, PatternRouter } from '@mokup/shared/hono';
8
- import { delay } from '@mokup/shared/timing';
9
- import { toPosix, hasIgnoredPrefix } from '@mokup/shared/path-utils';
10
- import { fileURLToPath, pathToFileURL } from 'node:url';
11
- import { build } from '@mokup/shared/esbuild';
12
- import { parse } from '@mokup/shared/jsonc-parser';
13
- import { compareRouteScore, parseRouteTemplate } from '@mokup/runtime';
14
-
15
- function normalizeMethod(method) {
16
- if (!method) {
17
- return void 0;
18
- }
19
- const normalized = method.toUpperCase();
20
- if (methodSet.has(normalized)) {
21
- return normalized;
22
- }
23
- return void 0;
24
- }
25
- function normalizePrefix(prefix) {
26
- if (!prefix) {
27
- return "";
28
- }
29
- const normalized = prefix.startsWith("/") ? prefix : `/${prefix}`;
30
- return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
31
- }
32
- function resolveDirs(dir, root) {
33
- const raw = typeof dir === "function" ? dir(root) : dir;
34
- const resolved = Array.isArray(raw) ? raw : raw ? [raw] : ["mock"];
35
- const normalized = resolved.map(
36
- (entry) => isAbsolute(entry) ? entry : resolve(root, entry)
37
- );
38
- return Array.from(new Set(normalized));
39
- }
40
- function normalizeIgnorePrefix(value, fallback = ["."]) {
41
- const list = typeof value === "undefined" ? fallback : Array.isArray(value) ? value : [value];
42
- return list.filter((entry) => typeof entry === "string" && entry.length > 0);
43
- }
44
-
45
- const require$1 = createRequire(import.meta.url);
46
- const mimeTypes = {
47
- ".html": "text/html; charset=utf-8",
48
- ".css": "text/css; charset=utf-8",
49
- ".js": "text/javascript; charset=utf-8",
50
- ".map": "application/json; charset=utf-8",
51
- ".json": "application/json; charset=utf-8",
52
- ".svg": "image/svg+xml",
53
- ".png": "image/png",
54
- ".jpg": "image/jpeg",
55
- ".jpeg": "image/jpeg",
56
- ".ico": "image/x-icon"
57
- };
58
- function resolvePlaygroundDist() {
59
- const pkgPath = require$1.resolve("@mokup/playground/package.json");
60
- return join(pkgPath, "..", "dist");
61
- }
62
- function sendJson(res, data, statusCode = 200) {
63
- res.statusCode = statusCode;
64
- res.setHeader("Content-Type", "application/json; charset=utf-8");
65
- res.end(JSON.stringify(data, null, 2));
66
- }
67
- function sendFile(res, content, contentType) {
68
- res.statusCode = 200;
69
- res.setHeader("Content-Type", contentType);
70
- res.end(content);
71
- }
72
-
73
- function normalizePlaygroundPath(value) {
74
- if (!value) {
75
- return "/__mokup";
76
- }
77
- const normalized = value.startsWith("/") ? value : `/${value}`;
78
- return normalized.length > 1 && normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
79
- }
80
- function normalizeBase(base) {
81
- if (!base || base === "/") {
82
- return "";
83
- }
84
- return base.endsWith("/") ? base.slice(0, -1) : base;
85
- }
86
- function resolvePlaygroundRequestPath(base, playgroundPath) {
87
- const normalizedBase = normalizeBase(base);
88
- const normalizedPath = normalizePlaygroundPath(playgroundPath);
89
- if (!normalizedBase) {
90
- return normalizedPath;
91
- }
92
- if (normalizedPath.startsWith(normalizedBase)) {
93
- return normalizedPath;
94
- }
95
- return `${normalizedBase}${normalizedPath}`;
96
- }
97
- function resolvePlaygroundOptions(playground) {
98
- if (playground === false) {
99
- return { enabled: false, path: "/__mokup", build: false };
100
- }
101
- if (playground && typeof playground === "object") {
102
- return {
103
- enabled: playground.enabled !== false,
104
- path: normalizePlaygroundPath(playground.path),
105
- build: playground.build === true
106
- };
107
- }
108
- return { enabled: true, path: "/__mokup", build: false };
109
- }
110
-
111
- function injectPlaygroundHmr(html, base) {
112
- if (html.includes("mokup-playground-hmr")) {
113
- return html;
114
- }
115
- const normalizedBase = normalizeBase(base);
116
- const clientPath = `${normalizedBase}/@vite/client`;
117
- const snippet = [
118
- '<script type="module" id="mokup-playground-hmr">',
119
- `import('${clientPath}').then(({ createHotContext }) => {`,
120
- " const hot = createHotContext('/@mokup/playground')",
121
- " hot.on('mokup:routes-changed', () => {",
122
- " const api = window.__MOKUP_PLAYGROUND__",
123
- " if (api && typeof api.reloadRoutes === 'function') {",
124
- " api.reloadRoutes()",
125
- " if (typeof api.notifyHotReload === 'function') {",
126
- " api.notifyHotReload()",
127
- " }",
128
- " return",
129
- " }",
130
- " window.location.reload()",
131
- " })",
132
- "}).catch(() => {})",
133
- "<\/script>"
134
- ].join("\n");
135
- if (html.includes("</body>")) {
136
- return html.replace("</body>", `${snippet}
137
- </body>`);
138
- }
139
- return `${html}
140
- ${snippet}`;
141
- }
142
- function injectPlaygroundSw(html, script) {
143
- if (!script) {
144
- return html;
145
- }
146
- if (html.includes("mokup-playground-sw")) {
147
- return html;
148
- }
149
- const snippet = [
150
- '<script type="module" id="mokup-playground-sw">',
151
- script,
152
- "<\/script>"
153
- ].join("\n");
154
- if (html.includes("</head>")) {
155
- return html.replace("</head>", `${snippet}
156
- </head>`);
157
- }
158
- if (html.includes("</body>")) {
159
- return html.replace("</body>", `${snippet}
160
- </body>`);
161
- }
162
- return `${html}
163
- ${snippet}`;
164
- }
165
- function isViteDevServer(server) {
166
- return !!server && "ws" in server;
167
- }
168
-
169
- const disabledReasonSet = /* @__PURE__ */ new Set([
170
- "disabled",
171
- "disabled-dir",
172
- "exclude",
173
- "ignore-prefix",
174
- "include",
175
- "unknown"
176
- ]);
177
- const ignoredReasonSet = /* @__PURE__ */ new Set([
178
- "unsupported",
179
- "invalid-route",
180
- "unknown"
181
- ]);
182
- function normalizeDisabledReason(reason) {
183
- if (reason && disabledReasonSet.has(reason)) {
184
- return reason;
185
- }
186
- return "unknown";
187
- }
188
- function normalizeIgnoredReason(reason) {
189
- if (reason && ignoredReasonSet.has(reason)) {
190
- return reason;
191
- }
192
- return "unknown";
193
- }
194
- function toPlaygroundRoute(route, root, groups) {
195
- const matchedGroup = resolveRouteGroup(route.file, groups);
196
- const preSources = route.middlewares?.filter((entry) => entry.position === "pre").map((entry) => formatRouteFile(entry.source, root)) ?? [];
197
- const postSources = route.middlewares?.filter((entry) => entry.position === "post").map((entry) => formatRouteFile(entry.source, root)) ?? [];
198
- const normalSources = route.middlewares?.filter((entry) => entry.position !== "pre" && entry.position !== "post").map((entry) => formatRouteFile(entry.source, root)) ?? [];
199
- const combinedSources = [
200
- ...preSources,
201
- ...normalSources,
202
- ...postSources
203
- ];
204
- const configChain = route.configChain?.map((entry) => formatRouteFile(entry, root)) ?? [];
205
- return {
206
- method: route.method,
207
- url: route.template,
208
- file: formatRouteFile(route.file, root),
209
- type: typeof route.handler === "function" ? "handler" : "static",
210
- status: route.status,
211
- delay: route.delay,
212
- middlewareCount: combinedSources.length,
213
- middlewares: combinedSources,
214
- preMiddlewareCount: preSources.length,
215
- normalMiddlewareCount: normalSources.length,
216
- postMiddlewareCount: postSources.length,
217
- preMiddlewares: preSources,
218
- normalMiddlewares: normalSources,
219
- postMiddlewares: postSources,
220
- configChain: configChain.length > 0 ? configChain : void 0,
221
- groupKey: matchedGroup?.key,
222
- group: matchedGroup?.label
223
- };
224
- }
225
- function formatDecisionChain(chain, root) {
226
- return chain.map((entry) => {
227
- const formatted = {
228
- step: entry.step,
229
- result: entry.result
230
- };
231
- if (typeof entry.detail !== "undefined") {
232
- formatted.detail = entry.detail;
233
- }
234
- if (typeof entry.source !== "undefined") {
235
- const source = entry.source;
236
- formatted.source = source && isAbsolute(source) ? formatRouteFile(source, root) : source;
237
- }
238
- return formatted;
239
- });
240
- }
241
- function toPlaygroundDisabledRoute(route, root, groups) {
242
- const matchedGroup = resolveRouteGroup(route.file, groups);
243
- const disabled = {
244
- file: formatRouteFile(route.file, root),
245
- reason: normalizeDisabledReason(route.reason)
246
- };
247
- if (typeof route.method !== "undefined") {
248
- disabled.method = route.method;
249
- }
250
- if (typeof route.url !== "undefined") {
251
- disabled.url = route.url;
252
- }
253
- if (route.configChain && route.configChain.length > 0) {
254
- disabled.configChain = route.configChain.map((entry) => formatRouteFile(entry, root));
255
- }
256
- if (route.decisionChain && route.decisionChain.length > 0) {
257
- disabled.decisionChain = formatDecisionChain(route.decisionChain, root);
258
- }
259
- if (route.effectiveConfig && Object.keys(route.effectiveConfig).length > 0) {
260
- disabled.effectiveConfig = route.effectiveConfig;
261
- }
262
- if (matchedGroup) {
263
- disabled.groupKey = matchedGroup.key;
264
- disabled.group = matchedGroup.label;
265
- }
266
- return disabled;
267
- }
268
- function toPlaygroundIgnoredRoute(route, root, groups) {
269
- const matchedGroup = resolveRouteGroup(route.file, groups);
270
- const ignored = {
271
- file: formatRouteFile(route.file, root),
272
- reason: normalizeIgnoredReason(route.reason)
273
- };
274
- if (matchedGroup) {
275
- ignored.groupKey = matchedGroup.key;
276
- ignored.group = matchedGroup.label;
277
- }
278
- if (route.configChain && route.configChain.length > 0) {
279
- ignored.configChain = route.configChain.map((entry) => formatRouteFile(entry, root));
280
- }
281
- if (route.decisionChain && route.decisionChain.length > 0) {
282
- ignored.decisionChain = formatDecisionChain(route.decisionChain, root);
283
- }
284
- if (route.effectiveConfig && Object.keys(route.effectiveConfig).length > 0) {
285
- ignored.effectiveConfig = route.effectiveConfig;
286
- }
287
- return ignored;
288
- }
289
- function toPlaygroundConfigFile(entry, root, groups) {
290
- const matchedGroup = resolveRouteGroup(entry.file, groups);
291
- const configFile = {
292
- file: formatRouteFile(entry.file, root)
293
- };
294
- if (matchedGroup) {
295
- configFile.groupKey = matchedGroup.key;
296
- configFile.group = matchedGroup.label;
297
- }
298
- return configFile;
299
- }
300
-
301
- function createPlaygroundMiddleware(params) {
302
- const distDir = resolvePlaygroundDist();
303
- const playgroundPath = params.config.path;
304
- const indexPath = join(distDir, "index.html");
305
- return async (req, res, next) => {
306
- if (!params.config.enabled) {
307
- return next();
308
- }
309
- const server = params.getServer?.();
310
- const requestPath = resolvePlaygroundRequestPath(server?.config?.base ?? "/", playgroundPath);
311
- const requestUrl = req.url ?? "/";
312
- const url = new URL(requestUrl, "http://mokup.local");
313
- const pathname = url.pathname;
314
- const matchedPath = pathname.startsWith(requestPath) ? requestPath : pathname.startsWith(playgroundPath) ? playgroundPath : null;
315
- if (!matchedPath) {
316
- return next();
317
- }
318
- const subPath = pathname.slice(matchedPath.length);
319
- if (subPath === "") {
320
- const suffix = url.search ?? "";
321
- res.statusCode = 302;
322
- res.setHeader("Location", `${matchedPath}/${suffix}`);
323
- res.end();
324
- return;
325
- }
326
- if (subPath === "" || subPath === "/" || subPath === "/index.html") {
327
- try {
328
- const html = await promises.readFile(indexPath, "utf8");
329
- let output = html;
330
- if (isViteDevServer(server)) {
331
- output = injectPlaygroundHmr(output, server.config.base ?? "/");
332
- output = injectPlaygroundSw(output, params.getSwScript?.());
333
- }
334
- const contentType = mimeTypes[".html"] ?? "text/html; charset=utf-8";
335
- sendFile(res, output, contentType);
336
- } catch (error) {
337
- params.logger.error("Failed to load playground index:", error);
338
- res.statusCode = 500;
339
- res.end("Playground is not available.");
340
- }
341
- return;
342
- }
343
- if (subPath === "/routes") {
344
- const dirs = params.getDirs?.() ?? [];
345
- const baseRoot = resolveGroupRoot(dirs, server?.config?.root);
346
- const groups = resolveGroups(dirs, baseRoot);
347
- const routes = params.getRoutes();
348
- const disabledRoutes = params.getDisabledRoutes?.() ?? [];
349
- const ignoredRoutes = params.getIgnoredRoutes?.() ?? [];
350
- const configFiles = params.getConfigFiles?.() ?? [];
351
- const disabledConfigFiles = params.getDisabledConfigFiles?.() ?? [];
352
- sendJson(res, {
353
- basePath: matchedPath,
354
- root: baseRoot,
355
- count: routes.length,
356
- groups: groups.map((group) => ({ key: group.key, label: group.label })),
357
- routes: routes.map((route) => toPlaygroundRoute(route, baseRoot, groups)),
358
- disabled: disabledRoutes.map((route) => toPlaygroundDisabledRoute(route, baseRoot, groups)),
359
- ignored: ignoredRoutes.map((route) => toPlaygroundIgnoredRoute(route, baseRoot, groups)),
360
- configs: configFiles.map((entry) => toPlaygroundConfigFile(entry, baseRoot, groups)),
361
- disabledConfigs: disabledConfigFiles.map((entry) => toPlaygroundConfigFile(entry, baseRoot, groups))
362
- });
363
- return;
364
- }
365
- const relPath = subPath.replace(/^\/+/, "");
366
- if (relPath.includes("..")) {
367
- res.statusCode = 400;
368
- res.end("Invalid path.");
369
- return;
370
- }
371
- const normalizedPath = normalize(relPath);
372
- const filePath = join(distDir, normalizedPath);
373
- try {
374
- const content = await promises.readFile(filePath);
375
- const ext = extname(filePath);
376
- const contentType = mimeTypes[ext] ?? "application/octet-stream";
377
- sendFile(res, content, contentType);
378
- } catch {
379
- return next();
380
- }
381
- };
382
- }
383
-
384
- const defaultSwPath = "/mokup-sw.js";
385
- const defaultSwScope = "/";
386
- function normalizeSwPath(path) {
387
- if (!path) {
388
- return defaultSwPath;
389
- }
390
- return path.startsWith("/") ? path : `/${path}`;
391
- }
392
- function normalizeSwScope(scope) {
393
- if (!scope) {
394
- return defaultSwScope;
395
- }
396
- return scope.startsWith("/") ? scope : `/${scope}`;
397
- }
398
- function normalizeBasePath(value) {
399
- if (!value) {
400
- return "/";
401
- }
402
- const normalized = value.startsWith("/") ? value : `/${value}`;
403
- if (normalized.length > 1 && normalized.endsWith("/")) {
404
- return normalized.slice(0, -1);
405
- }
406
- return normalized;
407
- }
408
- function resolveSwConfigFromEntries(entries, logger) {
409
- let path = defaultSwPath;
410
- let scope = defaultSwScope;
411
- let register = true;
412
- let unregister = false;
413
- const basePaths = [];
414
- let hasPath = false;
415
- let hasScope = false;
416
- let hasRegister = false;
417
- let hasUnregister = false;
418
- for (const entry of entries) {
419
- const config = entry.sw;
420
- if (config?.path) {
421
- const next = normalizeSwPath(config.path);
422
- if (!hasPath) {
423
- path = next;
424
- hasPath = true;
425
- } else if (path !== next) {
426
- logger.warn(`SW path "${next}" ignored; using "${path}".`);
427
- }
428
- }
429
- if (config?.scope) {
430
- const next = normalizeSwScope(config.scope);
431
- if (!hasScope) {
432
- scope = next;
433
- hasScope = true;
434
- } else if (scope !== next) {
435
- logger.warn(`SW scope "${next}" ignored; using "${scope}".`);
436
- }
437
- }
438
- if (typeof config?.register === "boolean") {
439
- if (!hasRegister) {
440
- register = config.register;
441
- hasRegister = true;
442
- } else if (register !== config.register) {
443
- logger.warn(
444
- `SW register="${String(config.register)}" ignored; using "${String(register)}".`
445
- );
446
- }
447
- }
448
- if (typeof config?.unregister === "boolean") {
449
- if (!hasUnregister) {
450
- unregister = config.unregister;
451
- hasUnregister = true;
452
- } else if (unregister !== config.unregister) {
453
- logger.warn(
454
- `SW unregister="${String(config.unregister)}" ignored; using "${String(unregister)}".`
455
- );
456
- }
457
- }
458
- if (typeof config?.basePath !== "undefined") {
459
- const values = Array.isArray(config.basePath) ? config.basePath : [config.basePath];
460
- for (const value of values) {
461
- basePaths.push(normalizeBasePath(value));
462
- }
463
- continue;
464
- }
465
- const normalizedPrefix = normalizePrefix(entry.prefix ?? "");
466
- if (normalizedPrefix) {
467
- basePaths.push(normalizedPrefix);
468
- }
469
- }
470
- return {
471
- path,
472
- scope,
473
- register,
474
- unregister,
475
- basePaths: Array.from(new Set(basePaths))
476
- };
477
- }
478
- function resolveSwConfig(options, logger) {
479
- const swEntries = options.filter((entry) => entry.mode === "sw");
480
- if (swEntries.length === 0) {
481
- return null;
482
- }
483
- return resolveSwConfigFromEntries(swEntries, logger);
484
- }
485
- function resolveSwUnregisterConfig(options, logger) {
486
- return resolveSwConfigFromEntries(options, logger);
487
- }
488
- function buildSwScript(params) {
489
- const { routes, root } = params;
490
- const runtimeImportPath = params.runtimeImportPath ?? "mokup/runtime";
491
- const loggerImportPath = params.loggerImportPath ?? "@mokup/shared/logger";
492
- const basePaths = params.basePaths ?? [];
493
- const resolveModulePath = params.resolveModulePath ?? toViteImportPath;
494
- const { manifest, modules } = buildManifestData({
495
- routes,
496
- root,
497
- resolveModulePath
498
- });
499
- const imports = [
500
- `import { createLogger } from ${JSON.stringify(loggerImportPath)}`,
501
- `import { createRuntimeApp, handle } from ${JSON.stringify(runtimeImportPath)}`
502
- ];
503
- const moduleEntries = [];
504
- let moduleIndex = 0;
505
- for (const entry of modules) {
506
- const name = `module${moduleIndex++}`;
507
- imports.push(`import * as ${name} from '${entry.id}'`);
508
- moduleEntries.push({ id: entry.id, name, kind: entry.kind });
509
- }
510
- const lines = [];
511
- lines.push(...imports, "");
512
- lines.push(
513
- "const logger = createLogger()",
514
- "",
515
- "const resolveModuleExport = (mod) => mod?.default ?? mod",
516
- "",
517
- "const toRuntimeRule = (value) => {",
518
- " if (typeof value === 'undefined') {",
519
- " return null",
520
- " }",
521
- " if (typeof value === 'function') {",
522
- " return { response: value }",
523
- " }",
524
- " if (value === null) {",
525
- " return { response: null }",
526
- " }",
527
- " if (typeof value === 'object') {",
528
- " if ('response' in value) {",
529
- " return value",
530
- " }",
531
- " if ('handler' in value) {",
532
- " const handlerRule = value",
533
- " return {",
534
- " response: handlerRule.handler,",
535
- " ...(typeof handlerRule.status === 'number' ? { status: handlerRule.status } : {}),",
536
- " ...(handlerRule.headers ? { headers: handlerRule.headers } : {}),",
537
- " ...(typeof handlerRule.delay === 'number' ? { delay: handlerRule.delay } : {}),",
538
- " }",
539
- " }",
540
- " return { response: value }",
541
- " }",
542
- " return { response: value }",
543
- "}",
544
- "",
545
- "const toRuntimeRules = (value) => {",
546
- " if (typeof value === 'undefined') {",
547
- " return []",
548
- " }",
549
- " if (Array.isArray(value)) {",
550
- " return value.map(toRuntimeRule).filter(Boolean)",
551
- " }",
552
- " const rule = toRuntimeRule(value)",
553
- " return rule ? [rule] : []",
554
- "}",
555
- ""
556
- );
557
- lines.push(
558
- `const manifest = ${JSON.stringify(manifest, null, 2)}`,
559
- ""
560
- );
561
- if (moduleEntries.length > 0) {
562
- lines.push("const moduleMap = {");
563
- for (const entry of moduleEntries) {
564
- if (entry.kind === "rule") {
565
- lines.push(
566
- ` ${JSON.stringify(entry.id)}: { default: toRuntimeRules(resolveModuleExport(${entry.name})) },`
567
- );
568
- continue;
569
- }
570
- lines.push(
571
- ` ${JSON.stringify(entry.id)}: ${entry.name},`
572
- );
573
- }
574
- lines.push("}", "");
575
- }
576
- const runtimeOptions = moduleEntries.length > 0 ? "{ manifest, moduleMap }" : "{ manifest }";
577
- lines.push(
578
- `const basePaths = ${JSON.stringify(basePaths)}`,
579
- "",
580
- "self.addEventListener('install', () => {",
581
- " self.skipWaiting()",
582
- "})",
583
- "",
584
- "self.addEventListener('activate', (event) => {",
585
- " event.waitUntil(self.clients.claim())",
586
- "})",
587
- "",
588
- "const shouldHandle = (request) => {",
589
- " if (!basePaths || basePaths.length === 0) {",
590
- " return true",
591
- " }",
592
- " const pathname = new URL(request.url).pathname",
593
- " return basePaths.some((basePath) => {",
594
- " if (basePath === '/') {",
595
- " return true",
596
- " }",
597
- " return pathname === basePath || pathname.startsWith(basePath + '/')",
598
- " })",
599
- "}",
600
- "",
601
- "const registerHandler = async () => {",
602
- ` const app = await createRuntimeApp(${runtimeOptions})`,
603
- " const handler = handle(app)",
604
- " self.addEventListener('fetch', (event) => {",
605
- " if (!shouldHandle(event.request)) {",
606
- " return",
607
- " }",
608
- " handler(event)",
609
- " })",
610
- "}",
611
- "",
612
- "registerHandler().catch((error) => {",
613
- " logger.error('Failed to build service worker app:', error)",
614
- "})",
615
- ""
616
- );
617
- return lines.join("\n");
618
- }
619
-
620
- function toHonoPath(route) {
621
- if (!route.tokens || route.tokens.length === 0) {
622
- return "/";
623
- }
624
- const segments = route.tokens.map((token) => {
625
- if (token.type === "static") {
626
- return token.value;
627
- }
628
- if (token.type === "param") {
629
- return `:${token.name}`;
630
- }
631
- if (token.type === "catchall") {
632
- return `:${token.name}{.+}`;
633
- }
634
- return `:${token.name}{.+}?`;
635
- });
636
- return `/${segments.join("/")}`;
637
- }
638
- function isValidStatus(status) {
639
- return typeof status === "number" && Number.isFinite(status) && status >= 200 && status <= 599;
640
- }
641
- function resolveStatus(routeStatus, responseStatus) {
642
- if (isValidStatus(routeStatus)) {
643
- return routeStatus;
644
- }
645
- if (isValidStatus(responseStatus)) {
646
- return responseStatus;
647
- }
648
- return 200;
649
- }
650
- function applyRouteOverrides(response, route) {
651
- const headers = new Headers(response.headers);
652
- const hasHeaders = !!route.headers && Object.keys(route.headers).length > 0;
653
- if (route.headers) {
654
- for (const [key, value] of Object.entries(route.headers)) {
655
- headers.set(key, value);
656
- }
657
- }
658
- const status = resolveStatus(route.status, response.status);
659
- if (status === response.status && !hasHeaders) {
660
- return response;
661
- }
662
- return new Response(response.body, { status, headers });
663
- }
664
- function resolveResponse(value, fallback) {
665
- if (value instanceof Response) {
666
- return value;
667
- }
668
- if (value && typeof value === "object" && "res" in value) {
669
- const resolved = value.res;
670
- if (resolved instanceof Response) {
671
- return resolved;
672
- }
673
- }
674
- return fallback;
675
- }
676
- function normalizeHandlerValue(c, value) {
677
- if (value instanceof Response) {
678
- return value;
679
- }
680
- if (typeof value === "undefined") {
681
- const response = c.body(null);
682
- if (response.status === 200) {
683
- return new Response(response.body, {
684
- status: 204,
685
- headers: response.headers
686
- });
687
- }
688
- return response;
689
- }
690
- if (typeof value === "string") {
691
- return c.text(value);
692
- }
693
- if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
694
- if (!c.res.headers.get("content-type")) {
695
- c.header("content-type", "application/octet-stream");
696
- }
697
- const data = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value);
698
- return c.body(data);
699
- }
700
- return c.json(value);
701
- }
702
- function createRouteHandler(route) {
703
- return async (c) => {
704
- const value = typeof route.handler === "function" ? await route.handler(c) : route.handler;
705
- return normalizeHandlerValue(c, value);
706
- };
707
- }
708
- function createFinalizeMiddleware(route) {
709
- return async (c, next) => {
710
- const response = await next();
711
- const resolved = resolveResponse(response, c.res);
712
- if (route.delay && route.delay > 0) {
713
- await delay(route.delay);
714
- }
715
- const overridden = applyRouteOverrides(resolved, route);
716
- c.res = overridden;
717
- return overridden;
718
- };
719
- }
720
- function wrapMiddleware(handler) {
721
- return async (c, next) => {
722
- const response = await handler(c, next);
723
- return resolveResponse(response, c.res);
724
- };
725
- }
726
- function splitRouteMiddlewares(route) {
727
- const before = [];
728
- const normal = [];
729
- const after = [];
730
- for (const entry of route.middlewares ?? []) {
731
- const wrapped = wrapMiddleware(entry.handle);
732
- if (entry.position === "post") {
733
- after.push(wrapped);
734
- } else if (entry.position === "pre") {
735
- before.push(wrapped);
736
- } else {
737
- normal.push(wrapped);
738
- }
739
- }
740
- return { before, normal, after };
741
- }
742
- function createHonoApp(routes) {
743
- const app = new Hono({ router: new PatternRouter(), strict: false });
744
- for (const route of routes) {
745
- const { before, normal, after } = splitRouteMiddlewares(route);
746
- app.on(
747
- route.method,
748
- toHonoPath(route),
749
- createFinalizeMiddleware(route),
750
- ...before,
751
- ...normal,
752
- ...after,
753
- createRouteHandler(route)
754
- );
755
- }
756
- return app;
757
- }
758
- async function readRawBody(req) {
759
- return await new Promise((resolve, reject) => {
760
- const chunks = [];
761
- req.on("data", (chunk) => {
762
- if (typeof chunk === "string") {
763
- chunks.push(Buffer.from(chunk));
764
- return;
765
- }
766
- if (chunk instanceof Uint8Array) {
767
- chunks.push(chunk);
768
- return;
769
- }
770
- chunks.push(Buffer.from(String(chunk)));
771
- });
772
- req.on("end", () => {
773
- if (chunks.length === 0) {
774
- resolve(null);
775
- return;
776
- }
777
- resolve(Buffer.concat(chunks));
778
- });
779
- req.on("error", reject);
780
- });
781
- }
782
- function buildHeaders(headers) {
783
- const result = new Headers();
784
- for (const [key, value] of Object.entries(headers)) {
785
- if (typeof value === "undefined") {
786
- continue;
787
- }
788
- if (Array.isArray(value)) {
789
- result.set(key, value.join(","));
790
- } else {
791
- result.set(key, value);
792
- }
793
- }
794
- return result;
795
- }
796
- async function toRequest(req) {
797
- const url = new URL(req.url ?? "/", "http://mokup.local");
798
- const method = req.method ?? "GET";
799
- const headers = buildHeaders(req.headers);
800
- const init = { method, headers };
801
- const rawBody = await readRawBody(req);
802
- if (rawBody && method !== "GET" && method !== "HEAD") {
803
- init.body = rawBody;
804
- }
805
- return new Request(url.toString(), init);
806
- }
807
- async function sendResponse(res, response) {
808
- res.statusCode = response.status;
809
- response.headers.forEach((value, key) => {
810
- res.setHeader(key, value);
811
- });
812
- if (!response.body) {
813
- res.end();
814
- return;
815
- }
816
- const buffer = new Uint8Array(await response.arrayBuffer());
817
- res.end(buffer);
818
- }
819
- function hasMatch(app, method, pathname) {
820
- const matchMethod = method === "HEAD" ? "GET" : method;
821
- const match = app.router.match(matchMethod, pathname);
822
- return !!match && match[0].length > 0;
823
- }
824
- function createMiddleware(getApp, logger) {
825
- return async (req, res, next) => {
826
- const app = getApp();
827
- if (!app) {
828
- return next();
829
- }
830
- const url = req.url ?? "/";
831
- const parsedUrl = new URL(url, "http://mokup.local");
832
- const pathname = parsedUrl.pathname;
833
- const method = normalizeMethod(req.method) ?? "GET";
834
- if (!hasMatch(app, method, pathname)) {
835
- return next();
836
- }
837
- const startedAt = Date.now();
838
- try {
839
- const response = await app.fetch(await toRequest(req));
840
- if (res.writableEnded) {
841
- return;
842
- }
843
- await sendResponse(res, response);
844
- logger.info(`${method} ${pathname} ${Date.now() - startedAt}ms`);
845
- } catch (error) {
846
- if (!res.headersSent) {
847
- res.statusCode = 500;
848
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
849
- }
850
- res.end("Mock handler error");
851
- logger.error("Mock handler failed:", error);
852
- }
853
- };
854
- }
855
-
856
- const jsonExtensions = /* @__PURE__ */ new Set([".json", ".jsonc"]);
857
- function resolveTemplate(template, prefix) {
858
- const normalized = template.startsWith("/") ? template : `/${template}`;
859
- if (!prefix) {
860
- return normalized;
861
- }
862
- const normalizedPrefix = normalizePrefix(prefix);
863
- if (!normalizedPrefix) {
864
- return normalized;
865
- }
866
- if (normalized === normalizedPrefix || normalized.startsWith(`${normalizedPrefix}/`)) {
867
- return normalized;
868
- }
869
- if (normalized === "/") {
870
- return `${normalizedPrefix}/`;
871
- }
872
- return `${normalizedPrefix}${normalized}`;
873
- }
874
- function stripMethodSuffix(base) {
875
- const segments = base.split(".");
876
- const last = segments.at(-1);
877
- if (last && methodSuffixSet.has(last.toLowerCase())) {
878
- segments.pop();
879
- return {
880
- name: segments.join("."),
881
- method: last.toUpperCase()
882
- };
883
- }
884
- return {
885
- name: base,
886
- method: void 0
887
- };
888
- }
889
- function deriveRouteFromFile(file, rootDir, logger) {
890
- const rel = toPosix(relative(rootDir, file));
891
- const ext = extname(rel);
892
- const withoutExt = rel.slice(0, rel.length - ext.length);
893
- const dir = dirname(withoutExt);
894
- const base = basename(withoutExt);
895
- const { name, method } = stripMethodSuffix(base);
896
- const resolvedMethod = method ?? (jsonExtensions.has(ext) ? "GET" : void 0);
897
- if (!resolvedMethod) {
898
- logger.warn(`Skip mock without method suffix: ${file}`);
899
- return null;
900
- }
901
- if (!name) {
902
- logger.warn(`Skip mock with empty route name: ${file}`);
903
- return null;
904
- }
905
- const joined = dir === "." ? name : join(dir, name);
906
- const segments = toPosix(joined).split("/");
907
- if (segments.at(-1) === "index") {
908
- segments.pop();
909
- }
910
- const template = segments.length === 0 ? "/" : `/${segments.join("/")}`;
911
- const parsed = parseRouteTemplate(template);
912
- if (parsed.errors.length > 0) {
913
- for (const error of parsed.errors) {
914
- logger.warn(`${error} in ${file}`);
915
- }
916
- return null;
917
- }
918
- for (const warning of parsed.warnings) {
919
- logger.warn(`${warning} in ${file}`);
920
- }
921
- return {
922
- template: parsed.template,
923
- method: resolvedMethod,
924
- tokens: parsed.tokens,
925
- score: parsed.score
926
- };
927
- }
928
- function resolveRule(params) {
929
- const method = params.derivedMethod;
930
- if (!method) {
931
- params.logger.warn(`Skip mock without method suffix: ${params.file}`);
932
- return null;
933
- }
934
- const template = resolveTemplate(params.derivedTemplate, params.prefix);
935
- const parsed = parseRouteTemplate(template);
936
- if (parsed.errors.length > 0) {
937
- for (const error of parsed.errors) {
938
- params.logger.warn(`${error} in ${params.file}`);
939
- }
940
- return null;
941
- }
942
- for (const warning of parsed.warnings) {
943
- params.logger.warn(`${warning} in ${params.file}`);
944
- }
945
- const route = {
946
- file: params.file,
947
- template: parsed.template,
948
- method,
949
- tokens: parsed.tokens,
950
- score: parsed.score,
951
- handler: params.rule.handler
952
- };
953
- if (typeof params.rule.status === "number") {
954
- route.status = params.rule.status;
955
- }
956
- if (params.rule.headers) {
957
- route.headers = params.rule.headers;
958
- }
959
- if (typeof params.rule.delay === "number") {
960
- route.delay = params.rule.delay;
961
- }
962
- return route;
963
- }
964
- function sortRoutes(routes) {
965
- return routes.sort((a, b) => {
966
- if (a.method !== b.method) {
967
- return a.method.localeCompare(b.method);
968
- }
969
- const scoreCompare = compareRouteScore(a.score, b.score);
970
- if (scoreCompare !== 0) {
971
- return scoreCompare;
972
- }
973
- return a.template.localeCompare(b.template);
974
- });
975
- }
976
-
977
- async function walkDir(dir, rootDir, files) {
978
- const entries = await promises.readdir(dir, { withFileTypes: true });
979
- for (const entry of entries) {
980
- if (entry.name === "node_modules" || entry.name === ".git") {
981
- continue;
982
- }
983
- const fullPath = join(dir, entry.name);
984
- if (entry.isDirectory()) {
985
- await walkDir(fullPath, rootDir, files);
986
- continue;
987
- }
988
- if (entry.isFile()) {
989
- files.push({ file: fullPath, rootDir });
990
- }
991
- }
992
- }
993
- async function exists(path) {
994
- try {
995
- await promises.stat(path);
996
- return true;
997
- } catch {
998
- return false;
999
- }
1000
- }
1001
- async function collectFiles(dirs) {
1002
- const files = [];
1003
- for (const dir of dirs) {
1004
- if (!await exists(dir)) {
1005
- continue;
1006
- }
1007
- await walkDir(dir, dir, files);
1008
- }
1009
- return files;
1010
- }
1011
- function isConfigFile(file) {
1012
- if (file.endsWith(".d.ts")) {
1013
- return false;
1014
- }
1015
- const base = basename(file);
1016
- if (!base.startsWith("index.config.")) {
1017
- return false;
1018
- }
1019
- const ext = extname(file).toLowerCase();
1020
- return configExtensions.includes(ext);
1021
- }
1022
- function isSupportedFile(file) {
1023
- if (file.endsWith(".d.ts")) {
1024
- return false;
1025
- }
1026
- if (isConfigFile(file)) {
1027
- return false;
1028
- }
1029
- const ext = extname(file).toLowerCase();
1030
- return supportedExtensions.has(ext);
1031
- }
1032
-
1033
- const sourceRoot = dirname(fileURLToPath(import.meta.url));
1034
- function resolveWorkspaceEntry(candidates) {
1035
- for (const candidate of candidates) {
1036
- if (existsSync(candidate)) {
1037
- return candidate;
1038
- }
1039
- }
1040
- return null;
1041
- }
1042
- const mokupSourceEntry = resolveWorkspaceEntry([
1043
- resolve(sourceRoot, "../index.ts"),
1044
- resolve(sourceRoot, "../../src/index.ts")
1045
- ]);
1046
- const mokupViteSourceEntry = resolveWorkspaceEntry([
1047
- resolve(sourceRoot, "../vite.ts"),
1048
- resolve(sourceRoot, "../../src/vite.ts")
1049
- ]);
1050
- function createWorkspaceResolvePlugin() {
1051
- if (!mokupSourceEntry && !mokupViteSourceEntry) {
1052
- return null;
1053
- }
1054
- return {
1055
- name: "mokup:resolve-workspace",
1056
- setup(build) {
1057
- if (mokupSourceEntry) {
1058
- build.onResolve({ filter: /^mokup$/ }, () => ({ path: mokupSourceEntry }));
1059
- }
1060
- if (mokupViteSourceEntry) {
1061
- build.onResolve({ filter: /^mokup\/vite$/ }, () => ({ path: mokupViteSourceEntry }));
1062
- }
1063
- }
1064
- };
1065
- }
1066
- const workspaceResolvePlugin = createWorkspaceResolvePlugin();
1067
- async function loadModule(file) {
1068
- const ext = extname(file).toLowerCase();
1069
- if (ext === ".cjs") {
1070
- const require = createRequire(import.meta.url);
1071
- delete require.cache[file];
1072
- return require(file);
1073
- }
1074
- if (ext === ".js" || ext === ".mjs") {
1075
- return import(`${pathToFileURL(file).href}?t=${Date.now()}`);
1076
- }
1077
- if (ext === ".ts") {
1078
- const result = await build({
1079
- entryPoints: [file],
1080
- bundle: true,
1081
- format: "esm",
1082
- platform: "node",
1083
- sourcemap: "inline",
1084
- target: "es2020",
1085
- write: false,
1086
- ...workspaceResolvePlugin ? { plugins: [workspaceResolvePlugin] } : {}
1087
- });
1088
- const output = result.outputFiles[0];
1089
- const code = output?.text ?? "";
1090
- const dataUrl = `data:text/javascript;base64,${Buffer.from(code).toString(
1091
- "base64"
1092
- )}`;
1093
- return import(`${dataUrl}#${Date.now()}`);
1094
- }
1095
- return null;
1096
- }
1097
- async function loadModuleWithVite(server, file) {
1098
- const asDevServer = server;
1099
- if ("ssrLoadModule" in asDevServer) {
1100
- const moduleNode = asDevServer.moduleGraph.getModuleById(file);
1101
- if (moduleNode) {
1102
- asDevServer.moduleGraph.invalidateModule(moduleNode);
1103
- }
1104
- return asDevServer.ssrLoadModule(file);
1105
- }
1106
- return loadModule(file);
1107
- }
1108
-
1109
- const middlewareSymbol = Symbol.for("mokup.config.middlewares");
1110
- function getConfigFileCandidates(dir) {
1111
- return configExtensions.map((extension) => join(dir, `index.config${extension}`));
1112
- }
1113
- async function findConfigFile(dir, cache) {
1114
- const cached = cache.get(dir);
1115
- if (cached !== void 0) {
1116
- return cached;
1117
- }
1118
- for (const candidate of getConfigFileCandidates(dir)) {
1119
- try {
1120
- await promises.stat(candidate);
1121
- cache.set(dir, candidate);
1122
- return candidate;
1123
- } catch {
1124
- continue;
1125
- }
1126
- }
1127
- cache.set(dir, null);
1128
- return null;
1129
- }
1130
- async function loadConfig(file, server) {
1131
- const mod = server ? await loadModuleWithVite(server, file) : await loadModule(file);
1132
- if (!mod) {
1133
- return null;
1134
- }
1135
- const raw = mod?.default ?? mod;
1136
- const value = isPromise(raw) ? await raw : raw;
1137
- if (!value || typeof value !== "object") {
1138
- return null;
1139
- }
1140
- return value;
1141
- }
1142
- function isPromise(value) {
1143
- return !!value && typeof value.then === "function";
1144
- }
1145
- function normalizeMiddlewares(value, source, logger, position) {
1146
- if (!value) {
1147
- return [];
1148
- }
1149
- const list = Array.isArray(value) ? value : [value];
1150
- const middlewares = [];
1151
- for (const [index, entry] of list.entries()) {
1152
- if (typeof entry !== "function") {
1153
- logger.warn(`Invalid middleware in ${source}`);
1154
- continue;
1155
- }
1156
- middlewares.push({
1157
- handle: entry,
1158
- source,
1159
- index,
1160
- position
1161
- });
1162
- }
1163
- return middlewares;
1164
- }
1165
- function readMiddlewareMeta(config) {
1166
- const value = config[middlewareSymbol];
1167
- if (!value || typeof value !== "object") {
1168
- return null;
1169
- }
1170
- const meta = value;
1171
- return {
1172
- pre: Array.isArray(meta.pre) ? meta.pre : [],
1173
- normal: Array.isArray(meta.normal) ? meta.normal : [],
1174
- post: Array.isArray(meta.post) ? meta.post : []
1175
- };
1176
- }
1177
- async function resolveDirectoryConfig(params) {
1178
- const { file, rootDir, server, logger, configCache, fileCache } = params;
1179
- const resolvedRoot = normalize(rootDir);
1180
- const resolvedFileDir = normalize(dirname(file));
1181
- const chain = [];
1182
- let current = resolvedFileDir;
1183
- while (true) {
1184
- chain.push(current);
1185
- if (current === resolvedRoot) {
1186
- break;
1187
- }
1188
- const parent = dirname(current);
1189
- if (parent === current) {
1190
- break;
1191
- }
1192
- current = parent;
1193
- }
1194
- chain.reverse();
1195
- const merged = {};
1196
- const preMiddlewares = [];
1197
- const normalMiddlewares = [];
1198
- const postMiddlewares = [];
1199
- const configChain = [];
1200
- const configSources = {};
1201
- for (const dir of chain) {
1202
- const configPath = await findConfigFile(dir, fileCache);
1203
- if (!configPath) {
1204
- continue;
1205
- }
1206
- let config = configCache.get(configPath);
1207
- if (config === void 0) {
1208
- config = await loadConfig(configPath, server);
1209
- configCache.set(configPath, config);
1210
- }
1211
- if (!config) {
1212
- logger.warn(`Invalid config in ${configPath}`);
1213
- continue;
1214
- }
1215
- configChain.push(configPath);
1216
- if (config.headers) {
1217
- merged.headers = { ...merged.headers ?? {}, ...config.headers };
1218
- configSources.headers = configPath;
1219
- }
1220
- if (typeof config.status === "number") {
1221
- merged.status = config.status;
1222
- configSources.status = configPath;
1223
- }
1224
- if (typeof config.delay === "number") {
1225
- merged.delay = config.delay;
1226
- configSources.delay = configPath;
1227
- }
1228
- if (typeof config.enabled === "boolean") {
1229
- merged.enabled = config.enabled;
1230
- configSources.enabled = configPath;
1231
- }
1232
- if (typeof config.ignorePrefix !== "undefined") {
1233
- merged.ignorePrefix = config.ignorePrefix;
1234
- configSources.ignorePrefix = configPath;
1235
- }
1236
- if (typeof config.include !== "undefined") {
1237
- merged.include = config.include;
1238
- configSources.include = configPath;
1239
- }
1240
- if (typeof config.exclude !== "undefined") {
1241
- merged.exclude = config.exclude;
1242
- configSources.exclude = configPath;
1243
- }
1244
- const meta = readMiddlewareMeta(config);
1245
- const normalizedPre = normalizeMiddlewares(
1246
- meta?.pre,
1247
- configPath,
1248
- logger,
1249
- "pre"
1250
- );
1251
- const normalizedNormal = normalizeMiddlewares(
1252
- meta?.normal,
1253
- configPath,
1254
- logger,
1255
- "normal"
1256
- );
1257
- const normalizedLegacy = normalizeMiddlewares(
1258
- config.middleware,
1259
- configPath,
1260
- logger,
1261
- "normal"
1262
- );
1263
- const normalizedPost = normalizeMiddlewares(
1264
- meta?.post,
1265
- configPath,
1266
- logger,
1267
- "post"
1268
- );
1269
- if (normalizedPre.length > 0) {
1270
- preMiddlewares.push(...normalizedPre);
1271
- }
1272
- if (normalizedNormal.length > 0) {
1273
- normalMiddlewares.push(...normalizedNormal);
1274
- }
1275
- if (normalizedLegacy.length > 0) {
1276
- normalMiddlewares.push(...normalizedLegacy);
1277
- }
1278
- if (normalizedPost.length > 0) {
1279
- postMiddlewares.push(...normalizedPost);
1280
- }
1281
- }
1282
- return {
1283
- ...merged,
1284
- middlewares: [...preMiddlewares, ...normalMiddlewares, ...postMiddlewares],
1285
- configChain,
1286
- configSources
1287
- };
1288
- }
1289
-
1290
- async function readJsonFile(file, logger) {
1291
- try {
1292
- const content = await promises.readFile(file, "utf8");
1293
- const errors = [];
1294
- const data = parse(content, errors, {
1295
- allowTrailingComma: true,
1296
- disallowComments: false
1297
- });
1298
- if (errors.length > 0) {
1299
- logger.warn(`Invalid JSONC in ${file}`);
1300
- return void 0;
1301
- }
1302
- return data;
1303
- } catch (error) {
1304
- logger.warn(`Failed to read ${file}: ${String(error)}`);
1305
- return void 0;
1306
- }
1307
- }
1308
- async function loadRules(file, server, logger) {
1309
- const ext = extname(file).toLowerCase();
1310
- if (ext === ".json" || ext === ".jsonc") {
1311
- const json = await readJsonFile(file, logger);
1312
- if (typeof json === "undefined") {
1313
- return [];
1314
- }
1315
- return [
1316
- {
1317
- handler: json
1318
- }
1319
- ];
1320
- }
1321
- const mod = server ? await loadModuleWithVite(server, file) : await loadModule(file);
1322
- const value = mod?.default ?? mod;
1323
- if (!value) {
1324
- return [];
1325
- }
1326
- if (Array.isArray(value)) {
1327
- return value;
1328
- }
1329
- if (typeof value === "function") {
1330
- return [
1331
- {
1332
- handler: value
1333
- }
1334
- ];
1335
- }
1336
- return [value];
1337
- }
1338
-
1339
- const silentLogger = {
1340
- info: () => {
1341
- },
1342
- warn: () => {
1343
- },
1344
- error: () => {
1345
- },
1346
- log: () => {
1347
- }
1348
- };
1349
- function resolveSkipRoute(params) {
1350
- const derived = params.derived ?? deriveRouteFromFile(params.file, params.rootDir, silentLogger);
1351
- if (!derived?.method) {
1352
- return null;
1353
- }
1354
- const resolved = resolveRule({
1355
- rule: { handler: null },
1356
- derivedTemplate: derived.template,
1357
- derivedMethod: derived.method,
1358
- prefix: params.prefix,
1359
- file: params.file,
1360
- logger: silentLogger
1361
- });
1362
- if (!resolved) {
1363
- return null;
1364
- }
1365
- return {
1366
- method: resolved.method,
1367
- url: resolved.template
1368
- };
1369
- }
1370
- function buildSkipInfo(file, reason, resolved, configChain, decisionChain, effectiveConfig) {
1371
- const info = { file, reason };
1372
- if (resolved) {
1373
- info.method = resolved.method;
1374
- info.url = resolved.url;
1375
- }
1376
- if (configChain && configChain.length > 0) {
1377
- info.configChain = configChain;
1378
- }
1379
- if (decisionChain && decisionChain.length > 0) {
1380
- info.decisionChain = decisionChain;
1381
- }
1382
- if (effectiveConfig && Object.keys(effectiveConfig).length > 0) {
1383
- info.effectiveConfig = effectiveConfig;
1384
- }
1385
- return info;
1386
- }
1387
- function toFilterStrings(value) {
1388
- if (!value) {
1389
- return [];
1390
- }
1391
- const list = Array.isArray(value) ? value : [value];
1392
- return list.filter((entry) => entry instanceof RegExp).map((entry) => entry.toString());
1393
- }
1394
- function toStringList(value) {
1395
- return value.length === 1 ? value[0] : [...value];
1396
- }
1397
- function formatList(value) {
1398
- return value.join(", ");
1399
- }
1400
- function testPatterns(patterns, value) {
1401
- const list = Array.isArray(patterns) ? patterns : [patterns];
1402
- return list.some((pattern) => pattern.test(value));
1403
- }
1404
- function buildEffectiveConfig(params) {
1405
- const { config, effectiveInclude, effectiveExclude, effectiveIgnorePrefix } = params;
1406
- const includeList = toFilterStrings(effectiveInclude);
1407
- const excludeList = toFilterStrings(effectiveExclude);
1408
- const effectiveConfig = {};
1409
- if (config.headers && Object.keys(config.headers).length > 0) {
1410
- effectiveConfig.headers = config.headers;
1411
- }
1412
- if (typeof config.status === "number") {
1413
- effectiveConfig.status = config.status;
1414
- }
1415
- if (typeof config.delay === "number") {
1416
- effectiveConfig.delay = config.delay;
1417
- }
1418
- if (typeof config.enabled !== "undefined") {
1419
- effectiveConfig.enabled = config.enabled;
1420
- }
1421
- if (effectiveIgnorePrefix.length > 0) {
1422
- effectiveConfig.ignorePrefix = toStringList(effectiveIgnorePrefix);
1423
- }
1424
- if (includeList.length > 0) {
1425
- effectiveConfig.include = toStringList(includeList);
1426
- }
1427
- if (excludeList.length > 0) {
1428
- effectiveConfig.exclude = toStringList(excludeList);
1429
- }
1430
- return effectiveConfig;
1431
- }
1432
-
1433
- function pushDecisionStep(chain, entry) {
1434
- const step = {
1435
- step: entry.step,
1436
- result: entry.result
1437
- };
1438
- if (typeof entry.source !== "undefined") {
1439
- step.source = entry.source;
1440
- }
1441
- if (typeof entry.detail !== "undefined") {
1442
- step.detail = entry.detail;
1443
- }
1444
- chain.push(step);
1445
- }
1446
- function runRoutePrechecks(params) {
1447
- const {
1448
- fileInfo,
1449
- prefix,
1450
- config,
1451
- configChain,
1452
- globalIgnorePrefix,
1453
- include,
1454
- exclude,
1455
- shouldCollectSkip,
1456
- shouldCollectIgnore,
1457
- onSkip,
1458
- onIgnore
1459
- } = params;
1460
- const configSources = config.configSources ?? {};
1461
- const decisionChain = [];
1462
- const isConfigEnabled = config.enabled !== false;
1463
- pushDecisionStep(decisionChain, {
1464
- step: "config.enabled",
1465
- result: isConfigEnabled ? "pass" : "fail",
1466
- source: configSources.enabled,
1467
- detail: config.enabled === false ? "enabled=false" : typeof config.enabled === "boolean" ? "enabled=true" : "enabled=true (default)"
1468
- });
1469
- const effectiveIgnorePrefix = typeof config.ignorePrefix !== "undefined" ? normalizeIgnorePrefix(config.ignorePrefix, []) : globalIgnorePrefix;
1470
- const effectiveInclude = typeof config.include !== "undefined" ? config.include : include;
1471
- const effectiveExclude = typeof config.exclude !== "undefined" ? config.exclude : exclude;
1472
- const effectiveConfigParams = {
1473
- config,
1474
- effectiveIgnorePrefix
1475
- };
1476
- if (typeof effectiveInclude !== "undefined") {
1477
- effectiveConfigParams.effectiveInclude = effectiveInclude;
1478
- }
1479
- if (typeof effectiveExclude !== "undefined") {
1480
- effectiveConfigParams.effectiveExclude = effectiveExclude;
1481
- }
1482
- const effectiveConfig = buildEffectiveConfig(effectiveConfigParams);
1483
- const effectiveConfigValue = Object.keys(effectiveConfig).length > 0 ? effectiveConfig : void 0;
1484
- if (!isConfigEnabled) {
1485
- if (shouldCollectSkip && isSupportedFile(fileInfo.file)) {
1486
- const resolved = resolveSkipRoute({
1487
- file: fileInfo.file,
1488
- rootDir: fileInfo.rootDir,
1489
- prefix
1490
- });
1491
- onSkip?.(buildSkipInfo(
1492
- fileInfo.file,
1493
- "disabled-dir",
1494
- resolved,
1495
- configChain,
1496
- decisionChain,
1497
- effectiveConfigValue
1498
- ));
1499
- }
1500
- return null;
1501
- }
1502
- if (effectiveIgnorePrefix.length > 0) {
1503
- const ignoredByPrefix = hasIgnoredPrefix(fileInfo.file, fileInfo.rootDir, effectiveIgnorePrefix);
1504
- pushDecisionStep(decisionChain, {
1505
- step: "ignore-prefix",
1506
- result: ignoredByPrefix ? "fail" : "pass",
1507
- source: configSources.ignorePrefix,
1508
- detail: `prefixes: ${formatList(effectiveIgnorePrefix)}`
1509
- });
1510
- if (ignoredByPrefix) {
1511
- if (shouldCollectSkip && isSupportedFile(fileInfo.file)) {
1512
- const resolved = resolveSkipRoute({
1513
- file: fileInfo.file,
1514
- rootDir: fileInfo.rootDir,
1515
- prefix
1516
- });
1517
- onSkip?.(buildSkipInfo(
1518
- fileInfo.file,
1519
- "ignore-prefix",
1520
- resolved,
1521
- configChain,
1522
- decisionChain,
1523
- effectiveConfigValue
1524
- ));
1525
- }
1526
- return null;
1527
- }
1528
- }
1529
- const supportedFile = isSupportedFile(fileInfo.file);
1530
- pushDecisionStep(decisionChain, {
1531
- step: "file.supported",
1532
- result: supportedFile ? "pass" : "fail",
1533
- detail: supportedFile ? void 0 : "unsupported file type"
1534
- });
1535
- if (!supportedFile) {
1536
- if (shouldCollectIgnore) {
1537
- const ignoreInfo = {
1538
- file: fileInfo.file,
1539
- reason: "unsupported",
1540
- configChain,
1541
- decisionChain
1542
- };
1543
- if (effectiveConfigValue) {
1544
- ignoreInfo.effectiveConfig = effectiveConfigValue;
1545
- }
1546
- onIgnore?.(ignoreInfo);
1547
- }
1548
- return null;
1549
- }
1550
- const normalizedFile = toPosix(fileInfo.file);
1551
- if (typeof effectiveExclude !== "undefined") {
1552
- const excluded = testPatterns(effectiveExclude, normalizedFile);
1553
- const patterns = toFilterStrings(effectiveExclude);
1554
- pushDecisionStep(decisionChain, {
1555
- step: "filter.exclude",
1556
- result: excluded ? "fail" : "pass",
1557
- source: configSources.exclude,
1558
- detail: patterns.length > 0 ? `${excluded ? "matched" : "no match"}: ${patterns.join(", ")}` : void 0
1559
- });
1560
- if (excluded) {
1561
- if (shouldCollectSkip) {
1562
- const resolved = resolveSkipRoute({
1563
- file: fileInfo.file,
1564
- rootDir: fileInfo.rootDir,
1565
- prefix
1566
- });
1567
- onSkip?.(buildSkipInfo(
1568
- fileInfo.file,
1569
- "exclude",
1570
- resolved,
1571
- configChain,
1572
- decisionChain,
1573
- effectiveConfigValue
1574
- ));
1575
- }
1576
- return null;
1577
- }
1578
- }
1579
- if (typeof effectiveInclude !== "undefined") {
1580
- const included = testPatterns(effectiveInclude, normalizedFile);
1581
- const patterns = toFilterStrings(effectiveInclude);
1582
- pushDecisionStep(decisionChain, {
1583
- step: "filter.include",
1584
- result: included ? "pass" : "fail",
1585
- source: configSources.include,
1586
- detail: patterns.length > 0 ? `${included ? "matched" : "no match"}: ${patterns.join(", ")}` : void 0
1587
- });
1588
- if (!included) {
1589
- if (shouldCollectSkip) {
1590
- const resolved = resolveSkipRoute({
1591
- file: fileInfo.file,
1592
- rootDir: fileInfo.rootDir,
1593
- prefix
1594
- });
1595
- onSkip?.(buildSkipInfo(
1596
- fileInfo.file,
1597
- "include",
1598
- resolved,
1599
- configChain,
1600
- decisionChain,
1601
- effectiveConfigValue
1602
- ));
1603
- }
1604
- return null;
1605
- }
1606
- }
1607
- const result = { decisionChain };
1608
- if (effectiveConfigValue) {
1609
- result.effectiveConfigValue = effectiveConfigValue;
1610
- }
1611
- return result;
1612
- }
1613
-
1614
- async function scanRoutes(params) {
1615
- const routes = [];
1616
- const seen = /* @__PURE__ */ new Set();
1617
- const files = await collectFiles(params.dirs);
1618
- const globalIgnorePrefix = normalizeIgnorePrefix(params.ignorePrefix);
1619
- const configCache = /* @__PURE__ */ new Map();
1620
- const fileCache = /* @__PURE__ */ new Map();
1621
- const shouldCollectSkip = typeof params.onSkip === "function";
1622
- const shouldCollectIgnore = typeof params.onIgnore === "function";
1623
- const shouldCollectConfig = typeof params.onConfig === "function";
1624
- for (const fileInfo of files) {
1625
- if (isConfigFile(fileInfo.file)) {
1626
- if (shouldCollectConfig) {
1627
- const configParams2 = {
1628
- file: fileInfo.file,
1629
- rootDir: fileInfo.rootDir,
1630
- logger: params.logger,
1631
- configCache,
1632
- fileCache
1633
- };
1634
- if (params.server) {
1635
- configParams2.server = params.server;
1636
- }
1637
- const config2 = await resolveDirectoryConfig(configParams2);
1638
- params.onConfig?.({ file: fileInfo.file, enabled: config2.enabled !== false });
1639
- }
1640
- continue;
1641
- }
1642
- const configParams = {
1643
- file: fileInfo.file,
1644
- rootDir: fileInfo.rootDir,
1645
- logger: params.logger,
1646
- configCache,
1647
- fileCache
1648
- };
1649
- if (params.server) {
1650
- configParams.server = params.server;
1651
- }
1652
- const config = await resolveDirectoryConfig(configParams);
1653
- const configChain = config.configChain ?? [];
1654
- const precheckParams = {
1655
- fileInfo,
1656
- prefix: params.prefix,
1657
- config,
1658
- configChain,
1659
- globalIgnorePrefix,
1660
- shouldCollectSkip,
1661
- shouldCollectIgnore
1662
- };
1663
- if (params.onSkip) {
1664
- precheckParams.onSkip = params.onSkip;
1665
- }
1666
- if (params.onIgnore) {
1667
- precheckParams.onIgnore = params.onIgnore;
1668
- }
1669
- if (params.include) {
1670
- precheckParams.include = params.include;
1671
- }
1672
- if (params.exclude) {
1673
- precheckParams.exclude = params.exclude;
1674
- }
1675
- const precheck = runRoutePrechecks(precheckParams);
1676
- if (!precheck) {
1677
- continue;
1678
- }
1679
- const { decisionChain, effectiveConfigValue } = precheck;
1680
- const derived = deriveRouteFromFile(fileInfo.file, fileInfo.rootDir, params.logger);
1681
- if (!derived) {
1682
- if (shouldCollectIgnore) {
1683
- decisionChain.push({
1684
- step: "route.derived",
1685
- result: "fail",
1686
- source: fileInfo.file,
1687
- detail: "invalid route name"
1688
- });
1689
- const ignoreInfo = {
1690
- file: fileInfo.file,
1691
- reason: "invalid-route",
1692
- configChain,
1693
- decisionChain
1694
- };
1695
- if (effectiveConfigValue) {
1696
- ignoreInfo.effectiveConfig = effectiveConfigValue;
1697
- }
1698
- params.onIgnore?.(ignoreInfo);
1699
- }
1700
- continue;
1701
- }
1702
- decisionChain.push({
1703
- step: "route.derived",
1704
- result: "pass",
1705
- source: fileInfo.file
1706
- });
1707
- const rules = await loadRules(fileInfo.file, params.server, params.logger);
1708
- for (const [index, rule] of rules.entries()) {
1709
- if (!rule || typeof rule !== "object") {
1710
- continue;
1711
- }
1712
- if (rule.enabled === false) {
1713
- if (shouldCollectSkip) {
1714
- const resolved2 = resolveSkipRoute({
1715
- file: fileInfo.file,
1716
- rootDir: fileInfo.rootDir,
1717
- prefix: params.prefix,
1718
- derived
1719
- });
1720
- const ruleDecisionStep = {
1721
- step: "rule.enabled",
1722
- result: "fail",
1723
- source: fileInfo.file,
1724
- detail: "enabled=false"
1725
- };
1726
- const ruleDecisionChain = [...decisionChain, ruleDecisionStep];
1727
- params.onSkip?.(buildSkipInfo(
1728
- fileInfo.file,
1729
- "disabled",
1730
- resolved2,
1731
- configChain,
1732
- ruleDecisionChain,
1733
- effectiveConfigValue
1734
- ));
1735
- }
1736
- continue;
1737
- }
1738
- const ruleValue = rule;
1739
- const unsupportedKeys = ["response", "url", "method"].filter(
1740
- (key2) => key2 in ruleValue
1741
- );
1742
- if (unsupportedKeys.length > 0) {
1743
- params.logger.warn(
1744
- `Skip mock with unsupported fields (${unsupportedKeys.join(", ")}): ${fileInfo.file}`
1745
- );
1746
- continue;
1747
- }
1748
- if (typeof rule.handler === "undefined") {
1749
- params.logger.warn(`Skip mock without handler: ${fileInfo.file}`);
1750
- continue;
1751
- }
1752
- const resolved = resolveRule({
1753
- rule,
1754
- derivedTemplate: derived.template,
1755
- derivedMethod: derived.method,
1756
- prefix: params.prefix,
1757
- file: fileInfo.file,
1758
- logger: params.logger
1759
- });
1760
- if (!resolved) {
1761
- continue;
1762
- }
1763
- resolved.ruleIndex = index;
1764
- if (configChain.length > 0) {
1765
- resolved.configChain = configChain;
1766
- }
1767
- if (config.headers) {
1768
- resolved.headers = { ...config.headers, ...resolved.headers ?? {} };
1769
- }
1770
- if (typeof resolved.status === "undefined" && typeof config.status === "number") {
1771
- resolved.status = config.status;
1772
- }
1773
- if (typeof resolved.delay === "undefined" && typeof config.delay === "number") {
1774
- resolved.delay = config.delay;
1775
- }
1776
- if (config.middlewares.length > 0) {
1777
- resolved.middlewares = config.middlewares;
1778
- }
1779
- const key = `${resolved.method} ${resolved.template}`;
1780
- if (seen.has(key)) {
1781
- params.logger.warn(`Duplicate mock route ${key} from ${fileInfo.file}`);
1782
- }
1783
- seen.add(key);
1784
- routes.push(resolved);
1785
- }
1786
- }
1787
- return sortRoutes(routes);
1788
- }
1789
-
1790
- export { sortRoutes as a, buildSwScript as b, createHonoApp as c, resolvePlaygroundOptions as d, resolveSwConfig as e, resolveSwUnregisterConfig as f, createPlaygroundMiddleware as g, createMiddleware as h, resolvePlaygroundDist as i, injectPlaygroundSw as j, resolvePlaygroundRequestPath as k, toPlaygroundIgnoredRoute as l, toPlaygroundDisabledRoute as m, normalizePlaygroundPath as n, toPlaygroundRoute as o, resolveDirs as r, scanRoutes as s, toPlaygroundConfigFile as t };