@teamvelix/velix 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3387 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // ../../node_modules/.pnpm/tsup@8.5.1_jiti@1.21.7_post_49c9ba138cf4e7dd637766b727229610/node_modules/tsup/assets/esm_shims.js
12
+ import path from "path";
13
+ import { fileURLToPath } from "url";
14
+ var init_esm_shims = __esm({
15
+ "../../node_modules/.pnpm/tsup@8.5.1_jiti@1.21.7_post_49c9ba138cf4e7dd637766b727229610/node_modules/tsup/assets/esm_shims.js"() {
16
+ "use strict";
17
+ }
18
+ });
19
+
20
+ // server/image-optimizer.ts
21
+ var image_optimizer_exports = {};
22
+ __export(image_optimizer_exports, {
23
+ handleImageOptimization: () => handleImageOptimization
24
+ });
25
+ import fs6 from "fs";
26
+ import path7 from "path";
27
+ async function handleImageOptimization(req, res, projectRoot) {
28
+ let sharp;
29
+ try {
30
+ sharp = await import("sharp").then((m) => m.default || m);
31
+ } catch (e) {
32
+ }
33
+ try {
34
+ const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
35
+ const imageUrl = url.searchParams.get("url");
36
+ const widthStr = url.searchParams.get("w");
37
+ const qualityStr = url.searchParams.get("q");
38
+ if (!imageUrl) {
39
+ res.writeHead(400);
40
+ res.end("Missing url parameter");
41
+ return;
42
+ }
43
+ const width = widthStr ? parseInt(widthStr, 10) : void 0;
44
+ const quality = qualityStr ? parseInt(qualityStr, 10) : 75;
45
+ let imageBuffer = null;
46
+ if (imageUrl.startsWith("http")) {
47
+ const response = await fetch(imageUrl);
48
+ if (!response.ok) throw new Error(`Failed to fetch ${imageUrl}`);
49
+ imageBuffer = Buffer.from(await response.arrayBuffer());
50
+ } else {
51
+ const publicDir = path7.join(projectRoot, "public");
52
+ const resolvedPath = path7.join(publicDir, imageUrl.startsWith("/") ? imageUrl.slice(1) : imageUrl);
53
+ if (!resolvedPath.startsWith(publicDir) || !fs6.existsSync(resolvedPath)) {
54
+ res.writeHead(404);
55
+ res.end("Image not found");
56
+ return;
57
+ }
58
+ imageBuffer = fs6.readFileSync(resolvedPath);
59
+ }
60
+ if (!sharp) {
61
+ res.writeHead(200, {
62
+ "Content-Type": "image/jpeg",
63
+ "Cache-Control": "public, max-age=31536000, immutable"
64
+ });
65
+ res.end(imageBuffer);
66
+ return;
67
+ }
68
+ let processor = sharp(imageBuffer);
69
+ if (width) {
70
+ processor = processor.resize(width);
71
+ }
72
+ processor = processor.webp({ quality });
73
+ const optimizedBuffer = await processor.toBuffer();
74
+ res.writeHead(200, {
75
+ "Content-Type": "image/webp",
76
+ "Cache-Control": "public, max-age=31536000, immutable"
77
+ });
78
+ res.end(optimizedBuffer);
79
+ } catch (error) {
80
+ console.error("Image optimization error:", error);
81
+ res.writeHead(500);
82
+ res.end("Error processing image");
83
+ }
84
+ }
85
+ var init_image_optimizer = __esm({
86
+ "server/image-optimizer.ts"() {
87
+ "use strict";
88
+ init_esm_shims();
89
+ }
90
+ });
91
+
92
+ // index.ts
93
+ init_esm_shims();
94
+
95
+ // config.ts
96
+ init_esm_shims();
97
+ import fs from "fs";
98
+ import path2 from "path";
99
+ import { pathToFileURL } from "url";
100
+ import { z } from "zod";
101
+ import pc from "picocolors";
102
+ var AppConfigSchema = z.object({
103
+ name: z.string().default("Velix App"),
104
+ url: z.string().url().optional()
105
+ }).default({});
106
+ var ServerConfigSchema = z.object({
107
+ port: z.number().min(1).max(65535).default(3e3),
108
+ host: z.string().default("localhost")
109
+ }).default({});
110
+ var RoutingConfigSchema = z.object({
111
+ trailingSlash: z.boolean().default(false)
112
+ }).default({});
113
+ var SEOConfigSchema = z.object({
114
+ sitemap: z.boolean().default(true),
115
+ robots: z.boolean().default(true),
116
+ openGraph: z.boolean().default(true)
117
+ }).default({});
118
+ var BuildConfigSchema = z.object({
119
+ target: z.string().default("es2022"),
120
+ minify: z.boolean().default(true),
121
+ sourcemap: z.boolean().default(true),
122
+ splitting: z.boolean().default(true),
123
+ outDir: z.string().default(".velix")
124
+ }).default({});
125
+ var ExperimentalConfigSchema = z.object({
126
+ islands: z.boolean().default(true),
127
+ streaming: z.boolean().default(true)
128
+ }).default({});
129
+ var PluginSchema = z.union([
130
+ z.string(),
131
+ z.object({
132
+ name: z.string()
133
+ }).passthrough()
134
+ ]);
135
+ var VelixConfigSchema = z.object({
136
+ // App identity
137
+ app: AppConfigSchema,
138
+ // DevTools toggle
139
+ devtools: z.boolean().default(true),
140
+ // Server options
141
+ server: ServerConfigSchema,
142
+ // Routing options
143
+ routing: RoutingConfigSchema,
144
+ // SEO configuration
145
+ seo: SEOConfigSchema,
146
+ // Build options
147
+ build: BuildConfigSchema,
148
+ // Experimental features
149
+ experimental: ExperimentalConfigSchema,
150
+ // Plugins
151
+ plugins: z.array(PluginSchema).default([]),
152
+ // Directories (resolved automatically)
153
+ appDir: z.string().default("app"),
154
+ publicDir: z.string().default("public"),
155
+ // Stylesheets
156
+ styles: z.array(z.string()).default([]),
157
+ // Favicon
158
+ favicon: z.string().nullable().default(null)
159
+ });
160
+ var defaultConfig = VelixConfigSchema.parse({});
161
+ function defineConfig(config) {
162
+ return config;
163
+ }
164
+ async function loadConfig(projectRoot) {
165
+ const configPathTs = path2.join(projectRoot, "velix.config.ts");
166
+ const configPathJs = path2.join(projectRoot, "velix.config.js");
167
+ const configPathLegacyTs = path2.join(projectRoot, "flexireact.config.ts");
168
+ const configPathLegacyJs = path2.join(projectRoot, "flexireact.config.js");
169
+ let configPath = null;
170
+ if (fs.existsSync(configPathTs)) configPath = configPathTs;
171
+ else if (fs.existsSync(configPathJs)) configPath = configPathJs;
172
+ else if (fs.existsSync(configPathLegacyTs)) configPath = configPathLegacyTs;
173
+ else if (fs.existsSync(configPathLegacyJs)) configPath = configPathLegacyJs;
174
+ let userConfig = {};
175
+ if (configPath) {
176
+ try {
177
+ const configUrl = pathToFileURL(configPath).href;
178
+ const module = await import(`${configUrl}?t=${Date.now()}`);
179
+ userConfig = module.default || module;
180
+ } catch (error) {
181
+ console.warn(pc.yellow(`\u26A0 Failed to load config: ${error.message}`));
182
+ }
183
+ }
184
+ const merged = deepMerge(defaultConfig, userConfig);
185
+ try {
186
+ return VelixConfigSchema.parse(merged);
187
+ } catch (err) {
188
+ if (err instanceof z.ZodError) {
189
+ console.error(pc.red("\u2716 Configuration validation failed:"));
190
+ for (const issue of err.issues) {
191
+ console.error(pc.dim(` - ${issue.path.join(".")}: ${issue.message}`));
192
+ }
193
+ process.exit(1);
194
+ }
195
+ throw err;
196
+ }
197
+ }
198
+ function resolvePaths(config, projectRoot) {
199
+ return {
200
+ ...config,
201
+ resolvedAppDir: path2.resolve(projectRoot, config.appDir),
202
+ resolvedPublicDir: path2.resolve(projectRoot, config.publicDir),
203
+ resolvedOutDir: path2.resolve(projectRoot, config.build.outDir)
204
+ };
205
+ }
206
+ function deepMerge(target, source) {
207
+ const result = { ...target };
208
+ for (const key in source) {
209
+ if (source[key] && typeof source[key] === "object" && !Array.isArray(source[key])) {
210
+ result[key] = deepMerge(target[key] || {}, source[key]);
211
+ } else {
212
+ result[key] = source[key];
213
+ }
214
+ }
215
+ return result;
216
+ }
217
+
218
+ // helpers.ts
219
+ init_esm_shims();
220
+ var RedirectError = class extends Error {
221
+ url;
222
+ statusCode;
223
+ type = "redirect";
224
+ constructor(url, statusCode = 307) {
225
+ super(`Redirect to ${url}`);
226
+ this.name = "RedirectError";
227
+ this.url = url;
228
+ this.statusCode = statusCode;
229
+ }
230
+ };
231
+ var NotFoundError = class extends Error {
232
+ type = "notFound";
233
+ constructor(message = "Page not found") {
234
+ super(message);
235
+ this.name = "NotFoundError";
236
+ }
237
+ };
238
+ function redirect(url, type = "replace") {
239
+ const statusCode = type === "permanent" ? 308 : 307;
240
+ throw new RedirectError(url, statusCode);
241
+ }
242
+ function notFound(message) {
243
+ throw new NotFoundError(message);
244
+ }
245
+ function json(data, options = {}) {
246
+ const { status = 200, headers: headers2 = {} } = options;
247
+ return new Response(JSON.stringify(data), {
248
+ status,
249
+ headers: { "Content-Type": "application/json", ...headers2 }
250
+ });
251
+ }
252
+ function html(content, options = {}) {
253
+ const { status = 200, headers: headers2 = {} } = options;
254
+ return new Response(content, {
255
+ status,
256
+ headers: { "Content-Type": "text/html; charset=utf-8", ...headers2 }
257
+ });
258
+ }
259
+ function text(content, options = {}) {
260
+ const { status = 200, headers: headers2 = {} } = options;
261
+ return new Response(content, {
262
+ status,
263
+ headers: { "Content-Type": "text/plain; charset=utf-8", ...headers2 }
264
+ });
265
+ }
266
+ var cookies = {
267
+ parse(cookieHeader) {
268
+ const cookies2 = {};
269
+ if (!cookieHeader) return cookies2;
270
+ cookieHeader.split(";").forEach((cookie) => {
271
+ const [name, ...rest] = cookie.split("=");
272
+ if (name) {
273
+ cookies2[name.trim()] = decodeURIComponent(rest.join("=").trim());
274
+ }
275
+ });
276
+ return cookies2;
277
+ },
278
+ get(request, name) {
279
+ const cookieHeader = request.headers.get("cookie") || "";
280
+ return this.parse(cookieHeader)[name];
281
+ },
282
+ getAll(request) {
283
+ const cookieHeader = request.headers.get("cookie") || "";
284
+ return this.parse(cookieHeader);
285
+ },
286
+ serialize(name, value, options = {}) {
287
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
288
+ if (options.maxAge !== void 0) cookie += `; Max-Age=${options.maxAge}`;
289
+ if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
290
+ if (options.path) cookie += `; Path=${options.path}`;
291
+ if (options.domain) cookie += `; Domain=${options.domain}`;
292
+ if (options.secure) cookie += "; Secure";
293
+ if (options.httpOnly) cookie += "; HttpOnly";
294
+ if (options.sameSite) {
295
+ cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`;
296
+ }
297
+ return cookie;
298
+ },
299
+ set(name, value, options = {}) {
300
+ return this.serialize(name, value, {
301
+ path: "/",
302
+ httpOnly: true,
303
+ secure: process.env.NODE_ENV === "production",
304
+ sameSite: "lax",
305
+ ...options
306
+ });
307
+ },
308
+ delete(name, options = {}) {
309
+ return this.serialize(name, "", { ...options, path: "/", maxAge: 0 });
310
+ }
311
+ };
312
+ var headers = {
313
+ create(init) {
314
+ return new Headers(init);
315
+ },
316
+ get(request, name) {
317
+ return request.headers.get(name);
318
+ },
319
+ getAll(request) {
320
+ const result = {};
321
+ request.headers.forEach((value, key) => {
322
+ result[key] = value;
323
+ });
324
+ return result;
325
+ },
326
+ has(request, name) {
327
+ return request.headers.has(name);
328
+ },
329
+ contentType(request) {
330
+ return request.headers.get("content-type");
331
+ },
332
+ acceptsJson(request) {
333
+ const accept = request.headers.get("accept") || "";
334
+ return accept.includes("application/json") || accept.includes("*/*");
335
+ },
336
+ isAjax(request) {
337
+ return request.headers.get("x-requested-with") === "XMLHttpRequest" || this.acceptsJson(request);
338
+ },
339
+ authorization(request) {
340
+ const auth = request.headers.get("authorization");
341
+ if (!auth) return null;
342
+ const [type, ...rest] = auth.split(" ");
343
+ return { type: type.toLowerCase(), credentials: rest.join(" ") };
344
+ },
345
+ bearerToken(request) {
346
+ const auth = this.authorization(request);
347
+ return auth?.type === "bearer" ? auth.credentials : null;
348
+ },
349
+ security() {
350
+ return {
351
+ "X-Content-Type-Options": "nosniff",
352
+ "X-Frame-Options": "DENY",
353
+ "X-XSS-Protection": "1; mode=block",
354
+ "Referrer-Policy": "strict-origin-when-cross-origin",
355
+ "Permissions-Policy": "camera=(), microphone=(), geolocation=()"
356
+ };
357
+ },
358
+ cors(options = {}) {
359
+ const {
360
+ origin = "*",
361
+ methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
362
+ headers: allowHeaders = ["Content-Type", "Authorization"],
363
+ credentials = false,
364
+ maxAge = 86400
365
+ } = options;
366
+ const corsHeaders = {
367
+ "Access-Control-Allow-Origin": origin,
368
+ "Access-Control-Allow-Methods": methods.join(", "),
369
+ "Access-Control-Allow-Headers": allowHeaders.join(", "),
370
+ "Access-Control-Max-Age": String(maxAge)
371
+ };
372
+ if (credentials) corsHeaders["Access-Control-Allow-Credentials"] = "true";
373
+ return corsHeaders;
374
+ },
375
+ cache(options = {}) {
376
+ if (options.noStore) {
377
+ return { "Cache-Control": "no-store, no-cache, must-revalidate" };
378
+ }
379
+ const directives = [];
380
+ directives.push(options.private ? "private" : "public");
381
+ if (options.maxAge !== void 0) directives.push(`max-age=${options.maxAge}`);
382
+ if (options.sMaxAge !== void 0) directives.push(`s-maxage=${options.sMaxAge}`);
383
+ if (options.staleWhileRevalidate !== void 0) directives.push(`stale-while-revalidate=${options.staleWhileRevalidate}`);
384
+ return { "Cache-Control": directives.join(", ") };
385
+ }
386
+ };
387
+ async function parseJson(request) {
388
+ try {
389
+ return await request.json();
390
+ } catch {
391
+ throw new Error("Invalid JSON body");
392
+ }
393
+ }
394
+ async function parseFormData(request) {
395
+ return await request.formData();
396
+ }
397
+ function parseSearchParams(request) {
398
+ return new URL(request.url).searchParams;
399
+ }
400
+ function getMethod(request) {
401
+ return request.method.toUpperCase();
402
+ }
403
+ function getPathname(request) {
404
+ return new URL(request.url).pathname;
405
+ }
406
+ function isMethod(request, method) {
407
+ const reqMethod = getMethod(request);
408
+ return Array.isArray(method) ? method.map((m) => m.toUpperCase()).includes(reqMethod) : reqMethod === method.toUpperCase();
409
+ }
410
+
411
+ // router/index.ts
412
+ init_esm_shims();
413
+ import fs3 from "fs";
414
+ import path4 from "path";
415
+
416
+ // utils.ts
417
+ init_esm_shims();
418
+ import fs2 from "fs";
419
+ import path3 from "path";
420
+ import crypto from "crypto";
421
+ function generateHash(content) {
422
+ return crypto.createHash("md5").update(content).digest("hex").slice(0, 8);
423
+ }
424
+ function escapeHtml(str) {
425
+ const htmlEntities = {
426
+ "&": "&",
427
+ "<": "&lt;",
428
+ ">": "&gt;",
429
+ '"': "&quot;",
430
+ "'": "&#39;"
431
+ };
432
+ return String(str).replace(/[&<>"']/g, (char) => htmlEntities[char]);
433
+ }
434
+ function findFiles(dir, pattern, files = []) {
435
+ if (!fs2.existsSync(dir)) return files;
436
+ const entries = fs2.readdirSync(dir, { withFileTypes: true });
437
+ for (const entry of entries) {
438
+ const fullPath = path3.join(dir, entry.name);
439
+ if (entry.isDirectory()) findFiles(fullPath, pattern, files);
440
+ else if (pattern.test(entry.name)) files.push(fullPath);
441
+ }
442
+ return files;
443
+ }
444
+ function ensureDir(dir) {
445
+ if (!fs2.existsSync(dir)) fs2.mkdirSync(dir, { recursive: true });
446
+ }
447
+ function cleanDir(dir) {
448
+ if (fs2.existsSync(dir)) fs2.rmSync(dir, { recursive: true, force: true });
449
+ fs2.mkdirSync(dir, { recursive: true });
450
+ }
451
+ function copyDir(src, dest) {
452
+ ensureDir(dest);
453
+ const entries = fs2.readdirSync(src, { withFileTypes: true });
454
+ for (const entry of entries) {
455
+ const srcPath = path3.join(src, entry.name);
456
+ const destPath = path3.join(dest, entry.name);
457
+ if (entry.isDirectory()) copyDir(srcPath, destPath);
458
+ else fs2.copyFileSync(srcPath, destPath);
459
+ }
460
+ }
461
+ function debounce(fn, delay) {
462
+ let timeout;
463
+ return (...args) => {
464
+ clearTimeout(timeout);
465
+ timeout = setTimeout(() => fn(...args), delay);
466
+ };
467
+ }
468
+ function formatBytes(bytes) {
469
+ if (bytes === 0) return "0 B";
470
+ const k = 1024;
471
+ const sizes = ["B", "KB", "MB", "GB"];
472
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
473
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
474
+ }
475
+ function formatTime(ms) {
476
+ if (ms < 1e3) return `${ms}ms`;
477
+ return `${(ms / 1e3).toFixed(2)}s`;
478
+ }
479
+ function sleep(ms) {
480
+ return new Promise((resolve) => setTimeout(resolve, ms));
481
+ }
482
+ function isServerComponent(filePath) {
483
+ try {
484
+ const content = fs2.readFileSync(filePath, "utf-8");
485
+ const firstLine = content.split("\n")[0].trim();
486
+ return firstLine === "'use server'" || firstLine === '"use server"';
487
+ } catch {
488
+ return false;
489
+ }
490
+ }
491
+ function isClientComponent(filePath) {
492
+ try {
493
+ const content = fs2.readFileSync(filePath, "utf-8");
494
+ const firstLine = content.split("\n")[0].trim();
495
+ return firstLine === "'use client'" || firstLine === '"use client"';
496
+ } catch {
497
+ return false;
498
+ }
499
+ }
500
+ function isIsland(filePath) {
501
+ try {
502
+ const content = fs2.readFileSync(filePath, "utf-8");
503
+ const firstLine = content.split("\n")[0].trim();
504
+ return firstLine === "'use island'" || firstLine === '"use island"';
505
+ } catch {
506
+ return false;
507
+ }
508
+ }
509
+
510
+ // router/index.ts
511
+ var RouteType = {
512
+ PAGE: "page",
513
+ API: "api",
514
+ LAYOUT: "layout",
515
+ LOADING: "loading",
516
+ ERROR: "error",
517
+ NOT_FOUND: "not-found"
518
+ };
519
+ function buildRouteTree(appDir) {
520
+ const projectRoot = path4.dirname(appDir);
521
+ const routes = {
522
+ pages: [],
523
+ api: [],
524
+ layouts: /* @__PURE__ */ new Map(),
525
+ tree: {},
526
+ appRoutes: []
527
+ };
528
+ if (fs3.existsSync(appDir)) {
529
+ scanAppDirectory(appDir, appDir, routes);
530
+ }
531
+ const serverApiDir = path4.join(projectRoot, "server", "api");
532
+ if (fs3.existsSync(serverApiDir)) {
533
+ scanApiDirectory(serverApiDir, serverApiDir, routes);
534
+ }
535
+ const rootLayoutTsx = path4.join(appDir, "layout.tsx");
536
+ const rootLayoutJsx = path4.join(appDir, "layout.jsx");
537
+ if (fs3.existsSync(rootLayoutTsx)) routes.rootLayout = rootLayoutTsx;
538
+ else if (fs3.existsSync(rootLayoutJsx)) routes.rootLayout = rootLayoutJsx;
539
+ routes.tree = buildTree(routes.appRoutes);
540
+ return routes;
541
+ }
542
+ function scanAppDirectory(baseDir, currentDir, routes, parentSegments = [], parentLayout = null, parentMiddleware = null) {
543
+ const entries = fs3.readdirSync(currentDir, { withFileTypes: true });
544
+ const specialFiles = {
545
+ page: null,
546
+ layout: null,
547
+ loading: null,
548
+ error: null,
549
+ notFound: null,
550
+ template: null,
551
+ middleware: null
552
+ };
553
+ for (const entry of entries) {
554
+ if (entry.isFile()) {
555
+ const name = entry.name.replace(/\.(jsx|js|tsx|ts)$/, "");
556
+ const fullPath = path4.join(currentDir, entry.name);
557
+ const ext = path4.extname(entry.name);
558
+ if (![".tsx", ".jsx", ".ts", ".js"].includes(ext)) continue;
559
+ if (name === "page") specialFiles.page = fullPath;
560
+ if (name === "layout") specialFiles.layout = fullPath;
561
+ if (name === "loading") specialFiles.loading = fullPath;
562
+ if (name === "error") specialFiles.error = fullPath;
563
+ if (name === "not-found") specialFiles.notFound = fullPath;
564
+ if (name === "template") specialFiles.template = fullPath;
565
+ if (name === "middleware" || name === "_middleware") specialFiles.middleware = fullPath;
566
+ if (name.startsWith("[") && name.endsWith("]") && [".tsx", ".jsx"].includes(ext)) {
567
+ const paramName = name.slice(1, -1);
568
+ let segmentName;
569
+ if (paramName.startsWith("...")) {
570
+ segmentName = "*" + paramName.slice(3);
571
+ } else {
572
+ segmentName = ":" + paramName;
573
+ }
574
+ const routePath = "/" + [...parentSegments, segmentName].join("/");
575
+ routes.appRoutes.push({
576
+ type: RouteType.PAGE,
577
+ path: routePath.replace(/\/+/g, "/"),
578
+ filePath: fullPath,
579
+ pattern: createRoutePattern(routePath),
580
+ segments: [...parentSegments, segmentName],
581
+ layout: specialFiles.layout || parentLayout,
582
+ loading: specialFiles.loading,
583
+ error: specialFiles.error,
584
+ notFound: specialFiles.notFound,
585
+ template: specialFiles.template,
586
+ middleware: specialFiles.middleware || parentMiddleware,
587
+ isServerComponent: isServerComponent(fullPath),
588
+ isClientComponent: isClientComponent(fullPath),
589
+ isIsland: isIsland(fullPath)
590
+ });
591
+ }
592
+ }
593
+ }
594
+ if (specialFiles.page) {
595
+ const routePath = "/" + parentSegments.join("/") || "/";
596
+ routes.appRoutes.push({
597
+ type: RouteType.PAGE,
598
+ path: routePath.replace(/\/+/g, "/") || "/",
599
+ filePath: specialFiles.page,
600
+ pattern: createRoutePattern(routePath || "/"),
601
+ segments: parentSegments,
602
+ layout: specialFiles.layout || parentLayout,
603
+ loading: specialFiles.loading,
604
+ error: specialFiles.error,
605
+ notFound: specialFiles.notFound,
606
+ template: specialFiles.template,
607
+ middleware: specialFiles.middleware || parentMiddleware,
608
+ isServerComponent: isServerComponent(specialFiles.page),
609
+ isClientComponent: isClientComponent(specialFiles.page),
610
+ isIsland: isIsland(specialFiles.page)
611
+ });
612
+ }
613
+ for (const entry of entries) {
614
+ if (entry.isDirectory()) {
615
+ const fullPath = path4.join(currentDir, entry.name);
616
+ if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
617
+ const isGroup = entry.name.startsWith("(") && entry.name.endsWith(")");
618
+ let segmentName = entry.name;
619
+ if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
620
+ segmentName = ":" + entry.name.slice(1, -1);
621
+ if (entry.name.startsWith("[...")) {
622
+ segmentName = "*" + entry.name.slice(4, -1);
623
+ }
624
+ if (entry.name.startsWith("[[...")) {
625
+ segmentName = "*" + entry.name.slice(5, -2);
626
+ }
627
+ }
628
+ const newSegments = isGroup ? parentSegments : [...parentSegments, segmentName];
629
+ const newLayout = specialFiles.layout || parentLayout;
630
+ const newMiddleware = specialFiles.middleware || parentMiddleware;
631
+ scanAppDirectory(baseDir, fullPath, routes, newSegments, newLayout, newMiddleware);
632
+ }
633
+ }
634
+ }
635
+ function scanApiDirectory(baseDir, currentDir, routes, parentSegments = []) {
636
+ const entries = fs3.readdirSync(currentDir, { withFileTypes: true });
637
+ for (const entry of entries) {
638
+ const fullPath = path4.join(currentDir, entry.name);
639
+ if (entry.isDirectory()) {
640
+ scanApiDirectory(baseDir, fullPath, routes, [...parentSegments, entry.name]);
641
+ } else if (entry.isFile()) {
642
+ const ext = path4.extname(entry.name);
643
+ if (![".ts", ".js"].includes(ext)) continue;
644
+ const baseName = path4.basename(entry.name, ext);
645
+ const apiSegments = baseName === "route" || baseName === "index" ? parentSegments : [...parentSegments, baseName];
646
+ const apiPath = "/api/" + apiSegments.join("/");
647
+ routes.api.push({
648
+ type: RouteType.API,
649
+ path: apiPath.replace(/\/+/g, "/") || "/api",
650
+ filePath: fullPath,
651
+ pattern: createRoutePattern(apiPath),
652
+ segments: ["api", ...apiSegments].filter(Boolean)
653
+ });
654
+ }
655
+ }
656
+ }
657
+ function createRoutePattern(routePath) {
658
+ let pattern = routePath.replace(/\*[^/]*/g, "(.*)").replace(/:[^/]+/g, "([^/]+)").replace(/\//g, "\\/");
659
+ return new RegExp(`^${pattern}$`);
660
+ }
661
+ function matchRoute(urlPath, routes) {
662
+ const normalizedPath = urlPath === "" ? "/" : urlPath.split("?")[0];
663
+ for (const route of routes) {
664
+ const match = normalizedPath.match(route.pattern);
665
+ if (match) {
666
+ const params = extractParams(route.path, match);
667
+ return { ...route, params };
668
+ }
669
+ }
670
+ return null;
671
+ }
672
+ function extractParams(routePath, match) {
673
+ const params = {};
674
+ const paramNames = [];
675
+ const paramRegex = /:([^/]+)|\*([^/]*)/g;
676
+ let paramMatch;
677
+ while ((paramMatch = paramRegex.exec(routePath)) !== null) {
678
+ paramNames.push(paramMatch[1] || paramMatch[2] || "splat");
679
+ }
680
+ paramNames.forEach((name, index) => {
681
+ params[name] = match[index + 1];
682
+ });
683
+ return params;
684
+ }
685
+ function findRouteLayouts(route, layoutsMap) {
686
+ const layouts = [];
687
+ for (const segment of route.segments) {
688
+ if (layoutsMap.has(segment)) {
689
+ layouts.push({ name: segment, filePath: layoutsMap.get(segment) });
690
+ }
691
+ }
692
+ if (route.layout) {
693
+ layouts.push({ name: "route", filePath: route.layout });
694
+ }
695
+ if (layoutsMap.has("root")) {
696
+ layouts.unshift({ name: "root", filePath: layoutsMap.get("root") });
697
+ }
698
+ return layouts;
699
+ }
700
+ function buildTree(routes) {
701
+ const tree = { children: {}, routes: [] };
702
+ for (const route of routes) {
703
+ let current = tree;
704
+ for (const segment of route.segments) {
705
+ if (!current.children[segment]) {
706
+ current.children[segment] = { children: {}, routes: [] };
707
+ }
708
+ current = current.children[segment];
709
+ }
710
+ current.routes.push(route);
711
+ }
712
+ return tree;
713
+ }
714
+
715
+ // server/index.ts
716
+ init_esm_shims();
717
+ import http from "http";
718
+ import fs7 from "fs";
719
+ import path8 from "path";
720
+ import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL3 } from "url";
721
+ import React2 from "react";
722
+ import { renderToString } from "react-dom/server";
723
+
724
+ // middleware/index.ts
725
+ init_esm_shims();
726
+ import fs4 from "fs";
727
+ import path5 from "path";
728
+ var middlewares = {
729
+ cors(options = {}) {
730
+ const {
731
+ origin = "*",
732
+ methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
733
+ headers: allowHeaders = ["Content-Type", "Authorization"],
734
+ credentials = false,
735
+ maxAge = 86400
736
+ } = options;
737
+ return async (req, res, next) => {
738
+ const originHeader = typeof origin === "string" ? origin : origin.includes(req.headers.origin) ? req.headers.origin : "";
739
+ res.header("Access-Control-Allow-Origin", originHeader);
740
+ res.header("Access-Control-Allow-Methods", methods.join(", "));
741
+ res.header("Access-Control-Allow-Headers", allowHeaders.join(", "));
742
+ res.header("Access-Control-Max-Age", String(maxAge));
743
+ if (credentials) {
744
+ res.header("Access-Control-Allow-Credentials", "true");
745
+ }
746
+ if (req.method === "OPTIONS") {
747
+ res.status(204);
748
+ return;
749
+ }
750
+ await next();
751
+ };
752
+ },
753
+ rateLimit(options = {}) {
754
+ const { windowMs = 6e4, max = 100, message = "Too many requests" } = options;
755
+ const store = /* @__PURE__ */ new Map();
756
+ return async (req, res, next) => {
757
+ const ip = req.headers["x-forwarded-for"] || "unknown";
758
+ const now = Date.now();
759
+ const record = store.get(ip);
760
+ if (!record || now > record.resetTime) {
761
+ store.set(ip, { count: 1, resetTime: now + windowMs });
762
+ } else if (record.count >= max) {
763
+ res.status(429).json({ error: message });
764
+ return;
765
+ } else {
766
+ record.count++;
767
+ }
768
+ await next();
769
+ };
770
+ },
771
+ security() {
772
+ return async (_req, res, next) => {
773
+ res.header("X-Content-Type-Options", "nosniff");
774
+ res.header("X-Frame-Options", "DENY");
775
+ res.header("X-XSS-Protection", "1; mode=block");
776
+ res.header("Referrer-Policy", "strict-origin-when-cross-origin");
777
+ await next();
778
+ };
779
+ }
780
+ };
781
+ async function loadMiddleware(projectRoot) {
782
+ const middlewareDir = path5.join(projectRoot, "middleware");
783
+ const fns = [];
784
+ if (!fs4.existsSync(middlewareDir)) return fns;
785
+ const files = fs4.readdirSync(middlewareDir).filter((f) => /\.(ts|js)$/.test(f)).sort();
786
+ for (const file of files) {
787
+ try {
788
+ const filePath = path5.join(middlewareDir, file);
789
+ const { pathToFileURL: pathToFileURL4 } = await import("url");
790
+ const url = pathToFileURL4(filePath).href;
791
+ const mod = await import(`${url}?t=${Date.now()}`);
792
+ const fn = mod.default || mod.middleware;
793
+ if (typeof fn === "function") fns.push(fn);
794
+ } catch (err) {
795
+ console.warn(`\u26A0 Failed to load middleware ${file}: ${err.message}`);
796
+ }
797
+ }
798
+ return fns;
799
+ }
800
+ async function runMiddleware(req, res, fns) {
801
+ const result = { continue: true, rewritten: false };
802
+ if (fns.length === 0) return result;
803
+ const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
804
+ const cookies2 = {};
805
+ const cookieHeader = req.headers.cookie;
806
+ if (cookieHeader) {
807
+ cookieHeader.split(";").forEach((c2) => {
808
+ const [k, ...v] = c2.split("=");
809
+ if (k) cookies2[k.trim()] = v.join("=").trim();
810
+ });
811
+ }
812
+ const mReq = {
813
+ url: req.url || "/",
814
+ method: req.method || "GET",
815
+ headers: req.headers,
816
+ cookies: cookies2,
817
+ params: {},
818
+ query: Object.fromEntries(url.searchParams),
819
+ raw: req
820
+ };
821
+ let ended = false;
822
+ const mRes = {
823
+ _statusCode: 200,
824
+ _headers: {},
825
+ _redirectUrl: null,
826
+ _rewriteUrl: null,
827
+ _ended: false,
828
+ status(code) {
829
+ this._statusCode = code;
830
+ return this;
831
+ },
832
+ header(name, value) {
833
+ this._headers[name] = value;
834
+ return this;
835
+ },
836
+ json(data) {
837
+ this._headers["Content-Type"] = "application/json";
838
+ res.writeHead(this._statusCode, this._headers);
839
+ res.end(JSON.stringify(data));
840
+ this._ended = true;
841
+ ended = true;
842
+ },
843
+ redirect(url2, status = 307) {
844
+ this._redirectUrl = url2;
845
+ this._statusCode = status;
846
+ res.writeHead(status, { Location: url2, ...this._headers });
847
+ res.end();
848
+ this._ended = true;
849
+ ended = true;
850
+ },
851
+ rewrite(url2) {
852
+ this._rewriteUrl = url2;
853
+ req.url = url2;
854
+ result.rewritten = true;
855
+ },
856
+ async next() {
857
+ }
858
+ };
859
+ let index = 0;
860
+ const next = async () => {
861
+ if (ended || index >= fns.length) return;
862
+ const fn = fns[index++];
863
+ await fn(mReq, mRes, next);
864
+ };
865
+ await next();
866
+ if (!ended) {
867
+ for (const [key, value] of Object.entries(mRes._headers)) {
868
+ res.setHeader(key, value);
869
+ }
870
+ }
871
+ result.continue = !ended;
872
+ return result;
873
+ }
874
+ function composeMiddleware(...fns) {
875
+ return async (req, res, next) => {
876
+ let index = 0;
877
+ const run = async () => {
878
+ if (index >= fns.length) {
879
+ await next();
880
+ return;
881
+ }
882
+ const fn = fns[index++];
883
+ await fn(req, res, run);
884
+ };
885
+ await run();
886
+ };
887
+ }
888
+
889
+ // plugins/index.ts
890
+ init_esm_shims();
891
+ import fs5 from "fs";
892
+ import path6 from "path";
893
+ import { pathToFileURL as pathToFileURL2 } from "url";
894
+ var PluginHooks = {
895
+ CONFIG: "config",
896
+ SERVER_START: "server:start",
897
+ REQUEST: "request",
898
+ RESPONSE: "response",
899
+ ROUTES_LOADED: "routes:loaded",
900
+ BEFORE_RENDER: "render:before",
901
+ AFTER_RENDER: "render:after",
902
+ BUILD_START: "build:start",
903
+ BUILD_END: "build:end"
904
+ };
905
+ var PluginManager = class {
906
+ plugins = [];
907
+ hooks = /* @__PURE__ */ new Map();
908
+ /**
909
+ * Register a plugin
910
+ */
911
+ register(plugin) {
912
+ this.plugins.push(plugin);
913
+ if (plugin.hooks) {
914
+ for (const [hookName, handler] of Object.entries(plugin.hooks)) {
915
+ if (handler) {
916
+ const existing = this.hooks.get(hookName) || [];
917
+ existing.push(handler);
918
+ this.hooks.set(hookName, existing);
919
+ }
920
+ }
921
+ }
922
+ }
923
+ /**
924
+ * Run a hook with arguments
925
+ */
926
+ async runHook(hookName, ...args) {
927
+ const handlers = this.hooks.get(hookName) || [];
928
+ for (const handler of handlers) {
929
+ await handler(...args);
930
+ }
931
+ }
932
+ /**
933
+ * Run a waterfall hook — each handler transforms the first argument
934
+ */
935
+ async runWaterfallHook(hookName, value, ...args) {
936
+ const handlers = this.hooks.get(hookName) || [];
937
+ let result = value;
938
+ for (const handler of handlers) {
939
+ const transformed = await handler(result, ...args);
940
+ if (transformed !== void 0) result = transformed;
941
+ }
942
+ return result;
943
+ }
944
+ /**
945
+ * Get all registered plugins
946
+ */
947
+ getPlugins() {
948
+ return [...this.plugins];
949
+ }
950
+ /**
951
+ * Check if a plugin is registered
952
+ */
953
+ hasPlugin(name) {
954
+ return this.plugins.some((p) => p.name === name);
955
+ }
956
+ };
957
+ var pluginManager = new PluginManager();
958
+ async function loadPlugins(projectRoot, config) {
959
+ const pluginEntries = config.plugins || [];
960
+ for (const entry of pluginEntries) {
961
+ try {
962
+ if (typeof entry === "string") {
963
+ const localPath = path6.join(projectRoot, "plugins", entry + ".ts");
964
+ const localPathJs = path6.join(projectRoot, "plugins", entry + ".js");
965
+ const localPathDir = path6.join(projectRoot, "plugins", entry, "index.ts");
966
+ let pluginPath = null;
967
+ if (fs5.existsSync(localPath)) pluginPath = localPath;
968
+ else if (fs5.existsSync(localPathJs)) pluginPath = localPathJs;
969
+ else if (fs5.existsSync(localPathDir)) pluginPath = localPathDir;
970
+ if (pluginPath) {
971
+ const url = pathToFileURL2(pluginPath).href;
972
+ const mod = await import(`${url}?t=${Date.now()}`);
973
+ const plugin = mod.default || mod;
974
+ if (plugin.name) {
975
+ pluginManager.register(plugin);
976
+ }
977
+ } else {
978
+ try {
979
+ const mod = await import(entry);
980
+ const plugin = mod.default || mod;
981
+ if (plugin.name) pluginManager.register(plugin);
982
+ } catch {
983
+ console.warn(`\u26A0 Plugin not found: ${entry}`);
984
+ }
985
+ }
986
+ } else if (typeof entry === "object" && entry.name) {
987
+ pluginManager.register(entry);
988
+ }
989
+ } catch (err) {
990
+ console.warn(`\u26A0 Failed to load plugin: ${err.message}`);
991
+ }
992
+ }
993
+ }
994
+ function definePlugin(definition) {
995
+ return definition;
996
+ }
997
+ var builtinPlugins = {
998
+ /**
999
+ * Security headers plugin
1000
+ */
1001
+ security: definePlugin({
1002
+ name: "velix:security",
1003
+ hooks: {
1004
+ [PluginHooks.RESPONSE]: (_req, res) => {
1005
+ if (!res.headersSent) {
1006
+ res.setHeader("X-Content-Type-Options", "nosniff");
1007
+ res.setHeader("X-Frame-Options", "DENY");
1008
+ res.setHeader("X-XSS-Protection", "1; mode=block");
1009
+ }
1010
+ }
1011
+ }
1012
+ }),
1013
+ /**
1014
+ * Request logging plugin
1015
+ */
1016
+ logger: definePlugin({
1017
+ name: "velix:logger",
1018
+ hooks: {
1019
+ [PluginHooks.RESPONSE]: (req, _res, duration) => {
1020
+ console.log(` ${req.method} ${req.url} ${duration}ms`);
1021
+ }
1022
+ }
1023
+ })
1024
+ };
1025
+
1026
+ // plugins/tailwind.ts
1027
+ init_esm_shims();
1028
+ import { spawnSync, spawn } from "child_process";
1029
+
1030
+ // logger.ts
1031
+ init_esm_shims();
1032
+ var colors = {
1033
+ reset: "\x1B[0m",
1034
+ bold: "\x1B[1m",
1035
+ dim: "\x1B[2m",
1036
+ red: "\x1B[31m",
1037
+ green: "\x1B[32m",
1038
+ yellow: "\x1B[33m",
1039
+ blue: "\x1B[34m",
1040
+ magenta: "\x1B[35m",
1041
+ cyan: "\x1B[36m",
1042
+ white: "\x1B[37m",
1043
+ gray: "\x1B[90m"
1044
+ };
1045
+ var c = colors;
1046
+ function getStatusColor(status) {
1047
+ if (status >= 500) return c.red;
1048
+ if (status >= 400) return c.yellow;
1049
+ if (status >= 300) return c.cyan;
1050
+ if (status >= 200) return c.green;
1051
+ return c.white;
1052
+ }
1053
+ function fmtTime(ms) {
1054
+ if (ms < 1) return `${c.gray}<1ms${c.reset}`;
1055
+ if (ms < 100) return `${c.green}${ms}ms${c.reset}`;
1056
+ if (ms < 500) return `${c.yellow}${ms}ms${c.reset}`;
1057
+ return `${c.red}${ms}ms${c.reset}`;
1058
+ }
1059
+ var VERSION = "5.0.0";
1060
+ var LOGO = `
1061
+ ${c.cyan}\u25B2${c.reset} ${c.bold}Velix${c.reset} ${c.dim}v${VERSION}${c.reset}
1062
+ `;
1063
+ var logger = {
1064
+ logo() {
1065
+ console.log(LOGO);
1066
+ console.log(`${c.dim} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${c.reset}`);
1067
+ console.log("");
1068
+ },
1069
+ serverStart(config, startTime = Date.now()) {
1070
+ const { port, host, mode, pagesDir } = config;
1071
+ const elapsed = Date.now() - startTime;
1072
+ console.log(LOGO);
1073
+ console.log(` ${c.green}\u2714${c.reset} ${c.bold}Ready${c.reset} in ${elapsed}ms`);
1074
+ console.log("");
1075
+ console.log(` ${c.bold}Local:${c.reset} ${c.cyan}http://${host}:${port}${c.reset}`);
1076
+ console.log(` ${c.bold}Mode:${c.reset} ${mode === "development" ? c.yellow : c.green}${mode}${c.reset}`);
1077
+ if (pagesDir) console.log(` ${c.bold}App:${c.reset} ${c.dim}${pagesDir}${c.reset}`);
1078
+ console.log("");
1079
+ },
1080
+ request(method, path10, status, time, extra = {}) {
1081
+ const statusColor = getStatusColor(status);
1082
+ const timeStr = fmtTime(time);
1083
+ let badge = `${c.dim}\u25CB${c.reset}`;
1084
+ if (extra.type === "dynamic" || extra.type === "ssr") badge = `${c.white}\u0192${c.reset}`;
1085
+ else if (extra.type === "api") badge = `${c.cyan}\u03BB${c.reset}`;
1086
+ const statusStr = `${statusColor}${status}${c.reset}`;
1087
+ console.log(` ${badge} ${c.white}${method}${c.reset} ${path10} ${statusStr} ${c.dim}${timeStr}${c.reset}`);
1088
+ },
1089
+ info(msg) {
1090
+ console.log(` ${c.cyan}\u2139${c.reset} ${msg}`);
1091
+ },
1092
+ success(msg) {
1093
+ console.log(` ${c.green}\u2714${c.reset} ${msg}`);
1094
+ },
1095
+ warn(msg) {
1096
+ console.log(` ${c.yellow}\u26A0${c.reset} ${c.yellow}${msg}${c.reset}`);
1097
+ },
1098
+ error(msg, err = null) {
1099
+ console.log(` ${c.red}\u2716${c.reset} ${c.red}${msg}${c.reset}`);
1100
+ if (err?.stack) {
1101
+ console.log("");
1102
+ console.log(`${c.dim}${err.stack.split("\n").slice(1, 4).join("\n")}${c.reset}`);
1103
+ console.log("");
1104
+ }
1105
+ },
1106
+ compile(file, time) {
1107
+ console.log(` ${c.white}\u25CF${c.reset} Compiling ${c.dim}${file}${c.reset} ${c.dim}(${time}ms)${c.reset}`);
1108
+ },
1109
+ hmr(file) {
1110
+ console.log(` ${c.green}\u21BB${c.reset} Fast Refresh ${c.dim}${file}${c.reset}`);
1111
+ },
1112
+ plugin(name) {
1113
+ console.log(` ${c.cyan}\u25C6${c.reset} Plugin ${c.dim}${name}${c.reset}`);
1114
+ },
1115
+ route(path10, type) {
1116
+ const typeLabel = type === "api" ? "\u03BB" : type === "dynamic" ? "\u0192" : "\u25CB";
1117
+ const color = type === "api" ? c.cyan : type === "dynamic" ? c.white : c.dim;
1118
+ console.log(` ${color}${typeLabel}${c.reset} ${path10}`);
1119
+ },
1120
+ divider() {
1121
+ console.log(`${c.dim} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${c.reset}`);
1122
+ },
1123
+ blank() {
1124
+ console.log("");
1125
+ },
1126
+ portInUse(port) {
1127
+ this.error(`Port ${port} is already in use.`);
1128
+ this.blank();
1129
+ console.log(` ${c.dim}Try:${c.reset}`);
1130
+ console.log(` 1. Kill the process on port ${port}`);
1131
+ console.log(` 2. Use a different port via PORT env var`);
1132
+ this.blank();
1133
+ },
1134
+ build(stats) {
1135
+ this.blank();
1136
+ console.log(` ${c.green}\u2714${c.reset} Build completed`);
1137
+ this.blank();
1138
+ console.log(` ${c.dim}Total time:${c.reset} ${c.white}${stats.time}ms${c.reset}`);
1139
+ this.blank();
1140
+ }
1141
+ };
1142
+ var logger_default = logger;
1143
+
1144
+ // plugins/tailwind.ts
1145
+ function tailwindPlugin(options = {}) {
1146
+ const input = options.input || "./app/globals.css";
1147
+ const output = options.output || "./public/tailwind.css";
1148
+ const configPath = options.config || "./tailwind.config.ts";
1149
+ return definePlugin({
1150
+ name: "velix:tailwind",
1151
+ hooks: {
1152
+ [PluginHooks.CONFIG]: (config) => {
1153
+ const relativeOutput = output.startsWith("./") ? output.substring(1) : output;
1154
+ const stylePath = relativeOutput.startsWith("/public") ? relativeOutput.substring(7) : relativeOutput;
1155
+ if (!config.styles) config.styles = [];
1156
+ if (!config.styles.includes(stylePath)) {
1157
+ config.styles.push(stylePath);
1158
+ }
1159
+ },
1160
+ [PluginHooks.BUILD_START]: async () => {
1161
+ logger_default.info("Building Tailwind CSS...");
1162
+ try {
1163
+ const args = ["tailwindcss", "-i", input, "-o", output];
1164
+ if (options.minify !== false) args.push("--minify");
1165
+ spawnSync("npx", args, {
1166
+ stdio: "inherit",
1167
+ cwd: process.cwd()
1168
+ });
1169
+ logger_default.success("Tailwind CSS built successfully");
1170
+ } catch (err) {
1171
+ logger_default.error("Tailwind build failed", err);
1172
+ }
1173
+ },
1174
+ [PluginHooks.SERVER_START]: async (server, isDev) => {
1175
+ if (!isDev) return;
1176
+ logger_default.info("Starting Tailwind CSS watcher...");
1177
+ const watcher = spawn("npx", ["tailwindcss", "-i", input, "-o", output, "--watch"], {
1178
+ stdio: "pipe",
1179
+ cwd: process.cwd()
1180
+ });
1181
+ watcher.stdout.on("data", (data) => {
1182
+ const msg = data.toString().trim();
1183
+ if (msg && !msg.includes("Rebuilding...")) {
1184
+ }
1185
+ });
1186
+ watcher.on("error", (err) => {
1187
+ logger_default.error("Tailwind watcher error", err);
1188
+ });
1189
+ process.on("exit", () => watcher.kill());
1190
+ }
1191
+ }
1192
+ });
1193
+ }
1194
+
1195
+ // metadata/index.ts
1196
+ init_esm_shims();
1197
+ function generateMetadataTags(metadata, baseUrl) {
1198
+ const tags = [];
1199
+ const base = baseUrl || metadata.metadataBase?.toString() || "";
1200
+ if (metadata.title) {
1201
+ const title = typeof metadata.title === "string" ? metadata.title : metadata.title.absolute || (metadata.title.template ? metadata.title.template.replace("%s", metadata.title.default) : metadata.title.default);
1202
+ tags.push(`<title>${escapeHtml2(title)}</title>`);
1203
+ }
1204
+ if (metadata.description) tags.push(`<meta name="description" content="${escapeHtml2(metadata.description)}">`);
1205
+ if (metadata.keywords) {
1206
+ const kw = Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords;
1207
+ tags.push(`<meta name="keywords" content="${escapeHtml2(kw)}">`);
1208
+ }
1209
+ if (metadata.authors) {
1210
+ const authors = Array.isArray(metadata.authors) ? metadata.authors : [metadata.authors];
1211
+ authors.forEach((a) => {
1212
+ if (a.name) tags.push(`<meta name="author" content="${escapeHtml2(a.name)}">`);
1213
+ if (a.url) tags.push(`<link rel="author" href="${a.url}">`);
1214
+ });
1215
+ }
1216
+ if (metadata.generator) tags.push(`<meta name="generator" content="${escapeHtml2(metadata.generator)}">`);
1217
+ if (metadata.applicationName) tags.push(`<meta name="application-name" content="${escapeHtml2(metadata.applicationName)}">`);
1218
+ if (metadata.referrer) tags.push(`<meta name="referrer" content="${metadata.referrer}">`);
1219
+ if (metadata.robots) {
1220
+ if (typeof metadata.robots === "string") {
1221
+ tags.push(`<meta name="robots" content="${metadata.robots}">`);
1222
+ } else {
1223
+ tags.push(`<meta name="robots" content="${generateRobotsContent(metadata.robots)}">`);
1224
+ if (metadata.robots.googleBot) {
1225
+ const gbc = typeof metadata.robots.googleBot === "string" ? metadata.robots.googleBot : generateRobotsContent(metadata.robots.googleBot);
1226
+ tags.push(`<meta name="googlebot" content="${gbc}">`);
1227
+ }
1228
+ }
1229
+ }
1230
+ if (metadata.viewport) {
1231
+ const vc = typeof metadata.viewport === "string" ? metadata.viewport : generateViewportContent(metadata.viewport);
1232
+ tags.push(`<meta name="viewport" content="${vc}">`);
1233
+ }
1234
+ if (metadata.themeColor) {
1235
+ const tcs = Array.isArray(metadata.themeColor) ? metadata.themeColor : [metadata.themeColor];
1236
+ tcs.forEach((tc) => {
1237
+ const media = typeof tc !== "string" && tc.media ? ` media="${tc.media}"` : "";
1238
+ const color = typeof tc === "string" ? tc : tc.color;
1239
+ tags.push(`<meta name="theme-color" content="${color}"${media}>`);
1240
+ });
1241
+ }
1242
+ if (metadata.colorScheme) tags.push(`<meta name="color-scheme" content="${metadata.colorScheme}">`);
1243
+ if (metadata.icons) {
1244
+ const addIcon = (icon, defaultRel) => {
1245
+ const rel = icon.rel || defaultRel;
1246
+ const attrs = [
1247
+ icon.type ? ` type="${icon.type}"` : "",
1248
+ icon.sizes ? ` sizes="${icon.sizes}"` : "",
1249
+ icon.color ? ` color="${icon.color}"` : ""
1250
+ ].join("");
1251
+ tags.push(`<link rel="${rel}" href="${resolveUrl(icon.url, base)}"${attrs}>`);
1252
+ };
1253
+ if (metadata.icons.icon) {
1254
+ (Array.isArray(metadata.icons.icon) ? metadata.icons.icon : [metadata.icons.icon]).forEach((i) => addIcon(i, "icon"));
1255
+ }
1256
+ if (metadata.icons.apple) {
1257
+ (Array.isArray(metadata.icons.apple) ? metadata.icons.apple : [metadata.icons.apple]).forEach((i) => addIcon(i, "apple-touch-icon"));
1258
+ }
1259
+ }
1260
+ if (metadata.manifest) tags.push(`<link rel="manifest" href="${resolveUrl(metadata.manifest, base)}">`);
1261
+ if (metadata.openGraph) {
1262
+ const og = metadata.openGraph;
1263
+ if (og.type) tags.push(`<meta property="og:type" content="${og.type}">`);
1264
+ if (og.title) tags.push(`<meta property="og:title" content="${escapeHtml2(og.title)}">`);
1265
+ if (og.description) tags.push(`<meta property="og:description" content="${escapeHtml2(og.description)}">`);
1266
+ if (og.url) tags.push(`<meta property="og:url" content="${resolveUrl(og.url, base)}">`);
1267
+ if (og.siteName) tags.push(`<meta property="og:site_name" content="${escapeHtml2(og.siteName)}">`);
1268
+ if (og.locale) tags.push(`<meta property="og:locale" content="${og.locale}">`);
1269
+ if (og.images) {
1270
+ (Array.isArray(og.images) ? og.images : [og.images]).forEach((img) => {
1271
+ tags.push(`<meta property="og:image" content="${resolveUrl(img.url, base)}">`);
1272
+ if (img.width) tags.push(`<meta property="og:image:width" content="${img.width}">`);
1273
+ if (img.height) tags.push(`<meta property="og:image:height" content="${img.height}">`);
1274
+ if (img.alt) tags.push(`<meta property="og:image:alt" content="${escapeHtml2(img.alt)}">`);
1275
+ });
1276
+ }
1277
+ if (og.type === "article") {
1278
+ if (og.publishedTime) tags.push(`<meta property="article:published_time" content="${og.publishedTime}">`);
1279
+ if (og.modifiedTime) tags.push(`<meta property="article:modified_time" content="${og.modifiedTime}">`);
1280
+ if (og.tags) og.tags.forEach((t) => tags.push(`<meta property="article:tag" content="${escapeHtml2(t)}">`));
1281
+ }
1282
+ }
1283
+ if (metadata.twitter) {
1284
+ const tw = metadata.twitter;
1285
+ if (tw.card) tags.push(`<meta name="twitter:card" content="${tw.card}">`);
1286
+ if (tw.site) tags.push(`<meta name="twitter:site" content="${tw.site}">`);
1287
+ if (tw.creator) tags.push(`<meta name="twitter:creator" content="${tw.creator}">`);
1288
+ if (tw.title) tags.push(`<meta name="twitter:title" content="${escapeHtml2(tw.title)}">`);
1289
+ if (tw.description) tags.push(`<meta name="twitter:description" content="${escapeHtml2(tw.description)}">`);
1290
+ if (tw.images) {
1291
+ (Array.isArray(tw.images) ? tw.images : [tw.images]).forEach((img) => {
1292
+ const url = typeof img === "string" ? img : img.url;
1293
+ tags.push(`<meta name="twitter:image" content="${resolveUrl(url, base)}">`);
1294
+ });
1295
+ }
1296
+ }
1297
+ if (metadata.verification) {
1298
+ if (metadata.verification.google) {
1299
+ (Array.isArray(metadata.verification.google) ? metadata.verification.google : [metadata.verification.google]).forEach((v) => tags.push(`<meta name="google-site-verification" content="${v}">`));
1300
+ }
1301
+ }
1302
+ if (metadata.alternates) {
1303
+ if (metadata.alternates.canonical) tags.push(`<link rel="canonical" href="${resolveUrl(metadata.alternates.canonical, base)}">`);
1304
+ if (metadata.alternates.languages) {
1305
+ Object.entries(metadata.alternates.languages).forEach(([lang, url]) => {
1306
+ tags.push(`<link rel="alternate" hreflang="${lang}" href="${resolveUrl(url, base)}">`);
1307
+ });
1308
+ }
1309
+ }
1310
+ return tags.join("\n ");
1311
+ }
1312
+ function mergeMetadata(parent, child) {
1313
+ return {
1314
+ ...parent,
1315
+ ...child,
1316
+ openGraph: child.openGraph ? { ...parent.openGraph, ...child.openGraph } : parent.openGraph,
1317
+ twitter: child.twitter ? { ...parent.twitter, ...child.twitter } : parent.twitter,
1318
+ icons: child.icons ? { ...parent.icons, ...child.icons } : parent.icons,
1319
+ alternates: child.alternates ? { ...parent.alternates, ...child.alternates } : parent.alternates
1320
+ };
1321
+ }
1322
+ function generateJsonLd(data) {
1323
+ return `<script type="application/ld+json">${JSON.stringify(data)}</script>`;
1324
+ }
1325
+ var jsonLd = {
1326
+ website: (c2) => ({
1327
+ "@context": "https://schema.org",
1328
+ "@type": "WebSite",
1329
+ name: c2.name,
1330
+ url: c2.url,
1331
+ description: c2.description
1332
+ }),
1333
+ article: (c2) => ({
1334
+ "@context": "https://schema.org",
1335
+ "@type": "Article",
1336
+ headline: c2.headline,
1337
+ description: c2.description,
1338
+ image: c2.image,
1339
+ datePublished: c2.datePublished,
1340
+ dateModified: c2.dateModified || c2.datePublished,
1341
+ author: Array.isArray(c2.author) ? c2.author.map((a) => ({ "@type": "Person", ...a })) : { "@type": "Person", ...c2.author }
1342
+ }),
1343
+ organization: (c2) => ({
1344
+ "@context": "https://schema.org",
1345
+ "@type": "Organization",
1346
+ name: c2.name,
1347
+ url: c2.url,
1348
+ logo: c2.logo,
1349
+ sameAs: c2.sameAs
1350
+ }),
1351
+ breadcrumb: (items) => ({
1352
+ "@context": "https://schema.org",
1353
+ "@type": "BreadcrumbList",
1354
+ itemListElement: items.map((item, i) => ({ "@type": "ListItem", position: i + 1, name: item.name, item: item.url }))
1355
+ })
1356
+ };
1357
+ function generateSitemap(routes, baseUrl) {
1358
+ const urls = routes.filter((r) => r.type === "page" && !r.path.includes(":") && !r.path.includes("*")).map((r) => {
1359
+ const loc = `${baseUrl.replace(/\/$/, "")}${r.path}`;
1360
+ return ` <url>
1361
+ <loc>${loc}</loc>
1362
+ <lastmod>${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}</lastmod>
1363
+ <changefreq>weekly</changefreq>
1364
+ <priority>${r.path === "/" ? "1.0" : "0.8"}</priority>
1365
+ </url>`;
1366
+ });
1367
+ return `<?xml version="1.0" encoding="UTF-8"?>
1368
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
1369
+ ${urls.join("\n")}
1370
+ </urlset>`;
1371
+ }
1372
+ function generateRobotsTxt(baseUrl, options = {}) {
1373
+ const lines = ["User-agent: *"];
1374
+ if (options.allow) options.allow.forEach((p) => lines.push(`Allow: ${p}`));
1375
+ if (options.disallow) options.disallow.forEach((p) => lines.push(`Disallow: ${p}`));
1376
+ else lines.push("Allow: /");
1377
+ lines.push("", `Sitemap: ${baseUrl.replace(/\/$/, "")}/sitemap.xml`);
1378
+ return lines.join("\n");
1379
+ }
1380
+ function escapeHtml2(str) {
1381
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
1382
+ }
1383
+ function resolveUrl(url, base) {
1384
+ if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//")) return url;
1385
+ return base ? `${base.replace(/\/$/, "")}${url.startsWith("/") ? "" : "/"}${url}` : url;
1386
+ }
1387
+ function generateRobotsContent(robots) {
1388
+ const parts = [];
1389
+ if (robots.index !== void 0) parts.push(robots.index ? "index" : "noindex");
1390
+ if (robots.follow !== void 0) parts.push(robots.follow ? "follow" : "nofollow");
1391
+ if (robots.noarchive) parts.push("noarchive");
1392
+ if (robots.nosnippet) parts.push("nosnippet");
1393
+ if (robots.noimageindex) parts.push("noimageindex");
1394
+ return parts.join(", ") || "index, follow";
1395
+ }
1396
+ function generateViewportContent(viewport) {
1397
+ const parts = [];
1398
+ if (viewport.width) parts.push(`width=${viewport.width}`);
1399
+ if (viewport.height) parts.push(`height=${viewport.height}`);
1400
+ if (viewport.initialScale !== void 0) parts.push(`initial-scale=${viewport.initialScale}`);
1401
+ if (viewport.maximumScale !== void 0) parts.push(`maximum-scale=${viewport.maximumScale}`);
1402
+ if (viewport.userScalable !== void 0) parts.push(`user-scalable=${viewport.userScalable ? "yes" : "no"}`);
1403
+ return parts.join(", ") || "width=device-width, initial-scale=1";
1404
+ }
1405
+
1406
+ // islands/index.ts
1407
+ init_esm_shims();
1408
+ import React from "react";
1409
+ import crypto2 from "crypto";
1410
+ var islandRegistry = /* @__PURE__ */ new Map();
1411
+ function generateIslandId(componentName) {
1412
+ const hash = crypto2.randomBytes(4).toString("hex");
1413
+ return `island-${componentName}-${hash}`;
1414
+ }
1415
+ function Island({ component: Component, props = {}, name, clientPath }) {
1416
+ const islandId = generateIslandId(name);
1417
+ islandRegistry.set(islandId, { id: islandId, name, clientPath, props });
1418
+ return React.createElement("div", {
1419
+ "data-island": islandId,
1420
+ "data-island-name": name,
1421
+ "data-island-props": JSON.stringify(props)
1422
+ }, React.createElement(Component, props));
1423
+ }
1424
+ function getRegisteredIslands() {
1425
+ const islands = Array.from(islandRegistry.values());
1426
+ islandRegistry.clear();
1427
+ return islands;
1428
+ }
1429
+ function createIsland(Component, options = {}) {
1430
+ const { name = Component.name || "Island", clientPath } = options;
1431
+ function IslandWrapper(props) {
1432
+ return Island({
1433
+ component: Component,
1434
+ props,
1435
+ name,
1436
+ clientPath: clientPath || `/__velix/islands/${name}.js`
1437
+ });
1438
+ }
1439
+ IslandWrapper.displayName = `Island(${name})`;
1440
+ IslandWrapper.isIsland = true;
1441
+ IslandWrapper.originalComponent = Component;
1442
+ return IslandWrapper;
1443
+ }
1444
+ var LoadStrategy = {
1445
+ IMMEDIATE: "immediate",
1446
+ VISIBLE: "visible",
1447
+ IDLE: "idle",
1448
+ MEDIA: "media"
1449
+ };
1450
+ function createLazyIsland(Component, options = {}) {
1451
+ const {
1452
+ name = Component.name || "LazyIsland",
1453
+ clientPath,
1454
+ strategy = LoadStrategy.VISIBLE,
1455
+ media = null
1456
+ } = options;
1457
+ function LazyIslandWrapper(props) {
1458
+ const islandId = generateIslandId(name);
1459
+ islandRegistry.set(islandId, {
1460
+ id: islandId,
1461
+ name,
1462
+ clientPath: clientPath || `/__velix/islands/${name}.js`,
1463
+ props,
1464
+ strategy,
1465
+ media
1466
+ });
1467
+ return React.createElement("div", {
1468
+ "data-island": islandId,
1469
+ "data-island-name": name,
1470
+ "data-island-strategy": strategy,
1471
+ "data-island-media": media,
1472
+ "data-island-props": JSON.stringify(props)
1473
+ });
1474
+ }
1475
+ LazyIslandWrapper.displayName = `LazyIsland(${name})`;
1476
+ LazyIslandWrapper.isIsland = true;
1477
+ LazyIslandWrapper.isLazy = true;
1478
+ return LazyIslandWrapper;
1479
+ }
1480
+ function generateHydrationScript(islands) {
1481
+ if (!islands.length) return "";
1482
+ const islandData = islands.map((island) => ({
1483
+ id: island.id,
1484
+ name: island.name,
1485
+ path: island.clientPath,
1486
+ props: island.props
1487
+ }));
1488
+ return `
1489
+ <script type="module">
1490
+ const islands = ${JSON.stringify(islandData)};
1491
+
1492
+ async function hydrateIslands() {
1493
+ const { hydrateRoot } = await import('/__velix/react-dom-client.js');
1494
+ const React = await import('/__velix/react.js');
1495
+
1496
+ for (const island of islands) {
1497
+ try {
1498
+ const el = document.querySelector(\`[data-island="\${island.id}"]\`);
1499
+ if (!el) continue;
1500
+ const mod = await import(island.path);
1501
+ hydrateRoot(el, React.createElement(mod.default, island.props));
1502
+ el.setAttribute('data-hydrated', 'true');
1503
+ } catch (error) {
1504
+ console.error(\`Failed to hydrate island \${island.name}:\`, error);
1505
+ }
1506
+ }
1507
+ }
1508
+
1509
+ if (document.readyState === 'loading') {
1510
+ document.addEventListener('DOMContentLoaded', hydrateIslands);
1511
+ } else {
1512
+ hydrateIslands();
1513
+ }
1514
+ </script>`;
1515
+ }
1516
+ function generateAdvancedHydrationScript(islands) {
1517
+ if (!islands.length) return "";
1518
+ const islandData = islands.map((island) => ({
1519
+ id: island.id,
1520
+ name: island.name,
1521
+ path: island.clientPath,
1522
+ props: island.props,
1523
+ strategy: island.strategy || LoadStrategy.IMMEDIATE,
1524
+ media: island.media
1525
+ }));
1526
+ return `
1527
+ <script type="module">
1528
+ const islands = ${JSON.stringify(islandData)};
1529
+
1530
+ async function hydrateIsland(island) {
1531
+ const el = document.querySelector(\`[data-island="\${island.id}"]\`);
1532
+ if (!el || el.hasAttribute('data-hydrated')) return;
1533
+
1534
+ try {
1535
+ const { hydrateRoot } = await import('/__velix/react-dom-client.js');
1536
+ const React = await import('/__velix/react.js');
1537
+ const mod = await import(island.path);
1538
+ hydrateRoot(el, React.createElement(mod.default, island.props));
1539
+ el.setAttribute('data-hydrated', 'true');
1540
+ } catch (error) {
1541
+ console.error(\`Failed to hydrate island \${island.name}:\`, error);
1542
+ }
1543
+ }
1544
+
1545
+ const visibleObserver = new IntersectionObserver((entries) => {
1546
+ entries.forEach(entry => {
1547
+ if (entry.isIntersecting) {
1548
+ const id = entry.target.getAttribute('data-island');
1549
+ const island = islands.find(i => i.id === id);
1550
+ if (island) { hydrateIsland(island); visibleObserver.unobserve(entry.target); }
1551
+ }
1552
+ });
1553
+ }, { rootMargin: '50px' });
1554
+
1555
+ function processIslands() {
1556
+ for (const island of islands) {
1557
+ const el = document.querySelector(\`[data-island="\${island.id}"]\`);
1558
+ if (!el) continue;
1559
+ switch (island.strategy) {
1560
+ case 'immediate': hydrateIsland(island); break;
1561
+ case 'visible': visibleObserver.observe(el); break;
1562
+ case 'idle': requestIdleCallback(() => hydrateIsland(island)); break;
1563
+ case 'media':
1564
+ if (island.media && window.matchMedia(island.media).matches) hydrateIsland(island);
1565
+ break;
1566
+ }
1567
+ }
1568
+ }
1569
+
1570
+ if (document.readyState === 'loading') {
1571
+ document.addEventListener('DOMContentLoaded', processIslands);
1572
+ } else {
1573
+ processIslands();
1574
+ }
1575
+ </script>`;
1576
+ }
1577
+
1578
+ // actions/index.ts
1579
+ init_esm_shims();
1580
+ import { useActionState, useOptimistic } from "react";
1581
+ import { useFormStatus } from "react-dom";
1582
+ import { useActionState as useActionStateReact } from "react";
1583
+ globalThis.__VELIX_ACTIONS__ = globalThis.__VELIX_ACTIONS__ || {};
1584
+ globalThis.__VELIX_ACTION_CONTEXT__ = null;
1585
+ function serverAction(fn, actionId) {
1586
+ const id = actionId || `action_${fn.name}_${generateActionId()}`;
1587
+ globalThis.__VELIX_ACTIONS__[id] = fn;
1588
+ const proxy = (async (...args) => {
1589
+ if (typeof window === "undefined") return await executeAction(id, args);
1590
+ return await callServerAction(id, args);
1591
+ });
1592
+ proxy.$$typeof = /* @__PURE__ */ Symbol.for("react.server.action");
1593
+ proxy.$$id = id;
1594
+ proxy.$$bound = null;
1595
+ return proxy;
1596
+ }
1597
+ function registerAction(id, fn) {
1598
+ globalThis.__VELIX_ACTIONS__[id] = fn;
1599
+ }
1600
+ function getAction(id) {
1601
+ return globalThis.__VELIX_ACTIONS__[id];
1602
+ }
1603
+ async function executeAction(actionId, args, context) {
1604
+ const action = globalThis.__VELIX_ACTIONS__[actionId];
1605
+ if (!action) return { success: false, error: `Server action not found: ${actionId}` };
1606
+ const actionContext = {
1607
+ request: context?.request || new Request("http://localhost"),
1608
+ cookies,
1609
+ headers,
1610
+ redirect,
1611
+ notFound
1612
+ };
1613
+ globalThis.__VELIX_ACTION_CONTEXT__ = actionContext;
1614
+ try {
1615
+ const result = await action(...args);
1616
+ return { success: true, data: result };
1617
+ } catch (error) {
1618
+ if (error instanceof RedirectError) return { success: true, redirect: error.url };
1619
+ if (error instanceof NotFoundError) return { success: false, error: "Not found" };
1620
+ return { success: false, error: error.message || "Action failed" };
1621
+ } finally {
1622
+ globalThis.__VELIX_ACTION_CONTEXT__ = null;
1623
+ }
1624
+ }
1625
+ async function callServerAction(actionId, args) {
1626
+ try {
1627
+ const response = await fetch("/__velix/action", {
1628
+ method: "POST",
1629
+ headers: { "Content-Type": "application/json", "X-Velix-Action": actionId },
1630
+ body: JSON.stringify({ actionId, args: serializeArgs(args) }),
1631
+ credentials: "same-origin"
1632
+ });
1633
+ if (!response.ok) throw new Error(`Action failed: ${response.statusText}`);
1634
+ const result = await response.json();
1635
+ if (result.redirect) {
1636
+ window.location.href = result.redirect;
1637
+ }
1638
+ return result;
1639
+ } catch (error) {
1640
+ return { success: false, error: error.message || "Network error" };
1641
+ }
1642
+ }
1643
+ function serializeArgs(args) {
1644
+ return args.map((arg) => {
1645
+ if (arg instanceof FormData) {
1646
+ const obj = {};
1647
+ arg.forEach((value, key) => {
1648
+ if (obj[key]) {
1649
+ obj[key] = Array.isArray(obj[key]) ? [...obj[key], value] : [obj[key], value];
1650
+ } else {
1651
+ obj[key] = value;
1652
+ }
1653
+ });
1654
+ return { $$type: "FormData", data: obj };
1655
+ }
1656
+ if (arg instanceof Date) return { $$type: "Date", value: arg.toISOString() };
1657
+ if (typeof arg === "object" && arg !== null) return JSON.parse(JSON.stringify(arg));
1658
+ return arg;
1659
+ });
1660
+ }
1661
+ var ALLOWED_TYPES = /* @__PURE__ */ new Set(["FormData", "Date", "File"]);
1662
+ var MAX_DEPTH = 10;
1663
+ function validateInput(obj, depth = 0) {
1664
+ if (depth > MAX_DEPTH) throw new Error("Payload too deeply nested");
1665
+ if (obj === null || obj === void 0 || typeof obj !== "object") return true;
1666
+ if ("__proto__" in obj || "constructor" in obj || "prototype" in obj) {
1667
+ throw new Error("Invalid payload: prototype pollution attempt detected");
1668
+ }
1669
+ if ("$$type" in obj && !ALLOWED_TYPES.has(obj.$$type)) {
1670
+ throw new Error(`Invalid serialized type: ${obj.$$type}`);
1671
+ }
1672
+ if (Array.isArray(obj)) obj.forEach((item) => validateInput(item, depth + 1));
1673
+ else Object.values(obj).forEach((val) => validateInput(val, depth + 1));
1674
+ return true;
1675
+ }
1676
+ function deserializeArgs(args) {
1677
+ validateInput(args);
1678
+ return args.map((arg) => {
1679
+ if (arg && typeof arg === "object") {
1680
+ if (arg.$$type === "FormData") {
1681
+ const fd = new FormData();
1682
+ for (const [key, value] of Object.entries(arg.data || {})) {
1683
+ if (typeof key !== "string" || key.startsWith("__")) continue;
1684
+ if (Array.isArray(value)) value.forEach((v) => {
1685
+ if (typeof v === "string" || typeof v === "number") fd.append(key, String(v));
1686
+ });
1687
+ else if (typeof value === "string" || typeof value === "number") fd.append(key, String(value));
1688
+ }
1689
+ return fd;
1690
+ }
1691
+ if (arg.$$type === "Date") {
1692
+ const d = new Date(arg.value);
1693
+ if (isNaN(d.getTime())) throw new Error("Invalid date");
1694
+ return d;
1695
+ }
1696
+ if (arg.$$type === "File") return { name: String(arg.name || ""), type: String(arg.type || ""), size: Number(arg.size || 0) };
1697
+ }
1698
+ return arg;
1699
+ });
1700
+ }
1701
+ function generateActionId() {
1702
+ return Math.random().toString(36).substring(2, 10);
1703
+ }
1704
+ function useActionContext() {
1705
+ return globalThis.__VELIX_ACTION_CONTEXT__;
1706
+ }
1707
+ function formAction(action) {
1708
+ return async (formData) => {
1709
+ try {
1710
+ const result = await action(formData);
1711
+ return { success: true, data: result };
1712
+ } catch (error) {
1713
+ if (error instanceof RedirectError) return { success: true, redirect: error.url };
1714
+ return { success: false, error: error.message };
1715
+ }
1716
+ };
1717
+ }
1718
+ function useVelixAction(action, initialState, permalink) {
1719
+ return useActionStateReact(action, initialState, permalink);
1720
+ }
1721
+ function bindArgs(action, ...boundArgs) {
1722
+ const bound = (async (...args) => await action(...boundArgs, ...args));
1723
+ bound.$$typeof = action.$$typeof;
1724
+ bound.$$id = action.$$id;
1725
+ bound.$$bound = boundArgs;
1726
+ return bound;
1727
+ }
1728
+
1729
+ // server/index.ts
1730
+ import esbuild from "esbuild";
1731
+
1732
+ // server/devtools.ts
1733
+ init_esm_shims();
1734
+ function generateDevToolsHtml(isDev) {
1735
+ if (!isDev) return "";
1736
+ return `<style>
1737
+ @keyframes velix-pulse {
1738
+ 0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(34, 211, 238, 0.7); }
1739
+ 70% { transform: scale(1.05); box-shadow: 0 0 0 10px rgba(34, 211, 238, 0); }
1740
+ 100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(34, 211, 238, 0); }
1741
+ }
1742
+
1743
+ @keyframes velix-spin {
1744
+ from { transform: rotate(0deg); }
1745
+ to { transform: rotate(360deg); }
1746
+ }
1747
+
1748
+ .velix-idle { background: #0f172a !important; border: 2px solid #22D3EE !important; }
1749
+ .velix-rendering { background: #ea580c !important; border: 2px solid #fb923c !important; animation: velix-pulse 1.5s infinite !important; }
1750
+ .velix-compiling { background: #16a34a !important; border: 2px solid #4ade80 !important; animation: velix-spin 2s linear infinite !important; }
1751
+ .velix-navigating { background: #2563eb !important; border: 2px solid #60a5fa !important; animation: velix-pulse 1s infinite !important; }
1752
+ .velix-error { background: #dc2626 !important; border: 2px solid #f87171 !important; animation: velix-pulse 0.8s infinite !important; }
1753
+
1754
+ .velix-status-badge {
1755
+ position: absolute;
1756
+ top: -4px;
1757
+ right: -4px;
1758
+ width: 12px;
1759
+ height: 12px;
1760
+ border-radius: 50%;
1761
+ border: 2px solid #0f172a;
1762
+ }
1763
+
1764
+ .velix-status-idle { background: #22D3EE; }
1765
+ .velix-status-rendering { background: #fb923c; }
1766
+ .velix-status-compiling { background: #4ade80; }
1767
+ .velix-status-navigating { background: #60a5fa; }
1768
+ .velix-status-error { background: #f87171; }
1769
+ </style>
1770
+
1771
+ <script>
1772
+ // DevTools State Management
1773
+ window.__VELIX_DEV_TOOLS__ = {
1774
+ status: 'idle',
1775
+ setStatus: function(newStatus) {
1776
+ this.status = newStatus;
1777
+ const widget = document.getElementById('__velix-dev-tools');
1778
+ const badge = document.getElementById('__velix-status-badge');
1779
+ const statusText = document.getElementById('__velix-status-text');
1780
+
1781
+ if (widget) {
1782
+ widget.className = 'velix-' + newStatus;
1783
+ }
1784
+
1785
+ if (badge) {
1786
+ badge.className = 'velix-status-badge velix-status-' + newStatus;
1787
+ }
1788
+
1789
+ if (statusText) {
1790
+ const statusLabels = {
1791
+ idle: 'Ready',
1792
+ rendering: 'Rendering',
1793
+ compiling: 'Compiling',
1794
+ navigating: 'Navigating',
1795
+ error: 'Error'
1796
+ };
1797
+ statusText.textContent = statusLabels[newStatus] || 'Unknown';
1798
+ statusText.style.color = {
1799
+ idle: '#22D3EE',
1800
+ rendering: '#fb923c',
1801
+ compiling: '#4ade80',
1802
+ navigating: '#60a5fa',
1803
+ error: '#f87171'
1804
+ }[newStatus] || '#94a3b8';
1805
+ }
1806
+ }
1807
+ };
1808
+
1809
+ // HMR Connection
1810
+ const es = new EventSource('/__velix/hmr');
1811
+ es.onmessage = (e) => {
1812
+ const data = e.data;
1813
+
1814
+ if (data === 'reload') {
1815
+ window.__VELIX_DEV_TOOLS__.setStatus('idle');
1816
+ setTimeout(() => location.reload(), 100);
1817
+ }
1818
+
1819
+ if (data === 'building') {
1820
+ window.__VELIX_DEV_TOOLS__.setStatus('compiling');
1821
+ }
1822
+
1823
+ if (data === 'built') {
1824
+ window.__VELIX_DEV_TOOLS__.setStatus('idle');
1825
+ }
1826
+
1827
+ if (data.startsWith('rendering:')) {
1828
+ window.__VELIX_DEV_TOOLS__.setStatus('rendering');
1829
+ setTimeout(() => window.__VELIX_DEV_TOOLS__.setStatus('idle'), 1000);
1830
+ }
1831
+
1832
+ if (data.startsWith('error:')) {
1833
+ window.__VELIX_DEV_TOOLS__.setStatus('error');
1834
+ }
1835
+ };
1836
+
1837
+ es.onerror = () => {
1838
+ window.__VELIX_DEV_TOOLS__.setStatus('error');
1839
+ };
1840
+ </script>
1841
+
1842
+ <div id="__velix-dev-tools" class="velix-idle" style="position:fixed;bottom:16px;left:16px;z-index:9999;border-radius:50%;padding:4px;box-shadow:0 4px 12px rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;width:40px;height:40px;cursor:pointer;transition:all 0.3s ease;" onmouseover="this.style.transform='scale(1.1)'" onmouseout="this.style.transform='scale(1)'" onclick="document.getElementById('__velix-dev-panel').style.display='block'" title="Velix DevTools">
1843
+ <img src="/__velix/logo.webp" alt="Velix DevTools" style="width:22px;height:22px;" />
1844
+ <div id="__velix-status-badge" class="velix-status-badge velix-status-idle"></div>
1845
+ </div>
1846
+
1847
+ <div id="__velix-dev-panel" style="display:none;position:fixed;bottom:70px;left:16px;width:320px;background:#0f172a;color:white;border-radius:16px;padding:20px;font-family:ui-sans-serif,system-ui,-apple-system,sans-serif;box-shadow:0 20px 50px rgba(0,0,0,0.4);z-index:10000;border:1px solid #1e293b;">
1848
+ <div style="display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #334155;padding-bottom:16px;margin-bottom:16px;">
1849
+ <h3 style="margin:0;font-size:16px;font-weight:700;display:flex;align-items:center;gap:10px;">
1850
+ <img src="/__velix/logo.webp" style="width:18px;height:18px;" />
1851
+ Velix DevTools
1852
+ </h3>
1853
+ <button onclick="document.getElementById('__velix-dev-panel').style.display='none'" style="background:transparent;border:none;color:#94a3b8;cursor:pointer;font-size:22px;line-height:1;padding:0;margin:0;transition:color 0.2s;" onmouseover="this.style.color='white'" onmouseout="this.style.color='#94a3b8'">&times;</button>
1854
+ </div>
1855
+
1856
+ <div style="margin-bottom:16px;padding:12px;background:#1e293b;border-radius:8px;border:1px solid #334155;">
1857
+ <div style="font-size:12px;color:#94a3b8;margin-bottom:4px;text-transform:uppercase;letter-spacing:0.5px;">Status</div>
1858
+ <div id="__velix-status-text" style="font-size:16px;font-weight:600;color:#22D3EE;">Ready</div>
1859
+ </div>
1860
+
1861
+ <div style="font-size:13px;color:#cbd5e1;line-height:2;">
1862
+ <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid #1e293b;">
1863
+ <span style="color:#94a3b8;">Framework</span>
1864
+ <strong style="color:white;font-weight:600;">v5.0.0</strong>
1865
+ </div>
1866
+ <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid #1e293b;">
1867
+ <span style="color:#94a3b8;">Environment</span>
1868
+ <strong style="color:#10b981;font-weight:600;">Development</strong>
1869
+ </div>
1870
+ <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid #1e293b;">
1871
+ <span style="color:#94a3b8;">Router</span>
1872
+ <strong style="color:white;font-weight:600;">App Directory</strong>
1873
+ </div>
1874
+ <div style="display:flex;justify-content:space-between;padding:8px 0;">
1875
+ <span style="color:#94a3b8;">Rendering</span>
1876
+ <strong style="color:#60a5fa;font-weight:600;">Streaming SSR</strong>
1877
+ </div>
1878
+ </div>
1879
+
1880
+ <div style="margin-top:16px;padding-top:16px;border-top:1px solid #334155;">
1881
+ <div style="font-size:11px;color:#64748b;text-align:center;">
1882
+ <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#22D3EE;margin-right:4px;"></span> Idle
1883
+ <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#fb923c;margin:0 4px 0 12px;"></span> Rendering
1884
+ <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#4ade80;margin:0 4px 0 12px;"></span> Compiling
1885
+ </div>
1886
+ </div>
1887
+ </div>`;
1888
+ }
1889
+
1890
+ // server/error-pages.ts
1891
+ init_esm_shims();
1892
+ function generate404Page(pathname = "/") {
1893
+ return `<!DOCTYPE html>
1894
+ <html lang="en">
1895
+ <head>
1896
+ <meta charset="UTF-8">
1897
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1898
+ <title>404 - Page Not Found | Velix v5</title>
1899
+ <style>
1900
+ * { margin: 0; padding: 0; box-sizing: border-box; }
1901
+ body {
1902
+ margin: 0;
1903
+ background: linear-gradient(135deg, #0F172A 0%, #1E293B 100%);
1904
+ color: white;
1905
+ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1906
+ display: flex;
1907
+ align-items: center;
1908
+ justify-content: center;
1909
+ min-height: 100vh;
1910
+ text-align: center;
1911
+ overflow: hidden;
1912
+ }
1913
+ .container {
1914
+ max-width: 700px;
1915
+ padding: 60px 40px;
1916
+ position: relative;
1917
+ z-index: 10;
1918
+ }
1919
+ .bg-pattern {
1920
+ position: absolute;
1921
+ inset: 0;
1922
+ background-image: radial-gradient(circle at 20% 50%, rgba(34, 211, 238, 0.1) 0%, transparent 50%),
1923
+ radial-gradient(circle at 80% 80%, rgba(37, 99, 235, 0.1) 0%, transparent 50%);
1924
+ z-index: 1;
1925
+ }
1926
+ h1 {
1927
+ font-size: 180px;
1928
+ font-weight: 900;
1929
+ margin: 0;
1930
+ background: linear-gradient(135deg, #22D3EE 0%, #2563EB 100%);
1931
+ -webkit-background-clip: text;
1932
+ -webkit-text-fill-color: transparent;
1933
+ line-height: 1;
1934
+ letter-spacing: -0.05em;
1935
+ animation: fadeInUp 0.6s ease-out;
1936
+ }
1937
+ h2 {
1938
+ font-size: 36px;
1939
+ font-weight: 800;
1940
+ margin: 30px 0 15px;
1941
+ color: #F8FAFC;
1942
+ animation: fadeInUp 0.6s ease-out 0.1s backwards;
1943
+ }
1944
+ p {
1945
+ color: #94A3B8;
1946
+ font-size: 18px;
1947
+ line-height: 1.7;
1948
+ margin-bottom: 40px;
1949
+ animation: fadeInUp 0.6s ease-out 0.2s backwards;
1950
+ }
1951
+ code {
1952
+ background: rgba(255,255,255,0.1);
1953
+ padding: 4px 10px;
1954
+ border-radius: 6px;
1955
+ font-family: 'Fira Code', 'Courier New', monospace;
1956
+ color: #22D3EE;
1957
+ font-size: 16px;
1958
+ border: 1px solid rgba(34, 211, 238, 0.2);
1959
+ }
1960
+ .btn-group {
1961
+ display: flex;
1962
+ gap: 16px;
1963
+ justify-content: center;
1964
+ flex-wrap: wrap;
1965
+ animation: fadeInUp 0.6s ease-out 0.3s backwards;
1966
+ }
1967
+ .btn {
1968
+ display: inline-block;
1969
+ background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%);
1970
+ color: white;
1971
+ text-decoration: none;
1972
+ padding: 14px 36px;
1973
+ border-radius: 12px;
1974
+ font-weight: 600;
1975
+ font-size: 16px;
1976
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
1977
+ box-shadow: 0 10px 30px rgba(37, 99, 235, 0.3);
1978
+ border: none;
1979
+ cursor: pointer;
1980
+ }
1981
+ .btn:hover {
1982
+ transform: translateY(-2px);
1983
+ box-shadow: 0 15px 40px rgba(37, 99, 235, 0.4);
1984
+ }
1985
+ .btn-outline {
1986
+ background: transparent;
1987
+ color: #22D3EE;
1988
+ border: 2px solid #22D3EE;
1989
+ box-shadow: none;
1990
+ }
1991
+ .btn-outline:hover {
1992
+ background: rgba(34, 211, 238, 0.1);
1993
+ box-shadow: 0 10px 30px rgba(34, 211, 238, 0.2);
1994
+ }
1995
+ @keyframes fadeInUp {
1996
+ from {
1997
+ opacity: 0;
1998
+ transform: translateY(30px);
1999
+ }
2000
+ to {
2001
+ opacity: 1;
2002
+ transform: translateY(0);
2003
+ }
2004
+ }
2005
+ </style>
2006
+ </head>
2007
+ <body>
2008
+ <div class="bg-pattern"></div>
2009
+ <div class="container">
2010
+ <h1>404</h1>
2011
+ <h2>Page Not Found</h2>
2012
+ <p>The page <code>${pathname}</code> could not be found.<br>It may have been moved or deleted.</p>
2013
+ <div class="btn-group">
2014
+ <a href="/" class="btn">Return Home</a>
2015
+ <a href="javascript:history.back()" class="btn btn-outline">Go Back</a>
2016
+ </div>
2017
+ </div>
2018
+ </body>
2019
+ </html>`;
2020
+ }
2021
+ function generate500Page(options) {
2022
+ const { title, message, stack, isDev, pathname } = options;
2023
+ let callStackCards = "";
2024
+ let frameCount = 0;
2025
+ if (isDev && stack) {
2026
+ const stackLines = stack.split("\n").filter((line) => line.trim());
2027
+ const frames = stackLines.slice(1).filter((line) => line.includes("at "));
2028
+ frameCount = frames.length;
2029
+ callStackCards = frames.map((frame, index) => {
2030
+ const match = frame.match(/at\s+(.+?)\s+\((.+?)\)/) || frame.match(/at\s+(.+)/);
2031
+ if (match) {
2032
+ const funcName = match[1] || "anonymous";
2033
+ const location = match[2] || match[1];
2034
+ return `
2035
+ <div class="error-card" data-frame="${index}">
2036
+ <div class="card-header">
2037
+ <div class="card-title">${funcName.trim()}</div>
2038
+ <div class="card-number">${index + 1}</div>
2039
+ </div>
2040
+ <div class="card-location">${location.trim()}</div>
2041
+ </div>
2042
+ `;
2043
+ }
2044
+ return "";
2045
+ }).join("");
2046
+ }
2047
+ return `<!DOCTYPE html>
2048
+ <html lang="en">
2049
+ <head>
2050
+ <meta charset="UTF-8">
2051
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
2052
+ <title>Error | Velix v5</title>
2053
+ <style>
2054
+ * { margin: 0; padding: 0; box-sizing: border-box; }
2055
+ body {
2056
+ margin: 0;
2057
+ background: linear-gradient(135deg, #0F172A 0%, #1E293B 100%);
2058
+ color: #F8FAFC;
2059
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
2060
+ min-height: 100vh;
2061
+ overflow-x: hidden;
2062
+ }
2063
+ .container {
2064
+ max-width: 900px;
2065
+ margin: 0 auto;
2066
+ padding: 40px 20px;
2067
+ }
2068
+ .error-header {
2069
+ background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%);
2070
+ color: white;
2071
+ padding: 20px 28px;
2072
+ border-radius: 16px;
2073
+ display: flex;
2074
+ align-items: center;
2075
+ gap: 14px;
2076
+ margin-bottom: 28px;
2077
+ font-size: 18px;
2078
+ font-weight: 700;
2079
+ box-shadow: 0 10px 40px rgba(239, 68, 68, 0.3);
2080
+ }
2081
+ .error-header svg {
2082
+ width: 24px;
2083
+ height: 24px;
2084
+ flex-shrink: 0;
2085
+ }
2086
+ .error-badge {
2087
+ display: inline-block;
2088
+ background: linear-gradient(135deg, #1E40AF 0%, #1E3A8A 100%);
2089
+ color: #60A5FA;
2090
+ padding: 6px 16px;
2091
+ border-radius: 8px;
2092
+ font-size: 13px;
2093
+ font-weight: 700;
2094
+ margin-bottom: 18px;
2095
+ text-transform: uppercase;
2096
+ letter-spacing: 0.8px;
2097
+ box-shadow: 0 4px 12px rgba(30, 64, 175, 0.3);
2098
+ }
2099
+ .route-badge {
2100
+ background: linear-gradient(135deg, #0C4A6E 0%, #075985 100%);
2101
+ color: #22D3EE;
2102
+ padding: 10px 18px;
2103
+ border-radius: 10px;
2104
+ font-size: 14px;
2105
+ margin-bottom: 24px;
2106
+ font-family: 'Courier New', monospace;
2107
+ box-shadow: 0 4px 12px rgba(12, 74, 110, 0.3);
2108
+ border: 1px solid rgba(34, 211, 238, 0.2);
2109
+ }
2110
+ .error-message {
2111
+ background: rgba(239, 68, 68, 0.1);
2112
+ border-left: 4px solid #EF4444;
2113
+ padding: 18px 20px;
2114
+ border-radius: 10px;
2115
+ margin-bottom: 32px;
2116
+ }
2117
+ .error-message-text {
2118
+ color: #FCA5A5;
2119
+ font-size: 16px;
2120
+ font-weight: 600;
2121
+ line-height: 1.6;
2122
+ font-family: 'Courier New', monospace;
2123
+ }
2124
+ .stack-section {
2125
+ margin-top: 32px;
2126
+ }
2127
+ .stack-header {
2128
+ display: flex;
2129
+ align-items: center;
2130
+ justify-content: space-between;
2131
+ margin-bottom: 20px;
2132
+ }
2133
+ .stack-title {
2134
+ font-size: 18px;
2135
+ font-weight: 700;
2136
+ color: #F1F5F9;
2137
+ display: flex;
2138
+ align-items: center;
2139
+ gap: 10px;
2140
+ }
2141
+ .frame-counter {
2142
+ background: linear-gradient(135deg, #1F2937 0%, #111827 100%);
2143
+ color: #22D3EE;
2144
+ padding: 6px 14px;
2145
+ border-radius: 8px;
2146
+ font-size: 13px;
2147
+ font-weight: 700;
2148
+ border: 1px solid rgba(34, 211, 238, 0.2);
2149
+ }
2150
+ .error-card {
2151
+ background: linear-gradient(135deg, #1E293B 0%, #0F172A 100%);
2152
+ border: 1px solid rgba(34, 211, 238, 0.2);
2153
+ border-radius: 14px;
2154
+ padding: 20px;
2155
+ margin-bottom: 12px;
2156
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
2157
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
2158
+ display: none;
2159
+ }
2160
+ .error-card.active {
2161
+ display: block;
2162
+ animation: slideIn 0.3s ease-out;
2163
+ }
2164
+ .error-card:hover {
2165
+ border-color: rgba(34, 211, 238, 0.5);
2166
+ box-shadow: 0 8px 24px rgba(34, 211, 238, 0.2);
2167
+ transform: translateY(-2px);
2168
+ }
2169
+ .card-header {
2170
+ display: flex;
2171
+ justify-content: space-between;
2172
+ align-items: center;
2173
+ margin-bottom: 12px;
2174
+ }
2175
+ .card-title {
2176
+ color: #22D3EE;
2177
+ font-size: 15px;
2178
+ font-weight: 700;
2179
+ font-family: 'Courier New', monospace;
2180
+ }
2181
+ .card-number {
2182
+ background: rgba(34, 211, 238, 0.2);
2183
+ color: #22D3EE;
2184
+ padding: 4px 10px;
2185
+ border-radius: 6px;
2186
+ font-size: 12px;
2187
+ font-weight: 700;
2188
+ }
2189
+ .card-location {
2190
+ color: #94A3B8;
2191
+ font-size: 13px;
2192
+ font-family: 'Courier New', monospace;
2193
+ word-break: break-all;
2194
+ line-height: 1.6;
2195
+ }
2196
+ .pagination {
2197
+ display: flex;
2198
+ justify-content: center;
2199
+ align-items: center;
2200
+ gap: 12px;
2201
+ margin-top: 24px;
2202
+ }
2203
+ .pagination-btn {
2204
+ background: linear-gradient(135deg, #1E293B 0%, #0F172A 100%);
2205
+ border: 1px solid rgba(34, 211, 238, 0.3);
2206
+ color: #22D3EE;
2207
+ padding: 10px 20px;
2208
+ border-radius: 10px;
2209
+ font-size: 14px;
2210
+ font-weight: 600;
2211
+ cursor: pointer;
2212
+ transition: all 0.2s;
2213
+ }
2214
+ .pagination-btn:hover:not(:disabled) {
2215
+ background: linear-gradient(135deg, #22D3EE 0%, #06B6D4 100%);
2216
+ color: #0F172A;
2217
+ transform: translateY(-2px);
2218
+ box-shadow: 0 6px 20px rgba(34, 211, 238, 0.4);
2219
+ }
2220
+ .pagination-btn:disabled {
2221
+ opacity: 0.3;
2222
+ cursor: not-allowed;
2223
+ }
2224
+ .pagination-info {
2225
+ color: #94A3B8;
2226
+ font-size: 14px;
2227
+ font-weight: 600;
2228
+ }
2229
+ .footer {
2230
+ margin-top: 48px;
2231
+ padding-top: 28px;
2232
+ border-top: 1px solid rgba(34, 211, 238, 0.2);
2233
+ display: flex;
2234
+ justify-content: space-between;
2235
+ align-items: center;
2236
+ flex-wrap: wrap;
2237
+ gap: 20px;
2238
+ }
2239
+ .brand {
2240
+ display: flex;
2241
+ align-items: center;
2242
+ gap: 10px;
2243
+ font-weight: 700;
2244
+ color: #22D3EE;
2245
+ font-size: 15px;
2246
+ }
2247
+ .brand img {
2248
+ width: 20px;
2249
+ height: 20px;
2250
+ }
2251
+ .footer-links {
2252
+ display: flex;
2253
+ gap: 24px;
2254
+ flex-wrap: wrap;
2255
+ }
2256
+ .footer-links a {
2257
+ color: #60A5FA;
2258
+ text-decoration: none;
2259
+ font-weight: 600;
2260
+ transition: all 0.2s;
2261
+ font-size: 14px;
2262
+ }
2263
+ .footer-links a:hover {
2264
+ color: #22D3EE;
2265
+ transform: translateY(-1px);
2266
+ }
2267
+ .no-stack {
2268
+ background: rgba(239, 68, 68, 0.1);
2269
+ border: 1px solid rgba(239, 68, 68, 0.3);
2270
+ border-radius: 12px;
2271
+ padding: 32px;
2272
+ color: #FCA5A5;
2273
+ text-align: center;
2274
+ font-size: 15px;
2275
+ }
2276
+ @keyframes slideIn {
2277
+ from {
2278
+ opacity: 0;
2279
+ transform: translateY(10px);
2280
+ }
2281
+ to {
2282
+ opacity: 1;
2283
+ transform: translateY(0);
2284
+ }
2285
+ }
2286
+ </style>
2287
+ </head>
2288
+ <body>
2289
+ <div class="container">
2290
+ <div class="error-header">
2291
+ <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
2292
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
2293
+ </svg>
2294
+ <span>Unhandled Runtime Error</span>
2295
+ </div>
2296
+
2297
+ <div class="error-badge">SERVER ERROR 500</div>
2298
+ ${pathname ? `<div class="route-badge">Route: ${pathname}</div>` : ""}
2299
+
2300
+ <div class="error-message">
2301
+ <div class="error-message-text">${message}</div>
2302
+ </div>
2303
+
2304
+ ${isDev && callStackCards ? `
2305
+ <div class="stack-section">
2306
+ <div class="stack-header">
2307
+ <div class="stack-title">
2308
+ <svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2309
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
2310
+ </svg>
2311
+ Call Stack
2312
+ </div>
2313
+ <div class="frame-counter">${frameCount}</div>
2314
+ </div>
2315
+ <div id="error-cards">
2316
+ ${callStackCards}
2317
+ </div>
2318
+ ${frameCount > 1 ? `
2319
+ <div class="pagination">
2320
+ <button class="pagination-btn" id="prev-btn" onclick="changePage(-1)">
2321
+ <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="display:inline;vertical-align:middle;margin-right:4px;">
2322
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
2323
+ </svg>
2324
+ Previous
2325
+ </button>
2326
+ <div class="pagination-info">
2327
+ <span id="current-page">1</span> / <span id="total-pages">${frameCount}</span>
2328
+ </div>
2329
+ <button class="pagination-btn" id="next-btn" onclick="changePage(1)">
2330
+ Next
2331
+ <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="display:inline;vertical-align:middle;margin-left:4px;">
2332
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
2333
+ </svg>
2334
+ </button>
2335
+ </div>
2336
+ ` : ""}
2337
+ </div>
2338
+ ` : '<div class="no-stack">An error occurred while processing your request. Please check the server logs for more details.</div>'}
2339
+
2340
+ <div class="footer">
2341
+ <div class="brand">
2342
+ <img src="/__velix/logo.webp" alt="Velix" onerror="this.style.display='none'"/>
2343
+ <span>Velix v5.0.0</span>
2344
+ </div>
2345
+ <div class="footer-links">
2346
+ <a href="/">Home</a>
2347
+ <a href="javascript:location.reload()">Reload</a>
2348
+ <a href="https://github.com/velix/velix/tree/main/docs" target="_blank">Documentation</a>
2349
+ ${isDev ? '<span style="color:#94A3B8;">Development Mode</span>' : ""}
2350
+ </div>
2351
+ </div>
2352
+ </div>
2353
+
2354
+ ${isDev && frameCount > 0 ? `
2355
+ <script>
2356
+ let currentPage = 1;
2357
+ const totalPages = ${frameCount};
2358
+ const cards = document.querySelectorAll('.error-card');
2359
+ const prevBtn = document.getElementById('prev-btn');
2360
+ const nextBtn = document.getElementById('next-btn');
2361
+ const currentPageSpan = document.getElementById('current-page');
2362
+
2363
+ function showPage(page) {
2364
+ cards.forEach((card, index) => {
2365
+ card.classList.remove('active');
2366
+ if (index === page - 1) {
2367
+ card.classList.add('active');
2368
+ }
2369
+ });
2370
+
2371
+ currentPage = page;
2372
+ currentPageSpan.textContent = page;
2373
+
2374
+ if (prevBtn) prevBtn.disabled = page === 1;
2375
+ if (nextBtn) nextBtn.disabled = page === totalPages;
2376
+ }
2377
+
2378
+ function changePage(direction) {
2379
+ const newPage = currentPage + direction;
2380
+ if (newPage >= 1 && newPage <= totalPages) {
2381
+ showPage(newPage);
2382
+ }
2383
+ }
2384
+
2385
+ // Show first page on load
2386
+ showPage(1);
2387
+
2388
+ // Keyboard navigation
2389
+ document.addEventListener('keydown', (e) => {
2390
+ if (e.key === 'ArrowLeft') changePage(-1);
2391
+ if (e.key === 'ArrowRight') changePage(1);
2392
+ });
2393
+ </script>
2394
+ ` : ""}
2395
+ </body>
2396
+ </html>`;
2397
+ }
2398
+
2399
+ // server/index.ts
2400
+ var MIME_TYPES = {
2401
+ ".html": "text/html; charset=utf-8",
2402
+ ".css": "text/css; charset=utf-8",
2403
+ ".js": "application/javascript; charset=utf-8",
2404
+ ".mjs": "application/javascript; charset=utf-8",
2405
+ ".json": "application/json",
2406
+ ".png": "image/png",
2407
+ ".jpg": "image/jpeg",
2408
+ ".jpeg": "image/jpeg",
2409
+ ".gif": "image/gif",
2410
+ ".svg": "image/svg+xml",
2411
+ ".ico": "image/x-icon",
2412
+ ".webp": "image/webp",
2413
+ ".woff": "font/woff",
2414
+ ".woff2": "font/woff2",
2415
+ ".ttf": "font/ttf",
2416
+ ".otf": "font/otf",
2417
+ ".txt": "text/plain; charset=utf-8",
2418
+ ".xml": "application/xml",
2419
+ ".mp4": "video/mp4",
2420
+ ".webm": "video/webm",
2421
+ ".mp3": "audio/mpeg",
2422
+ ".pdf": "application/pdf",
2423
+ ".map": "application/json"
2424
+ };
2425
+ async function createServer(options = {}) {
2426
+ const projectRoot = options.projectRoot || process.cwd();
2427
+ const mode = options.mode || process.env.NODE_ENV || "development";
2428
+ const isDev = mode === "development";
2429
+ const rawConfig = await loadConfig(projectRoot);
2430
+ const config = resolvePaths(rawConfig, projectRoot);
2431
+ await loadPlugins(projectRoot, config);
2432
+ await pluginManager.runHook(PluginHooks.CONFIG, config);
2433
+ const middlewareFns = await loadMiddleware(projectRoot);
2434
+ const appDir = config.resolvedAppDir || path8.join(projectRoot, "app");
2435
+ const routes = buildRouteTree(appDir);
2436
+ await pluginManager.runHook(PluginHooks.ROUTES_LOADED, routes);
2437
+ const startTime = Date.now();
2438
+ await pluginManager.runHook(PluginHooks.SERVER_START, { config, isDev, projectRoot }, isDev);
2439
+ const server = http.createServer(async (req, res) => {
2440
+ const requestStart = Date.now();
2441
+ const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
2442
+ const pathname = url.pathname;
2443
+ try {
2444
+ if (middlewareFns.length > 0) {
2445
+ const middlewareResult = await runMiddleware(req, res, middlewareFns);
2446
+ if (!middlewareResult.continue) return;
2447
+ }
2448
+ await pluginManager.runHook(PluginHooks.REQUEST, req, res);
2449
+ if (pathname === "/sitemap.xml" && config.seo.sitemap) {
2450
+ const baseUrl = config.app.url || `http://${config.server.host}:${config.server.port}`;
2451
+ const sitemap = generateSitemap(routes.appRoutes, baseUrl);
2452
+ res.writeHead(200, { "Content-Type": "application/xml" });
2453
+ res.end(sitemap);
2454
+ return;
2455
+ }
2456
+ if (pathname === "/robots.txt" && config.seo.robots) {
2457
+ const baseUrl = config.app.url || `http://${config.server.host}:${config.server.port}`;
2458
+ const robotsTxt = generateRobotsTxt(baseUrl);
2459
+ res.writeHead(200, { "Content-Type": "text/plain" });
2460
+ res.end(robotsTxt);
2461
+ return;
2462
+ }
2463
+ if (pathname === "/__velix/action" && req.method === "POST") {
2464
+ await handleServerAction(req, res);
2465
+ return;
2466
+ }
2467
+ if (pathname === "/__velix/image") {
2468
+ const { handleImageOptimization: handleImageOptimization2 } = await Promise.resolve().then(() => (init_image_optimizer(), image_optimizer_exports));
2469
+ await handleImageOptimization2(req, res, projectRoot);
2470
+ return;
2471
+ }
2472
+ if (pathname.startsWith("/__velix/")) {
2473
+ await serveVelixInternal(pathname, req, res, projectRoot);
2474
+ return;
2475
+ }
2476
+ const publicDir = config.resolvedPublicDir || path8.join(projectRoot, "public");
2477
+ if (await serveStaticFile(pathname, publicDir, res, isDev)) {
2478
+ if (isDev) logger_default.request(req.method || "GET", pathname, 200, Date.now() - requestStart, { type: "static" });
2479
+ return;
2480
+ }
2481
+ const apiMatch = matchRoute(pathname, routes.api);
2482
+ if (apiMatch) {
2483
+ await handleApiRoute(apiMatch, req, res, url);
2484
+ if (isDev) logger_default.request(req.method || "GET", pathname, res.statusCode, Date.now() - requestStart, { type: "api" });
2485
+ return;
2486
+ }
2487
+ const pageMatch = matchRoute(pathname, routes.appRoutes);
2488
+ if (pageMatch) {
2489
+ await handlePageRoute(pageMatch, routes, req, res, url, config, isDev, projectRoot);
2490
+ if (isDev) logger_default.request(req.method || "GET", pathname, res.statusCode, Date.now() - requestStart, { type: "ssr" });
2491
+ return;
2492
+ }
2493
+ res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
2494
+ res.end(generate404Page(pathname));
2495
+ if (isDev) logger_default.request(req.method || "GET", pathname, 404, Date.now() - requestStart);
2496
+ } catch (error) {
2497
+ console.error("Server error:", error);
2498
+ if (!res.headersSent) {
2499
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
2500
+ res.end(generate500Page({
2501
+ statusCode: 500,
2502
+ title: "Server Error",
2503
+ message: error.message || "An unexpected error occurred",
2504
+ stack: isDev ? error.stack : void 0,
2505
+ isDev,
2506
+ pathname
2507
+ }));
2508
+ }
2509
+ }
2510
+ });
2511
+ const __hmrClients = /* @__PURE__ */ new Set();
2512
+ server.__hmrClients = __hmrClients;
2513
+ server.broadcastHMR = (msg) => {
2514
+ __hmrClients.forEach((c2) => c2.write(`data: ${msg}
2515
+
2516
+ `));
2517
+ };
2518
+ const port = config.server.port;
2519
+ const host = config.server.host;
2520
+ server.listen(port, host, () => {
2521
+ logger_default.serverStart({ port, host, mode, pagesDir: appDir }, startTime);
2522
+ if (isDev) {
2523
+ routes.appRoutes.forEach((r) => {
2524
+ const type = r.path.includes(":") || r.path.includes("*") ? "dynamic" : "static";
2525
+ logger_default.route(r.path, type);
2526
+ });
2527
+ routes.api.forEach((r) => logger_default.route(r.path, "api"));
2528
+ logger_default.blank();
2529
+ }
2530
+ });
2531
+ server.on("error", (err) => {
2532
+ if (err.code === "EADDRINUSE") {
2533
+ logger_default.portInUse(port);
2534
+ process.exit(1);
2535
+ }
2536
+ throw err;
2537
+ });
2538
+ return {
2539
+ server,
2540
+ config: rawConfig,
2541
+ close: () => server.close()
2542
+ };
2543
+ }
2544
+ async function serveStaticFile(pathname, publicDir, res, isDev = false) {
2545
+ const filePath = path8.join(publicDir, pathname);
2546
+ if (!filePath.startsWith(publicDir)) return false;
2547
+ if (!fs7.existsSync(filePath) || fs7.statSync(filePath).isDirectory()) return false;
2548
+ const ext = path8.extname(filePath);
2549
+ const contentType = MIME_TYPES[ext] || "application/octet-stream";
2550
+ const content = fs7.readFileSync(filePath);
2551
+ res.writeHead(200, {
2552
+ "Content-Type": contentType,
2553
+ "Content-Length": content.length,
2554
+ "Cache-Control": isDev ? "no-store, no-cache, must-revalidate" : "public, max-age=31536000, immutable"
2555
+ });
2556
+ res.end(content);
2557
+ return true;
2558
+ }
2559
+ async function handleApiRoute(route, req, res, url) {
2560
+ try {
2561
+ const fileUrl = pathToFileURL3(route.filePath).href;
2562
+ const mod = await import(`${fileUrl}?t=${Date.now()}`);
2563
+ const method = req.method?.toUpperCase() || "GET";
2564
+ const handler = mod[method] || mod.default;
2565
+ if (!handler) {
2566
+ res.writeHead(405, { "Content-Type": "application/json" });
2567
+ res.end(JSON.stringify({ error: "Method not allowed" }));
2568
+ return;
2569
+ }
2570
+ let body;
2571
+ if (["POST", "PUT", "PATCH"].includes(method)) {
2572
+ body = await parseRequestBody(req);
2573
+ }
2574
+ const request = {
2575
+ method,
2576
+ url: req.url,
2577
+ headers: req.headers,
2578
+ params: route.params || {},
2579
+ query: Object.fromEntries(url.searchParams),
2580
+ body,
2581
+ json: () => body
2582
+ };
2583
+ const response = await handler(request);
2584
+ if (response instanceof Response) {
2585
+ const headers2 = {};
2586
+ response.headers.forEach((v, k) => {
2587
+ headers2[k] = v;
2588
+ });
2589
+ res.writeHead(response.status, headers2);
2590
+ const text2 = await response.text();
2591
+ res.end(text2);
2592
+ } else if (typeof response === "object") {
2593
+ res.writeHead(200, { "Content-Type": "application/json" });
2594
+ res.end(JSON.stringify(response));
2595
+ } else {
2596
+ res.writeHead(200, { "Content-Type": "text/plain" });
2597
+ res.end(String(response));
2598
+ }
2599
+ } catch (err) {
2600
+ res.writeHead(500, { "Content-Type": "application/json" });
2601
+ res.end(JSON.stringify({ error: err.message }));
2602
+ }
2603
+ }
2604
+ async function handleServerAction(req, res) {
2605
+ try {
2606
+ const body = await parseRequestBody(req);
2607
+ if (!body?.actionId || typeof body.actionId !== "string") {
2608
+ res.writeHead(400, { "Content-Type": "application/json" });
2609
+ res.end(JSON.stringify({ error: "Missing actionId" }));
2610
+ return;
2611
+ }
2612
+ const args = body.args ? deserializeArgs(body.args) : [];
2613
+ const result = await executeAction(body.actionId, args);
2614
+ res.writeHead(200, { "Content-Type": "application/json" });
2615
+ res.end(JSON.stringify(result));
2616
+ } catch (err) {
2617
+ res.writeHead(500, { "Content-Type": "application/json" });
2618
+ res.end(JSON.stringify({ success: false, error: err.message }));
2619
+ }
2620
+ }
2621
+ async function handlePageRoute(route, routes, req, res, url, config, isDev, projectRoot) {
2622
+ try {
2623
+ const fileUrl = pathToFileURL3(route.filePath).href;
2624
+ const mod = await import(`${fileUrl}?t=${Date.now()}`);
2625
+ const PageComponent = mod.default;
2626
+ let metadata = mod.metadata || mod.generateMetadata?.(route.params) || {};
2627
+ let LayoutComponent = ({ children }) => React2.createElement(React2.Fragment, null, children);
2628
+ let layoutParams = route.params;
2629
+ try {
2630
+ const layoutPath = path8.join(path8.dirname(route.filePath), "layout.tsx");
2631
+ if (fs7.existsSync(layoutPath)) {
2632
+ const layoutMod = await import(`${pathToFileURL3(layoutPath).href}?t=${Date.now()}`);
2633
+ if (layoutMod.metadata) {
2634
+ metadata = { ...layoutMod.metadata, ...metadata };
2635
+ }
2636
+ if (layoutMod.default) {
2637
+ LayoutComponent = layoutMod.default;
2638
+ }
2639
+ }
2640
+ } catch (e) {
2641
+ }
2642
+ const baseUrl = config.app.url || `http://${config.server.host}:${config.server.port}`;
2643
+ const metaTags = generateMetadataTags({
2644
+ ...metadata,
2645
+ generator: `Velix v5.0.0`,
2646
+ viewport: metadata.viewport || "width=device-width, initial-scale=1"
2647
+ }, baseUrl);
2648
+ const islands = getRegisteredIslands();
2649
+ const hydrationScript = generateAdvancedHydrationScript(islands);
2650
+ const devToolsHtml = generateDevToolsHtml(isDev);
2651
+ const headInjections = `
2652
+ <meta charset="utf-8">
2653
+ ${metaTags}
2654
+ ${config.favicon ? `<link rel="icon" href="${config.favicon}">` : ""}
2655
+ ${config.styles.map((s) => `<link rel="stylesheet" href="${s}">`).join("\n ")}
2656
+ `;
2657
+ const searchParams = Object.fromEntries(url.searchParams.entries());
2658
+ let pageElement = React2.createElement(PageComponent, { params: route.params, searchParams, query: searchParams });
2659
+ if (typeof PageComponent === "function") {
2660
+ try {
2661
+ const result = PageComponent({ params: route.params, searchParams, query: searchParams });
2662
+ if (result instanceof Promise) {
2663
+ pageElement = await result;
2664
+ }
2665
+ } catch (e) {
2666
+ }
2667
+ }
2668
+ let layoutElement = React2.createElement(LayoutComponent, { params: layoutParams, searchParams }, pageElement);
2669
+ if (typeof LayoutComponent === "function") {
2670
+ try {
2671
+ const result = LayoutComponent({ params: layoutParams, searchParams, children: pageElement });
2672
+ if (result instanceof Promise) {
2673
+ layoutElement = await result;
2674
+ }
2675
+ } catch (e) {
2676
+ }
2677
+ }
2678
+ const ssrContent = renderToString(layoutElement);
2679
+ let finalHtml = await pluginManager.runWaterfallHook(PluginHooks.AFTER_RENDER, ssrContent, { route, config, isDev });
2680
+ const headInjectionsHtml = `
2681
+ ${headInjections}
2682
+ `;
2683
+ const bodyInjectionsHtml = `
2684
+ <div id="__velix-islands"></div>
2685
+ ${hydrationScript}${devToolsHtml}
2686
+ `;
2687
+ if (finalHtml.includes("<html")) {
2688
+ const headEnd = finalHtml.lastIndexOf("</head>");
2689
+ if (headEnd !== -1) {
2690
+ finalHtml = finalHtml.slice(0, headEnd) + headInjectionsHtml + finalHtml.slice(headEnd);
2691
+ } else {
2692
+ const bodyStart = finalHtml.search(/<body[^>]*>/i);
2693
+ if (bodyStart !== -1) {
2694
+ finalHtml = finalHtml.slice(0, bodyStart) + `<head>${headInjectionsHtml}</head>` + finalHtml.slice(bodyStart);
2695
+ }
2696
+ }
2697
+ const bodyEnd = finalHtml.lastIndexOf("</body>");
2698
+ if (bodyEnd !== -1) {
2699
+ finalHtml = finalHtml.slice(0, bodyEnd) + bodyInjectionsHtml + finalHtml.slice(bodyEnd);
2700
+ } else {
2701
+ finalHtml += bodyInjectionsHtml;
2702
+ }
2703
+ if (!finalHtml.trim().startsWith("<!DOCTYPE")) {
2704
+ finalHtml = "<!DOCTYPE html>\n" + finalHtml;
2705
+ }
2706
+ } else {
2707
+ finalHtml = `<!DOCTYPE html>
2708
+ <html lang="en">
2709
+ <head>
2710
+ ${headInjectionsHtml}
2711
+ </head>
2712
+ <body>
2713
+ <div id="__velix">${ssrContent}</div>
2714
+ ${bodyInjectionsHtml}
2715
+ </body>
2716
+ </html>`;
2717
+ }
2718
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2719
+ res.end(finalHtml);
2720
+ } catch (err) {
2721
+ logger_default.error(`Render error: ${route.path}`, err);
2722
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
2723
+ res.end(generate500Page({
2724
+ statusCode: 500,
2725
+ title: "Render Error",
2726
+ message: err.message || "Failed to render page",
2727
+ stack: isDev ? err.stack : void 0,
2728
+ isDev,
2729
+ pathname: route.path
2730
+ }));
2731
+ }
2732
+ }
2733
+ async function serveVelixInternal(pathname, req, res, projectRoot) {
2734
+ if (pathname === "/__velix/hmr") {
2735
+ res.writeHead(200, {
2736
+ "Content-Type": "text/event-stream",
2737
+ "Cache-Control": "no-cache",
2738
+ "Connection": "keep-alive"
2739
+ });
2740
+ res.write("data: connected\n\n");
2741
+ const interval = setInterval(() => res.write(":heartbeat\n\n"), 3e4);
2742
+ if (res.req?.socket?.server?.__hmrClients) res.req.socket.server.__hmrClients.add(res);
2743
+ req.on("close", () => {
2744
+ clearInterval(interval);
2745
+ if (res.req?.socket?.server?.__hmrClients) res.req.socket.server.__hmrClients.delete(res);
2746
+ });
2747
+ return;
2748
+ }
2749
+ if (pathname === "/__velix/logo.webp") {
2750
+ const __filename2 = fileURLToPath2(import.meta.url);
2751
+ const __dirname2 = path8.dirname(__filename2);
2752
+ const fallbackPath = path8.join(path8.dirname(pathToFileURL3(__dirname2).pathname), "..", "assets", "logo.webp");
2753
+ const logoPath = fs7.existsSync(fallbackPath) ? fallbackPath : path8.join(process.cwd(), "node_modules", "velix", "assets", "logo.webp");
2754
+ if (fs7.existsSync(logoPath)) {
2755
+ res.writeHead(200, { "Content-Type": "image/webp", "Cache-Control": "public, max-age=31536000, immutable" });
2756
+ res.end(fs7.readFileSync(logoPath));
2757
+ } else {
2758
+ res.writeHead(404);
2759
+ res.end();
2760
+ }
2761
+ return;
2762
+ }
2763
+ if (pathname.startsWith("/__velix/islands/") && pathname.endsWith(".js")) {
2764
+ const componentName = pathname.replace("/__velix/islands/", "").replace(".js", "");
2765
+ try {
2766
+ const searchDirs = [
2767
+ path8.join(projectRoot, "components"),
2768
+ path8.join(projectRoot, "app"),
2769
+ path8.join(projectRoot, "islands")
2770
+ ];
2771
+ let componentPath = "";
2772
+ for (const dir of searchDirs) {
2773
+ if (!fs7.existsSync(dir)) continue;
2774
+ const files = fs7.readdirSync(dir, { recursive: true });
2775
+ const found = files.find((f) => f.replace(/\\/g, "/").endsWith(`${componentName}.tsx`) || f.replace(/\\/g, "/").endsWith(`${componentName}.jsx`));
2776
+ if (found) {
2777
+ componentPath = path8.join(dir, found);
2778
+ break;
2779
+ }
2780
+ }
2781
+ if (!componentPath) {
2782
+ logger_default.error(`Island component not found: ${componentName}`);
2783
+ res.writeHead(404);
2784
+ res.end("Island component not found");
2785
+ return;
2786
+ }
2787
+ const result = await esbuild.build({
2788
+ entryPoints: [componentPath],
2789
+ bundle: true,
2790
+ format: "esm",
2791
+ platform: "browser",
2792
+ target: ["es2022"],
2793
+ minify: false,
2794
+ sourcemap: "inline",
2795
+ jsx: "automatic",
2796
+ external: ["react", "react-dom"],
2797
+ write: false
2798
+ });
2799
+ res.writeHead(200, { "Content-Type": "application/javascript" });
2800
+ res.end(result.outputFiles[0].text);
2801
+ return;
2802
+ } catch (err) {
2803
+ logger_default.error(`Island bundling failed: ${componentName}`, err);
2804
+ res.writeHead(500);
2805
+ res.end(`console.error("Island bundling failed: ${err.message}");`);
2806
+ return;
2807
+ }
2808
+ }
2809
+ if (pathname === "/__velix/react.js" || pathname === "/__velix/react-dom-client.js") {
2810
+ const dep = pathname === "/__velix/react.js" ? "react" : "react-dom/client";
2811
+ try {
2812
+ const result = await esbuild.build({
2813
+ entryPoints: [dep],
2814
+ bundle: true,
2815
+ format: "esm",
2816
+ platform: "browser",
2817
+ target: ["es2022"],
2818
+ minify: true,
2819
+ write: false
2820
+ });
2821
+ res.writeHead(200, { "Content-Type": "application/javascript", "Cache-Control": "public, max-age=31536000, immutable" });
2822
+ res.end(result.outputFiles[0].text);
2823
+ return;
2824
+ } catch (err) {
2825
+ res.writeHead(500);
2826
+ res.end();
2827
+ return;
2828
+ }
2829
+ }
2830
+ res.writeHead(404);
2831
+ res.end("Not found");
2832
+ }
2833
+ function parseRequestBody(req) {
2834
+ return new Promise((resolve, reject) => {
2835
+ let body = "";
2836
+ req.on("data", (chunk) => {
2837
+ body += chunk;
2838
+ });
2839
+ req.on("end", () => {
2840
+ try {
2841
+ const ct = req.headers["content-type"] || "";
2842
+ if (ct.includes("application/json")) resolve(JSON.parse(body));
2843
+ else resolve(body);
2844
+ } catch {
2845
+ resolve(body);
2846
+ }
2847
+ });
2848
+ req.on("error", reject);
2849
+ });
2850
+ }
2851
+
2852
+ // actions/revalidation.ts
2853
+ init_esm_shims();
2854
+ var CacheManager = class {
2855
+ cache = /* @__PURE__ */ new Map();
2856
+ tagIndex = /* @__PURE__ */ new Map();
2857
+ set(path10, data, tags = []) {
2858
+ const entry = {
2859
+ path: path10,
2860
+ tags: new Set(tags),
2861
+ timestamp: Date.now(),
2862
+ data
2863
+ };
2864
+ this.cache.set(path10, entry);
2865
+ tags.forEach((tag) => {
2866
+ if (!this.tagIndex.has(tag)) {
2867
+ this.tagIndex.set(tag, /* @__PURE__ */ new Set());
2868
+ }
2869
+ this.tagIndex.get(tag).add(path10);
2870
+ });
2871
+ }
2872
+ get(path10) {
2873
+ const entry = this.cache.get(path10);
2874
+ return entry ? entry.data : null;
2875
+ }
2876
+ revalidatePath(path10) {
2877
+ this.cache.delete(path10);
2878
+ }
2879
+ revalidateTag(tag) {
2880
+ const paths = this.tagIndex.get(tag);
2881
+ if (paths) {
2882
+ paths.forEach((path10) => this.cache.delete(path10));
2883
+ this.tagIndex.delete(tag);
2884
+ }
2885
+ }
2886
+ clear() {
2887
+ this.cache.clear();
2888
+ this.tagIndex.clear();
2889
+ }
2890
+ has(path10) {
2891
+ return this.cache.has(path10);
2892
+ }
2893
+ };
2894
+ var cacheManager = new CacheManager();
2895
+ function revalidatePath(path10, type = "path") {
2896
+ cacheManager.revalidatePath(path10);
2897
+ if (typeof global !== "undefined" && global.__VELIX_HMR_SERVER__) {
2898
+ global.__VELIX_HMR_SERVER__.broadcast(JSON.stringify({
2899
+ type: "revalidate",
2900
+ path: path10,
2901
+ revalidationType: type
2902
+ }));
2903
+ }
2904
+ }
2905
+ function revalidateTag(tag) {
2906
+ cacheManager.revalidateTag(tag);
2907
+ if (typeof global !== "undefined" && global.__VELIX_HMR_SERVER__) {
2908
+ global.__VELIX_HMR_SERVER__.broadcast(JSON.stringify({
2909
+ type: "revalidate",
2910
+ tag
2911
+ }));
2912
+ }
2913
+ }
2914
+ function unstable_cache(fn, keys, options) {
2915
+ return async () => {
2916
+ const cacheKey = keys.join(":");
2917
+ if (cacheManager.has(cacheKey)) {
2918
+ return cacheManager.get(cacheKey);
2919
+ }
2920
+ const result = await fn();
2921
+ cacheManager.set(cacheKey, result, options?.tags || []);
2922
+ if (options?.revalidate) {
2923
+ setTimeout(() => {
2924
+ cacheManager.revalidatePath(cacheKey);
2925
+ }, options.revalidate * 1e3);
2926
+ }
2927
+ return result;
2928
+ };
2929
+ }
2930
+
2931
+ // hooks/index.ts
2932
+ init_esm_shims();
2933
+ import { useActionState as useActionState2, useOptimistic as useOptimistic2, use } from "react";
2934
+ import { useFormStatus as useFormStatus2 } from "react-dom";
2935
+
2936
+ // context.ts
2937
+ init_esm_shims();
2938
+ import React3 from "react";
2939
+ var RequestContext = React3.createContext(null);
2940
+ var RouteContext = React3.createContext(null);
2941
+ var LayoutContext = React3.createContext(null);
2942
+ function createRequestContext(req, res, params = {}, query = {}) {
2943
+ return {
2944
+ req,
2945
+ res,
2946
+ params,
2947
+ query,
2948
+ url: req.url,
2949
+ method: req.method,
2950
+ headers: req.headers,
2951
+ cookies: parseCookies(req.headers.cookie || "")
2952
+ };
2953
+ }
2954
+ function parseCookies(cookieHeader) {
2955
+ const cookies2 = {};
2956
+ if (!cookieHeader) return cookies2;
2957
+ cookieHeader.split(";").forEach((cookie) => {
2958
+ const [name, ...rest] = cookie.split("=");
2959
+ if (name) cookies2[name.trim()] = rest.join("=").trim();
2960
+ });
2961
+ return cookies2;
2962
+ }
2963
+ function useRequest() {
2964
+ const context = React3.useContext(RequestContext);
2965
+ if (!context) throw new Error("useRequest must be used within a RequestContext provider");
2966
+ return context;
2967
+ }
2968
+ function useParams() {
2969
+ const context = React3.useContext(RouteContext);
2970
+ return context?.params || {};
2971
+ }
2972
+ function useQuery() {
2973
+ const context = React3.useContext(RouteContext);
2974
+ return context?.query || {};
2975
+ }
2976
+ function usePathname() {
2977
+ const context = React3.useContext(RouteContext);
2978
+ return context?.pathname || "/";
2979
+ }
2980
+
2981
+ // hooks/index.ts
2982
+ import { use as use2, useOptimistic as useOptimisticReact } from "react";
2983
+ function useAsyncData(promise) {
2984
+ return use2(promise);
2985
+ }
2986
+ function useOptimisticMutation(currentState2, updateFn) {
2987
+ return useOptimisticReact(currentState2, updateFn);
2988
+ }
2989
+ function preloadResource(fetcher) {
2990
+ return fetcher();
2991
+ }
2992
+
2993
+ // client/index.ts
2994
+ init_esm_shims();
2995
+ import React4 from "react";
2996
+ var listeners = /* @__PURE__ */ new Set();
2997
+ var currentState = {
2998
+ pathname: typeof window !== "undefined" ? window.location.pathname : "/",
2999
+ query: {},
3000
+ params: {}
3001
+ };
3002
+ function notify() {
3003
+ listeners.forEach((fn) => fn());
3004
+ }
3005
+ var router = {
3006
+ push(url) {
3007
+ if (typeof window === "undefined") return;
3008
+ window.history.pushState({}, "", url);
3009
+ currentState = { ...currentState, pathname: url.split("?")[0] };
3010
+ notify();
3011
+ },
3012
+ replace(url) {
3013
+ if (typeof window === "undefined") return;
3014
+ window.history.replaceState({}, "", url);
3015
+ currentState = { ...currentState, pathname: url.split("?")[0] };
3016
+ notify();
3017
+ },
3018
+ back() {
3019
+ if (typeof window === "undefined") return;
3020
+ window.history.back();
3021
+ },
3022
+ forward() {
3023
+ if (typeof window === "undefined") return;
3024
+ window.history.forward();
3025
+ },
3026
+ refresh() {
3027
+ if (typeof window === "undefined") return;
3028
+ window.location.reload();
3029
+ },
3030
+ prefetch(_url) {
3031
+ },
3032
+ subscribe(listener) {
3033
+ listeners.add(listener);
3034
+ return () => listeners.delete(listener);
3035
+ },
3036
+ getState() {
3037
+ return currentState;
3038
+ }
3039
+ };
3040
+ function useRouter() {
3041
+ return router;
3042
+ }
3043
+ if (typeof window !== "undefined") {
3044
+ window.addEventListener("popstate", () => {
3045
+ currentState = { ...currentState, pathname: window.location.pathname };
3046
+ notify();
3047
+ });
3048
+ }
3049
+ function Link({ href, prefetch = false, replace: shouldReplace = false, scroll = true, shallow = false, children, onClick, onMouseEnter, ...rest }) {
3050
+ const linkRef = React4.useRef(null);
3051
+ const [isPrefetched, setIsPrefetched] = React4.useState(false);
3052
+ const handleMouseEnter = (e) => {
3053
+ if (prefetch === "hover" && !isPrefetched) {
3054
+ router.prefetch(href);
3055
+ setIsPrefetched(true);
3056
+ }
3057
+ onMouseEnter?.(e);
3058
+ };
3059
+ React4.useEffect(() => {
3060
+ if (prefetch === "visible" && linkRef.current && !isPrefetched) {
3061
+ const observer = new IntersectionObserver(
3062
+ (entries) => {
3063
+ if (entries[0].isIntersecting) {
3064
+ router.prefetch(href);
3065
+ setIsPrefetched(true);
3066
+ observer.disconnect();
3067
+ }
3068
+ },
3069
+ { rootMargin: "100px" }
3070
+ );
3071
+ observer.observe(linkRef.current);
3072
+ return () => observer.disconnect();
3073
+ }
3074
+ }, [href, prefetch, isPrefetched]);
3075
+ React4.useEffect(() => {
3076
+ if (prefetch === true && !isPrefetched) {
3077
+ router.prefetch(href);
3078
+ setIsPrefetched(true);
3079
+ }
3080
+ }, [href, prefetch, isPrefetched]);
3081
+ const handleClick = (e) => {
3082
+ if (href.startsWith("http") || href.startsWith("//") || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.button !== 0) {
3083
+ onClick?.(e);
3084
+ return;
3085
+ }
3086
+ e.preventDefault();
3087
+ onClick?.(e);
3088
+ if (typeof window !== "undefined" && window.__VELIX_DEV_TOOLS__) {
3089
+ window.__VELIX_DEV_TOOLS__.setStatus("navigating");
3090
+ }
3091
+ if (shouldReplace) {
3092
+ router.replace(href);
3093
+ } else {
3094
+ router.push(href);
3095
+ }
3096
+ if (scroll) {
3097
+ window.scrollTo({ top: 0, behavior: "smooth" });
3098
+ }
3099
+ };
3100
+ return React4.createElement("a", { ref: linkRef, href, onClick: handleClick, onMouseEnter: handleMouseEnter, ...rest }, children);
3101
+ }
3102
+ async function hydrate() {
3103
+ if (typeof window === "undefined") return;
3104
+ const { hydrateRoot } = await import("react-dom/client");
3105
+ const rootElement = document.getElementById("__velix");
3106
+ if (!rootElement) {
3107
+ console.warn("[Velix] No #__velix element found for hydration");
3108
+ return;
3109
+ }
3110
+ console.log("[Velix] Hydration complete");
3111
+ }
3112
+
3113
+ // components/Image.tsx
3114
+ init_esm_shims();
3115
+ import { forwardRef, useState } from "react";
3116
+ import { jsx } from "react/jsx-runtime";
3117
+ var defaultWidths = [640, 750, 828, 1080, 1200, 1920, 2048, 3840];
3118
+ var defaultQuality = 75;
3119
+ var Image = forwardRef(({
3120
+ src,
3121
+ alt,
3122
+ width,
3123
+ height,
3124
+ quality = defaultQuality,
3125
+ priority = false,
3126
+ unoptimized = false,
3127
+ className,
3128
+ style,
3129
+ ...rest
3130
+ }, ref) => {
3131
+ const [isLoaded, setIsLoaded] = useState(false);
3132
+ const isExternal = src.startsWith("http");
3133
+ const skipOptimization = unoptimized || isExternal && !src.includes("our-domain");
3134
+ const generateSrcSet = () => {
3135
+ if (skipOptimization) return void 0;
3136
+ return defaultWidths.map((w) => `/__velix/image?url=${encodeURIComponent(src)}&w=${w}&q=${quality} ${w}w`).join(", ");
3137
+ };
3138
+ const optimizedSrc = skipOptimization ? src : `/__velix/image?url=${encodeURIComponent(src)}&w=${width || 1080}&q=${quality}`;
3139
+ return /* @__PURE__ */ jsx(
3140
+ "img",
3141
+ {
3142
+ ref,
3143
+ src: optimizedSrc,
3144
+ srcSet: generateSrcSet(),
3145
+ alt,
3146
+ width,
3147
+ height,
3148
+ loading: priority ? "eager" : "lazy",
3149
+ decoding: priority ? "sync" : "async",
3150
+ className,
3151
+ style: {
3152
+ color: "transparent",
3153
+ ...style
3154
+ },
3155
+ onLoad: (e) => {
3156
+ setIsLoaded(true);
3157
+ if (rest.onLoad) rest.onLoad(e);
3158
+ },
3159
+ ...rest
3160
+ }
3161
+ );
3162
+ });
3163
+ Image.displayName = "Image";
3164
+
3165
+ // build/index.ts
3166
+ init_esm_shims();
3167
+ import esbuild2 from "esbuild";
3168
+ import fs8 from "fs";
3169
+ import path9 from "path";
3170
+ async function build(options = {}) {
3171
+ const projectRoot = options.projectRoot || process.cwd();
3172
+ const config = await loadConfig(projectRoot);
3173
+ const resolved = resolvePaths(config, projectRoot);
3174
+ const outDir = options.outDir || resolved.resolvedOutDir;
3175
+ const startTime = Date.now();
3176
+ logger_default.logo();
3177
+ logger_default.info("Building for production...");
3178
+ logger_default.blank();
3179
+ cleanDir(outDir);
3180
+ const appDir = resolved.resolvedAppDir;
3181
+ const routes = buildRouteTree(appDir);
3182
+ const sourceFiles = findFiles(appDir, /\.(tsx?|jsx?)$/);
3183
+ if (sourceFiles.length === 0) {
3184
+ logger_default.warn("No source files found in app/ directory");
3185
+ return;
3186
+ }
3187
+ try {
3188
+ const serverOutDir = path9.join(outDir, "server");
3189
+ ensureDir(serverOutDir);
3190
+ await esbuild2.build({
3191
+ entryPoints: sourceFiles,
3192
+ outdir: serverOutDir,
3193
+ bundle: false,
3194
+ format: "esm",
3195
+ platform: "node",
3196
+ target: config.build.target,
3197
+ minify: options.minify ?? config.build.minify,
3198
+ sourcemap: options.sourcemap ?? config.build.sourcemap,
3199
+ jsx: "automatic",
3200
+ logLevel: "silent"
3201
+ });
3202
+ logger_default.success("Server bundle built");
3203
+ } catch (err) {
3204
+ logger_default.error("Server build failed", err);
3205
+ process.exit(1);
3206
+ }
3207
+ try {
3208
+ const clientOutDir = path9.join(outDir, "client");
3209
+ ensureDir(clientOutDir);
3210
+ const clientFiles = sourceFiles.filter((f) => {
3211
+ const content = fs8.readFileSync(f, "utf-8");
3212
+ const firstLine = content.split("\n")[0]?.trim();
3213
+ return firstLine === "'use client'" || firstLine === '"use client"' || firstLine === "'use island'" || firstLine === '"use island"';
3214
+ });
3215
+ if (clientFiles.length > 0) {
3216
+ await esbuild2.build({
3217
+ entryPoints: clientFiles,
3218
+ outdir: clientOutDir,
3219
+ bundle: true,
3220
+ format: "esm",
3221
+ platform: "browser",
3222
+ target: ["es2022"],
3223
+ minify: options.minify ?? config.build.minify,
3224
+ sourcemap: options.sourcemap ?? config.build.sourcemap,
3225
+ splitting: config.build.splitting,
3226
+ jsx: "automatic",
3227
+ logLevel: "silent",
3228
+ external: ["react", "react-dom"]
3229
+ });
3230
+ logger_default.success(`Client bundle built (${clientFiles.length} components)`);
3231
+ }
3232
+ } catch (err) {
3233
+ logger_default.error("Client build failed", err);
3234
+ process.exit(1);
3235
+ }
3236
+ const publicDir = resolved.resolvedPublicDir;
3237
+ if (fs8.existsSync(publicDir)) {
3238
+ const publicOutDir = path9.join(outDir, "public");
3239
+ ensureDir(publicOutDir);
3240
+ copyDirRecursive(publicDir, publicOutDir);
3241
+ logger_default.success("Static assets copied");
3242
+ }
3243
+ const manifest = {
3244
+ version: "5.0.0",
3245
+ buildTime: (/* @__PURE__ */ new Date()).toISOString(),
3246
+ routes: routes.appRoutes.map((r) => ({
3247
+ path: r.path,
3248
+ type: r.path.includes(":") ? "dynamic" : "static"
3249
+ })),
3250
+ api: routes.api.map((r) => ({ path: r.path }))
3251
+ };
3252
+ fs8.writeFileSync(path9.join(outDir, "manifest.json"), JSON.stringify(manifest, null, 2));
3253
+ const elapsed = Date.now() - startTime;
3254
+ const totalSize = getDirSize(outDir);
3255
+ logger_default.blank();
3256
+ logger_default.divider();
3257
+ logger_default.blank();
3258
+ routes.appRoutes.forEach((r) => {
3259
+ const type = r.path.includes(":") || r.path.includes("*") ? "dynamic" : "static";
3260
+ logger_default.route(r.path, type);
3261
+ });
3262
+ routes.api.forEach((r) => logger_default.route(r.path, "api"));
3263
+ logger_default.blank();
3264
+ logger_default.build({ time: elapsed });
3265
+ logger_default.info(`Output: ${outDir} (${formatBytes(totalSize)})`);
3266
+ logger_default.blank();
3267
+ }
3268
+ function copyDirRecursive(src, dest) {
3269
+ ensureDir(dest);
3270
+ const entries = fs8.readdirSync(src, { withFileTypes: true });
3271
+ for (const entry of entries) {
3272
+ const srcPath = path9.join(src, entry.name);
3273
+ const destPath = path9.join(dest, entry.name);
3274
+ if (entry.isDirectory()) copyDirRecursive(srcPath, destPath);
3275
+ else fs8.copyFileSync(srcPath, destPath);
3276
+ }
3277
+ }
3278
+ function getDirSize(dir) {
3279
+ let size = 0;
3280
+ if (!fs8.existsSync(dir)) return size;
3281
+ const entries = fs8.readdirSync(dir, { withFileTypes: true });
3282
+ for (const entry of entries) {
3283
+ const fullPath = path9.join(dir, entry.name);
3284
+ if (entry.isDirectory()) size += getDirSize(fullPath);
3285
+ else size += fs8.statSync(fullPath).size;
3286
+ }
3287
+ return size;
3288
+ }
3289
+ export {
3290
+ Image,
3291
+ Island,
3292
+ LayoutContext,
3293
+ Link,
3294
+ LoadStrategy,
3295
+ NotFoundError,
3296
+ PluginHooks,
3297
+ PluginManager,
3298
+ RedirectError,
3299
+ RequestContext,
3300
+ RouteContext,
3301
+ VelixConfigSchema,
3302
+ bindArgs,
3303
+ build,
3304
+ buildRouteTree,
3305
+ cacheManager,
3306
+ callServerAction,
3307
+ cleanDir,
3308
+ composeMiddleware,
3309
+ cookies,
3310
+ copyDir,
3311
+ createIsland,
3312
+ createLazyIsland,
3313
+ createRequestContext,
3314
+ createServer,
3315
+ debounce,
3316
+ defaultConfig,
3317
+ defineConfig,
3318
+ definePlugin,
3319
+ deserializeArgs,
3320
+ ensureDir,
3321
+ escapeHtml,
3322
+ executeAction,
3323
+ findFiles,
3324
+ findRouteLayouts,
3325
+ formAction,
3326
+ formatBytes,
3327
+ formatTime,
3328
+ generateAdvancedHydrationScript,
3329
+ generateHash,
3330
+ generateHydrationScript,
3331
+ generateJsonLd,
3332
+ generateMetadataTags,
3333
+ generateRobotsTxt,
3334
+ generateSitemap,
3335
+ getAction,
3336
+ getMethod,
3337
+ getPathname,
3338
+ getRegisteredIslands,
3339
+ headers,
3340
+ html,
3341
+ hydrate,
3342
+ isClientComponent,
3343
+ isIsland as isIslandComponent,
3344
+ isMethod,
3345
+ isServerComponent,
3346
+ json,
3347
+ jsonLd,
3348
+ loadConfig,
3349
+ loadMiddleware,
3350
+ loadPlugins,
3351
+ logger,
3352
+ matchRoute,
3353
+ mergeMetadata,
3354
+ middlewares,
3355
+ notFound,
3356
+ parseFormData,
3357
+ parseJson,
3358
+ parseSearchParams,
3359
+ pluginManager,
3360
+ preloadResource,
3361
+ redirect,
3362
+ registerAction,
3363
+ resolvePaths,
3364
+ revalidatePath,
3365
+ revalidateTag,
3366
+ router,
3367
+ runMiddleware,
3368
+ serverAction,
3369
+ sleep,
3370
+ tailwindPlugin,
3371
+ text,
3372
+ unstable_cache,
3373
+ use,
3374
+ useActionContext,
3375
+ useActionState,
3376
+ useAsyncData,
3377
+ useFormStatus,
3378
+ useOptimistic,
3379
+ useOptimisticMutation,
3380
+ useParams,
3381
+ usePathname,
3382
+ useQuery,
3383
+ useRequest,
3384
+ useRouter,
3385
+ useVelixAction
3386
+ };
3387
+ //# sourceMappingURL=index.js.map