mokup 0.2.1 → 1.0.0

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.
@@ -0,0 +1,1420 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import { Hono, PatternRouter } from '@mokup/shared/hono';
3
+ import { promises } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { cwd } from 'node:process';
6
+ import { resolve, isAbsolute, join, normalize, extname, dirname, relative, basename } from '@mokup/shared/pathe';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { build } from '@mokup/shared/esbuild';
9
+ import { parse } from '@mokup/shared/jsonc-parser';
10
+ import { compareRouteScore, parseRouteTemplate } from '@mokup/runtime';
11
+
12
+ function createLogger(enabled) {
13
+ return {
14
+ info: (...args) => {
15
+ if (enabled) {
16
+ console.info("[mokup]", ...args);
17
+ }
18
+ },
19
+ warn: (...args) => {
20
+ if (enabled) {
21
+ console.warn("[mokup]", ...args);
22
+ }
23
+ },
24
+ error: (...args) => {
25
+ if (enabled) {
26
+ console.error("[mokup]", ...args);
27
+ }
28
+ }
29
+ };
30
+ }
31
+
32
+ const methodSet = /* @__PURE__ */ new Set([
33
+ "GET",
34
+ "POST",
35
+ "PUT",
36
+ "PATCH",
37
+ "DELETE",
38
+ "OPTIONS",
39
+ "HEAD"
40
+ ]);
41
+ const methodSuffixSet = new Set(
42
+ Array.from(methodSet, (method) => method.toLowerCase())
43
+ );
44
+ const supportedExtensions = /* @__PURE__ */ new Set([
45
+ ".json",
46
+ ".jsonc",
47
+ ".ts",
48
+ ".js",
49
+ ".mjs",
50
+ ".cjs"
51
+ ]);
52
+
53
+ function normalizeMethod(method) {
54
+ if (!method) {
55
+ return void 0;
56
+ }
57
+ const normalized = method.toUpperCase();
58
+ if (methodSet.has(normalized)) {
59
+ return normalized;
60
+ }
61
+ return void 0;
62
+ }
63
+ function normalizePrefix(prefix) {
64
+ if (!prefix) {
65
+ return "";
66
+ }
67
+ const normalized = prefix.startsWith("/") ? prefix : `/${prefix}`;
68
+ return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
69
+ }
70
+ function resolveDirs(dir, root) {
71
+ const raw = typeof dir === "function" ? dir(root) : dir;
72
+ const resolved = Array.isArray(raw) ? raw : raw ? [raw] : ["mock"];
73
+ const normalized = resolved.map(
74
+ (entry) => isAbsolute(entry) ? entry : resolve(root, entry)
75
+ );
76
+ return Array.from(new Set(normalized));
77
+ }
78
+ function createDebouncer(delayMs, fn) {
79
+ let timer = null;
80
+ return () => {
81
+ if (timer) {
82
+ clearTimeout(timer);
83
+ }
84
+ timer = setTimeout(() => {
85
+ timer = null;
86
+ fn();
87
+ }, delayMs);
88
+ };
89
+ }
90
+ function toPosix(value) {
91
+ return value.replace(/\\/g, "/");
92
+ }
93
+ function isInDirs(file, dirs) {
94
+ const normalized = toPosix(file);
95
+ return dirs.some((dir) => {
96
+ const normalizedDir = toPosix(dir).replace(/\/$/, "");
97
+ return normalized === normalizedDir || normalized.startsWith(`${normalizedDir}/`);
98
+ });
99
+ }
100
+ function testPatterns(patterns, value) {
101
+ const list = Array.isArray(patterns) ? patterns : [patterns];
102
+ return list.some((pattern) => pattern.test(value));
103
+ }
104
+ function matchesFilter(file, include, exclude) {
105
+ const normalized = toPosix(file);
106
+ if (exclude && testPatterns(exclude, normalized)) {
107
+ return false;
108
+ }
109
+ if (include) {
110
+ return testPatterns(include, normalized);
111
+ }
112
+ return true;
113
+ }
114
+ function delay(ms) {
115
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
116
+ }
117
+
118
+ function toHonoPath(route) {
119
+ if (!route.tokens || route.tokens.length === 0) {
120
+ return "/";
121
+ }
122
+ const segments = route.tokens.map((token) => {
123
+ if (token.type === "static") {
124
+ return token.value;
125
+ }
126
+ if (token.type === "param") {
127
+ return `:${token.name}`;
128
+ }
129
+ if (token.type === "catchall") {
130
+ return `:${token.name}{.+}`;
131
+ }
132
+ return `:${token.name}{.+}?`;
133
+ });
134
+ return `/${segments.join("/")}`;
135
+ }
136
+ function isValidStatus(status) {
137
+ return typeof status === "number" && Number.isFinite(status) && status >= 200 && status <= 599;
138
+ }
139
+ function resolveStatus(routeStatus, responseStatus) {
140
+ if (isValidStatus(routeStatus)) {
141
+ return routeStatus;
142
+ }
143
+ if (isValidStatus(responseStatus)) {
144
+ return responseStatus;
145
+ }
146
+ return 200;
147
+ }
148
+ function applyRouteOverrides(response, route) {
149
+ const headers = new Headers(response.headers);
150
+ const hasHeaders = !!route.headers && Object.keys(route.headers).length > 0;
151
+ if (route.headers) {
152
+ for (const [key, value] of Object.entries(route.headers)) {
153
+ headers.set(key, value);
154
+ }
155
+ }
156
+ const status = resolveStatus(route.status, response.status);
157
+ if (status === response.status && !hasHeaders) {
158
+ return response;
159
+ }
160
+ return new Response(response.body, { status, headers });
161
+ }
162
+ function normalizeHandlerValue(c, value) {
163
+ if (value instanceof Response) {
164
+ return value;
165
+ }
166
+ if (typeof value === "undefined") {
167
+ const response = c.body(null);
168
+ if (response.status === 200) {
169
+ return new Response(response.body, {
170
+ status: 204,
171
+ headers: response.headers
172
+ });
173
+ }
174
+ return response;
175
+ }
176
+ if (typeof value === "string") {
177
+ return c.text(value);
178
+ }
179
+ if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
180
+ if (!c.res.headers.get("content-type")) {
181
+ c.header("content-type", "application/octet-stream");
182
+ }
183
+ const data = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value);
184
+ return c.body(data);
185
+ }
186
+ return c.json(value);
187
+ }
188
+ function createRouteHandler(route) {
189
+ return async (c) => {
190
+ const value = typeof route.handler === "function" ? await route.handler(c) : route.handler;
191
+ return normalizeHandlerValue(c, value);
192
+ };
193
+ }
194
+ function createFinalizeMiddleware(route) {
195
+ return async (c, next) => {
196
+ const response = await next();
197
+ const resolved = response ?? c.res;
198
+ if (route.delay && route.delay > 0) {
199
+ await delay(route.delay);
200
+ }
201
+ return applyRouteOverrides(resolved, route);
202
+ };
203
+ }
204
+ function wrapMiddleware(handler) {
205
+ return async (c, next) => {
206
+ const response = await handler(c, next);
207
+ return response ?? c.res;
208
+ };
209
+ }
210
+ function createHonoApp(routes) {
211
+ const app = new Hono({ router: new PatternRouter(), strict: false });
212
+ for (const route of routes) {
213
+ const middlewares = route.middlewares?.map((entry) => wrapMiddleware(entry.handle)) ?? [];
214
+ app.on(
215
+ route.method,
216
+ toHonoPath(route),
217
+ createFinalizeMiddleware(route),
218
+ ...middlewares,
219
+ createRouteHandler(route)
220
+ );
221
+ }
222
+ return app;
223
+ }
224
+ async function readRawBody(req) {
225
+ return await new Promise((resolve, reject) => {
226
+ const chunks = [];
227
+ req.on("data", (chunk) => {
228
+ if (typeof chunk === "string") {
229
+ chunks.push(Buffer.from(chunk));
230
+ return;
231
+ }
232
+ if (chunk instanceof Uint8Array) {
233
+ chunks.push(chunk);
234
+ return;
235
+ }
236
+ chunks.push(Buffer.from(String(chunk)));
237
+ });
238
+ req.on("end", () => {
239
+ if (chunks.length === 0) {
240
+ resolve(null);
241
+ return;
242
+ }
243
+ resolve(Buffer.concat(chunks));
244
+ });
245
+ req.on("error", reject);
246
+ });
247
+ }
248
+ function buildHeaders(headers) {
249
+ const result = new Headers();
250
+ for (const [key, value] of Object.entries(headers)) {
251
+ if (typeof value === "undefined") {
252
+ continue;
253
+ }
254
+ if (Array.isArray(value)) {
255
+ result.set(key, value.join(","));
256
+ } else {
257
+ result.set(key, value);
258
+ }
259
+ }
260
+ return result;
261
+ }
262
+ async function toRequest(req) {
263
+ const url = new URL(req.url ?? "/", "http://mokup.local");
264
+ const method = req.method ?? "GET";
265
+ const headers = buildHeaders(req.headers);
266
+ const init = { method, headers };
267
+ const rawBody = await readRawBody(req);
268
+ if (rawBody && method !== "GET" && method !== "HEAD") {
269
+ init.body = rawBody;
270
+ }
271
+ return new Request(url.toString(), init);
272
+ }
273
+ async function sendResponse(res, response) {
274
+ res.statusCode = response.status;
275
+ response.headers.forEach((value, key) => {
276
+ res.setHeader(key, value);
277
+ });
278
+ if (!response.body) {
279
+ res.end();
280
+ return;
281
+ }
282
+ const buffer = new Uint8Array(await response.arrayBuffer());
283
+ res.end(buffer);
284
+ }
285
+ function hasMatch(app, method, pathname) {
286
+ const matchMethod = method === "HEAD" ? "GET" : method;
287
+ const match = app.router.match(matchMethod, pathname);
288
+ return !!match && match[0].length > 0;
289
+ }
290
+ function createMiddleware(getApp, logger) {
291
+ return async (req, res, next) => {
292
+ const app = getApp();
293
+ if (!app) {
294
+ return next();
295
+ }
296
+ const url = req.url ?? "/";
297
+ const parsedUrl = new URL(url, "http://mokup.local");
298
+ const pathname = parsedUrl.pathname;
299
+ const method = normalizeMethod(req.method) ?? "GET";
300
+ if (!hasMatch(app, method, pathname)) {
301
+ return next();
302
+ }
303
+ const startedAt = Date.now();
304
+ try {
305
+ const response = await app.fetch(await toRequest(req));
306
+ if (res.writableEnded) {
307
+ return;
308
+ }
309
+ await sendResponse(res, response);
310
+ logger.info(`${method} ${pathname} ${Date.now() - startedAt}ms`);
311
+ } catch (error) {
312
+ if (!res.headersSent) {
313
+ res.statusCode = 500;
314
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
315
+ }
316
+ res.end("Mock handler error");
317
+ logger.error("Mock handler failed:", error);
318
+ }
319
+ };
320
+ }
321
+
322
+ const require$1 = createRequire(import.meta.url);
323
+ const mimeTypes = {
324
+ ".html": "text/html; charset=utf-8",
325
+ ".css": "text/css; charset=utf-8",
326
+ ".js": "text/javascript; charset=utf-8",
327
+ ".map": "application/json; charset=utf-8",
328
+ ".json": "application/json; charset=utf-8",
329
+ ".svg": "image/svg+xml",
330
+ ".png": "image/png",
331
+ ".jpg": "image/jpeg",
332
+ ".jpeg": "image/jpeg",
333
+ ".ico": "image/x-icon"
334
+ };
335
+ function normalizePlaygroundPath(value) {
336
+ if (!value) {
337
+ return "/_mokup";
338
+ }
339
+ const normalized = value.startsWith("/") ? value : `/${value}`;
340
+ return normalized.length > 1 && normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
341
+ }
342
+ function normalizeBase(base) {
343
+ if (!base || base === "/") {
344
+ return "";
345
+ }
346
+ return base.endsWith("/") ? base.slice(0, -1) : base;
347
+ }
348
+ function resolvePlaygroundRequestPath(base, playgroundPath) {
349
+ const normalizedBase = normalizeBase(base);
350
+ const normalizedPath = normalizePlaygroundPath(playgroundPath);
351
+ if (!normalizedBase) {
352
+ return normalizedPath;
353
+ }
354
+ if (normalizedPath.startsWith(normalizedBase)) {
355
+ return normalizedPath;
356
+ }
357
+ return `${normalizedBase}${normalizedPath}`;
358
+ }
359
+ function injectPlaygroundHmr(html, base) {
360
+ if (html.includes("mokup-playground-hmr")) {
361
+ return html;
362
+ }
363
+ const normalizedBase = normalizeBase(base);
364
+ const clientPath = `${normalizedBase}/@vite/client`;
365
+ const snippet = [
366
+ '<script type="module" id="mokup-playground-hmr">',
367
+ `import('${clientPath}').then(({ createHotContext }) => {`,
368
+ " const hot = createHotContext('/@mokup/playground')",
369
+ " hot.on('mokup:routes-changed', () => {",
370
+ " const api = window.__MOKUP_PLAYGROUND__",
371
+ " if (api && typeof api.reloadRoutes === 'function') {",
372
+ " api.reloadRoutes()",
373
+ " return",
374
+ " }",
375
+ " window.location.reload()",
376
+ " })",
377
+ "}).catch(() => {})",
378
+ "<\/script>"
379
+ ].join("\n");
380
+ if (html.includes("</body>")) {
381
+ return html.replace("</body>", `${snippet}
382
+ </body>`);
383
+ }
384
+ return `${html}
385
+ ${snippet}`;
386
+ }
387
+ function injectPlaygroundSw(html, script) {
388
+ if (!script) {
389
+ return html;
390
+ }
391
+ if (html.includes("mokup-playground-sw")) {
392
+ return html;
393
+ }
394
+ const snippet = [
395
+ '<script type="module" id="mokup-playground-sw">',
396
+ script,
397
+ "<\/script>"
398
+ ].join("\n");
399
+ if (html.includes("</head>")) {
400
+ return html.replace("</head>", `${snippet}
401
+ </head>`);
402
+ }
403
+ if (html.includes("</body>")) {
404
+ return html.replace("</body>", `${snippet}
405
+ </body>`);
406
+ }
407
+ return `${html}
408
+ ${snippet}`;
409
+ }
410
+ function isViteDevServer(server) {
411
+ return !!server && "ws" in server;
412
+ }
413
+ function resolvePlaygroundOptions(playground) {
414
+ if (playground === false) {
415
+ return { enabled: false, path: "/_mokup" };
416
+ }
417
+ if (playground && typeof playground === "object") {
418
+ return {
419
+ enabled: playground.enabled !== false,
420
+ path: normalizePlaygroundPath(playground.path)
421
+ };
422
+ }
423
+ return { enabled: true, path: "/_mokup" };
424
+ }
425
+ function resolvePlaygroundDist() {
426
+ const pkgPath = require$1.resolve("@mokup/playground/package.json");
427
+ return join(pkgPath, "..", "dist");
428
+ }
429
+ function sendJson(res, data, statusCode = 200) {
430
+ res.statusCode = statusCode;
431
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
432
+ res.end(JSON.stringify(data, null, 2));
433
+ }
434
+ function sendFile(res, content, contentType) {
435
+ res.statusCode = 200;
436
+ res.setHeader("Content-Type", contentType);
437
+ res.end(content);
438
+ }
439
+ function toPosixPath(value) {
440
+ return value.replace(/\\/g, "/");
441
+ }
442
+ function normalizePath(value) {
443
+ return toPosixPath(normalize(value));
444
+ }
445
+ function isAncestor(parent, child) {
446
+ const normalizedParent = normalizePath(parent).replace(/\/$/, "");
447
+ const normalizedChild = normalizePath(child);
448
+ return normalizedChild === normalizedParent || normalizedChild.startsWith(`${normalizedParent}/`);
449
+ }
450
+ function resolveGroupRoot(dirs, serverRoot) {
451
+ if (!dirs || dirs.length === 0) {
452
+ return serverRoot ?? cwd();
453
+ }
454
+ if (serverRoot) {
455
+ const normalizedRoot = normalizePath(serverRoot);
456
+ const canUseRoot = dirs.every((dir) => isAncestor(normalizedRoot, dir));
457
+ if (canUseRoot) {
458
+ return normalizedRoot;
459
+ }
460
+ }
461
+ if (dirs.length === 1) {
462
+ return normalizePath(dirname(dirs[0]));
463
+ }
464
+ let common = normalizePath(dirs[0]);
465
+ for (const dir of dirs.slice(1)) {
466
+ const normalizedDir = normalizePath(dir);
467
+ while (common && !isAncestor(common, normalizedDir)) {
468
+ const parent = normalizePath(dirname(common));
469
+ if (parent === common) {
470
+ break;
471
+ }
472
+ common = parent;
473
+ }
474
+ }
475
+ if (!common || common === "/") {
476
+ return serverRoot ?? cwd();
477
+ }
478
+ return common;
479
+ }
480
+ function formatRouteFile(file, root) {
481
+ if (!root) {
482
+ return toPosixPath(file);
483
+ }
484
+ const rel = toPosixPath(relative(root, file));
485
+ if (!rel || rel.startsWith("..")) {
486
+ return toPosixPath(file);
487
+ }
488
+ return rel;
489
+ }
490
+ function resolveGroups(dirs, root) {
491
+ const groups = [];
492
+ const seen = /* @__PURE__ */ new Set();
493
+ for (const dir of dirs) {
494
+ const normalized = normalizePath(dir);
495
+ if (seen.has(normalized)) {
496
+ continue;
497
+ }
498
+ seen.add(normalized);
499
+ const rel = toPosixPath(relative(root, normalized));
500
+ const label = rel && !rel.startsWith("..") ? rel : normalized;
501
+ groups.push({
502
+ key: normalized,
503
+ label,
504
+ path: normalized
505
+ });
506
+ }
507
+ return groups;
508
+ }
509
+ function resolveRouteGroup(routeFile, groups) {
510
+ if (groups.length === 0) {
511
+ return void 0;
512
+ }
513
+ const normalizedFile = toPosixPath(normalize(routeFile));
514
+ let matched;
515
+ for (const group of groups) {
516
+ if (normalizedFile === group.path || normalizedFile.startsWith(`${group.path}/`)) {
517
+ if (!matched || group.path.length > matched.path.length) {
518
+ matched = group;
519
+ }
520
+ }
521
+ }
522
+ return matched;
523
+ }
524
+ function toPlaygroundRoute(route, root, groups) {
525
+ const matchedGroup = resolveRouteGroup(route.file, groups);
526
+ const middlewareSources = route.middlewares?.map((entry) => formatRouteFile(entry.source, root));
527
+ return {
528
+ method: route.method,
529
+ url: route.template,
530
+ file: formatRouteFile(route.file, root),
531
+ type: typeof route.handler === "function" ? "handler" : "static",
532
+ status: route.status,
533
+ delay: route.delay,
534
+ middlewareCount: middlewareSources?.length ?? 0,
535
+ middlewares: middlewareSources,
536
+ groupKey: matchedGroup?.key,
537
+ group: matchedGroup?.label
538
+ };
539
+ }
540
+ function createPlaygroundMiddleware(params) {
541
+ const distDir = resolvePlaygroundDist();
542
+ const playgroundPath = params.config.path;
543
+ const indexPath = join(distDir, "index.html");
544
+ return async (req, res, next) => {
545
+ if (!params.config.enabled) {
546
+ return next();
547
+ }
548
+ const server = params.getServer?.();
549
+ const requestPath = resolvePlaygroundRequestPath(server?.config?.base ?? "/", playgroundPath);
550
+ const requestUrl = req.url ?? "/";
551
+ const url = new URL(requestUrl, "http://mokup.local");
552
+ const pathname = url.pathname;
553
+ const matchedPath = pathname.startsWith(requestPath) ? requestPath : pathname.startsWith(playgroundPath) ? playgroundPath : null;
554
+ if (!matchedPath) {
555
+ return next();
556
+ }
557
+ const subPath = pathname.slice(matchedPath.length);
558
+ if (subPath === "") {
559
+ const suffix = url.search ?? "";
560
+ res.statusCode = 302;
561
+ res.setHeader("Location", `${matchedPath}/${suffix}`);
562
+ res.end();
563
+ return;
564
+ }
565
+ if (subPath === "" || subPath === "/" || subPath === "/index.html") {
566
+ try {
567
+ const html = await promises.readFile(indexPath, "utf8");
568
+ let output = html;
569
+ if (isViteDevServer(server)) {
570
+ output = injectPlaygroundHmr(output, server.config.base ?? "/");
571
+ output = injectPlaygroundSw(output, params.getSwScript?.());
572
+ }
573
+ const contentType = mimeTypes[".html"] ?? "text/html; charset=utf-8";
574
+ sendFile(res, output, contentType);
575
+ } catch (error) {
576
+ params.logger.error("Failed to load playground index:", error);
577
+ res.statusCode = 500;
578
+ res.end("Playground is not available.");
579
+ }
580
+ return;
581
+ }
582
+ if (subPath === "/routes") {
583
+ const dirs = params.getDirs?.() ?? [];
584
+ const baseRoot = resolveGroupRoot(dirs, server?.config?.root);
585
+ const groups = resolveGroups(dirs, baseRoot);
586
+ const routes = params.getRoutes();
587
+ sendJson(res, {
588
+ basePath: matchedPath,
589
+ root: baseRoot,
590
+ count: routes.length,
591
+ groups: groups.map((group) => ({ key: group.key, label: group.label })),
592
+ routes: routes.map((route) => toPlaygroundRoute(route, baseRoot, groups))
593
+ });
594
+ return;
595
+ }
596
+ const relPath = subPath.replace(/^\/+/, "");
597
+ if (relPath.includes("..")) {
598
+ res.statusCode = 400;
599
+ res.end("Invalid path.");
600
+ return;
601
+ }
602
+ const normalizedPath = normalize(relPath);
603
+ const filePath = join(distDir, normalizedPath);
604
+ try {
605
+ const content = await promises.readFile(filePath);
606
+ const ext = extname(filePath);
607
+ const contentType = mimeTypes[ext] ?? "application/octet-stream";
608
+ sendFile(res, content, contentType);
609
+ } catch {
610
+ return next();
611
+ }
612
+ };
613
+ }
614
+
615
+ const jsonExtensions = /* @__PURE__ */ new Set([".json", ".jsonc"]);
616
+ function resolveTemplate(template, prefix) {
617
+ const normalized = template.startsWith("/") ? template : `/${template}`;
618
+ if (!prefix) {
619
+ return normalized;
620
+ }
621
+ const normalizedPrefix = normalizePrefix(prefix);
622
+ if (!normalizedPrefix) {
623
+ return normalized;
624
+ }
625
+ if (normalized === normalizedPrefix || normalized.startsWith(`${normalizedPrefix}/`)) {
626
+ return normalized;
627
+ }
628
+ if (normalized === "/") {
629
+ return `${normalizedPrefix}/`;
630
+ }
631
+ return `${normalizedPrefix}${normalized}`;
632
+ }
633
+ function stripMethodSuffix(base) {
634
+ const segments = base.split(".");
635
+ const last = segments.at(-1);
636
+ if (last && methodSuffixSet.has(last.toLowerCase())) {
637
+ segments.pop();
638
+ return {
639
+ name: segments.join("."),
640
+ method: last.toUpperCase()
641
+ };
642
+ }
643
+ return {
644
+ name: base,
645
+ method: void 0
646
+ };
647
+ }
648
+ function deriveRouteFromFile(file, rootDir, logger) {
649
+ const rel = toPosix(relative(rootDir, file));
650
+ const ext = extname(rel);
651
+ const withoutExt = rel.slice(0, rel.length - ext.length);
652
+ const dir = dirname(withoutExt);
653
+ const base = basename(withoutExt);
654
+ const { name, method } = stripMethodSuffix(base);
655
+ const resolvedMethod = method ?? (jsonExtensions.has(ext) ? "GET" : void 0);
656
+ if (!resolvedMethod) {
657
+ logger.warn(`Skip mock without method suffix: ${file}`);
658
+ return null;
659
+ }
660
+ if (!name) {
661
+ logger.warn(`Skip mock with empty route name: ${file}`);
662
+ return null;
663
+ }
664
+ const joined = dir === "." ? name : join(dir, name);
665
+ const segments = toPosix(joined).split("/");
666
+ if (segments.at(-1) === "index") {
667
+ segments.pop();
668
+ }
669
+ const template = segments.length === 0 ? "/" : `/${segments.join("/")}`;
670
+ const parsed = parseRouteTemplate(template);
671
+ if (parsed.errors.length > 0) {
672
+ for (const error of parsed.errors) {
673
+ logger.warn(`${error} in ${file}`);
674
+ }
675
+ return null;
676
+ }
677
+ for (const warning of parsed.warnings) {
678
+ logger.warn(`${warning} in ${file}`);
679
+ }
680
+ return {
681
+ template: parsed.template,
682
+ method: resolvedMethod,
683
+ tokens: parsed.tokens,
684
+ score: parsed.score
685
+ };
686
+ }
687
+ function resolveRule(params) {
688
+ const method = params.derivedMethod;
689
+ if (!method) {
690
+ params.logger.warn(`Skip mock without method suffix: ${params.file}`);
691
+ return null;
692
+ }
693
+ const template = resolveTemplate(params.derivedTemplate, params.prefix);
694
+ const parsed = parseRouteTemplate(template);
695
+ if (parsed.errors.length > 0) {
696
+ for (const error of parsed.errors) {
697
+ params.logger.warn(`${error} in ${params.file}`);
698
+ }
699
+ return null;
700
+ }
701
+ for (const warning of parsed.warnings) {
702
+ params.logger.warn(`${warning} in ${params.file}`);
703
+ }
704
+ const route = {
705
+ file: params.file,
706
+ template: parsed.template,
707
+ method,
708
+ tokens: parsed.tokens,
709
+ score: parsed.score,
710
+ handler: params.rule.handler
711
+ };
712
+ if (typeof params.rule.status === "number") {
713
+ route.status = params.rule.status;
714
+ }
715
+ if (params.rule.headers) {
716
+ route.headers = params.rule.headers;
717
+ }
718
+ if (typeof params.rule.delay === "number") {
719
+ route.delay = params.rule.delay;
720
+ }
721
+ return route;
722
+ }
723
+ function sortRoutes(routes) {
724
+ return routes.sort((a, b) => {
725
+ if (a.method !== b.method) {
726
+ return a.method.localeCompare(b.method);
727
+ }
728
+ const scoreCompare = compareRouteScore(a.score, b.score);
729
+ if (scoreCompare !== 0) {
730
+ return scoreCompare;
731
+ }
732
+ return a.template.localeCompare(b.template);
733
+ });
734
+ }
735
+
736
+ const configExtensions = [".ts", ".js", ".mjs", ".cjs"];
737
+ async function loadModule$1(file) {
738
+ const ext = configExtensions.find((extension) => file.endsWith(extension));
739
+ if (ext === ".cjs") {
740
+ const require = createRequire(import.meta.url);
741
+ delete require.cache[file];
742
+ return require(file);
743
+ }
744
+ if (ext === ".js" || ext === ".mjs") {
745
+ return import(`${pathToFileURL(file).href}?t=${Date.now()}`);
746
+ }
747
+ if (ext === ".ts") {
748
+ const result = await build({
749
+ entryPoints: [file],
750
+ bundle: true,
751
+ format: "esm",
752
+ platform: "node",
753
+ sourcemap: "inline",
754
+ target: "es2020",
755
+ write: false
756
+ });
757
+ const output = result.outputFiles[0];
758
+ const code = output?.text ?? "";
759
+ const dataUrl = `data:text/javascript;base64,${Buffer.from(code).toString(
760
+ "base64"
761
+ )}`;
762
+ return import(`${dataUrl}#${Date.now()}`);
763
+ }
764
+ return null;
765
+ }
766
+ async function loadModuleWithVite$1(server, file) {
767
+ const asDevServer = server;
768
+ if ("ssrLoadModule" in asDevServer) {
769
+ const moduleNode = asDevServer.moduleGraph.getModuleById(file);
770
+ if (moduleNode) {
771
+ asDevServer.moduleGraph.invalidateModule(moduleNode);
772
+ }
773
+ return asDevServer.ssrLoadModule(file);
774
+ }
775
+ return loadModule$1(file);
776
+ }
777
+ function getConfigFileCandidates(dir) {
778
+ return configExtensions.map((extension) => join(dir, `index.config${extension}`));
779
+ }
780
+ async function findConfigFile(dir, cache) {
781
+ const cached = cache.get(dir);
782
+ if (cached !== void 0) {
783
+ return cached;
784
+ }
785
+ for (const candidate of getConfigFileCandidates(dir)) {
786
+ try {
787
+ await promises.stat(candidate);
788
+ cache.set(dir, candidate);
789
+ return candidate;
790
+ } catch {
791
+ continue;
792
+ }
793
+ }
794
+ cache.set(dir, null);
795
+ return null;
796
+ }
797
+ async function loadConfig(file, server) {
798
+ const mod = server ? await loadModuleWithVite$1(server, file) : await loadModule$1(file);
799
+ if (!mod) {
800
+ return null;
801
+ }
802
+ const value = mod?.default ?? mod;
803
+ if (!value || typeof value !== "object") {
804
+ return null;
805
+ }
806
+ return value;
807
+ }
808
+ function normalizeMiddlewares(value, source, logger) {
809
+ if (!value) {
810
+ return [];
811
+ }
812
+ const list = Array.isArray(value) ? value : [value];
813
+ const middlewares = [];
814
+ for (const [index, entry] of list.entries()) {
815
+ if (typeof entry !== "function") {
816
+ logger.warn(`Invalid middleware in ${source}`);
817
+ continue;
818
+ }
819
+ middlewares.push({ handle: entry, source, index });
820
+ }
821
+ return middlewares;
822
+ }
823
+ async function resolveDirectoryConfig(params) {
824
+ const { file, rootDir, server, logger, configCache, fileCache } = params;
825
+ const resolvedRoot = normalize(rootDir);
826
+ const resolvedFileDir = normalize(dirname(file));
827
+ const chain = [];
828
+ let current = resolvedFileDir;
829
+ while (true) {
830
+ chain.push(current);
831
+ if (current === resolvedRoot) {
832
+ break;
833
+ }
834
+ const parent = dirname(current);
835
+ if (parent === current) {
836
+ break;
837
+ }
838
+ current = parent;
839
+ }
840
+ chain.reverse();
841
+ const merged = { middlewares: [] };
842
+ for (const dir of chain) {
843
+ const configPath = await findConfigFile(dir, fileCache);
844
+ if (!configPath) {
845
+ continue;
846
+ }
847
+ let config = configCache.get(configPath);
848
+ if (config === void 0) {
849
+ config = await loadConfig(configPath, server);
850
+ configCache.set(configPath, config);
851
+ }
852
+ if (!config) {
853
+ logger.warn(`Invalid config in ${configPath}`);
854
+ continue;
855
+ }
856
+ if (config.headers) {
857
+ merged.headers = { ...merged.headers ?? {}, ...config.headers };
858
+ }
859
+ if (typeof config.status === "number") {
860
+ merged.status = config.status;
861
+ }
862
+ if (typeof config.delay === "number") {
863
+ merged.delay = config.delay;
864
+ }
865
+ if (typeof config.enabled === "boolean") {
866
+ merged.enabled = config.enabled;
867
+ }
868
+ const normalized = normalizeMiddlewares(config.middleware, configPath, logger);
869
+ if (normalized.length > 0) {
870
+ merged.middlewares.push(...normalized);
871
+ }
872
+ }
873
+ return merged;
874
+ }
875
+
876
+ async function walkDir(dir, rootDir, files) {
877
+ const entries = await promises.readdir(dir, { withFileTypes: true });
878
+ for (const entry of entries) {
879
+ if (entry.name === "node_modules" || entry.name === ".git") {
880
+ continue;
881
+ }
882
+ const fullPath = join(dir, entry.name);
883
+ if (entry.isDirectory()) {
884
+ await walkDir(fullPath, rootDir, files);
885
+ continue;
886
+ }
887
+ if (entry.isFile()) {
888
+ files.push({ file: fullPath, rootDir });
889
+ }
890
+ }
891
+ }
892
+ async function exists(path) {
893
+ try {
894
+ await promises.stat(path);
895
+ return true;
896
+ } catch {
897
+ return false;
898
+ }
899
+ }
900
+ async function collectFiles(dirs) {
901
+ const files = [];
902
+ for (const dir of dirs) {
903
+ if (!await exists(dir)) {
904
+ continue;
905
+ }
906
+ await walkDir(dir, dir, files);
907
+ }
908
+ return files;
909
+ }
910
+ function isSupportedFile(file) {
911
+ if (file.endsWith(".d.ts")) {
912
+ return false;
913
+ }
914
+ if (basename(file).startsWith("index.config.")) {
915
+ return false;
916
+ }
917
+ const ext = extname(file).toLowerCase();
918
+ return supportedExtensions.has(ext);
919
+ }
920
+
921
+ async function loadModule(file) {
922
+ const ext = extname(file).toLowerCase();
923
+ if (ext === ".cjs") {
924
+ const require = createRequire(import.meta.url);
925
+ delete require.cache[file];
926
+ return require(file);
927
+ }
928
+ if (ext === ".js" || ext === ".mjs") {
929
+ return import(`${pathToFileURL(file).href}?t=${Date.now()}`);
930
+ }
931
+ if (ext === ".ts") {
932
+ const result = await build({
933
+ entryPoints: [file],
934
+ bundle: true,
935
+ format: "esm",
936
+ platform: "node",
937
+ sourcemap: "inline",
938
+ target: "es2020",
939
+ write: false
940
+ });
941
+ const output = result.outputFiles[0];
942
+ const code = output?.text ?? "";
943
+ const dataUrl = `data:text/javascript;base64,${Buffer.from(code).toString(
944
+ "base64"
945
+ )}`;
946
+ return import(`${dataUrl}#${Date.now()}`);
947
+ }
948
+ return null;
949
+ }
950
+ async function loadModuleWithVite(server, file) {
951
+ const asDevServer = server;
952
+ if ("ssrLoadModule" in asDevServer) {
953
+ const moduleNode = asDevServer.moduleGraph.getModuleById(file);
954
+ if (moduleNode) {
955
+ asDevServer.moduleGraph.invalidateModule(moduleNode);
956
+ }
957
+ return asDevServer.ssrLoadModule(file);
958
+ }
959
+ return loadModule(file);
960
+ }
961
+ async function readJsonFile(file, logger) {
962
+ try {
963
+ const content = await promises.readFile(file, "utf8");
964
+ const errors = [];
965
+ const data = parse(content, errors, {
966
+ allowTrailingComma: true,
967
+ disallowComments: false
968
+ });
969
+ if (errors.length > 0) {
970
+ logger.warn(`Invalid JSONC in ${file}`);
971
+ return void 0;
972
+ }
973
+ return data;
974
+ } catch (error) {
975
+ logger.warn(`Failed to read ${file}: ${String(error)}`);
976
+ return void 0;
977
+ }
978
+ }
979
+ async function loadRules(file, server, logger) {
980
+ const ext = extname(file).toLowerCase();
981
+ if (ext === ".json" || ext === ".jsonc") {
982
+ const json = await readJsonFile(file, logger);
983
+ if (typeof json === "undefined") {
984
+ return [];
985
+ }
986
+ return [
987
+ {
988
+ handler: json
989
+ }
990
+ ];
991
+ }
992
+ const mod = server ? await loadModuleWithVite(server, file) : await loadModule(file);
993
+ const value = mod?.default ?? mod;
994
+ if (!value) {
995
+ return [];
996
+ }
997
+ if (Array.isArray(value)) {
998
+ return value;
999
+ }
1000
+ if (typeof value === "function") {
1001
+ return [
1002
+ {
1003
+ handler: value
1004
+ }
1005
+ ];
1006
+ }
1007
+ return [value];
1008
+ }
1009
+
1010
+ async function scanRoutes(params) {
1011
+ const routes = [];
1012
+ const seen = /* @__PURE__ */ new Set();
1013
+ const files = await collectFiles(params.dirs);
1014
+ const configCache = /* @__PURE__ */ new Map();
1015
+ const fileCache = /* @__PURE__ */ new Map();
1016
+ for (const fileInfo of files) {
1017
+ if (!isSupportedFile(fileInfo.file)) {
1018
+ continue;
1019
+ }
1020
+ if (!matchesFilter(fileInfo.file, params.include, params.exclude)) {
1021
+ continue;
1022
+ }
1023
+ const configParams = {
1024
+ file: fileInfo.file,
1025
+ rootDir: fileInfo.rootDir,
1026
+ logger: params.logger,
1027
+ configCache,
1028
+ fileCache
1029
+ };
1030
+ if (params.server) {
1031
+ configParams.server = params.server;
1032
+ }
1033
+ const config = await resolveDirectoryConfig(configParams);
1034
+ if (config.enabled === false) {
1035
+ continue;
1036
+ }
1037
+ const derived = deriveRouteFromFile(fileInfo.file, fileInfo.rootDir, params.logger);
1038
+ if (!derived) {
1039
+ continue;
1040
+ }
1041
+ const rules = await loadRules(fileInfo.file, params.server, params.logger);
1042
+ for (const [index, rule] of rules.entries()) {
1043
+ if (!rule || typeof rule !== "object") {
1044
+ continue;
1045
+ }
1046
+ const ruleValue = rule;
1047
+ const unsupportedKeys = ["response", "url", "method"].filter(
1048
+ (key2) => key2 in ruleValue
1049
+ );
1050
+ if (unsupportedKeys.length > 0) {
1051
+ params.logger.warn(
1052
+ `Skip mock with unsupported fields (${unsupportedKeys.join(", ")}): ${fileInfo.file}`
1053
+ );
1054
+ continue;
1055
+ }
1056
+ if (typeof rule.handler === "undefined") {
1057
+ params.logger.warn(`Skip mock without handler: ${fileInfo.file}`);
1058
+ continue;
1059
+ }
1060
+ const resolved = resolveRule({
1061
+ rule,
1062
+ derivedTemplate: derived.template,
1063
+ derivedMethod: derived.method,
1064
+ prefix: params.prefix,
1065
+ file: fileInfo.file,
1066
+ logger: params.logger
1067
+ });
1068
+ if (!resolved) {
1069
+ continue;
1070
+ }
1071
+ resolved.ruleIndex = index;
1072
+ if (config.headers) {
1073
+ resolved.headers = { ...config.headers, ...resolved.headers ?? {} };
1074
+ }
1075
+ if (typeof resolved.status === "undefined" && typeof config.status === "number") {
1076
+ resolved.status = config.status;
1077
+ }
1078
+ if (typeof resolved.delay === "undefined" && typeof config.delay === "number") {
1079
+ resolved.delay = config.delay;
1080
+ }
1081
+ if (config.middlewares.length > 0) {
1082
+ resolved.middlewares = config.middlewares;
1083
+ }
1084
+ const key = `${resolved.method} ${resolved.template}`;
1085
+ if (seen.has(key)) {
1086
+ params.logger.warn(`Duplicate mock route ${key} from ${fileInfo.file}`);
1087
+ }
1088
+ seen.add(key);
1089
+ routes.push(resolved);
1090
+ }
1091
+ }
1092
+ return sortRoutes(routes);
1093
+ }
1094
+
1095
+ const defaultSwPath = "/mokup-sw.js";
1096
+ const defaultSwScope = "/";
1097
+ function normalizeSwPath(path) {
1098
+ if (!path) {
1099
+ return defaultSwPath;
1100
+ }
1101
+ return path.startsWith("/") ? path : `/${path}`;
1102
+ }
1103
+ function normalizeSwScope(scope) {
1104
+ if (!scope) {
1105
+ return defaultSwScope;
1106
+ }
1107
+ return scope.startsWith("/") ? scope : `/${scope}`;
1108
+ }
1109
+ function normalizeBasePath(value) {
1110
+ if (!value) {
1111
+ return "/";
1112
+ }
1113
+ const normalized = value.startsWith("/") ? value : `/${value}`;
1114
+ if (normalized.length > 1 && normalized.endsWith("/")) {
1115
+ return normalized.slice(0, -1);
1116
+ }
1117
+ return normalized;
1118
+ }
1119
+ function resolveSwConfigFromEntries(entries, logger) {
1120
+ let path = defaultSwPath;
1121
+ let scope = defaultSwScope;
1122
+ let register = true;
1123
+ let unregister = false;
1124
+ const basePaths = [];
1125
+ let hasPath = false;
1126
+ let hasScope = false;
1127
+ let hasRegister = false;
1128
+ let hasUnregister = false;
1129
+ for (const entry of entries) {
1130
+ const config = entry.sw;
1131
+ if (config?.path) {
1132
+ const next = normalizeSwPath(config.path);
1133
+ if (!hasPath) {
1134
+ path = next;
1135
+ hasPath = true;
1136
+ } else if (path !== next) {
1137
+ logger.warn(`SW path "${next}" ignored; using "${path}".`);
1138
+ }
1139
+ }
1140
+ if (config?.scope) {
1141
+ const next = normalizeSwScope(config.scope);
1142
+ if (!hasScope) {
1143
+ scope = next;
1144
+ hasScope = true;
1145
+ } else if (scope !== next) {
1146
+ logger.warn(`SW scope "${next}" ignored; using "${scope}".`);
1147
+ }
1148
+ }
1149
+ if (typeof config?.register === "boolean") {
1150
+ if (!hasRegister) {
1151
+ register = config.register;
1152
+ hasRegister = true;
1153
+ } else if (register !== config.register) {
1154
+ logger.warn(
1155
+ `SW register="${String(config.register)}" ignored; using "${String(register)}".`
1156
+ );
1157
+ }
1158
+ }
1159
+ if (typeof config?.unregister === "boolean") {
1160
+ if (!hasUnregister) {
1161
+ unregister = config.unregister;
1162
+ hasUnregister = true;
1163
+ } else if (unregister !== config.unregister) {
1164
+ logger.warn(
1165
+ `SW unregister="${String(config.unregister)}" ignored; using "${String(unregister)}".`
1166
+ );
1167
+ }
1168
+ }
1169
+ if (typeof config?.basePath !== "undefined") {
1170
+ const values = Array.isArray(config.basePath) ? config.basePath : [config.basePath];
1171
+ for (const value of values) {
1172
+ basePaths.push(normalizeBasePath(value));
1173
+ }
1174
+ continue;
1175
+ }
1176
+ const normalizedPrefix = normalizePrefix(entry.prefix ?? "");
1177
+ if (normalizedPrefix) {
1178
+ basePaths.push(normalizedPrefix);
1179
+ }
1180
+ }
1181
+ return {
1182
+ path,
1183
+ scope,
1184
+ register,
1185
+ unregister,
1186
+ basePaths: Array.from(new Set(basePaths))
1187
+ };
1188
+ }
1189
+ function resolveSwConfig(options, logger) {
1190
+ const swEntries = options.filter((entry) => entry.mode === "sw");
1191
+ if (swEntries.length === 0) {
1192
+ return null;
1193
+ }
1194
+ return resolveSwConfigFromEntries(swEntries, logger);
1195
+ }
1196
+ function resolveSwUnregisterConfig(options, logger) {
1197
+ return resolveSwConfigFromEntries(options, logger);
1198
+ }
1199
+ function toViteImportPath(file, root) {
1200
+ const absolute = isAbsolute(file) ? file : resolve(root, file);
1201
+ const rel = relative(root, absolute);
1202
+ if (!rel.startsWith("..") && !isAbsolute(rel)) {
1203
+ return `/${toPosix(rel)}`;
1204
+ }
1205
+ return `/@fs/${toPosix(absolute)}`;
1206
+ }
1207
+ function shouldModuleize(handler) {
1208
+ if (typeof handler === "function") {
1209
+ return true;
1210
+ }
1211
+ if (typeof Response !== "undefined" && handler instanceof Response) {
1212
+ return true;
1213
+ }
1214
+ return false;
1215
+ }
1216
+ function toBinaryBody(handler) {
1217
+ if (handler instanceof ArrayBuffer) {
1218
+ return Buffer.from(new Uint8Array(handler)).toString("base64");
1219
+ }
1220
+ if (handler instanceof Uint8Array) {
1221
+ return Buffer.from(handler).toString("base64");
1222
+ }
1223
+ if (Buffer.isBuffer(handler)) {
1224
+ return handler.toString("base64");
1225
+ }
1226
+ return null;
1227
+ }
1228
+ function buildManifestResponse(route, moduleId) {
1229
+ if (moduleId) {
1230
+ const response = {
1231
+ type: "module",
1232
+ module: moduleId
1233
+ };
1234
+ if (typeof route.ruleIndex === "number") {
1235
+ response.ruleIndex = route.ruleIndex;
1236
+ }
1237
+ return response;
1238
+ }
1239
+ const handler = route.handler;
1240
+ if (typeof handler === "string") {
1241
+ return {
1242
+ type: "text",
1243
+ body: handler
1244
+ };
1245
+ }
1246
+ const binary = toBinaryBody(handler);
1247
+ if (binary) {
1248
+ return {
1249
+ type: "binary",
1250
+ body: binary,
1251
+ encoding: "base64"
1252
+ };
1253
+ }
1254
+ return {
1255
+ type: "json",
1256
+ body: handler
1257
+ };
1258
+ }
1259
+ function buildSwScript(params) {
1260
+ const { routes, root } = params;
1261
+ const runtimeImportPath = params.runtimeImportPath ?? "mokup/runtime";
1262
+ const basePaths = params.basePaths ?? [];
1263
+ const resolveModulePath = params.resolveModulePath ?? toViteImportPath;
1264
+ const ruleModules = /* @__PURE__ */ new Map();
1265
+ const middlewareModules = /* @__PURE__ */ new Map();
1266
+ const manifestRoutes = routes.map((route) => {
1267
+ const moduleId = shouldModuleize(route.handler) ? resolveModulePath(route.file, root) : null;
1268
+ if (moduleId) {
1269
+ ruleModules.set(moduleId, moduleId);
1270
+ }
1271
+ const middleware = route.middlewares?.map((entry) => {
1272
+ const modulePath = resolveModulePath(entry.source, root);
1273
+ middlewareModules.set(modulePath, modulePath);
1274
+ return {
1275
+ module: modulePath,
1276
+ ruleIndex: entry.index
1277
+ };
1278
+ });
1279
+ const response = buildManifestResponse(route, moduleId);
1280
+ const manifestRoute = {
1281
+ method: route.method,
1282
+ url: route.template,
1283
+ ...route.tokens ? { tokens: route.tokens } : {},
1284
+ ...route.score ? { score: route.score } : {},
1285
+ ...route.status ? { status: route.status } : {},
1286
+ ...route.headers ? { headers: route.headers } : {},
1287
+ ...route.delay ? { delay: route.delay } : {},
1288
+ ...middleware && middleware.length > 0 ? { middleware } : {},
1289
+ response
1290
+ };
1291
+ return manifestRoute;
1292
+ });
1293
+ const manifest = {
1294
+ version: 1,
1295
+ routes: manifestRoutes
1296
+ };
1297
+ const imports = [
1298
+ `import { createRuntimeApp, handle } from ${JSON.stringify(runtimeImportPath)}`
1299
+ ];
1300
+ const moduleEntries = [];
1301
+ let moduleIndex = 0;
1302
+ for (const id of ruleModules.keys()) {
1303
+ const name = `module${moduleIndex++}`;
1304
+ imports.push(`import * as ${name} from '${id}'`);
1305
+ moduleEntries.push({ id, name, kind: "rule" });
1306
+ }
1307
+ for (const id of middlewareModules.keys()) {
1308
+ const name = `module${moduleIndex++}`;
1309
+ imports.push(`import * as ${name} from '${id}'`);
1310
+ moduleEntries.push({ id, name, kind: "middleware" });
1311
+ }
1312
+ const lines = [];
1313
+ lines.push(...imports, "");
1314
+ lines.push(
1315
+ "const resolveModuleExport = (mod) => mod?.default ?? mod",
1316
+ "",
1317
+ "const toRuntimeRule = (value) => {",
1318
+ " if (typeof value === 'undefined') {",
1319
+ " return null",
1320
+ " }",
1321
+ " if (typeof value === 'function') {",
1322
+ " return { response: value }",
1323
+ " }",
1324
+ " if (value === null) {",
1325
+ " return { response: null }",
1326
+ " }",
1327
+ " if (typeof value === 'object') {",
1328
+ " if ('response' in value) {",
1329
+ " return value",
1330
+ " }",
1331
+ " if ('handler' in value) {",
1332
+ " const handlerRule = value",
1333
+ " return {",
1334
+ " response: handlerRule.handler,",
1335
+ " ...(typeof handlerRule.status === 'number' ? { status: handlerRule.status } : {}),",
1336
+ " ...(handlerRule.headers ? { headers: handlerRule.headers } : {}),",
1337
+ " ...(typeof handlerRule.delay === 'number' ? { delay: handlerRule.delay } : {}),",
1338
+ " }",
1339
+ " }",
1340
+ " return { response: value }",
1341
+ " }",
1342
+ " return { response: value }",
1343
+ "}",
1344
+ "",
1345
+ "const toRuntimeRules = (value) => {",
1346
+ " if (typeof value === 'undefined') {",
1347
+ " return []",
1348
+ " }",
1349
+ " if (Array.isArray(value)) {",
1350
+ " return value.map(toRuntimeRule).filter(Boolean)",
1351
+ " }",
1352
+ " const rule = toRuntimeRule(value)",
1353
+ " return rule ? [rule] : []",
1354
+ "}",
1355
+ ""
1356
+ );
1357
+ lines.push(
1358
+ `const manifest = ${JSON.stringify(manifest, null, 2)}`,
1359
+ ""
1360
+ );
1361
+ if (moduleEntries.length > 0) {
1362
+ lines.push("const moduleMap = {");
1363
+ for (const entry of moduleEntries) {
1364
+ if (entry.kind === "rule") {
1365
+ lines.push(
1366
+ ` ${JSON.stringify(entry.id)}: { default: toRuntimeRules(resolveModuleExport(${entry.name})) },`
1367
+ );
1368
+ continue;
1369
+ }
1370
+ lines.push(
1371
+ ` ${JSON.stringify(entry.id)}: ${entry.name},`
1372
+ );
1373
+ }
1374
+ lines.push("}", "");
1375
+ }
1376
+ const runtimeOptions = moduleEntries.length > 0 ? "{ manifest, moduleMap }" : "{ manifest }";
1377
+ lines.push(
1378
+ `const basePaths = ${JSON.stringify(basePaths)}`,
1379
+ "",
1380
+ "self.addEventListener('install', () => {",
1381
+ " self.skipWaiting()",
1382
+ "})",
1383
+ "",
1384
+ "self.addEventListener('activate', (event) => {",
1385
+ " event.waitUntil(self.clients.claim())",
1386
+ "})",
1387
+ "",
1388
+ "const shouldHandle = (request) => {",
1389
+ " if (!basePaths || basePaths.length === 0) {",
1390
+ " return true",
1391
+ " }",
1392
+ " const pathname = new URL(request.url).pathname",
1393
+ " return basePaths.some((basePath) => {",
1394
+ " if (basePath === '/') {",
1395
+ " return true",
1396
+ " }",
1397
+ " return pathname === basePath || pathname.startsWith(basePath + '/')",
1398
+ " })",
1399
+ "}",
1400
+ "",
1401
+ "const registerHandler = async () => {",
1402
+ ` const app = await createRuntimeApp(${runtimeOptions})`,
1403
+ " const handler = handle(app)",
1404
+ " self.addEventListener('fetch', (event) => {",
1405
+ " if (!shouldHandle(event.request)) {",
1406
+ " return",
1407
+ " }",
1408
+ " handler(event)",
1409
+ " })",
1410
+ "}",
1411
+ "",
1412
+ "registerHandler().catch((error) => {",
1413
+ " console.error('[mokup] Failed to build service worker app:', error)",
1414
+ "})",
1415
+ ""
1416
+ );
1417
+ return lines.join("\n");
1418
+ }
1419
+
1420
+ export { resolveSwConfig as a, resolveSwUnregisterConfig as b, createPlaygroundMiddleware as c, buildSwScript as d, createLogger as e, createMiddleware as f, createDebouncer as g, resolveDirs as h, isInDirs as i, sortRoutes as j, createHonoApp as k, resolvePlaygroundOptions as r, scanRoutes as s, toPosix as t };