veryfront 0.0.31 → 0.0.33

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/cli.js CHANGED
@@ -143,7 +143,6 @@ function __loggerResetForTests(options = {}) {
143
143
  var LogLevel, originalConsole, cachedLogLevel, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, logger;
144
144
  var init_logger = __esm({
145
145
  "src/core/utils/logger/logger.ts"() {
146
- "use strict";
147
146
  init_env();
148
147
  LogLevel = /* @__PURE__ */ ((LogLevel2) => {
149
148
  LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
@@ -347,7 +346,6 @@ function getUnoCSSTailwindResetUrl() {
347
346
  var ESM_CDN_BASE, JSDELIVR_CDN_BASE, DENO_STD_BASE, REACT_VERSION_17, REACT_VERSION_18_2, REACT_VERSION_18_3, REACT_VERSION_19_RC, REACT_VERSION_19, REACT_DEFAULT_VERSION, DEFAULT_ALLOWED_CDN_HOSTS, DENO_STD_VERSION, UNOCSS_VERSION;
348
347
  var init_cdn = __esm({
349
348
  "src/core/utils/constants/cdn.ts"() {
350
- "use strict";
351
349
  ESM_CDN_BASE = "https://esm.sh";
352
350
  JSDELIVR_CDN_BASE = "https://cdn.jsdelivr.net";
353
351
  DENO_STD_BASE = "https://deno.land";
@@ -562,8 +560,15 @@ var init_deno = __esm({
562
560
  "deno.json"() {
563
561
  deno_default = {
564
562
  name: "veryfront",
565
- version: "0.0.31",
566
- nodeModulesDir: "auto",
563
+ version: "0.0.33",
564
+ exclude: [
565
+ "npm/",
566
+ "dist/",
567
+ "coverage/",
568
+ "scripts/",
569
+ "examples/",
570
+ "tests/"
571
+ ],
567
572
  exports: {
568
573
  ".": "./src/index.ts",
569
574
  "./cli": "./src/cli/main.ts",
@@ -657,11 +662,13 @@ var init_deno = __esm({
657
662
  unified: "https://esm.sh/unified@11.0.5?dts",
658
663
  ai: "https://esm.sh/ai@5.0.76?deps=react@18.3.1,react-dom@18.3.1",
659
664
  "ai/react": "https://esm.sh/@ai-sdk/react@2.0.59?deps=react@18.3.1,react-dom@18.3.1",
665
+ "@ai-sdk/react": "https://esm.sh/@ai-sdk/react@2.0.59?deps=react@18.3.1,react-dom@18.3.1",
660
666
  "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",
661
667
  "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.4",
662
668
  unocss: "https://esm.sh/unocss@0.59.0",
663
669
  "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",
664
- "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0"
670
+ "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0",
671
+ redis: "npm:redis"
665
672
  },
666
673
  compilerOptions: {
667
674
  jsx: "react-jsx",
@@ -687,8 +694,6 @@ var init_deno = __esm({
687
694
  test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",
688
695
  "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",
689
696
  "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",
690
- "test:batches": "deno run --allow-all scripts/test-batches.ts",
691
- "test:unsafe": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net",
692
697
  "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",
693
698
  "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",
694
699
  "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",
@@ -702,6 +707,7 @@ var init_deno = __esm({
702
707
  "lint:ban-deep-imports": "deno run --allow-read scripts/ban-deep-imports.ts",
703
708
  "lint:ban-internal-root-imports": "deno run --allow-read scripts/ban-internal-root-imports.ts",
704
709
  "lint:check-awaits": "deno run --allow-read scripts/check-unawaited-promises.ts",
710
+ "lint:platform": "deno run --allow-read scripts/lint-platform-agnostic.ts",
705
711
  "check:circular": "deno run -A jsr:@cunarist/deno-circular-deps src/index.ts"
706
712
  },
707
713
  lint: {
@@ -750,6 +756,10 @@ var init_deno = __esm({
750
756
  });
751
757
 
752
758
  // src/platform/compat/runtime.ts
759
+ function isNodeRuntime() {
760
+ const _global = globalThis;
761
+ return typeof Deno === "undefined" && typeof _global.process !== "undefined" && !!_global.process?.versions?.node;
762
+ }
753
763
  var isDeno, isNode, isBun, isCloudflare;
754
764
  var init_runtime = __esm({
755
765
  "src/platform/compat/runtime.ts"() {
@@ -768,80 +778,125 @@ __export(process_exports, {
768
778
  cwd: () => cwd,
769
779
  deleteEnv: () => deleteEnv,
770
780
  env: () => env,
781
+ execPath: () => execPath,
771
782
  exit: () => exit,
772
783
  getArgs: () => getArgs,
773
784
  getEnv: () => getEnv,
774
785
  getNetworkInterfaces: () => getNetworkInterfaces,
775
786
  getRuntimeVersion: () => getRuntimeVersion,
787
+ getStdout: () => getStdout,
776
788
  isInteractive: () => isInteractive,
777
789
  memoryUsage: () => memoryUsage,
790
+ onSignal: () => onSignal,
778
791
  pid: () => pid,
779
792
  ppid: () => ppid,
780
- setEnv: () => setEnv
793
+ requireEnv: () => requireEnv,
794
+ setEnv: () => setEnv,
795
+ unrefTimer: () => unrefTimer,
796
+ uptime: () => uptime
781
797
  });
782
- import process2 from "node:process";
783
798
  function getArgs() {
784
799
  if (isDeno) {
785
800
  return Deno.args;
786
801
  }
787
- return process2.argv.slice(2);
802
+ if (hasNodeProcess2) {
803
+ return nodeProcess.argv.slice(2);
804
+ }
805
+ return [];
788
806
  }
789
807
  function exit(code) {
790
808
  if (isDeno) {
791
809
  Deno.exit(code);
792
810
  }
793
- process2.exit(code);
811
+ if (hasNodeProcess2) {
812
+ nodeProcess.exit(code);
813
+ }
814
+ throw new Error("exit() is not supported in this runtime");
794
815
  }
795
816
  function cwd() {
796
817
  if (isDeno) {
797
818
  return Deno.cwd();
798
819
  }
799
- return process2.cwd();
820
+ if (hasNodeProcess2) {
821
+ return nodeProcess.cwd();
822
+ }
823
+ throw new Error("cwd() is not supported in this runtime");
800
824
  }
801
825
  function chdir(directory) {
802
826
  if (isDeno) {
803
827
  Deno.chdir(directory);
804
828
  } else {
805
- process2.chdir(directory);
829
+ if (hasNodeProcess2) {
830
+ nodeProcess.chdir(directory);
831
+ return;
832
+ }
833
+ throw new Error("chdir() is not supported in this runtime");
806
834
  }
807
835
  }
808
836
  function env() {
809
837
  if (isDeno) {
810
838
  return Deno.env.toObject();
811
839
  }
812
- return process2.env;
840
+ if (hasNodeProcess2) {
841
+ return nodeProcess.env;
842
+ }
843
+ return {};
813
844
  }
814
845
  function getEnv(key) {
815
846
  if (isDeno) {
816
847
  return Deno.env.get(key);
817
848
  }
818
- return process2.env[key];
849
+ if (hasNodeProcess2) {
850
+ return nodeProcess.env[key];
851
+ }
852
+ return void 0;
853
+ }
854
+ function requireEnv(key) {
855
+ const value = getEnv(key);
856
+ if (value === void 0) {
857
+ throw new Error(`Required environment variable "${key}" is not set`);
858
+ }
859
+ return value;
819
860
  }
820
861
  function setEnv(key, value) {
821
862
  if (isDeno) {
822
863
  Deno.env.set(key, value);
823
864
  } else {
824
- process2.env[key] = value;
865
+ if (hasNodeProcess2) {
866
+ nodeProcess.env[key] = value;
867
+ return;
868
+ }
869
+ throw new Error("setEnv() is not supported in this runtime");
825
870
  }
826
871
  }
827
872
  function deleteEnv(key) {
828
873
  if (isDeno) {
829
874
  Deno.env.delete(key);
830
875
  } else {
831
- delete process2.env[key];
876
+ if (hasNodeProcess2) {
877
+ delete nodeProcess.env[key];
878
+ return;
879
+ }
880
+ throw new Error("deleteEnv() is not supported in this runtime");
832
881
  }
833
882
  }
834
883
  function pid() {
835
884
  if (isDeno) {
836
885
  return Deno.pid;
837
886
  }
838
- return process2.pid;
887
+ if (hasNodeProcess2) {
888
+ return nodeProcess.pid;
889
+ }
890
+ return 0;
839
891
  }
840
892
  function ppid() {
841
893
  if (isDeno && "ppid" in Deno) {
842
894
  return Deno.ppid || 0;
843
895
  }
844
- return process2.ppid || 0;
896
+ if (hasNodeProcess2) {
897
+ return nodeProcess.ppid || 0;
898
+ }
899
+ return 0;
845
900
  }
846
901
  function memoryUsage() {
847
902
  if (isDeno) {
@@ -853,7 +908,10 @@ function memoryUsage() {
853
908
  external: usage2.external
854
909
  };
855
910
  }
856
- const usage = process2.memoryUsage();
911
+ if (!hasNodeProcess2) {
912
+ throw new Error("memoryUsage() is not supported in this runtime");
913
+ }
914
+ const usage = nodeProcess.memoryUsage();
857
915
  return {
858
916
  rss: usage.rss,
859
917
  heapTotal: usage.heapTotal,
@@ -865,7 +923,10 @@ function isInteractive() {
865
923
  if (isDeno) {
866
924
  return Deno.stdin.isTerminal();
867
925
  }
868
- return process2.stdin.isTTY ?? false;
926
+ if (hasNodeProcess2) {
927
+ return nodeProcess.stdin.isTTY ?? false;
928
+ }
929
+ return false;
869
930
  }
870
931
  async function getNetworkInterfaces() {
871
932
  if (isDeno) {
@@ -876,6 +937,9 @@ async function getNetworkInterfaces() {
876
937
  family: iface.family
877
938
  }));
878
939
  }
940
+ if (!hasNodeProcess2) {
941
+ throw new Error("networkInterfaces() is not supported in this runtime");
942
+ }
879
943
  const os = await import("node:os");
880
944
  const interfaces = os.networkInterfaces();
881
945
  const result = [];
@@ -899,12 +963,68 @@ function getRuntimeVersion() {
899
963
  if ("Bun" in globalThis) {
900
964
  return `Bun ${globalThis.Bun.version}`;
901
965
  }
902
- return `Node.js ${process2.version}`;
966
+ if (hasNodeProcess2) {
967
+ return `Node.js ${nodeProcess.version}`;
968
+ }
969
+ return "unknown";
970
+ }
971
+ function onSignal(signal, handler) {
972
+ if (isDeno) {
973
+ Deno.addSignalListener(signal, handler);
974
+ } else if (hasNodeProcess2) {
975
+ nodeProcess.on(signal, handler);
976
+ }
977
+ }
978
+ function unrefTimer(timerId) {
979
+ if (isDeno) {
980
+ Deno.unrefTimer(timerId);
981
+ } else if (timerId && typeof timerId === "object" && "unref" in timerId) {
982
+ timerId.unref();
983
+ }
903
984
  }
985
+ function execPath() {
986
+ if (isDeno) {
987
+ return Deno.execPath();
988
+ }
989
+ if (hasNodeProcess2) {
990
+ return nodeProcess.execPath;
991
+ }
992
+ return "";
993
+ }
994
+ function uptime() {
995
+ if (isDeno) {
996
+ return Deno.osUptime?.() ?? 0;
997
+ }
998
+ if (hasNodeProcess2) {
999
+ return nodeProcess.uptime?.() ?? 0;
1000
+ }
1001
+ return 0;
1002
+ }
1003
+ function getStdout() {
1004
+ if (isDeno) {
1005
+ const encoder = new TextEncoder();
1006
+ return {
1007
+ write: (data) => {
1008
+ Deno.stdout.writeSync(encoder.encode(data));
1009
+ }
1010
+ };
1011
+ }
1012
+ if (hasNodeProcess2 && nodeProcess.stdout) {
1013
+ return {
1014
+ write: (data) => {
1015
+ nodeProcess.stdout.write(data);
1016
+ }
1017
+ };
1018
+ }
1019
+ return null;
1020
+ }
1021
+ var nodeProcess, hasNodeProcess2;
904
1022
  var init_process = __esm({
905
1023
  "src/platform/compat/process.ts"() {
906
1024
  "use strict";
907
1025
  init_runtime();
1026
+ nodeProcess = globalThis.process;
1027
+ hasNodeProcess2 = !!nodeProcess?.versions?.node;
908
1028
  }
909
1029
  });
910
1030
 
@@ -1446,13 +1566,11 @@ var init_feature_flags = __esm({
1446
1566
 
1447
1567
  // src/core/utils/platform.ts
1448
1568
  function isCompiledBinary() {
1449
- const hasDeno = typeof Deno !== "undefined";
1450
- const hasExecPath = hasDeno && typeof Deno.execPath === "function";
1451
- if (!hasExecPath)
1569
+ if (!isDeno)
1452
1570
  return false;
1453
1571
  try {
1454
- const execPath = Deno.execPath();
1455
- return execPath.includes("veryfront");
1572
+ const path = execPath();
1573
+ return path.includes("veryfront");
1456
1574
  } catch {
1457
1575
  return false;
1458
1576
  }
@@ -1460,6 +1578,8 @@ function isCompiledBinary() {
1460
1578
  var init_platform = __esm({
1461
1579
  "src/core/utils/platform.ts"() {
1462
1580
  "use strict";
1581
+ init_runtime();
1582
+ init_process();
1463
1583
  }
1464
1584
  });
1465
1585
 
@@ -4279,12 +4399,12 @@ function createWatcherIterator(eventQueue, _getResolver, setResolver, isClosed,
4279
4399
  const event = eventQueue.shift();
4280
4400
  return Promise.resolve({ done: false, value: event });
4281
4401
  }
4282
- return new Promise((resolve5) => {
4402
+ return new Promise((resolve6) => {
4283
4403
  if (isClosed() || isAborted()) {
4284
- resolve5({ done: true, value: void 0 });
4404
+ resolve6({ done: true, value: void 0 });
4285
4405
  return;
4286
4406
  }
4287
- setResolver(resolve5);
4407
+ setResolver(resolve6);
4288
4408
  });
4289
4409
  },
4290
4410
  return() {
@@ -4379,9 +4499,9 @@ var init_filesystem_adapter = __esm({
4379
4499
  }
4380
4500
  async makeTempDir(prefix) {
4381
4501
  const { mkdtemp } = await import("node:fs/promises");
4382
- const { join: join13 } = await import("node:path");
4502
+ const { join: join14 } = await import("node:path");
4383
4503
  const { tmpdir } = await import("node:os");
4384
- return await mkdtemp(join13(tmpdir(), prefix));
4504
+ return await mkdtemp(join14(tmpdir(), prefix));
4385
4505
  }
4386
4506
  watch(paths, options) {
4387
4507
  const pathArray = Array.isArray(paths) ? paths : [paths];
@@ -4442,20 +4562,20 @@ var init_filesystem_adapter = __esm({
4442
4562
  });
4443
4563
 
4444
4564
  // src/platform/adapters/node/environment-adapter.ts
4445
- import process3 from "node:process";
4565
+ import process2 from "node:process";
4446
4566
  var NodeEnvironmentAdapter;
4447
4567
  var init_environment_adapter = __esm({
4448
4568
  "src/platform/adapters/node/environment-adapter.ts"() {
4449
4569
  "use strict";
4450
4570
  NodeEnvironmentAdapter = class {
4451
4571
  get(key) {
4452
- return process3.env[key];
4572
+ return process2.env[key];
4453
4573
  }
4454
4574
  set(key, value) {
4455
- process3.env[key] = value;
4575
+ process2.env[key] = value;
4456
4576
  }
4457
4577
  toObject() {
4458
- return { ...process3.env };
4578
+ return { ...process2.env };
4459
4579
  }
4460
4580
  };
4461
4581
  }
@@ -4467,8 +4587,8 @@ function createRequestId(req) {
4467
4587
  return typeof key === "string" ? key : (Array.isArray(key) ? key[0] : "") || crypto.randomUUID();
4468
4588
  }
4469
4589
  function registerWebSocketUpgrade(requestId) {
4470
- return new Promise((resolve5, reject) => {
4471
- pendingWebSocketUpgrades.set(requestId, { resolve: resolve5, reject });
4590
+ return new Promise((resolve6, reject) => {
4591
+ pendingWebSocketUpgrades.set(requestId, { resolve: resolve6, reject });
4472
4592
  setTimeout(() => {
4473
4593
  if (pendingWebSocketUpgrades.has(requestId)) {
4474
4594
  pendingWebSocketUpgrades.delete(requestId);
@@ -4557,10 +4677,10 @@ async function createNodeServer(handler, options = {}) {
4557
4677
  server.close();
4558
4678
  });
4559
4679
  }
4560
- return new Promise((resolve5) => {
4680
+ return new Promise((resolve6) => {
4561
4681
  server.listen(port, hostname, () => {
4562
4682
  onListen?.({ hostname, port });
4563
- resolve5(new NodeServer(server, hostname, port));
4683
+ resolve6(new NodeServer(server, hostname, port));
4564
4684
  });
4565
4685
  });
4566
4686
  }
@@ -4578,12 +4698,12 @@ var init_http_server = __esm({
4578
4698
  this.port = port;
4579
4699
  }
4580
4700
  stop() {
4581
- return new Promise((resolve5) => {
4701
+ return new Promise((resolve6) => {
4582
4702
  if (wsServer) {
4583
4703
  wsServer.close();
4584
4704
  wsServer = null;
4585
4705
  }
4586
- this.server.close(() => resolve5());
4706
+ this.server.close(() => resolve6());
4587
4707
  });
4588
4708
  }
4589
4709
  get addr() {
@@ -4893,9 +5013,9 @@ var init_filesystem_adapter2 = __esm({
4893
5013
  }
4894
5014
  async makeTempDir(prefix) {
4895
5015
  const { mkdtemp } = await import("node:fs/promises");
4896
- const { join: join13 } = await import("node:path");
5016
+ const { join: join14 } = await import("node:path");
4897
5017
  const { tmpdir } = await import("node:os");
4898
- return await mkdtemp(join13(tmpdir(), prefix));
5018
+ return await mkdtemp(join14(tmpdir(), prefix));
4899
5019
  }
4900
5020
  watch(paths, options) {
4901
5021
  const pathArray = Array.isArray(paths) ? paths : [paths];
@@ -5448,7 +5568,9 @@ var init_registry = __esm({
5448
5568
  "Cloudflare Workers detected but requires manual initialization. Use: await runtime.set(createCloudflareAdapter(env))"
5449
5569
  );
5450
5570
  }
5451
- return "node";
5571
+ throw new Error(
5572
+ "Unsupported runtime detected. Supported runtimes: deno, node, bun. For Cloudflare Workers, call runtime.set(createCloudflareAdapter(env))."
5573
+ );
5452
5574
  }
5453
5575
  /**
5454
5576
  * Initialize the adapter
@@ -5475,7 +5597,6 @@ __export(detect_exports, {
5475
5597
  nodeAdapter: () => nodeAdapter,
5476
5598
  runtime: () => runtime
5477
5599
  });
5478
- import process4 from "node:process";
5479
5600
  function isDeno2(global) {
5480
5601
  return "Deno" in global && typeof global.Deno === "object";
5481
5602
  }
@@ -5492,7 +5613,8 @@ function detectRuntime() {
5492
5613
  if (isBun2(globalThis)) {
5493
5614
  return "bun";
5494
5615
  }
5495
- if (process4?.versions?.node) {
5616
+ const globalProcess2 = globalThis.process;
5617
+ if (globalProcess2?.versions?.node) {
5496
5618
  return "node";
5497
5619
  }
5498
5620
  if (isCloudflare2(globalThis)) {
@@ -5780,8 +5902,8 @@ var init_lru_list_manager = __esm({
5780
5902
  var EvictionManager;
5781
5903
  var init_eviction_manager = __esm({
5782
5904
  "src/core/utils/cache/eviction/eviction-manager.ts"() {
5905
+ "use strict";
5783
5906
  EvictionManager = class {
5784
- onEvict;
5785
5907
  constructor(options = {}) {
5786
5908
  this.onEvict = options.onEvict;
5787
5909
  }
@@ -6217,17 +6339,14 @@ function isLruIntervalDisabled() {
6217
6339
  if (globalThis.__vfDisableLruInterval === true) {
6218
6340
  return true;
6219
6341
  }
6220
- try {
6221
- return process.env.VF_DISABLE_LRU_INTERVAL === "1";
6222
- } catch {
6223
- return false;
6224
- }
6342
+ return getEnv("VF_DISABLE_LRU_INTERVAL") === "1";
6225
6343
  }
6226
6344
  var MemoryCacheStore;
6227
6345
  var init_memory_store = __esm({
6228
6346
  "src/rendering/cache/stores/memory-store.ts"() {
6229
6347
  "use strict";
6230
6348
  init_lru_wrapper();
6349
+ init_process();
6231
6350
  MemoryCacheStore = class {
6232
6351
  constructor(options = {}) {
6233
6352
  const disableIntervals = isLruIntervalDisabled();
@@ -8545,10 +8664,10 @@ export default agent({
8545
8664
  import { prompt } from 'veryfront/ai';
8546
8665
 
8547
8666
  export default prompt({
8548
- name: 'assistant',
8667
+ id: 'assistant',
8549
8668
  description: 'System prompt for the AI assistant',
8550
8669
 
8551
- getContent: () => \`You are a helpful AI assistant with access to weather information.
8670
+ content: \`You are a helpful AI assistant with access to weather information.
8552
8671
 
8553
8672
  When users ask about the weather:
8554
8673
  1. Use the getWeather tool to fetch current conditions
@@ -8631,27 +8750,17 @@ export default function RootLayout({
8631
8750
  content: `/**
8632
8751
  * Chat API Route
8633
8752
  *
8634
- * Uses auto-discovered agent from ai/agents/ directory.
8635
- * The agent, tools, and prompts are all auto-registered by veryfront.
8753
+ * Imports the agent directly from ai/agents/ directory.
8754
+ * This ensures the agent is bundled with the route and available at runtime.
8636
8755
  */
8637
8756
 
8638
- import { agentRegistry } from 'veryfront/ai';
8757
+ import assistantAgent from '../../../ai/agents/assistant';
8639
8758
 
8640
8759
  export async function POST(request: Request) {
8641
8760
  const { messages } = await request.json();
8642
8761
 
8643
- // Get the auto-discovered agent from registry
8644
- const chatAgent = agentRegistry.get('assistant');
8645
-
8646
- if (!chatAgent) {
8647
- return new Response(
8648
- JSON.stringify({ error: 'Agent not found. Make sure ai/agents/assistant.ts exists.' }),
8649
- { status: 500, headers: { 'Content-Type': 'application/json' } }
8650
- );
8651
- }
8652
-
8653
8762
  // Stream response using the agent
8654
- const result = await chatAgent.stream({ messages });
8763
+ const result = await assistantAgent.stream({ messages });
8655
8764
 
8656
8765
  // Return Vercel AI SDK compatible streaming response
8657
8766
  return result.toDataStreamResponse();
@@ -9087,13 +9196,10 @@ function applyEnvFromAdapter(config, envAdapter) {
9087
9196
  }
9088
9197
  function applyEnvFromDeno(config) {
9089
9198
  try {
9090
- const denoEnv = globalThis.Deno?.env;
9091
- if (!denoEnv)
9092
- return;
9093
- config.enabled = denoEnv.get("OTEL_TRACES_ENABLED") === "true" || denoEnv.get("VERYFRONT_OTEL") === "1" || config.enabled;
9094
- config.serviceName = denoEnv.get("OTEL_SERVICE_NAME") || config.serviceName;
9095
- config.endpoint = denoEnv.get("OTEL_EXPORTER_OTLP_ENDPOINT") || denoEnv.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") || config.endpoint;
9096
- const exporterType = denoEnv.get("OTEL_TRACES_EXPORTER");
9199
+ config.enabled = getEnv("OTEL_TRACES_ENABLED") === "true" || getEnv("VERYFRONT_OTEL") === "1" || config.enabled;
9200
+ config.serviceName = getEnv("OTEL_SERVICE_NAME") || config.serviceName;
9201
+ config.endpoint = getEnv("OTEL_EXPORTER_OTLP_ENDPOINT") || getEnv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") || config.endpoint;
9202
+ const exporterType = getEnv("OTEL_TRACES_EXPORTER");
9097
9203
  if (isValidExporter(exporterType)) {
9098
9204
  config.exporter = exporterType;
9099
9205
  }
@@ -9107,6 +9213,7 @@ var DEFAULT_CONFIG2;
9107
9213
  var init_config5 = __esm({
9108
9214
  "src/observability/tracing/config.ts"() {
9109
9215
  "use strict";
9216
+ init_process();
9110
9217
  DEFAULT_CONFIG2 = {
9111
9218
  enabled: false,
9112
9219
  exporter: "console",
@@ -9406,14 +9513,11 @@ function loadConfig2(config, adapter) {
9406
9513
  }
9407
9514
  } else {
9408
9515
  try {
9409
- const env2 = process.env;
9410
- if (env2) {
9411
- finalConfig.enabled = env2.OTEL_METRICS_ENABLED === "true" || env2.VERYFRONT_OTEL === "1" || finalConfig.enabled;
9412
- finalConfig.endpoint = env2.OTEL_EXPORTER_OTLP_ENDPOINT || env2.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT || finalConfig.endpoint;
9413
- const exporterType = env2.OTEL_METRICS_EXPORTER;
9414
- if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {
9415
- finalConfig.exporter = exporterType;
9416
- }
9516
+ finalConfig.enabled = getEnv("OTEL_METRICS_ENABLED") === "true" || getEnv("VERYFRONT_OTEL") === "1" || finalConfig.enabled;
9517
+ finalConfig.endpoint = getEnv("OTEL_EXPORTER_OTLP_ENDPOINT") || getEnv("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT") || finalConfig.endpoint;
9518
+ const exporterType = getEnv("OTEL_METRICS_EXPORTER");
9519
+ if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {
9520
+ finalConfig.exporter = exporterType;
9417
9521
  }
9418
9522
  } catch {
9419
9523
  }
@@ -9422,10 +9526,7 @@ function loadConfig2(config, adapter) {
9422
9526
  }
9423
9527
  function getMemoryUsage() {
9424
9528
  try {
9425
- if (process?.memoryUsage) {
9426
- return process.memoryUsage();
9427
- }
9428
- return null;
9529
+ return memoryUsage();
9429
9530
  } catch {
9430
9531
  return null;
9431
9532
  }
@@ -9434,6 +9535,8 @@ var DEFAULT_METRICS_COLLECT_INTERVAL_MS2, DEFAULT_CONFIG3;
9434
9535
  var init_config6 = __esm({
9435
9536
  "src/observability/metrics/config.ts"() {
9436
9537
  "use strict";
9538
+ init_process();
9539
+ init_process();
9437
9540
  DEFAULT_METRICS_COLLECT_INTERVAL_MS2 = 6e4;
9438
9541
  DEFAULT_CONFIG3 = {
9439
9542
  enabled: false,
@@ -10552,6 +10655,7 @@ var init_constants3 = __esm({
10552
10655
  "src/security/http/cors/constants.ts"() {
10553
10656
  "use strict";
10554
10657
  init_config();
10658
+ init_process();
10555
10659
  DEFAULT_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
10556
10660
  DEFAULT_HEADERS = ["Content-Type", "Authorization"];
10557
10661
  DEFAULT_MAX_AGE = 86400;
@@ -11471,23 +11575,19 @@ function encodeBase64(value) {
11471
11575
  var AuthHandler;
11472
11576
  var init_auth = __esm({
11473
11577
  "src/security/http/auth.ts"() {
11474
- "use strict";
11475
11578
  init_base_handler();
11476
11579
  init_veryfront_error();
11477
11580
  AuthHandler = class extends BaseHandler {
11478
- constructor() {
11479
- super(...arguments);
11480
- this.metadata = {
11481
- name: "AuthHandler",
11482
- priority: 0,
11483
- // CRITICAL priority - runs first
11484
- patterns: []
11485
- // Checks all requests
11486
- };
11487
- this.basicUser = null;
11488
- this.basicPass = null;
11489
- this.bearerToken = null;
11490
- }
11581
+ metadata = {
11582
+ name: "AuthHandler",
11583
+ priority: 0,
11584
+ // CRITICAL priority - runs first
11585
+ patterns: []
11586
+ // Checks all requests
11587
+ };
11588
+ basicUser = null;
11589
+ basicPass = null;
11590
+ bearerToken = null;
11491
11591
  handle(req, ctx) {
11492
11592
  this.loadAuthConfig(ctx);
11493
11593
  if (req.method.toUpperCase() === "OPTIONS") {
@@ -11544,7 +11644,6 @@ var init_auth = __esm({
11544
11644
  var SecurityConfigLoader;
11545
11645
  var init_config7 = __esm({
11546
11646
  "src/security/http/config.ts"() {
11547
- "use strict";
11548
11647
  init_config();
11549
11648
  init_utils();
11550
11649
  init_security_handler();
@@ -11552,11 +11651,11 @@ var init_config7 = __esm({
11552
11651
  constructor(projectDir, adapter) {
11553
11652
  this.projectDir = projectDir;
11554
11653
  this.adapter = adapter;
11555
- this.securityConfig = null;
11556
- this.cspUserHeader = null;
11557
- this.isLoaded = false;
11558
- this.loadPromise = null;
11559
11654
  }
11655
+ securityConfig = null;
11656
+ cspUserHeader = null;
11657
+ isLoaded = false;
11658
+ loadPromise = null;
11560
11659
  /**
11561
11660
  * Ensure security config is loaded (singleton pattern)
11562
11661
  */
@@ -11740,9 +11839,9 @@ function resolvePathSegments(path) {
11740
11839
  const isAbs = normalized.startsWith("/");
11741
11840
  return isAbs ? `/${resolved.join("/")}` : resolved.join("/");
11742
11841
  }
11743
- function joinPaths(base, relative4) {
11842
+ function joinPaths(base, relative5) {
11744
11843
  const normalizedBase = normalizeSeparators(base).replace(/\/$/, "");
11745
- const normalizedRelative = normalizeSeparators(relative4).replace(/^\//, "");
11844
+ const normalizedRelative = normalizeSeparators(relative5).replace(/^\//, "");
11746
11845
  return `${normalizedBase}/${normalizedRelative}`;
11747
11846
  }
11748
11847
  function isWithinDirectory2(baseDir, targetPath) {
@@ -12607,7 +12706,14 @@ async function loadHandlerModule(options) {
12607
12706
  const { projectDir, modulePath, adapter, config } = options;
12608
12707
  const fs15 = createFileSystem();
12609
12708
  try {
12610
- const module = modulePath.endsWith(".js") ? await loadJSModule(modulePath) : await loadAndTranspileModule(modulePath, projectDir, adapter, fs15, config);
12709
+ let module;
12710
+ if (modulePath.endsWith(".js")) {
12711
+ module = await loadJSModule(modulePath);
12712
+ } else if (isDeno) {
12713
+ module = await loadTSModuleDirect(modulePath);
12714
+ } else {
12715
+ module = await loadAndTranspileModule(modulePath, projectDir, adapter, fs15, config);
12716
+ }
12611
12717
  return extractAPIRouteHandlers(module);
12612
12718
  } catch (error2) {
12613
12719
  const errorMsg = error2 instanceof Error ? error2.message : String(error2);
@@ -12618,6 +12724,12 @@ async function loadHandlerModule(options) {
12618
12724
  }));
12619
12725
  }
12620
12726
  }
12727
+ async function loadTSModuleDirect(modulePath) {
12728
+ const cacheBuster = `?v=${Date.now()}`;
12729
+ const url = modulePath.startsWith("file://") ? `${modulePath}${cacheBuster}` : `file://${modulePath}${cacheBuster}`;
12730
+ serverLogger.debug(`[API] Direct import (Deno): ${url}`);
12731
+ return await import(url);
12732
+ }
12621
12733
  async function loadJSModule(modulePath) {
12622
12734
  return await import(`file://${modulePath}`);
12623
12735
  }
@@ -12826,13 +12938,9 @@ async function loadModuleFromCode(code, _adapter, projectDir, fs15) {
12826
12938
  await fs15.remove(tempDir, { recursive: true });
12827
12939
  }
12828
12940
  }
12829
- function isNodeRuntime() {
12830
- const _global2 = globalThis;
12831
- return typeof Deno === "undefined" && typeof _global2.process !== "undefined" && !!_global2.process?.versions?.node;
12832
- }
12833
12941
  async function rewriteExternalImports(code, projectDir, fs15) {
12834
12942
  let transformed = code;
12835
- if (isNodeRuntime()) {
12943
+ if (isNode) {
12836
12944
  try {
12837
12945
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
12838
12946
  serverLogger.debug(`[API] Rewriting external imports for Node.js, projectDir: ${projectDir}`);
@@ -12980,7 +13088,7 @@ async function rewriteExternalImports(code, projectDir, fs15) {
12980
13088
  },
12981
13089
  { pattern: /import\s*\(\s*["']zod["']\s*\)/g, replacement: 'import("npm:zod@latest")' }
12982
13090
  ];
12983
- if (typeof Deno !== "undefined") {
13091
+ if (isDeno) {
12984
13092
  for (const { pattern, replacement } of externalPackages) {
12985
13093
  transformed = transformed.replace(pattern, replacement);
12986
13094
  }
@@ -13022,6 +13130,7 @@ var init_loader2 = __esm({
13022
13130
  init_veryfront_error();
13023
13131
  init_fs();
13024
13132
  init_path_helper();
13133
+ init_runtime();
13025
13134
  }
13026
13135
  });
13027
13136
 
@@ -13677,7 +13786,7 @@ async function requestWithRetry(url, apiToken, retryConfig, options = {}) {
13677
13786
  delay,
13678
13787
  error: lastError.message
13679
13788
  });
13680
- await new Promise((resolve5) => setTimeout(resolve5, delay));
13789
+ await new Promise((resolve6) => setTimeout(resolve6, delay));
13681
13790
  }
13682
13791
  }
13683
13792
  }
@@ -14803,8 +14912,8 @@ var init_templates2 = __esm({
14803
14912
  padding: 0;
14804
14913
  color: inherit;
14805
14914
  }`;
14806
- CLIENT_ROUTER_BUNDLE = 'var __defProp = Object.defineProperty;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __esm = (fn, res) => function __init() {\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n};\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/core/utils/runtime-guards.ts\nfunction hasDenoRuntime(global) {\n return typeof global === "object" && global !== null && "Deno" in global && typeof global.Deno?.env?.get === "function";\n}\nfunction hasNodeProcess(global) {\n return typeof global === "object" && global !== null && "process" in global && typeof global.process?.env === "object";\n}\nfunction hasBunRuntime(global) {\n return typeof global === "object" && global !== null && "Bun" in global && typeof global.Bun !== "undefined";\n}\nvar init_runtime_guards = __esm({\n "src/core/utils/runtime-guards.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/logger/env.ts\nfunction getEnvironmentVariable(name) {\n try {\n if (typeof Deno !== "undefined" && hasDenoRuntime(globalThis)) {\n const value = globalThis.Deno?.env.get(name);\n return value === "" ? void 0 : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = globalThis.process?.env[name];\n return value === "" ? void 0 : value;\n }\n } catch {\n return void 0;\n }\n return void 0;\n}\nfunction isTestEnvironment() {\n return getEnvironmentVariable("NODE_ENV") === "test";\n}\nfunction isProductionEnvironment() {\n return getEnvironmentVariable("NODE_ENV") === "production";\n}\nfunction isDevelopmentEnvironment() {\n const env = getEnvironmentVariable("NODE_ENV");\n return env === "development" || env === void 0;\n}\nvar init_env = __esm({\n "src/core/utils/logger/env.ts"() {\n "use strict";\n init_runtime_guards();\n }\n});\n\n// src/core/utils/logger/logger.ts\nfunction resolveLogLevel(force = false) {\n if (force || cachedLogLevel === void 0) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\nfunction parseLogLevel(levelString) {\n if (!levelString)\n return void 0;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case "DEBUG":\n return 0 /* DEBUG */;\n case "WARN":\n return 2 /* WARN */;\n case "ERROR":\n return 3 /* ERROR */;\n case "INFO":\n return 1 /* INFO */;\n default:\n return void 0;\n }\n}\nfunction createLogger(prefix) {\n const logger2 = new ConsoleLogger(prefix);\n trackedLoggers.add(logger2);\n return logger2;\n}\nfunction __loggerResetForTests(options = {}) {\n const updatedLevel = resolveLogLevel(true);\n for (const instance of trackedLoggers) {\n instance.setLevel(updatedLevel);\n }\n if (options.restoreConsole) {\n console.debug = originalConsole.debug;\n console.log = originalConsole.log;\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n }\n}\nvar LogLevel, originalConsole, cachedLogLevel, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, logger;\nvar init_logger = __esm({\n "src/core/utils/logger/logger.ts"() {\n "use strict";\n init_env();\n LogLevel = /* @__PURE__ */ ((LogLevel2) => {\n LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";\n LogLevel2[LogLevel2["INFO"] = 1] = "INFO";\n LogLevel2[LogLevel2["WARN"] = 2] = "WARN";\n LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";\n return LogLevel2;\n })(LogLevel || {});\n originalConsole = {\n debug: console.debug,\n log: console.log,\n warn: console.warn,\n error: console.error\n };\n ConsoleLogger = class {\n constructor(prefix, level = resolveLogLevel()) {\n this.prefix = prefix;\n this.level = level;\n }\n setLevel(level) {\n this.level = level;\n }\n getLevel() {\n return this.level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n async time(label, fn) {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error2) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error2);\n throw error2;\n }\n }\n };\n getDefaultLevel = () => {\n const envLevel = getEnvironmentVariable("LOG_LEVEL");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== void 0)\n return parsedLevel;\n const debugFlag = getEnvironmentVariable("VERYFRONT_DEBUG");\n if (debugFlag === "1" || debugFlag === "true")\n return 0 /* DEBUG */;\n return 1 /* INFO */;\n };\n trackedLoggers = /* @__PURE__ */ new Set();\n cliLogger = createLogger("CLI");\n serverLogger = createLogger("SERVER");\n rendererLogger = createLogger("RENDERER");\n bundlerLogger = createLogger("BUNDLER");\n agentLogger = createLogger("AGENT");\n logger = createLogger("VERYFRONT");\n }\n});\n\n// src/core/utils/logger/index.ts\nvar init_logger2 = __esm({\n "src/core/utils/logger/index.ts"() {\n "use strict";\n init_logger();\n init_env();\n }\n});\n\n// src/core/utils/constants/build.ts\nvar DEFAULT_BUILD_CONCURRENCY, IMAGE_OPTIMIZATION;\nvar init_build = __esm({\n "src/core/utils/constants/build.ts"() {\n "use strict";\n DEFAULT_BUILD_CONCURRENCY = 4;\n IMAGE_OPTIMIZATION = {\n DEFAULT_SIZES: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\n DEFAULT_QUALITY: 80\n };\n }\n});\n\n// src/core/utils/constants/cache.ts\nvar SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, MS_PER_SECOND, DEFAULT_LRU_MAX_ENTRIES, COMPONENT_LOADER_MAX_ENTRIES, COMPONENT_LOADER_TTL_MS, MDX_RENDERER_MAX_ENTRIES, MDX_RENDERER_TTL_MS, RENDERER_CORE_MAX_ENTRIES, RENDERER_CORE_TTL_MS, TSX_LAYOUT_MAX_ENTRIES, TSX_LAYOUT_TTL_MS, DATA_FETCHING_MAX_ENTRIES, DATA_FETCHING_TTL_MS, MDX_CACHE_TTL_PRODUCTION_MS, MDX_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_CACHE_TTL_PRODUCTION_MS, BUNDLE_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_MANIFEST_PROD_TTL_MS, BUNDLE_MANIFEST_DEV_TTL_MS, RSC_MANIFEST_CACHE_TTL_MS, SERVER_ACTION_DEFAULT_TTL_SEC, DENO_KV_SAFE_SIZE_LIMIT_BYTES, HTTP_CACHE_SHORT_MAX_AGE_SEC, HTTP_CACHE_MEDIUM_MAX_AGE_SEC, HTTP_CACHE_LONG_MAX_AGE_SEC, ONE_DAY_MS, CACHE_CLEANUP_INTERVAL_MS, LRU_DEFAULT_MAX_ENTRIES, LRU_DEFAULT_MAX_SIZE_BYTES, CLEANUP_INTERVAL_MULTIPLIER;\nvar init_cache = __esm({\n "src/core/utils/constants/cache.ts"() {\n "use strict";\n SECONDS_PER_MINUTE = 60;\n MINUTES_PER_HOUR = 60;\n HOURS_PER_DAY = 24;\n MS_PER_SECOND = 1e3;\n DEFAULT_LRU_MAX_ENTRIES = 100;\n COMPONENT_LOADER_MAX_ENTRIES = 100;\n COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_RENDERER_MAX_ENTRIES = 200;\n MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n RENDERER_CORE_MAX_ENTRIES = 100;\n RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n TSX_LAYOUT_MAX_ENTRIES = 50;\n TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n DATA_FETCHING_MAX_ENTRIES = 200;\n DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n RSC_MANIFEST_CACHE_TTL_MS = 5e3;\n SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\n DENO_KV_SAFE_SIZE_LIMIT_BYTES = 64e3;\n HTTP_CACHE_SHORT_MAX_AGE_SEC = 60;\n HTTP_CACHE_MEDIUM_MAX_AGE_SEC = 3600;\n HTTP_CACHE_LONG_MAX_AGE_SEC = 31536e3;\n ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n CACHE_CLEANUP_INTERVAL_MS = 6e4;\n LRU_DEFAULT_MAX_ENTRIES = 1e3;\n LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n CLEANUP_INTERVAL_MULTIPLIER = 2;\n }\n});\n\n// src/core/utils/constants/cdn.ts\nfunction getReactCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}`;\n}\nfunction getReactDOMCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}`;\n}\nfunction getReactDOMClientCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}/client`;\n}\nfunction getReactDOMServerCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}/server`;\n}\nfunction getReactJSXRuntimeCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}/jsx-runtime`;\n}\nfunction getReactJSXDevRuntimeCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}/jsx-dev-runtime`;\n}\nfunction getReactImportMap(version = REACT_DEFAULT_VERSION) {\n return {\n react: getReactCDNUrl(version),\n "react-dom": getReactDOMCDNUrl(version),\n "react-dom/client": getReactDOMClientCDNUrl(version),\n "react-dom/server": getReactDOMServerCDNUrl(version),\n "react/jsx-runtime": getReactJSXRuntimeCDNUrl(version),\n "react/jsx-dev-runtime": getReactJSXDevRuntimeCDNUrl(version)\n };\n}\nfunction getDenoStdNodeBase() {\n return `${DENO_STD_BASE}/std@${DENO_STD_VERSION}/node`;\n}\nfunction getUnoCSSTailwindResetUrl() {\n return `${ESM_CDN_BASE}/@unocss/reset@${UNOCSS_VERSION}/tailwind.css`;\n}\nvar ESM_CDN_BASE, JSDELIVR_CDN_BASE, DENO_STD_BASE, REACT_VERSION_17, REACT_VERSION_18_2, REACT_VERSION_18_3, REACT_VERSION_19_RC, REACT_VERSION_19, REACT_DEFAULT_VERSION, DEFAULT_ALLOWED_CDN_HOSTS, DENO_STD_VERSION, UNOCSS_VERSION;\nvar init_cdn = __esm({\n "src/core/utils/constants/cdn.ts"() {\n "use strict";\n ESM_CDN_BASE = "https://esm.sh";\n JSDELIVR_CDN_BASE = "https://cdn.jsdelivr.net";\n DENO_STD_BASE = "https://deno.land";\n REACT_VERSION_17 = "17.0.2";\n REACT_VERSION_18_2 = "18.2.0";\n REACT_VERSION_18_3 = "18.3.1";\n REACT_VERSION_19_RC = "19.0.0-rc.0";\n REACT_VERSION_19 = "19.1.1";\n REACT_DEFAULT_VERSION = REACT_VERSION_18_3;\n DEFAULT_ALLOWED_CDN_HOSTS = [ESM_CDN_BASE, DENO_STD_BASE];\n DENO_STD_VERSION = "0.220.0";\n UNOCSS_VERSION = "0.59.0";\n }\n});\n\n// src/core/utils/constants/hash.ts\nvar HASH_SEED_DJB2, HASH_SEED_FNV1A;\nvar init_hash = __esm({\n "src/core/utils/constants/hash.ts"() {\n "use strict";\n HASH_SEED_DJB2 = 5381;\n HASH_SEED_FNV1A = 2166136261;\n }\n});\n\n// src/core/utils/constants/http.ts\nvar KB_IN_BYTES, HTTP_MODULE_FETCH_TIMEOUT_MS, HMR_RECONNECT_DELAY_MS, HMR_RELOAD_DELAY_MS, HMR_FILE_WATCHER_DEBOUNCE_MS, HMR_KEEP_ALIVE_INTERVAL_MS, DASHBOARD_RECONNECT_DELAY_MS, SERVER_FUNCTION_DEFAULT_TIMEOUT_MS, PREFETCH_MAX_SIZE_BYTES, PREFETCH_DEFAULT_TIMEOUT_MS, PREFETCH_DEFAULT_DELAY_MS, HTTP_OK, HTTP_NO_CONTENT, HTTP_CREATED, HTTP_REDIRECT_FOUND, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED, HTTP_GONE, HTTP_PAYLOAD_TOO_LARGE, HTTP_URI_TOO_LONG, HTTP_TOO_MANY_REQUESTS, HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR, HTTP_BAD_GATEWAY, HTTP_NOT_IMPLEMENTED, HTTP_UNAVAILABLE, HTTP_NETWORK_CONNECT_TIMEOUT, HTTP_STATUS_SUCCESS_MIN, HTTP_STATUS_REDIRECT_MIN, HTTP_STATUS_CLIENT_ERROR_MIN, HTTP_STATUS_SERVER_ERROR_MIN, HTTP_CONTENT_TYPES, MS_PER_MINUTE, HTTP_CONTENT_TYPE_IMAGE_PNG, HTTP_CONTENT_TYPE_IMAGE_JPEG, HTTP_CONTENT_TYPE_IMAGE_WEBP, HTTP_CONTENT_TYPE_IMAGE_AVIF, HTTP_CONTENT_TYPE_IMAGE_SVG, HTTP_CONTENT_TYPE_IMAGE_GIF, HTTP_CONTENT_TYPE_IMAGE_ICO;\nvar init_http = __esm({\n "src/core/utils/constants/http.ts"() {\n "use strict";\n init_cache();\n KB_IN_BYTES = 1024;\n HTTP_MODULE_FETCH_TIMEOUT_MS = 2500;\n HMR_RECONNECT_DELAY_MS = 1e3;\n HMR_RELOAD_DELAY_MS = 1e3;\n HMR_FILE_WATCHER_DEBOUNCE_MS = 100;\n HMR_KEEP_ALIVE_INTERVAL_MS = 3e4;\n DASHBOARD_RECONNECT_DELAY_MS = 3e3;\n SERVER_FUNCTION_DEFAULT_TIMEOUT_MS = 3e4;\n PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\n PREFETCH_DEFAULT_TIMEOUT_MS = 1e4;\n PREFETCH_DEFAULT_DELAY_MS = 200;\n HTTP_OK = 200;\n HTTP_NO_CONTENT = 204;\n HTTP_CREATED = 201;\n HTTP_REDIRECT_FOUND = 302;\n HTTP_NOT_MODIFIED = 304;\n HTTP_BAD_REQUEST = 400;\n HTTP_UNAUTHORIZED = 401;\n HTTP_FORBIDDEN = 403;\n HTTP_NOT_FOUND = 404;\n HTTP_METHOD_NOT_ALLOWED = 405;\n HTTP_GONE = 410;\n HTTP_PAYLOAD_TOO_LARGE = 413;\n HTTP_URI_TOO_LONG = 414;\n HTTP_TOO_MANY_REQUESTS = 429;\n HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;\n HTTP_SERVER_ERROR = 500;\n HTTP_INTERNAL_SERVER_ERROR = 500;\n HTTP_BAD_GATEWAY = 502;\n HTTP_NOT_IMPLEMENTED = 501;\n HTTP_UNAVAILABLE = 503;\n HTTP_NETWORK_CONNECT_TIMEOUT = 599;\n HTTP_STATUS_SUCCESS_MIN = 200;\n HTTP_STATUS_REDIRECT_MIN = 300;\n HTTP_STATUS_CLIENT_ERROR_MIN = 400;\n HTTP_STATUS_SERVER_ERROR_MIN = 500;\n HTTP_CONTENT_TYPES = {\n JS: "application/javascript; charset=utf-8",\n JSON: "application/json; charset=utf-8",\n HTML: "text/html; charset=utf-8",\n CSS: "text/css; charset=utf-8",\n TEXT: "text/plain; charset=utf-8"\n };\n MS_PER_MINUTE = 6e4;\n HTTP_CONTENT_TYPE_IMAGE_PNG = "image/png";\n HTTP_CONTENT_TYPE_IMAGE_JPEG = "image/jpeg";\n HTTP_CONTENT_TYPE_IMAGE_WEBP = "image/webp";\n HTTP_CONTENT_TYPE_IMAGE_AVIF = "image/avif";\n HTTP_CONTENT_TYPE_IMAGE_SVG = "image/svg+xml";\n HTTP_CONTENT_TYPE_IMAGE_GIF = "image/gif";\n HTTP_CONTENT_TYPE_IMAGE_ICO = "image/x-icon";\n }\n});\n\n// src/core/utils/constants/hmr.ts\nfunction isValidHMRMessageType(type) {\n return Object.values(HMR_MESSAGE_TYPES).includes(\n type\n );\n}\nvar HMR_MAX_MESSAGE_SIZE_BYTES, HMR_MAX_MESSAGES_PER_MINUTE, HMR_CLIENT_RELOAD_DELAY_MS, HMR_PORT_OFFSET, HMR_RATE_LIMIT_WINDOW_MS, HMR_CLOSE_NORMAL, HMR_CLOSE_RATE_LIMIT, HMR_CLOSE_MESSAGE_TOO_LARGE, HMR_MESSAGE_TYPES;\nvar init_hmr = __esm({\n "src/core/utils/constants/hmr.ts"() {\n "use strict";\n init_http();\n HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n HMR_MAX_MESSAGES_PER_MINUTE = 100;\n HMR_CLIENT_RELOAD_DELAY_MS = 3e3;\n HMR_PORT_OFFSET = 1;\n HMR_RATE_LIMIT_WINDOW_MS = 6e4;\n HMR_CLOSE_NORMAL = 1e3;\n HMR_CLOSE_RATE_LIMIT = 1008;\n HMR_CLOSE_MESSAGE_TOO_LARGE = 1009;\n HMR_MESSAGE_TYPES = {\n CONNECTED: "connected",\n UPDATE: "update",\n RELOAD: "reload",\n PING: "ping",\n PONG: "pong"\n };\n }\n});\n\n// src/core/utils/constants/html.ts\nvar Z_INDEX_DEV_INDICATOR, Z_INDEX_ERROR_OVERLAY, BREAKPOINT_SM, BREAKPOINT_MD, BREAKPOINT_LG, BREAKPOINT_XL, PROSE_MAX_WIDTH;\nvar init_html = __esm({\n "src/core/utils/constants/html.ts"() {\n "use strict";\n Z_INDEX_DEV_INDICATOR = 9998;\n Z_INDEX_ERROR_OVERLAY = 9999;\n BREAKPOINT_SM = 640;\n BREAKPOINT_MD = 768;\n BREAKPOINT_LG = 1024;\n BREAKPOINT_XL = 1280;\n PROSE_MAX_WIDTH = "65ch";\n }\n});\n\n// src/core/utils/constants/network.ts\nvar DEFAULT_DEV_SERVER_PORT, DEFAULT_REDIS_PORT, DEFAULT_API_SERVER_PORT, DEFAULT_PREVIEW_SERVER_PORT, DEFAULT_METRICS_PORT, BYTES_PER_KB, BYTES_PER_MB, DEFAULT_IMAGE_THUMBNAIL_SIZE, DEFAULT_IMAGE_SMALL_SIZE, DEFAULT_IMAGE_LARGE_SIZE, RESPONSIVE_IMAGE_WIDTH_XS, RESPONSIVE_IMAGE_WIDTH_SM, RESPONSIVE_IMAGE_WIDTH_MD, RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS, MAX_CHUNK_SIZE_KB, MIN_PORT, MAX_PORT, DEFAULT_SERVER_PORT;\nvar init_network = __esm({\n "src/core/utils/constants/network.ts"() {\n "use strict";\n DEFAULT_DEV_SERVER_PORT = 3e3;\n DEFAULT_REDIS_PORT = 6379;\n DEFAULT_API_SERVER_PORT = 8080;\n DEFAULT_PREVIEW_SERVER_PORT = 5e3;\n DEFAULT_METRICS_PORT = 9e3;\n BYTES_PER_KB = 1024;\n BYTES_PER_MB = 1024 * 1024;\n DEFAULT_IMAGE_THUMBNAIL_SIZE = 256;\n DEFAULT_IMAGE_SMALL_SIZE = 512;\n DEFAULT_IMAGE_LARGE_SIZE = 2048;\n RESPONSIVE_IMAGE_WIDTH_XS = 320;\n RESPONSIVE_IMAGE_WIDTH_SM = 640;\n RESPONSIVE_IMAGE_WIDTH_MD = 1024;\n RESPONSIVE_IMAGE_WIDTH_LG = 1920;\n RESPONSIVE_IMAGE_WIDTHS = [\n RESPONSIVE_IMAGE_WIDTH_XS,\n RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_LG\n ];\n MAX_CHUNK_SIZE_KB = 4096;\n MIN_PORT = 1;\n MAX_PORT = 65535;\n DEFAULT_SERVER_PORT = 8e3;\n }\n});\n\n// src/core/utils/constants/security.ts\nvar MAX_PATH_TRAVERSAL_DEPTH, FORBIDDEN_PATH_PATTERNS, DIRECTORY_TRAVERSAL_PATTERN, ABSOLUTE_PATH_PATTERN, MAX_PATH_LENGTH, DEFAULT_MAX_STRING_LENGTH;\nvar init_security = __esm({\n "src/core/utils/constants/security.ts"() {\n "use strict";\n MAX_PATH_TRAVERSAL_DEPTH = 10;\n FORBIDDEN_PATH_PATTERNS = [\n /\\0/\n // Null bytes\n ];\n DIRECTORY_TRAVERSAL_PATTERN = /\\.\\.[\\/\\\\]/;\n ABSOLUTE_PATH_PATTERN = /^[\\/\\\\]/;\n MAX_PATH_LENGTH = 4096;\n DEFAULT_MAX_STRING_LENGTH = 1e3;\n }\n});\n\n// src/core/utils/constants/server.ts\nvar DEFAULT_DASHBOARD_PORT, DEV_SERVER_ENDPOINTS;\nvar init_server = __esm({\n "src/core/utils/constants/server.ts"() {\n "use strict";\n DEFAULT_DASHBOARD_PORT = 3002;\n DEV_SERVER_ENDPOINTS = {\n HMR_RUNTIME: "/_veryfront/hmr-runtime.js",\n ERROR_OVERLAY: "/_veryfront/error-overlay.js"\n };\n }\n});\n\n// src/core/utils/constants/index.ts\nvar init_constants = __esm({\n "src/core/utils/constants/index.ts"() {\n "use strict";\n init_build();\n init_cache();\n init_cdn();\n init_hash();\n init_hmr();\n init_html();\n init_http();\n init_network();\n init_security();\n init_server();\n }\n});\n\n// deno.json\nvar deno_default;\nvar init_deno = __esm({\n "deno.json"() {\n deno_default = {\n name: "veryfront",\n version: "0.0.31",\n nodeModulesDir: "auto",\n exports: {\n ".": "./src/index.ts",\n "./cli": "./src/cli/main.ts",\n "./server": "./src/server/index.ts",\n "./middleware": "./src/middleware/index.ts",\n "./components": "./src/react/components/index.ts",\n "./data": "./src/data/index.ts",\n "./config": "./src/core/config/index.ts",\n "./ai": "./src/ai/index.ts",\n "./ai/client": "./src/ai/client.ts",\n "./ai/react": "./src/ai/react/index.ts",\n "./ai/primitives": "./src/ai/react/primitives/index.ts",\n "./ai/components": "./src/ai/react/components/index.ts",\n "./ai/production": "./src/ai/production/index.ts",\n "./ai/dev": "./src/ai/dev/index.ts",\n "./ai/workflow": "./src/ai/workflow/index.ts",\n "./ai/workflow/react": "./src/ai/workflow/react/index.ts"\n },\n imports: {\n "@veryfront": "./src/index.ts",\n "@veryfront/": "./src/",\n "@veryfront/ai": "./src/ai/index.ts",\n "@veryfront/ai/": "./src/ai/",\n "@veryfront/platform": "./src/platform/index.ts",\n "@veryfront/platform/": "./src/platform/",\n "@veryfront/types": "./src/core/types/index.ts",\n "@veryfront/types/": "./src/core/types/",\n "@veryfront/utils": "./src/core/utils/index.ts",\n "@veryfront/utils/": "./src/core/utils/",\n "@veryfront/middleware": "./src/middleware/index.ts",\n "@veryfront/middleware/": "./src/middleware/",\n "@veryfront/errors": "./src/core/errors/index.ts",\n "@veryfront/errors/": "./src/core/errors/",\n "@veryfront/config": "./src/core/config/index.ts",\n "@veryfront/config/": "./src/core/config/",\n "@veryfront/observability": "./src/observability/index.ts",\n "@veryfront/observability/": "./src/observability/",\n "@veryfront/routing": "./src/routing/index.ts",\n "@veryfront/routing/": "./src/routing/",\n "@veryfront/transforms": "./src/build/transforms/index.ts",\n "@veryfront/transforms/": "./src/build/transforms/",\n "@veryfront/data": "./src/data/index.ts",\n "@veryfront/data/": "./src/data/",\n "@veryfront/security": "./src/security/index.ts",\n "@veryfront/security/": "./src/security/",\n "@veryfront/components": "./src/react/components/index.ts",\n "@veryfront/react": "./src/react/index.ts",\n "@veryfront/react/": "./src/react/",\n "@veryfront/html": "./src/html/index.ts",\n "@veryfront/html/": "./src/html/",\n "@veryfront/rendering": "./src/rendering/index.ts",\n "@veryfront/rendering/": "./src/rendering/",\n "@veryfront/build": "./src/build/index.ts",\n "@veryfront/build/": "./src/build/",\n "@veryfront/server": "./src/server/index.ts",\n "@veryfront/server/": "./src/server/",\n "@veryfront/modules": "./src/module-system/index.ts",\n "@veryfront/modules/": "./src/module-system/",\n "@veryfront/compat/console": "./src/platform/compat/console/index.ts",\n "@veryfront/compat/": "./src/platform/compat/",\n "std/": "https://deno.land/std@0.220.0/",\n "@std/path": "https://deno.land/std@0.220.0/path/mod.ts",\n "@std/testing/bdd.ts": "https://deno.land/std@0.220.0/testing/bdd.ts",\n "@std/expect": "https://deno.land/std@0.220.0/expect/mod.ts",\n csstype: "https://esm.sh/csstype@3.2.3",\n "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",\n "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",\n react: "https://esm.sh/react@18.3.1",\n "react-dom": "https://esm.sh/react-dom@18.3.1",\n "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",\n "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",\n "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",\n "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",\n "@mdx-js/mdx": "https://esm.sh/@mdx-js/mdx@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "@mdx-js/react": "https://esm.sh/@mdx-js/react@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "unist-util-visit": "https://esm.sh/unist-util-visit@5.0.0",\n "mdast-util-to-string": "https://esm.sh/mdast-util-to-string@4.0.0",\n "github-slugger": "https://esm.sh/github-slugger@2.0.0",\n "remark-gfm": "https://esm.sh/remark-gfm@4.0.1",\n "remark-frontmatter": "https://esm.sh/remark-frontmatter@5.0.0",\n "rehype-highlight": "https://esm.sh/rehype-highlight@7.0.2",\n "rehype-slug": "https://esm.sh/rehype-slug@6.0.0",\n esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",\n "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",\n "es-module-lexer": "https://esm.sh/es-module-lexer@1.5.0",\n zod: "https://esm.sh/zod@3.22.0",\n "mime-types": "https://esm.sh/mime-types@2.1.35",\n mdast: "https://esm.sh/@types/mdast@4.0.3",\n hast: "https://esm.sh/@types/hast@3.0.3",\n unist: "https://esm.sh/@types/unist@3.0.2",\n unified: "https://esm.sh/unified@11.0.5?dts",\n ai: "https://esm.sh/ai@5.0.76?deps=react@18.3.1,react-dom@18.3.1",\n "ai/react": "https://esm.sh/@ai-sdk/react@2.0.59?deps=react@18.3.1,react-dom@18.3.1",\n "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",\n "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.4",\n unocss: "https://esm.sh/unocss@0.59.0",\n "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",\n "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0"\n },\n compilerOptions: {\n jsx: "react-jsx",\n jsxImportSource: "react",\n strict: true,\n noImplicitAny: true,\n noUncheckedIndexedAccess: true,\n types: [],\n lib: [\n "deno.window",\n "dom",\n "dom.iterable",\n "dom.asynciterable",\n "deno.ns"\n ]\n },\n tasks: {\n setup: "deno run --allow-all scripts/setup.ts",\n dev: "deno run --allow-all --no-lock --unstable-net --unstable-worker-options src/cli/main.ts dev",\n build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",\n "build:npm": "deno run -A scripts/build-npm.ts",\n release: "deno run -A scripts/release.ts",\n test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",\n "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",\n "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",\n "test:batches": "deno run --allow-all scripts/test-batches.ts",\n "test:unsafe": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net",\n "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",\n "coverage:report": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --lcov > coverage/lcov.info && deno run --allow-read scripts/check-coverage.ts 80",\n "coverage:html": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --html",\n lint: "DENO_NO_PACKAGE_JSON=1 deno lint src/",\n fmt: "deno fmt src/",\n typecheck: "deno check src/index.ts src/cli/main.ts src/server/index.ts src/routing/api/index.ts src/rendering/index.ts src/platform/index.ts src/platform/adapters/index.ts src/build/index.ts src/build/production-build/index.ts src/build/transforms/index.ts src/core/config/index.ts src/core/utils/index.ts src/data/index.ts src/security/index.ts src/middleware/index.ts src/server/handlers/dev/index.ts src/server/handlers/request/api/index.ts src/rendering/cache/index.ts src/rendering/cache/stores/index.ts src/rendering/rsc/actions/index.ts src/html/index.ts src/module-system/index.ts",\n "docs:check-links": "deno run -A scripts/check-doc-links.ts",\n "lint:ban-console": "deno run --allow-read scripts/ban-console.ts",\n "lint:ban-deep-imports": "deno run --allow-read scripts/ban-deep-imports.ts",\n "lint:ban-internal-root-imports": "deno run --allow-read scripts/ban-internal-root-imports.ts",\n "lint:check-awaits": "deno run --allow-read scripts/check-unawaited-promises.ts",\n "check:circular": "deno run -A jsr:@cunarist/deno-circular-deps src/index.ts"\n },\n lint: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n rules: {\n tags: [\n "recommended"\n ],\n include: [\n "ban-untagged-todo"\n ],\n exclude: [\n "no-explicit-any",\n "no-process-global",\n "no-console"\n ]\n }\n },\n fmt: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n options: {\n useTabs: false,\n lineWidth: 100,\n indentWidth: 2,\n semiColons: true,\n singleQuote: false,\n proseWrap: "preserve"\n }\n }\n };\n }\n});\n\n// src/platform/compat/runtime.ts\nvar isDeno, isNode, isBun, isCloudflare;\nvar init_runtime = __esm({\n "src/platform/compat/runtime.ts"() {\n "use strict";\n isDeno = typeof Deno !== "undefined";\n isNode = typeof globalThis.process !== "undefined" && globalThis.process?.versions?.node !== void 0;\n isBun = typeof globalThis.Bun !== "undefined";\n isCloudflare = typeof globalThis !== "undefined" && "caches" in globalThis && "WebSocketPair" in globalThis;\n }\n});\n\n// src/platform/compat/process.ts\nimport process2 from "node:process";\nfunction getEnv(key) {\n if (isDeno) {\n return Deno.env.get(key);\n }\n return process2.env[key];\n}\nvar init_process = __esm({\n "src/platform/compat/process.ts"() {\n "use strict";\n init_runtime();\n }\n});\n\n// src/core/utils/version.ts\nvar VERSION;\nvar init_version = __esm({\n "src/core/utils/version.ts"() {\n "use strict";\n init_deno();\n init_process();\n VERSION = getEnv("VERYFRONT_VERSION") || (typeof deno_default.version === "string" ? deno_default.version : "0.0.0");\n }\n});\n\n// src/core/utils/paths.ts\nvar PATHS, VERYFRONT_PATHS, FILE_EXTENSIONS;\nvar init_paths = __esm({\n "src/core/utils/paths.ts"() {\n "use strict";\n PATHS = {\n PAGES_DIR: "pages",\n COMPONENTS_DIR: "components",\n PUBLIC_DIR: "public",\n STYLES_DIR: "styles",\n DIST_DIR: "dist",\n CONFIG_FILE: "veryfront.config.js"\n };\n VERYFRONT_PATHS = {\n INTERNAL_PREFIX: "/_veryfront",\n BUILD_DIR: "_veryfront",\n CHUNKS_DIR: "_veryfront/chunks",\n DATA_DIR: "_veryfront/data",\n ASSETS_DIR: "_veryfront/assets",\n HMR_RUNTIME: "/_veryfront/hmr-runtime.js",\n CLIENT_JS: "/_veryfront/client.js",\n ROUTER_JS: "/_veryfront/router.js",\n ERROR_OVERLAY: "/_veryfront/error-overlay.js"\n };\n FILE_EXTENSIONS = {\n MDX: [".mdx", ".md"],\n SCRIPT: [".tsx", ".ts", ".jsx", ".js"],\n STYLE: [".css", ".scss", ".sass"],\n ALL: [".mdx", ".md", ".tsx", ".ts", ".jsx", ".js", ".css"]\n };\n }\n});\n\n// src/core/utils/hash-utils.ts\nasync function computeHash(content) {\n const encoder = new TextEncoder();\n const data = encoder.encode(content);\n const hashBuffer = await crypto.subtle.digest("SHA-256", data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");\n}\nfunction getContentHash(content) {\n return computeHash(content);\n}\nfunction computeContentHash(content) {\n return computeHash(content);\n}\nfunction computeCodeHash(code) {\n const combined = code.code + (code.css || "") + (code.sourceMap || "");\n return computeHash(combined);\n}\nfunction simpleHash(str) {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n return Math.abs(hash);\n}\nasync function shortHash(content) {\n const fullHash = await computeHash(content);\n return fullHash.slice(0, 8);\n}\nvar init_hash_utils = __esm({\n "src/core/utils/hash-utils.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/memoize.ts\nfunction memoizeAsync(fn, keyHasher) {\n const cache = new MemoCache();\n return async (...args) => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = await fn(...args);\n cache.set(key, result);\n return result;\n };\n}\nfunction memoize(fn, keyHasher) {\n const cache = new MemoCache();\n return (...args) => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = fn(...args);\n cache.set(key, result);\n return result;\n };\n}\nfunction simpleHash2(...values) {\n const FNV_OFFSET_BASIS = 2166136261;\n const FNV_PRIME = 16777619;\n let hash = FNV_OFFSET_BASIS;\n for (const value of values) {\n const str = typeof value === "string" ? value : String(value);\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = Math.imul(hash, FNV_PRIME);\n }\n }\n return (hash >>> 0).toString(36);\n}\nvar MemoCache;\nvar init_memoize = __esm({\n "src/core/utils/memoize.ts"() {\n "use strict";\n MemoCache = class {\n constructor() {\n this.cache = /* @__PURE__ */ new Map();\n }\n get(key) {\n return this.cache.get(key);\n }\n set(key, value) {\n this.cache.set(key, value);\n }\n has(key) {\n return this.cache.has(key);\n }\n clear() {\n this.cache.clear();\n }\n size() {\n return this.cache.size;\n }\n };\n }\n});\n\n// src/core/utils/path-utils.ts\nfunction normalizePath(pathname) {\n pathname = pathname.replace(/\\\\+/g, "/").replace(/\\/\\.+\\//g, "/");\n if (pathname !== "/" && pathname.endsWith("/")) {\n pathname = pathname.slice(0, -1);\n }\n return pathname;\n}\nfunction joinPath(a, b) {\n return `${a.replace(/\\/$/, "")}/${b.replace(/^\\//, "")}`;\n}\nfunction isWithinDirectory(root, target) {\n const normalizedRoot = normalizePath(root);\n const normalizedTarget = normalizePath(target);\n return normalizedTarget.startsWith(`${normalizedRoot}/`) || normalizedTarget === normalizedRoot;\n}\nfunction getExtension(path) {\n const lastDot = path.lastIndexOf(".");\n if (lastDot === -1 || lastDot === path.length - 1) {\n return "";\n }\n return path.slice(lastDot);\n}\nfunction getDirectory(path) {\n const normalized = normalizePath(path);\n const lastSlash = normalized.lastIndexOf("/");\n return lastSlash <= 0 ? "/" : normalized.slice(0, lastSlash);\n}\nfunction hasHashedFilename(path) {\n return /\\.[a-f0-9]{8,}\\./.test(path);\n}\nfunction isAbsolutePath(path) {\n return path.startsWith("/") || /^[A-Za-z]:[\\\\/]/.test(path);\n}\nfunction toBase64Url(s) {\n const b64 = btoa(s);\n return b64.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");\n}\nfunction fromBase64Url(encoded) {\n const b64 = encoded.replaceAll("-", "+").replaceAll("_", "/");\n const pad = b64.length % 4 === 2 ? "==" : b64.length % 4 === 3 ? "=" : "";\n try {\n return atob(b64 + pad);\n } catch (error2) {\n logger.debug(`Failed to decode base64url string "${encoded}":`, error2);\n return "";\n }\n}\nvar init_path_utils = __esm({\n "src/core/utils/path-utils.ts"() {\n "use strict";\n init_logger();\n }\n});\n\n// src/core/utils/format-utils.ts\nfunction formatBytes(bytes) {\n if (bytes === 0)\n return "0 Bytes";\n const absBytes = Math.abs(bytes);\n if (absBytes < 1) {\n return `${absBytes} Bytes`;\n }\n const k = 1024;\n const sizes = ["Bytes", "KB", "MB", "GB", "TB"];\n const i = Math.floor(Math.log(absBytes) / Math.log(k));\n const index = Math.max(0, Math.min(i, sizes.length - 1));\n return `${parseFloat((absBytes / Math.pow(k, index)).toFixed(2))} ${sizes[index]}`;\n}\nfunction estimateSize(value) {\n if (value === null || value === void 0)\n return 8;\n switch (typeof value) {\n case "boolean":\n return 4;\n case "number":\n return 8;\n case "string":\n return value.length * 2;\n case "function":\n return 0;\n case "object":\n return estimateObjectSize(value);\n default:\n return 32;\n }\n}\nfunction estimateSizeWithCircularHandling(value) {\n const seen = /* @__PURE__ */ new WeakSet();\n const encoder = new TextEncoder();\n const json3 = JSON.stringify(value, (_key, val) => {\n if (typeof val === "object" && val !== null) {\n if (seen.has(val))\n return void 0;\n seen.add(val);\n if (val instanceof Map) {\n return { __type: "Map", entries: Array.from(val.entries()) };\n }\n if (val instanceof Set) {\n return { __type: "Set", values: Array.from(val.values()) };\n }\n }\n if (typeof val === "function")\n return void 0;\n if (val instanceof Uint8Array) {\n return { __type: "Uint8Array", length: val.length };\n }\n return val;\n });\n return encoder.encode(json3 ?? "").length;\n}\nfunction estimateObjectSize(value) {\n if (value instanceof ArrayBuffer)\n return value.byteLength;\n if (value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Uint32Array || value instanceof Int8Array || value instanceof Int16Array || value instanceof Int32Array) {\n return value.byteLength;\n }\n try {\n return JSON.stringify(value).length * 2;\n } catch (error2) {\n logger.debug("Failed to estimate size of non-serializable object:", error2);\n return 1024;\n }\n}\nfunction formatDuration(ms) {\n if (ms < 1e3)\n return `${ms}ms`;\n if (ms < 6e4)\n return `${(ms / 1e3).toFixed(1)}s`;\n if (ms < 36e5)\n return `${Math.floor(ms / 6e4)}m ${Math.floor(ms % 6e4 / 1e3)}s`;\n return `${Math.floor(ms / 36e5)}h ${Math.floor(ms % 36e5 / 6e4)}m`;\n}\nfunction formatNumber(num) {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ",");\n}\nfunction truncateString(str, maxLength) {\n if (str.length <= maxLength)\n return str;\n return str.slice(0, maxLength - 3) + "...";\n}\nvar init_format_utils = __esm({\n "src/core/utils/format-utils.ts"() {\n "use strict";\n init_logger();\n }\n});\n\n// src/core/utils/bundle-manifest.ts\nfunction setBundleManifestStore(store) {\n manifestStore = store;\n serverLogger.info("[bundle-manifest] Bundle manifest store configured", {\n type: store.constructor.name\n });\n}\nfunction getBundleManifestStore() {\n return manifestStore;\n}\nvar InMemoryBundleManifestStore, manifestStore;\nvar init_bundle_manifest = __esm({\n "src/core/utils/bundle-manifest.ts"() {\n "use strict";\n init_logger2();\n init_hash_utils();\n InMemoryBundleManifestStore = class {\n constructor() {\n this.metadata = /* @__PURE__ */ new Map();\n this.code = /* @__PURE__ */ new Map();\n this.sourceIndex = /* @__PURE__ */ new Map();\n }\n getBundleMetadata(key) {\n const entry = this.metadata.get(key);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleMetadata(key, metadata, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.metadata.set(key, { value: metadata, expiry });\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, /* @__PURE__ */ new Set());\n }\n this.sourceIndex.get(metadata.source).add(key);\n return Promise.resolve();\n }\n getBundleCode(hash) {\n const entry = this.code.get(hash);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleCode(hash, code, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n async deleteBundle(key) {\n const metadata = await this.getBundleMetadata(key);\n this.metadata.delete(key);\n if (metadata) {\n this.code.delete(metadata.codeHash);\n const sourceKeys = this.sourceIndex.get(metadata.source);\n if (sourceKeys) {\n sourceKeys.delete(key);\n if (sourceKeys.size === 0) {\n this.sourceIndex.delete(metadata.source);\n }\n }\n }\n }\n async invalidateSource(source) {\n const keys = this.sourceIndex.get(source);\n if (!keys)\n return 0;\n let count = 0;\n for (const key of Array.from(keys)) {\n await this.deleteBundle(key);\n count++;\n }\n this.sourceIndex.delete(source);\n return count;\n }\n clear() {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n isAvailable() {\n return Promise.resolve(true);\n }\n getStats() {\n let totalSize = 0;\n let oldest;\n let newest;\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest)\n oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest)\n newest = value.compiledAt;\n }\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest\n });\n }\n };\n manifestStore = new InMemoryBundleManifestStore();\n }\n});\n\n// src/core/utils/bundle-manifest-init.ts\nasync function initializeBundleManifest(config, mode, adapter) {\n const manifestConfig = config.cache?.bundleManifest;\n const enabled = manifestConfig?.enabled ?? mode === "production";\n if (!enabled) {\n serverLogger.info("[bundle-manifest] Bundle manifest disabled");\n setBundleManifestStore(new InMemoryBundleManifestStore());\n return;\n }\n const envType = adapter?.env.get("VERYFRONT_BUNDLE_MANIFEST_TYPE");\n const storeType = manifestConfig?.type || envType || "memory";\n serverLogger.info("[bundle-manifest] Initializing bundle manifest", {\n type: storeType,\n mode\n });\n try {\n let store;\n switch (storeType) {\n case "redis": {\n const { RedisBundleManifestStore } = await import("./bundle-manifest-redis.ts");\n const redisUrl = manifestConfig?.redisUrl || adapter?.env.get("VERYFRONT_BUNDLE_MANIFEST_REDIS_URL");\n store = new RedisBundleManifestStore(\n {\n url: redisUrl,\n keyPrefix: manifestConfig?.keyPrefix\n },\n adapter\n );\n const available = await store.isAvailable();\n if (!available) {\n serverLogger.warn("[bundle-manifest] Redis not available, falling back to in-memory");\n store = new InMemoryBundleManifestStore();\n } else {\n serverLogger.info("[bundle-manifest] Redis store initialized");\n }\n break;\n }\n case "kv": {\n const { KVBundleManifestStore } = await import("./bundle-manifest-kv.ts");\n store = new KVBundleManifestStore({\n keyPrefix: manifestConfig?.keyPrefix\n });\n const available = await store.isAvailable();\n if (!available) {\n serverLogger.warn("[bundle-manifest] KV not available, falling back to in-memory");\n store = new InMemoryBundleManifestStore();\n } else {\n serverLogger.info("[bundle-manifest] KV store initialized");\n }\n break;\n }\n case "memory":\n default: {\n store = new InMemoryBundleManifestStore();\n serverLogger.info("[bundle-manifest] In-memory store initialized");\n break;\n }\n }\n setBundleManifestStore(store);\n try {\n const stats = await store.getStats();\n serverLogger.info("[bundle-manifest] Store statistics", stats);\n } catch (error2) {\n serverLogger.debug("[bundle-manifest] Failed to get stats", { error: error2 });\n }\n } catch (error2) {\n serverLogger.error("[bundle-manifest] Failed to initialize store, using in-memory fallback", {\n error: error2\n });\n setBundleManifestStore(new InMemoryBundleManifestStore());\n }\n}\nfunction getBundleManifestTTL(config, mode) {\n const manifestConfig = config.cache?.bundleManifest;\n if (manifestConfig?.ttl) {\n return manifestConfig.ttl;\n }\n if (mode === "production") {\n return BUNDLE_MANIFEST_PROD_TTL_MS;\n } else {\n return BUNDLE_MANIFEST_DEV_TTL_MS;\n }\n}\nasync function warmupBundleManifest(store, keys) {\n serverLogger.info("[bundle-manifest] Warming up cache", { keys: keys.length });\n let loaded = 0;\n let failed = 0;\n for (const key of keys) {\n try {\n const metadata = await store.getBundleMetadata(key);\n if (metadata) {\n await store.getBundleCode(metadata.codeHash);\n loaded++;\n }\n } catch (error2) {\n serverLogger.debug("[bundle-manifest] Failed to warm up key", { key, error: error2 });\n failed++;\n }\n }\n serverLogger.info("[bundle-manifest] Cache warmup complete", { loaded, failed });\n}\nvar init_bundle_manifest_init = __esm({\n "src/core/utils/bundle-manifest-init.ts"() {\n "use strict";\n init_logger2();\n init_bundle_manifest();\n init_cache();\n }\n});\n\n// src/core/utils/feature-flags.ts\nfunction isRSCEnabled(config) {\n if (config?.experimental?.rsc !== void 0) {\n return config.experimental.rsc;\n }\n return getEnv("VERYFRONT_EXPERIMENTAL_RSC") === "1";\n}\nvar init_feature_flags = __esm({\n "src/core/utils/feature-flags.ts"() {\n "use strict";\n init_process();\n }\n});\n\n// src/core/utils/platform.ts\nfunction isCompiledBinary() {\n const hasDeno = typeof Deno !== "undefined";\n const hasExecPath = hasDeno && typeof Deno.execPath === "function";\n if (!hasExecPath)\n return false;\n try {\n const execPath = Deno.execPath();\n return execPath.includes("veryfront");\n } catch {\n return false;\n }\n}\nvar init_platform = __esm({\n "src/core/utils/platform.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/index.ts\nvar utils_exports = {};\n__export(utils_exports, {\n ABSOLUTE_PATH_PATTERN: () => ABSOLUTE_PATH_PATTERN,\n BREAKPOINT_LG: () => BREAKPOINT_LG,\n BREAKPOINT_MD: () => BREAKPOINT_MD,\n BREAKPOINT_SM: () => BREAKPOINT_SM,\n BREAKPOINT_XL: () => BREAKPOINT_XL,\n BUNDLE_CACHE_TTL_DEVELOPMENT_MS: () => BUNDLE_CACHE_TTL_DEVELOPMENT_MS,\n BUNDLE_CACHE_TTL_PRODUCTION_MS: () => BUNDLE_CACHE_TTL_PRODUCTION_MS,\n BUNDLE_MANIFEST_DEV_TTL_MS: () => BUNDLE_MANIFEST_DEV_TTL_MS,\n BUNDLE_MANIFEST_PROD_TTL_MS: () => BUNDLE_MANIFEST_PROD_TTL_MS,\n BYTES_PER_KB: () => BYTES_PER_KB,\n BYTES_PER_MB: () => BYTES_PER_MB,\n CACHE_CLEANUP_INTERVAL_MS: () => CACHE_CLEANUP_INTERVAL_MS,\n CLEANUP_INTERVAL_MULTIPLIER: () => CLEANUP_INTERVAL_MULTIPLIER,\n COMPONENT_LOADER_MAX_ENTRIES: () => COMPONENT_LOADER_MAX_ENTRIES,\n COMPONENT_LOADER_TTL_MS: () => COMPONENT_LOADER_TTL_MS,\n DASHBOARD_RECONNECT_DELAY_MS: () => DASHBOARD_RECONNECT_DELAY_MS,\n DATA_FETCHING_MAX_ENTRIES: () => DATA_FETCHING_MAX_ENTRIES,\n DATA_FETCHING_TTL_MS: () => DATA_FETCHING_TTL_MS,\n DEFAULT_ALLOWED_CDN_HOSTS: () => DEFAULT_ALLOWED_CDN_HOSTS,\n DEFAULT_API_SERVER_PORT: () => DEFAULT_API_SERVER_PORT,\n DEFAULT_BUILD_CONCURRENCY: () => DEFAULT_BUILD_CONCURRENCY,\n DEFAULT_DASHBOARD_PORT: () => DEFAULT_DASHBOARD_PORT,\n DEFAULT_DEV_SERVER_PORT: () => DEFAULT_DEV_SERVER_PORT,\n DEFAULT_IMAGE_LARGE_SIZE: () => DEFAULT_IMAGE_LARGE_SIZE,\n DEFAULT_IMAGE_SMALL_SIZE: () => DEFAULT_IMAGE_SMALL_SIZE,\n DEFAULT_IMAGE_THUMBNAIL_SIZE: () => DEFAULT_IMAGE_THUMBNAIL_SIZE,\n DEFAULT_LRU_MAX_ENTRIES: () => DEFAULT_LRU_MAX_ENTRIES,\n DEFAULT_MAX_STRING_LENGTH: () => DEFAULT_MAX_STRING_LENGTH,\n DEFAULT_METRICS_PORT: () => DEFAULT_METRICS_PORT,\n DEFAULT_PREVIEW_SERVER_PORT: () => DEFAULT_PREVIEW_SERVER_PORT,\n DEFAULT_REDIS_PORT: () => DEFAULT_REDIS_PORT,\n DEFAULT_SERVER_PORT: () => DEFAULT_SERVER_PORT,\n DENO_KV_SAFE_SIZE_LIMIT_BYTES: () => DENO_KV_SAFE_SIZE_LIMIT_BYTES,\n DENO_STD_BASE: () => DENO_STD_BASE,\n DENO_STD_VERSION: () => DENO_STD_VERSION,\n DEV_SERVER_ENDPOINTS: () => DEV_SERVER_ENDPOINTS,\n DIRECTORY_TRAVERSAL_PATTERN: () => DIRECTORY_TRAVERSAL_PATTERN,\n ESM_CDN_BASE: () => ESM_CDN_BASE,\n FILE_EXTENSIONS: () => FILE_EXTENSIONS,\n FORBIDDEN_PATH_PATTERNS: () => FORBIDDEN_PATH_PATTERNS,\n HASH_SEED_DJB2: () => HASH_SEED_DJB2,\n HASH_SEED_FNV1A: () => HASH_SEED_FNV1A,\n HMR_CLIENT_RELOAD_DELAY_MS: () => HMR_CLIENT_RELOAD_DELAY_MS,\n HMR_CLOSE_MESSAGE_TOO_LARGE: () => HMR_CLOSE_MESSAGE_TOO_LARGE,\n HMR_CLOSE_NORMAL: () => HMR_CLOSE_NORMAL,\n HMR_CLOSE_RATE_LIMIT: () => HMR_CLOSE_RATE_LIMIT,\n HMR_FILE_WATCHER_DEBOUNCE_MS: () => HMR_FILE_WATCHER_DEBOUNCE_MS,\n HMR_KEEP_ALIVE_INTERVAL_MS: () => HMR_KEEP_ALIVE_INTERVAL_MS,\n HMR_MAX_MESSAGES_PER_MINUTE: () => HMR_MAX_MESSAGES_PER_MINUTE,\n HMR_MAX_MESSAGE_SIZE_BYTES: () => HMR_MAX_MESSAGE_SIZE_BYTES,\n HMR_MESSAGE_TYPES: () => HMR_MESSAGE_TYPES,\n HMR_PORT_OFFSET: () => HMR_PORT_OFFSET,\n HMR_RATE_LIMIT_WINDOW_MS: () => HMR_RATE_LIMIT_WINDOW_MS,\n HMR_RECONNECT_DELAY_MS: () => HMR_RECONNECT_DELAY_MS,\n HMR_RELOAD_DELAY_MS: () => HMR_RELOAD_DELAY_MS,\n HOURS_PER_DAY: () => HOURS_PER_DAY,\n HTTP_BAD_GATEWAY: () => HTTP_BAD_GATEWAY,\n HTTP_BAD_REQUEST: () => HTTP_BAD_REQUEST,\n HTTP_CACHE_LONG_MAX_AGE_SEC: () => HTTP_CACHE_LONG_MAX_AGE_SEC,\n HTTP_CACHE_MEDIUM_MAX_AGE_SEC: () => HTTP_CACHE_MEDIUM_MAX_AGE_SEC,\n HTTP_CACHE_SHORT_MAX_AGE_SEC: () => HTTP_CACHE_SHORT_MAX_AGE_SEC,\n HTTP_CONTENT_TYPES: () => HTTP_CONTENT_TYPES,\n HTTP_CONTENT_TYPE_IMAGE_AVIF: () => HTTP_CONTENT_TYPE_IMAGE_AVIF,\n HTTP_CONTENT_TYPE_IMAGE_GIF: () => HTTP_CONTENT_TYPE_IMAGE_GIF,\n HTTP_CONTENT_TYPE_IMAGE_ICO: () => HTTP_CONTENT_TYPE_IMAGE_ICO,\n HTTP_CONTENT_TYPE_IMAGE_JPEG: () => HTTP_CONTENT_TYPE_IMAGE_JPEG,\n HTTP_CONTENT_TYPE_IMAGE_PNG: () => HTTP_CONTENT_TYPE_IMAGE_PNG,\n HTTP_CONTENT_TYPE_IMAGE_SVG: () => HTTP_CONTENT_TYPE_IMAGE_SVG,\n HTTP_CONTENT_TYPE_IMAGE_WEBP: () => HTTP_CONTENT_TYPE_IMAGE_WEBP,\n HTTP_CREATED: () => HTTP_CREATED,\n HTTP_FORBIDDEN: () => HTTP_FORBIDDEN,\n HTTP_GONE: () => HTTP_GONE,\n HTTP_INTERNAL_SERVER_ERROR: () => HTTP_INTERNAL_SERVER_ERROR,\n HTTP_METHOD_NOT_ALLOWED: () => HTTP_METHOD_NOT_ALLOWED,\n HTTP_MODULE_FETCH_TIMEOUT_MS: () => HTTP_MODULE_FETCH_TIMEOUT_MS,\n HTTP_NETWORK_CONNECT_TIMEOUT: () => HTTP_NETWORK_CONNECT_TIMEOUT,\n HTTP_NOT_FOUND: () => HTTP_NOT_FOUND,\n HTTP_NOT_IMPLEMENTED: () => HTTP_NOT_IMPLEMENTED,\n HTTP_NOT_MODIFIED: () => HTTP_NOT_MODIFIED,\n HTTP_NO_CONTENT: () => HTTP_NO_CONTENT,\n HTTP_OK: () => HTTP_OK,\n HTTP_PAYLOAD_TOO_LARGE: () => HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REDIRECT_FOUND: () => HTTP_REDIRECT_FOUND,\n HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: () => HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,\n HTTP_SERVER_ERROR: () => HTTP_SERVER_ERROR,\n HTTP_STATUS_CLIENT_ERROR_MIN: () => HTTP_STATUS_CLIENT_ERROR_MIN,\n HTTP_STATUS_REDIRECT_MIN: () => HTTP_STATUS_REDIRECT_MIN,\n HTTP_STATUS_SERVER_ERROR_MIN: () => HTTP_STATUS_SERVER_ERROR_MIN,\n HTTP_STATUS_SUCCESS_MIN: () => HTTP_STATUS_SUCCESS_MIN,\n HTTP_TOO_MANY_REQUESTS: () => HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED: () => HTTP_UNAUTHORIZED,\n HTTP_UNAVAILABLE: () => HTTP_UNAVAILABLE,\n HTTP_URI_TOO_LONG: () => HTTP_URI_TOO_LONG,\n IMAGE_OPTIMIZATION: () => IMAGE_OPTIMIZATION,\n InMemoryBundleManifestStore: () => InMemoryBundleManifestStore,\n JSDELIVR_CDN_BASE: () => JSDELIVR_CDN_BASE,\n KB_IN_BYTES: () => KB_IN_BYTES,\n LRU_DEFAULT_MAX_ENTRIES: () => LRU_DEFAULT_MAX_ENTRIES,\n LRU_DEFAULT_MAX_SIZE_BYTES: () => LRU_DEFAULT_MAX_SIZE_BYTES,\n LogLevel: () => LogLevel,\n MAX_CHUNK_SIZE_KB: () => MAX_CHUNK_SIZE_KB,\n MAX_PATH_LENGTH: () => MAX_PATH_LENGTH,\n MAX_PATH_TRAVERSAL_DEPTH: () => MAX_PATH_TRAVERSAL_DEPTH,\n MAX_PORT: () => MAX_PORT,\n MDX_CACHE_TTL_DEVELOPMENT_MS: () => MDX_CACHE_TTL_DEVELOPMENT_MS,\n MDX_CACHE_TTL_PRODUCTION_MS: () => MDX_CACHE_TTL_PRODUCTION_MS,\n MDX_RENDERER_MAX_ENTRIES: () => MDX_RENDERER_MAX_ENTRIES,\n MDX_RENDERER_TTL_MS: () => MDX_RENDERER_TTL_MS,\n MINUTES_PER_HOUR: () => MINUTES_PER_HOUR,\n MIN_PORT: () => MIN_PORT,\n MS_PER_MINUTE: () => MS_PER_MINUTE,\n MS_PER_SECOND: () => MS_PER_SECOND,\n MemoCache: () => MemoCache,\n ONE_DAY_MS: () => ONE_DAY_MS,\n PATHS: () => PATHS,\n PREFETCH_DEFAULT_DELAY_MS: () => PREFETCH_DEFAULT_DELAY_MS,\n PREFETCH_DEFAULT_TIMEOUT_MS: () => PREFETCH_DEFAULT_TIMEOUT_MS,\n PREFETCH_MAX_SIZE_BYTES: () => PREFETCH_MAX_SIZE_BYTES,\n PROSE_MAX_WIDTH: () => PROSE_MAX_WIDTH,\n REACT_DEFAULT_VERSION: () => REACT_DEFAULT_VERSION,\n REACT_VERSION_17: () => REACT_VERSION_17,\n REACT_VERSION_18_2: () => REACT_VERSION_18_2,\n REACT_VERSION_18_3: () => REACT_VERSION_18_3,\n REACT_VERSION_19: () => REACT_VERSION_19,\n REACT_VERSION_19_RC: () => REACT_VERSION_19_RC,\n RENDERER_CORE_MAX_ENTRIES: () => RENDERER_CORE_MAX_ENTRIES,\n RENDERER_CORE_TTL_MS: () => RENDERER_CORE_TTL_MS,\n RESPONSIVE_IMAGE_WIDTHS: () => RESPONSIVE_IMAGE_WIDTHS,\n RESPONSIVE_IMAGE_WIDTH_LG: () => RESPONSIVE_IMAGE_WIDTH_LG,\n RESPONSIVE_IMAGE_WIDTH_MD: () => RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_SM: () => RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_XS: () => RESPONSIVE_IMAGE_WIDTH_XS,\n RSC_MANIFEST_CACHE_TTL_MS: () => RSC_MANIFEST_CACHE_TTL_MS,\n SECONDS_PER_MINUTE: () => SECONDS_PER_MINUTE,\n SERVER_ACTION_DEFAULT_TTL_SEC: () => SERVER_ACTION_DEFAULT_TTL_SEC,\n SERVER_FUNCTION_DEFAULT_TIMEOUT_MS: () => SERVER_FUNCTION_DEFAULT_TIMEOUT_MS,\n TSX_LAYOUT_MAX_ENTRIES: () => TSX_LAYOUT_MAX_ENTRIES,\n TSX_LAYOUT_TTL_MS: () => TSX_LAYOUT_TTL_MS,\n UNOCSS_VERSION: () => UNOCSS_VERSION,\n VERSION: () => VERSION,\n VERYFRONT_PATHS: () => VERYFRONT_PATHS,\n Z_INDEX_DEV_INDICATOR: () => Z_INDEX_DEV_INDICATOR,\n Z_INDEX_ERROR_OVERLAY: () => Z_INDEX_ERROR_OVERLAY,\n __loggerResetForTests: () => __loggerResetForTests,\n agentLogger: () => agentLogger,\n bundlerLogger: () => bundlerLogger,\n cliLogger: () => cliLogger,\n computeCodeHash: () => computeCodeHash,\n computeContentHash: () => computeContentHash,\n computeHash: () => computeHash,\n estimateSize: () => estimateSize,\n estimateSizeWithCircularHandling: () => estimateSizeWithCircularHandling,\n formatBytes: () => formatBytes,\n formatDuration: () => formatDuration,\n formatNumber: () => formatNumber,\n fromBase64Url: () => fromBase64Url,\n getBundleManifestStore: () => getBundleManifestStore,\n getBundleManifestTTL: () => getBundleManifestTTL,\n getContentHash: () => getContentHash,\n getDenoStdNodeBase: () => getDenoStdNodeBase,\n getDirectory: () => getDirectory,\n getEnvironmentVariable: () => getEnvironmentVariable,\n getExtension: () => getExtension,\n getReactCDNUrl: () => getReactCDNUrl,\n getReactDOMCDNUrl: () => getReactDOMCDNUrl,\n getReactDOMClientCDNUrl: () => getReactDOMClientCDNUrl,\n getReactDOMServerCDNUrl: () => getReactDOMServerCDNUrl,\n getReactImportMap: () => getReactImportMap,\n getReactJSXDevRuntimeCDNUrl: () => getReactJSXDevRuntimeCDNUrl,\n getReactJSXRuntimeCDNUrl: () => getReactJSXRuntimeCDNUrl,\n getUnoCSSTailwindResetUrl: () => getUnoCSSTailwindResetUrl,\n hasBunRuntime: () => hasBunRuntime,\n hasDenoRuntime: () => hasDenoRuntime,\n hasHashedFilename: () => hasHashedFilename,\n hasNodeProcess: () => hasNodeProcess,\n initializeBundleManifest: () => initializeBundleManifest,\n isAbsolutePath: () => isAbsolutePath,\n isCompiledBinary: () => isCompiledBinary,\n isDevelopmentEnvironment: () => isDevelopmentEnvironment,\n isProductionEnvironment: () => isProductionEnvironment,\n isRSCEnabled: () => isRSCEnabled,\n isTestEnvironment: () => isTestEnvironment,\n isValidHMRMessageType: () => isValidHMRMessageType,\n isWithinDirectory: () => isWithinDirectory,\n joinPath: () => joinPath,\n logger: () => logger,\n memoize: () => memoize,\n memoizeAsync: () => memoizeAsync,\n memoizeHash: () => simpleHash2,\n normalizePath: () => normalizePath,\n numericHash: () => simpleHash,\n rendererLogger: () => rendererLogger,\n serverLogger: () => serverLogger,\n setBundleManifestStore: () => setBundleManifestStore,\n shortHash: () => shortHash,\n simpleHash: () => simpleHash,\n toBase64Url: () => toBase64Url,\n truncateString: () => truncateString,\n warmupBundleManifest: () => warmupBundleManifest\n});\nvar init_utils = __esm({\n "src/core/utils/index.ts"() {\n init_runtime_guards();\n init_logger2();\n init_constants();\n init_version();\n init_paths();\n init_hash_utils();\n init_memoize();\n init_path_utils();\n init_format_utils();\n init_bundle_manifest();\n init_bundle_manifest_init();\n init_feature_flags();\n init_platform();\n }\n});\n\n// src/_shims/std-path.ts\nvar std_path_exports = {};\n__export(std_path_exports, {\n SEPARATOR: () => SEPARATOR,\n SEPARATOR_PATTERN: () => SEPARATOR_PATTERN,\n basename: () => basename2,\n delimiter: () => delimiter2,\n dirname: () => dirname2,\n extname: () => extname2,\n format: () => format2,\n fromFileUrl: () => fromFileUrl,\n isAbsolute: () => isAbsolute2,\n join: () => join2,\n normalize: () => normalize2,\n parse: () => parse2,\n relative: () => relative2,\n resolve: () => resolve2,\n sep: () => sep2,\n toFileUrl: () => toFileUrl\n});\nimport * as nodeUrl from "node:url";\nimport * as nodePath from "node:path";\nfunction fromFileUrl(url) {\n return nodeUrl.fileURLToPath(url);\n}\nfunction toFileUrl(path) {\n return nodeUrl.pathToFileURL(path);\n}\nvar basename2, dirname2, extname2, join2, resolve2, relative2, isAbsolute2, normalize2, parse2, format2, sep2, delimiter2, SEPARATOR, SEPARATOR_PATTERN;\nvar init_std_path = __esm({\n "src/_shims/std-path.ts"() {\n basename2 = nodePath.basename;\n dirname2 = nodePath.dirname;\n extname2 = nodePath.extname;\n join2 = nodePath.join;\n resolve2 = nodePath.resolve;\n relative2 = nodePath.relative;\n isAbsolute2 = nodePath.isAbsolute;\n normalize2 = nodePath.normalize;\n parse2 = nodePath.parse;\n format2 = nodePath.format;\n sep2 = nodePath.sep;\n delimiter2 = nodePath.delimiter;\n SEPARATOR = nodePath.sep;\n SEPARATOR_PATTERN = nodePath.sep === "/" ? /\\/+/ : /[\\\\/]+/;\n }\n});\n\n// src/core/errors/veryfront-error.ts\nfunction createError(error2) {\n return error2;\n}\nfunction toError(veryfrontError) {\n const error2 = new Error(veryfrontError.message);\n error2.name = `VeryfrontError[${veryfrontError.type}]`;\n Object.defineProperty(error2, "context", {\n value: veryfrontError,\n enumerable: false,\n configurable: true\n });\n return error2;\n}\nvar init_veryfront_error = __esm({\n "src/core/errors/veryfront-error.ts"() {\n "use strict";\n }\n});\n\n// src/core/config/schema.ts\nimport { z } from "zod";\nvar corsSchema, veryfrontConfigSchema;\nvar init_schema = __esm({\n "src/core/config/schema.ts"() {\n "use strict";\n init_veryfront_error();\n corsSchema = z.union([z.boolean(), z.object({ origin: z.string().optional() }).strict()]);\n veryfrontConfigSchema = z.object({\n title: z.string().optional(),\n description: z.string().optional(),\n experimental: z.object({\n esmLayouts: z.boolean().optional(),\n precompileMDX: z.boolean().optional()\n }).partial().optional(),\n router: z.enum(["app", "pages"]).optional(),\n defaultLayout: z.string().optional(),\n theme: z.object({ colors: z.record(z.string()).optional() }).partial().optional(),\n build: z.object({\n outDir: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n esbuild: z.object({\n wasmURL: z.string().url().optional(),\n worker: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n cache: z.object({\n dir: z.string().optional(),\n bundleManifest: z.object({\n type: z.enum(["redis", "kv", "memory"]).optional(),\n redisUrl: z.string().optional(),\n keyPrefix: z.string().optional(),\n ttl: z.number().int().positive().optional(),\n enabled: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n dev: z.object({\n port: z.number().int().positive().optional(),\n host: z.string().optional(),\n open: z.boolean().optional(),\n hmr: z.boolean().optional(),\n components: z.array(z.string()).optional()\n }).partial().optional(),\n resolve: z.object({\n importMap: z.object({\n imports: z.record(z.string()).optional(),\n scopes: z.record(z.record(z.string())).optional()\n }).partial().optional()\n }).partial().optional(),\n security: z.object({\n csp: z.record(z.array(z.string())).optional(),\n remoteHosts: z.array(z.string().url()).optional(),\n cors: corsSchema.optional(),\n coop: z.enum(["same-origin", "same-origin-allow-popups", "unsafe-none"]).optional(),\n corp: z.enum(["same-origin", "same-site", "cross-origin"]).optional(),\n coep: z.enum(["require-corp", "unsafe-none"]).optional()\n }).partial().optional(),\n middleware: z.object({\n custom: z.array(z.function()).optional()\n }).partial().optional(),\n theming: z.object({\n brandName: z.string().optional(),\n logoHtml: z.string().optional()\n }).partial().optional(),\n assetPipeline: z.object({\n images: z.object({\n enabled: z.boolean().optional(),\n formats: z.array(z.enum(["webp", "avif", "jpeg", "png"])).optional(),\n sizes: z.array(z.number().int().positive()).optional(),\n quality: z.number().int().min(1).max(100).optional(),\n inputDir: z.string().optional(),\n outputDir: z.string().optional(),\n preserveOriginal: z.boolean().optional()\n }).partial().optional(),\n css: z.object({\n enabled: z.boolean().optional(),\n minify: z.boolean().optional(),\n autoprefixer: z.boolean().optional(),\n purge: z.boolean().optional(),\n criticalCSS: z.boolean().optional(),\n inputDir: z.string().optional(),\n outputDir: z.string().optional(),\n browsers: z.array(z.string()).optional(),\n purgeContent: z.array(z.string()).optional(),\n sourceMap: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n observability: z.object({\n tracing: z.object({\n enabled: z.boolean().optional(),\n exporter: z.enum(["jaeger", "zipkin", "otlp", "console"]).optional(),\n endpoint: z.string().optional(),\n serviceName: z.string().optional(),\n sampleRate: z.number().min(0).max(1).optional()\n }).partial().optional(),\n metrics: z.object({\n enabled: z.boolean().optional(),\n exporter: z.enum(["prometheus", "otlp", "console"]).optional(),\n endpoint: z.string().optional(),\n prefix: z.string().optional(),\n collectInterval: z.number().int().positive().optional()\n }).partial().optional()\n }).partial().optional(),\n fs: z.object({\n type: z.enum(["local", "veryfront-api", "memory"]).optional(),\n local: z.object({\n baseDir: z.string().optional()\n }).partial().optional(),\n veryfront: z.object({\n apiBaseUrl: z.string().url(),\n apiToken: z.string(),\n projectSlug: z.string(),\n cache: z.object({\n enabled: z.boolean().optional(),\n ttl: z.number().int().positive().optional(),\n maxSize: z.number().int().positive().optional()\n }).partial().optional(),\n retry: z.object({\n maxRetries: z.number().int().min(0).optional(),\n initialDelay: z.number().int().positive().optional(),\n maxDelay: z.number().int().positive().optional()\n }).partial().optional()\n }).partial().optional(),\n memory: z.object({\n files: z.record(z.union([z.string(), z.instanceof(Uint8Array)])).optional()\n }).partial().optional()\n }).partial().optional(),\n client: z.object({\n moduleResolution: z.enum(["cdn", "self-hosted", "bundled"]).optional(),\n cdn: z.object({\n provider: z.enum(["esm.sh", "unpkg", "jsdelivr"]).optional(),\n versions: z.union([\n z.literal("auto"),\n z.object({\n react: z.string().optional(),\n veryfront: z.string().optional()\n })\n ]).optional()\n }).partial().optional()\n }).partial().optional()\n }).partial();\n }\n});\n\n// src/core/config/loader.ts\nfunction getDefaultImportMapForConfig() {\n return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };\n}\nvar DEFAULT_CONFIG;\nvar init_loader = __esm({\n "src/core/config/loader.ts"() {\n "use strict";\n init_schema();\n init_std_path();\n init_logger();\n init_cdn();\n DEFAULT_CONFIG = {\n title: "Veryfront App",\n description: "Built with Veryfront",\n experimental: {\n esmLayouts: true\n },\n router: void 0,\n defaultLayout: void 0,\n theme: {\n colors: {\n primary: "#3B82F6"\n }\n },\n build: {\n outDir: "dist",\n trailingSlash: false,\n esbuild: {\n wasmURL: "https://deno.land/x/esbuild@v0.20.1/esbuild.wasm",\n worker: false\n }\n },\n cache: {\n dir: ".veryfront/cache",\n render: {\n type: "memory",\n ttl: void 0,\n maxEntries: 500,\n kvPath: void 0,\n redisUrl: void 0,\n redisKeyPrefix: void 0\n }\n },\n dev: {\n port: 3002,\n host: "localhost",\n open: false\n },\n resolve: {\n importMap: getDefaultImportMapForConfig()\n },\n client: {\n moduleResolution: "cdn",\n cdn: {\n provider: "esm.sh",\n versions: "auto"\n }\n }\n };\n }\n});\n\n// src/core/config/define-config.ts\nvar init_define_config = __esm({\n "src/core/config/define-config.ts"() {\n "use strict";\n init_veryfront_error();\n init_process();\n }\n});\n\n// src/core/config/defaults.ts\nvar DEFAULT_DEV_PORT, DEFAULT_PREFETCH_DELAY_MS, DURATION_HISTOGRAM_BOUNDARIES_MS, SIZE_HISTOGRAM_BOUNDARIES_KB, PAGE_TRANSITION_DELAY_MS;\nvar init_defaults = __esm({\n "src/core/config/defaults.ts"() {\n "use strict";\n DEFAULT_DEV_PORT = 3e3;\n DEFAULT_PREFETCH_DELAY_MS = 100;\n DURATION_HISTOGRAM_BOUNDARIES_MS = [\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1e3,\n 2500,\n 5e3,\n 7500,\n 1e4\n ];\n SIZE_HISTOGRAM_BOUNDARIES_KB = [\n 1,\n 5,\n 10,\n 25,\n 50,\n 100,\n 250,\n 500,\n 1e3,\n 2500,\n 5e3,\n 1e4\n ];\n PAGE_TRANSITION_DELAY_MS = 150;\n }\n});\n\n// src/core/config/network-defaults.ts\nvar init_network_defaults = __esm({\n "src/core/config/network-defaults.ts"() {\n "use strict";\n }\n});\n\n// src/core/config/index.ts\nvar init_config = __esm({\n "src/core/config/index.ts"() {\n init_loader();\n init_define_config();\n init_schema();\n init_defaults();\n init_network_defaults();\n }\n});\n\n// src/core/errors/types.ts\nvar VeryfrontError;\nvar init_types = __esm({\n "src/core/errors/types.ts"() {\n "use strict";\n VeryfrontError = class extends Error {\n constructor(message, code, context) {\n super(message);\n this.name = "VeryfrontError";\n this.code = code;\n this.context = context;\n }\n };\n }\n});\n\n// src/core/errors/agent-errors.ts\nvar init_agent_errors = __esm({\n "src/core/errors/agent-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/build-errors.ts\nvar init_build_errors = __esm({\n "src/core/errors/build-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/runtime-errors.ts\nvar init_runtime_errors = __esm({\n "src/core/errors/runtime-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/system-errors.ts\nvar NetworkError;\nvar init_system_errors = __esm({\n "src/core/errors/system-errors.ts"() {\n "use strict";\n init_types();\n NetworkError = class extends VeryfrontError {\n constructor(message, context) {\n super(message, "NETWORK_ERROR" /* NETWORK_ERROR */, context);\n this.name = "NetworkError";\n }\n };\n }\n});\n\n// src/core/errors/error-handlers.ts\nvar init_error_handlers = __esm({\n "src/core/errors/error-handlers.ts"() {\n "use strict";\n init_logger();\n init_types();\n }\n});\n\n// src/core/errors/error-codes.ts\nfunction getErrorDocsUrl(code) {\n return `https://veryfront.com/docs/errors/${code}`;\n}\nvar ErrorCode2;\nvar init_error_codes = __esm({\n "src/core/errors/error-codes.ts"() {\n "use strict";\n ErrorCode2 = {\n CONFIG_NOT_FOUND: "VF001",\n CONFIG_INVALID: "VF002",\n CONFIG_PARSE_ERROR: "VF003",\n CONFIG_VALIDATION_ERROR: "VF004",\n CONFIG_TYPE_ERROR: "VF005",\n IMPORT_MAP_INVALID: "VF006",\n CORS_CONFIG_INVALID: "VF007",\n BUILD_FAILED: "VF100",\n BUNDLE_ERROR: "VF101",\n TYPESCRIPT_ERROR: "VF102",\n MDX_COMPILE_ERROR: "VF103",\n ASSET_OPTIMIZATION_ERROR: "VF104",\n SSG_GENERATION_ERROR: "VF105",\n SOURCEMAP_ERROR: "VF106",\n HYDRATION_MISMATCH: "VF200",\n RENDER_ERROR: "VF201",\n COMPONENT_ERROR: "VF202",\n LAYOUT_NOT_FOUND: "VF203",\n PAGE_NOT_FOUND: "VF204",\n API_ERROR: "VF205",\n MIDDLEWARE_ERROR: "VF206",\n ROUTE_CONFLICT: "VF300",\n INVALID_ROUTE_FILE: "VF301",\n ROUTE_HANDLER_INVALID: "VF302",\n DYNAMIC_ROUTE_ERROR: "VF303",\n ROUTE_PARAMS_ERROR: "VF304",\n API_ROUTE_ERROR: "VF305",\n MODULE_NOT_FOUND: "VF400",\n IMPORT_RESOLUTION_ERROR: "VF401",\n CIRCULAR_DEPENDENCY: "VF402",\n INVALID_IMPORT: "VF403",\n DEPENDENCY_MISSING: "VF404",\n VERSION_MISMATCH: "VF405",\n PORT_IN_USE: "VF500",\n SERVER_START_ERROR: "VF501",\n HMR_ERROR: "VF502",\n CACHE_ERROR: "VF503",\n FILE_WATCH_ERROR: "VF504",\n REQUEST_ERROR: "VF505",\n CLIENT_BOUNDARY_VIOLATION: "VF600",\n SERVER_ONLY_IN_CLIENT: "VF601",\n CLIENT_ONLY_IN_SERVER: "VF602",\n INVALID_USE_CLIENT: "VF603",\n INVALID_USE_SERVER: "VF604",\n RSC_PAYLOAD_ERROR: "VF605",\n DEV_SERVER_ERROR: "VF700",\n FAST_REFRESH_ERROR: "VF701",\n ERROR_OVERLAY_ERROR: "VF702",\n SOURCE_MAP_ERROR: "VF703",\n DEPLOYMENT_ERROR: "VF800",\n PLATFORM_ERROR: "VF801",\n ENV_VAR_MISSING: "VF802",\n PRODUCTION_BUILD_REQUIRED: "VF803",\n UNKNOWN_ERROR: "VF900",\n PERMISSION_DENIED: "VF901",\n FILE_NOT_FOUND: "VF902",\n INVALID_ARGUMENT: "VF903",\n TIMEOUT_ERROR: "VF904"\n };\n }\n});\n\n// src/core/errors/catalog/factory.ts\nfunction createErrorSolution(code, config) {\n return {\n code,\n ...config,\n docs: config.docs ?? getErrorDocsUrl(code)\n };\n}\nfunction createSimpleError(code, title, message, steps) {\n return createErrorSolution(code, { title, message, steps });\n}\nvar init_factory = __esm({\n "src/core/errors/catalog/factory.ts"() {\n "use strict";\n init_error_codes();\n }\n});\n\n// src/core/errors/catalog/config-errors.ts\nvar CONFIG_ERROR_CATALOG;\nvar init_config_errors = __esm({\n "src/core/errors/catalog/config-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n CONFIG_ERROR_CATALOG = {\n [ErrorCode2.CONFIG_NOT_FOUND]: createErrorSolution(ErrorCode2.CONFIG_NOT_FOUND, {\n title: "Configuration file not found",\n message: "Veryfront could not find veryfront.config.js in your project root.",\n steps: [\n "Create veryfront.config.js in your project root directory",\n "Run \'veryfront init\' to generate a default configuration",\n "Or copy from an example project"\n ],\n example: `// veryfront.config.js\nexport default {\n title: "My App",\n dev: { port: 3002 }\n}`,\n tips: ["You can use .ts or .mjs extensions too", "Config is optional for simple projects"]\n }),\n [ErrorCode2.CONFIG_INVALID]: createErrorSolution(ErrorCode2.CONFIG_INVALID, {\n title: "Invalid configuration",\n message: "Your configuration file has invalid values or structure.",\n steps: [\n "Check that the config exports a default object",\n "Ensure all values are valid JavaScript types",\n "Remove any trailing commas",\n "Verify property names match the schema"\n ],\n example: `// \\u2713 Valid config\nexport default {\n title: "My App",\n dev: {\n port: 3002,\n open: true\n }\n}`\n }),\n [ErrorCode2.CONFIG_PARSE_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_PARSE_ERROR,\n "Configuration parse error",\n "Failed to parse your configuration file.",\n [\n "Check for syntax errors (missing brackets, quotes, etc.)",\n "Ensure the file has valid JavaScript/TypeScript syntax",\n "Look for the specific parse error in the output above"\n ]\n ),\n [ErrorCode2.CONFIG_VALIDATION_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_VALIDATION_ERROR,\n "Configuration validation failed",\n "Configuration values do not pass validation.",\n [\n "Check that port numbers are between 1-65535",\n "Ensure boolean flags are true/false (not strings)",\n "Verify URLs are properly formatted",\n "Check array/object structures match expected format"\n ]\n ),\n [ErrorCode2.CONFIG_TYPE_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_TYPE_ERROR,\n "Configuration type error",\n "A configuration value has the wrong type.",\n [\n "Check that numbers are not in quotes",\n \'Ensure booleans are true/false, not "true"/"false"\',\n "Verify arrays use [] brackets",\n "Check objects use {} braces"\n ]\n ),\n [ErrorCode2.IMPORT_MAP_INVALID]: createErrorSolution(ErrorCode2.IMPORT_MAP_INVALID, {\n title: "Invalid import map",\n message: "The import map in your configuration is invalid.",\n steps: [\n "Check import map structure: { imports: {}, scopes: {} }",\n "Ensure URLs are valid and accessible",\n "Verify package names are correct"\n ],\n example: `resolve: {\n importMap: {\n imports: {\n "react": "https://esm.sh/react@19",\n "@/utils": "./src/utils/index.ts"\n }\n }\n}`\n }),\n [ErrorCode2.CORS_CONFIG_INVALID]: createErrorSolution(ErrorCode2.CORS_CONFIG_INVALID, {\n title: "Invalid CORS configuration",\n message: "The CORS configuration is invalid.",\n steps: [\n "Use true for default CORS settings",\n "Or provide an object with origin, methods, headers",\n "Ensure origin is a string, not an array"\n ],\n example: `security: {\n cors: true // or { origin: "https://example.com" }\n}`\n })\n };\n }\n});\n\n// src/core/errors/catalog/build-errors.ts\nvar BUILD_ERROR_CATALOG;\nvar init_build_errors2 = __esm({\n "src/core/errors/catalog/build-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n BUILD_ERROR_CATALOG = {\n [ErrorCode2.BUILD_FAILED]: createErrorSolution(ErrorCode2.BUILD_FAILED, {\n title: "Build failed",\n message: "The build process encountered errors.",\n steps: [\n "Check the error messages above for specific issues",\n "Fix any TypeScript or syntax errors",\n "Ensure all imports can be resolved",\n "Run \'veryfront doctor\' to check your environment"\n ],\n tips: ["Try running with --verbose for more details", "Check build logs for warnings"]\n }),\n [ErrorCode2.BUNDLE_ERROR]: createSimpleError(\n ErrorCode2.BUNDLE_ERROR,\n "Bundle generation failed",\n "Failed to generate JavaScript bundles.",\n [\n "Check for circular dependencies",\n "Ensure all imports are valid",\n "Try clearing cache: veryfront clean"\n ]\n ),\n [ErrorCode2.TYPESCRIPT_ERROR]: createSimpleError(\n ErrorCode2.TYPESCRIPT_ERROR,\n "TypeScript compilation error",\n "TypeScript found errors in your code.",\n [\n "Fix the TypeScript errors shown above",\n "Check your tsconfig.json configuration",\n "Ensure all types are properly imported"\n ]\n ),\n [ErrorCode2.MDX_COMPILE_ERROR]: createErrorSolution(ErrorCode2.MDX_COMPILE_ERROR, {\n title: "MDX compilation failed",\n message: "Failed to compile MDX file.",\n steps: [\n "Check for syntax errors in your MDX file",\n "Ensure frontmatter YAML is valid",\n "Verify JSX components are properly imported",\n "Check for unclosed tags or brackets"\n ],\n example: `---\ntitle: My Post\n---\n\nimport Button from \'./components/Button.jsx\'\n\n# Hello World\n\n<Button>Click me</Button>`\n }),\n [ErrorCode2.ASSET_OPTIMIZATION_ERROR]: createSimpleError(\n ErrorCode2.ASSET_OPTIMIZATION_ERROR,\n "Asset optimization failed",\n "Failed to optimize assets (images, CSS, etc.).",\n [\n "Check that asset files are valid",\n "Ensure file paths are correct",\n "Try disabling optimization temporarily"\n ]\n ),\n [ErrorCode2.SSG_GENERATION_ERROR]: createSimpleError(\n ErrorCode2.SSG_GENERATION_ERROR,\n "Static site generation failed",\n "Failed to generate static pages.",\n [\n "Check that all routes are valid",\n "Ensure getStaticData functions return correctly",\n "Verify no dynamic content requires runtime"\n ]\n ),\n [ErrorCode2.SOURCEMAP_ERROR]: createSimpleError(\n ErrorCode2.SOURCEMAP_ERROR,\n "Source map generation failed",\n "Failed to generate source maps.",\n [\n "Try disabling source maps temporarily",\n "Check for very large files that might cause issues"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/runtime-errors.ts\nvar RUNTIME_ERROR_CATALOG;\nvar init_runtime_errors2 = __esm({\n "src/core/errors/catalog/runtime-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n RUNTIME_ERROR_CATALOG = {\n [ErrorCode2.HYDRATION_MISMATCH]: createErrorSolution(ErrorCode2.HYDRATION_MISMATCH, {\n title: "Hydration mismatch",\n message: "Client-side HTML does not match server-rendered HTML.",\n steps: [\n "Check for random values or timestamps in render",\n "Ensure Date() calls are consistent",\n "Avoid using browser-only APIs during SSR",\n "Check for white space or formatting differences"\n ],\n example: `// \\u274C Wrong - random on each render\n<div>{Math.random()}</div>\n\nconst [random, setRandom] = useState(0)\nuseEffect(() => setRandom(Math.random()), [])\n<div>{random}</div>`,\n relatedErrors: [ErrorCode2.RENDER_ERROR]\n }),\n [ErrorCode2.RENDER_ERROR]: createSimpleError(\n ErrorCode2.RENDER_ERROR,\n "Render error",\n "Failed to render component.",\n [\n "Check the component for errors",\n "Ensure all props are valid",\n "Look for null/undefined access",\n "Check error boundaries"\n ]\n ),\n [ErrorCode2.COMPONENT_ERROR]: createSimpleError(\n ErrorCode2.COMPONENT_ERROR,\n "Component error",\n "Error in component lifecycle or render.",\n [\n "Check component code for errors",\n "Ensure hooks follow Rules of Hooks",\n "Verify props are passed correctly"\n ]\n ),\n [ErrorCode2.LAYOUT_NOT_FOUND]: createErrorSolution(ErrorCode2.LAYOUT_NOT_FOUND, {\n title: "Layout file not found",\n message: "Required layout file is missing.",\n steps: [\n "Create app/layout.tsx in App Router",\n "Or create layouts/default.mdx for Pages Router",\n "Check file path and name are correct"\n ],\n example: `// app/layout.tsx\nexport default function RootLayout({ children }) {\n return (\n <html lang="en">\n <body>{children}</body>\n </html>\n )\n}`\n }),\n [ErrorCode2.PAGE_NOT_FOUND]: createSimpleError(\n ErrorCode2.PAGE_NOT_FOUND,\n "Page not found",\n "The requested page does not exist.",\n [\n "Check that the page file exists",\n "Verify file name matches route",\n "Ensure file extension is correct (.tsx, .jsx, .mdx)"\n ]\n ),\n [ErrorCode2.API_ERROR]: createSimpleError(\n ErrorCode2.API_ERROR,\n "API handler error",\n "Error in API route handler.",\n [\n "Check API handler code for errors",\n "Ensure proper error handling",\n "Verify request/response format"\n ]\n ),\n [ErrorCode2.MIDDLEWARE_ERROR]: createSimpleError(\n ErrorCode2.MIDDLEWARE_ERROR,\n "Middleware error",\n "Error in middleware execution.",\n [\n "Check middleware code for errors",\n "Ensure middleware returns Response",\n "Verify middleware is properly exported"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/route-errors.ts\nvar ROUTE_ERROR_CATALOG;\nvar init_route_errors = __esm({\n "src/core/errors/catalog/route-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n ROUTE_ERROR_CATALOG = {\n [ErrorCode2.ROUTE_CONFLICT]: createSimpleError(\n ErrorCode2.ROUTE_CONFLICT,\n "Route conflict",\n "Multiple files are trying to handle the same route.",\n [\n "Check for duplicate route files",\n "Remove conflicting routes",\n "Use dynamic routes [id] carefully"\n ]\n ),\n [ErrorCode2.INVALID_ROUTE_FILE]: createErrorSolution(ErrorCode2.INVALID_ROUTE_FILE, {\n title: "Invalid route file",\n message: "Route file has invalid structure or exports.",\n steps: [\n "API routes must export GET, POST, etc. functions",\n "Page routes must export default component",\n "Check for syntax errors"\n ],\n example: `// app/api/users/route.ts\nexport async function GET() {\n return Response.json({ users: [] })\n}`\n }),\n [ErrorCode2.ROUTE_HANDLER_INVALID]: createSimpleError(\n ErrorCode2.ROUTE_HANDLER_INVALID,\n "Invalid route handler",\n "Route handler does not return Response.",\n [\n "Ensure handler returns Response object",\n "Use Response.json() for JSON responses",\n "Check for missing return statement"\n ]\n ),\n [ErrorCode2.DYNAMIC_ROUTE_ERROR]: createSimpleError(\n ErrorCode2.DYNAMIC_ROUTE_ERROR,\n "Dynamic route error",\n "Error in dynamic route handling.",\n [\n "Check [param] syntax is correct",\n "Ensure params are accessed properly",\n "Verify dynamic segment names"\n ]\n ),\n [ErrorCode2.ROUTE_PARAMS_ERROR]: createSimpleError(\n ErrorCode2.ROUTE_PARAMS_ERROR,\n "Route parameters error",\n "Error accessing route parameters.",\n [\n "Check params object structure",\n "Ensure parameter names match route",\n "Verify params are strings"\n ]\n ),\n [ErrorCode2.API_ROUTE_ERROR]: createSimpleError(\n ErrorCode2.API_ROUTE_ERROR,\n "API route error",\n "Error in API route execution.",\n [\n "Check API handler code",\n "Ensure proper error handling",\n "Verify request parsing"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/module-errors.ts\nvar MODULE_ERROR_CATALOG;\nvar init_module_errors = __esm({\n "src/core/errors/catalog/module-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n MODULE_ERROR_CATALOG = {\n [ErrorCode2.MODULE_NOT_FOUND]: createErrorSolution(ErrorCode2.MODULE_NOT_FOUND, {\n title: "Module not found",\n message: "Cannot find the imported module.",\n steps: [\n "Check that the file path is correct",\n "Ensure the module is installed or exists",\n "Add missing module to import map",\n "Check for typos in import statement"\n ],\n example: `// Add to veryfront.config.js\nresolve: {\n importMap: {\n imports: {\n "missing-lib": "https://esm.sh/missing-lib@1.0.0"\n }\n }\n}`\n }),\n [ErrorCode2.IMPORT_RESOLUTION_ERROR]: createSimpleError(\n ErrorCode2.IMPORT_RESOLUTION_ERROR,\n "Import resolution failed",\n "Failed to resolve import specifier.",\n [\n "Check import paths are correct",\n "Ensure modules are in import map",\n "Verify network connectivity for remote imports"\n ]\n ),\n [ErrorCode2.CIRCULAR_DEPENDENCY]: createSimpleError(\n ErrorCode2.CIRCULAR_DEPENDENCY,\n "Circular dependency detected",\n "Files are importing each other in a circle.",\n [\n "Identify the circular import chain",\n "Extract shared code to separate file",\n "Use dependency injection or lazy imports"\n ]\n ),\n [ErrorCode2.INVALID_IMPORT]: createSimpleError(\n ErrorCode2.INVALID_IMPORT,\n "Invalid import statement",\n "Import statement has invalid syntax.",\n [\n \'Check import syntax: import X from "y"\',\n "Ensure quotes are properly closed",\n "Verify export exists in target module"\n ]\n ),\n [ErrorCode2.DEPENDENCY_MISSING]: createErrorSolution(ErrorCode2.DEPENDENCY_MISSING, {\n title: "Required dependency not found",\n message: "A required dependency is missing.",\n steps: [\n "Add React to your import map",\n "Ensure all peer dependencies are included",\n "Run \'veryfront doctor\' to verify setup"\n ],\n example: `// Minimum required imports\nresolve: {\n importMap: {\n imports: {\n "react": "https://esm.sh/react@19",\n "react-dom": "https://esm.sh/react-dom@19"\n }\n }\n}`\n }),\n [ErrorCode2.VERSION_MISMATCH]: createSimpleError(\n ErrorCode2.VERSION_MISMATCH,\n "Dependency version mismatch",\n "Incompatible versions of dependencies detected.",\n [\n "Ensure React and React-DOM versions match",\n "Check for multiple React instances",\n "Update dependencies to compatible versions"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/server-errors.ts\nvar SERVER_ERROR_CATALOG;\nvar init_server_errors = __esm({\n "src/core/errors/catalog/server-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n SERVER_ERROR_CATALOG = {\n [ErrorCode2.PORT_IN_USE]: createErrorSolution(ErrorCode2.PORT_IN_USE, {\n title: "Port already in use",\n message: "Another process is using the specified port.",\n steps: [\n "Stop the other process: lsof -i :PORT",\n "Use a different port: veryfront dev --port 3003",\n "Add port to config file"\n ],\n example: `// veryfront.config.js\ndev: {\n port: 3003\n}`\n }),\n [ErrorCode2.SERVER_START_ERROR]: createSimpleError(\n ErrorCode2.SERVER_START_ERROR,\n "Server failed to start",\n "Development server could not start.",\n [\n "Check for port conflicts",\n "Ensure file permissions are correct",\n "Verify configuration is valid"\n ]\n ),\n [ErrorCode2.HMR_ERROR]: createSimpleError(\n ErrorCode2.HMR_ERROR,\n "Hot Module Replacement error",\n "HMR failed to update module.",\n [\n "Try refreshing the page",\n "Check for syntax errors",\n "Restart dev server if persistent"\n ]\n ),\n [ErrorCode2.CACHE_ERROR]: createSimpleError(\n ErrorCode2.CACHE_ERROR,\n "Cache operation failed",\n "Error reading or writing cache.",\n [\n "Clear cache: veryfront clean --cache",\n "Check disk space",\n "Verify file permissions"\n ]\n ),\n [ErrorCode2.FILE_WATCH_ERROR]: createSimpleError(\n ErrorCode2.FILE_WATCH_ERROR,\n "File watching failed",\n "Could not watch files for changes.",\n [\n "Check system file watch limits",\n "Reduce number of watched files",\n "Try restarting dev server"\n ]\n ),\n [ErrorCode2.REQUEST_ERROR]: createSimpleError(\n ErrorCode2.REQUEST_ERROR,\n "Request handling error",\n "Error processing HTTP request.",\n [\n "Check request format and headers",\n "Verify route handler code",\n "Check for middleware errors"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/rsc-errors.ts\nvar RSC_ERROR_CATALOG;\nvar init_rsc_errors = __esm({\n "src/core/errors/catalog/rsc-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n RSC_ERROR_CATALOG = {\n [ErrorCode2.CLIENT_BOUNDARY_VIOLATION]: createErrorSolution(\n ErrorCode2.CLIENT_BOUNDARY_VIOLATION,\n {\n title: "Client/Server boundary violation",\n message: "Server-only code used in Client Component.",\n steps: [\n "Move server-only imports to Server Components",\n "Use \'use server\' for server actions",\n "Split component into server and client parts"\n ],\n example: `// \\u2713 Correct pattern\nimport { db } from \'./database\'\nexport default async function ServerComponent() {\n const data = await db.query(\'...\')\n return <ClientComponent data={data} />\n}\n\n\'use client\'\nexport default function ClientComponent({ data }) {\n return <div>{data}</div>\n}`\n }\n ),\n [ErrorCode2.SERVER_ONLY_IN_CLIENT]: createSimpleError(\n ErrorCode2.SERVER_ONLY_IN_CLIENT,\n "Server-only module in Client Component",\n "Cannot use server-only module in client code.",\n [\n "Move server logic to Server Component",\n "Use API routes for client data fetching",\n "Pass data as props from server"\n ]\n ),\n [ErrorCode2.CLIENT_ONLY_IN_SERVER]: createSimpleError(\n ErrorCode2.CLIENT_ONLY_IN_SERVER,\n "Client-only code in Server Component",\n "Cannot use browser APIs in Server Component.",\n [\n "Add \'use client\' directive",\n "Move client-only code to Client Component",\n "Use useEffect for client-side logic"\n ]\n ),\n [ErrorCode2.INVALID_USE_CLIENT]: createErrorSolution(ErrorCode2.INVALID_USE_CLIENT, {\n title: "Invalid \'use client\' directive",\n message: "\'use client\' directive is not properly placed.",\n steps: [\n "Place \'use client\' at the very top of file",\n "Must be before any imports",\n \'Use exact string: "use client"\'\n ],\n example: `\'use client\' // Must be first line\n\nimport React from \'react\'`\n }),\n [ErrorCode2.INVALID_USE_SERVER]: createSimpleError(\n ErrorCode2.INVALID_USE_SERVER,\n "Invalid \'use server\' directive",\n "\'use server\' directive is not properly placed.",\n [\n "Place \'use server\' at top of function",\n "Or at top of file for all functions",\n \'Use exact string: "use server"\'\n ]\n ),\n [ErrorCode2.RSC_PAYLOAD_ERROR]: createSimpleError(\n ErrorCode2.RSC_PAYLOAD_ERROR,\n "RSC payload error",\n "Error serializing Server Component payload.",\n [\n "Ensure props are JSON-serializable",\n "Avoid passing functions as props",\n "Check for circular references"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/dev-errors.ts\nvar DEV_ERROR_CATALOG;\nvar init_dev_errors = __esm({\n "src/core/errors/catalog/dev-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n DEV_ERROR_CATALOG = {\n [ErrorCode2.DEV_SERVER_ERROR]: createSimpleError(\n ErrorCode2.DEV_SERVER_ERROR,\n "Development server error",\n "Error in development server.",\n [\n "Check server logs for details",\n "Try restarting dev server",\n "Clear cache and restart"\n ]\n ),\n [ErrorCode2.FAST_REFRESH_ERROR]: createSimpleError(\n ErrorCode2.FAST_REFRESH_ERROR,\n "Fast Refresh error",\n "React Fast Refresh failed.",\n [\n "Check for syntax errors",\n "Ensure components follow Fast Refresh rules",\n "Try full page refresh"\n ]\n ),\n [ErrorCode2.ERROR_OVERLAY_ERROR]: createSimpleError(\n ErrorCode2.ERROR_OVERLAY_ERROR,\n "Error overlay failed",\n "Could not display error overlay.",\n [\n "Check browser console for details",\n "Try disabling browser extensions",\n "Refresh the page"\n ]\n ),\n [ErrorCode2.SOURCE_MAP_ERROR]: createSimpleError(\n ErrorCode2.SOURCE_MAP_ERROR,\n "Source map error",\n "Error loading or parsing source map.",\n [\n "Check that source maps are enabled",\n "Try rebuilding the project",\n "Check for corrupted build files"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/deployment-errors.ts\nvar DEPLOYMENT_ERROR_CATALOG;\nvar init_deployment_errors = __esm({\n "src/core/errors/catalog/deployment-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n DEPLOYMENT_ERROR_CATALOG = {\n [ErrorCode2.DEPLOYMENT_ERROR]: createSimpleError(\n ErrorCode2.DEPLOYMENT_ERROR,\n "Deployment failed",\n "Failed to deploy application.",\n [\n "Check deployment logs for details",\n "Verify platform credentials",\n "Ensure build succeeded first"\n ]\n ),\n [ErrorCode2.PLATFORM_ERROR]: createSimpleError(\n ErrorCode2.PLATFORM_ERROR,\n "Platform error",\n "Deployment platform returned an error.",\n [\n "Check platform status page",\n "Verify API keys and credentials",\n "Try deploying again"\n ]\n ),\n [ErrorCode2.ENV_VAR_MISSING]: createSimpleError(\n ErrorCode2.ENV_VAR_MISSING,\n "Environment variable missing",\n "Required environment variable is not set.",\n [\n "Add variable to .env file",\n "Set variable in deployment platform",\n "Check variable name is correct"\n ]\n ),\n [ErrorCode2.PRODUCTION_BUILD_REQUIRED]: createSimpleError(\n ErrorCode2.PRODUCTION_BUILD_REQUIRED,\n "Production build required",\n "Must build project before deploying.",\n [\n "Run \'veryfront build\' first",\n "Check that dist/ directory exists",\n "Verify build completed successfully"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/general-errors.ts\nvar GENERAL_ERROR_CATALOG;\nvar init_general_errors = __esm({\n "src/core/errors/catalog/general-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n GENERAL_ERROR_CATALOG = {\n [ErrorCode2.UNKNOWN_ERROR]: createSimpleError(\n ErrorCode2.UNKNOWN_ERROR,\n "Unknown error",\n "An unexpected error occurred.",\n [\n "Check error details above",\n "Run \'veryfront doctor\' to diagnose",\n "Try restarting the operation",\n "Check GitHub issues for similar problems"\n ]\n ),\n [ErrorCode2.PERMISSION_DENIED]: createSimpleError(\n ErrorCode2.PERMISSION_DENIED,\n "Permission denied",\n "Insufficient permissions to perform operation.",\n [\n "Check file/directory permissions",\n "Run with appropriate permissions",\n "Verify user has write access"\n ]\n ),\n [ErrorCode2.FILE_NOT_FOUND]: createSimpleError(\n ErrorCode2.FILE_NOT_FOUND,\n "File not found",\n "Required file does not exist.",\n [\n "Check that file path is correct",\n "Verify file exists in project",\n "Check for typos in file name"\n ]\n ),\n [ErrorCode2.INVALID_ARGUMENT]: createSimpleError(\n ErrorCode2.INVALID_ARGUMENT,\n "Invalid argument",\n "Command received invalid argument.",\n [\n "Check command syntax",\n "Verify argument values",\n "Run \'veryfront help <command>\' for usage"\n ]\n ),\n [ErrorCode2.TIMEOUT_ERROR]: createSimpleError(\n ErrorCode2.TIMEOUT_ERROR,\n "Operation timed out",\n "Operation took too long to complete.",\n [\n "Check network connectivity",\n "Try increasing timeout if available",\n "Check for very large files"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/index.ts\nvar ERROR_CATALOG;\nvar init_catalog = __esm({\n "src/core/errors/catalog/index.ts"() {\n "use strict";\n init_config_errors();\n init_build_errors2();\n init_runtime_errors2();\n init_route_errors();\n init_module_errors();\n init_server_errors();\n init_rsc_errors();\n init_dev_errors();\n init_deployment_errors();\n init_general_errors();\n init_factory();\n ERROR_CATALOG = {\n ...CONFIG_ERROR_CATALOG,\n ...BUILD_ERROR_CATALOG,\n ...RUNTIME_ERROR_CATALOG,\n ...ROUTE_ERROR_CATALOG,\n ...MODULE_ERROR_CATALOG,\n ...SERVER_ERROR_CATALOG,\n ...RSC_ERROR_CATALOG,\n ...DEV_ERROR_CATALOG,\n ...DEPLOYMENT_ERROR_CATALOG,\n ...GENERAL_ERROR_CATALOG\n };\n }\n});\n\n// src/core/errors/user-friendly/error-catalog.ts\nvar init_error_catalog = __esm({\n "src/core/errors/user-friendly/error-catalog.ts"() {\n "use strict";\n }\n});\n\n// src/platform/compat/console/ansi.ts\nvar ansi, red, green, yellow, blue, magenta, cyan, white, gray, bold, dim, italic, underline, strikethrough, reset;\nvar init_ansi = __esm({\n "src/platform/compat/console/ansi.ts"() {\n ansi = (open, close) => (text2) => `\\x1B[${open}m${text2}\\x1B[${close}m`;\n red = ansi(31, 39);\n green = ansi(32, 39);\n yellow = ansi(33, 39);\n blue = ansi(34, 39);\n magenta = ansi(35, 39);\n cyan = ansi(36, 39);\n white = ansi(37, 39);\n gray = ansi(90, 39);\n bold = ansi(1, 22);\n dim = ansi(2, 22);\n italic = ansi(3, 23);\n underline = ansi(4, 24);\n strikethrough = ansi(9, 29);\n reset = (text2) => `\\x1B[0m${text2}`;\n }\n});\n\n// src/platform/compat/console/deno.ts\nvar deno_exports = {};\n__export(deno_exports, {\n blue: () => blue,\n bold: () => bold,\n colors: () => colors,\n cyan: () => cyan,\n dim: () => dim,\n gray: () => gray,\n green: () => green,\n italic: () => italic,\n magenta: () => magenta,\n red: () => red,\n reset: () => reset,\n strikethrough: () => strikethrough,\n underline: () => underline,\n white: () => white,\n yellow: () => yellow\n});\nvar colors;\nvar init_deno2 = __esm({\n "src/platform/compat/console/deno.ts"() {\n "use strict";\n init_ansi();\n colors = {\n red,\n green,\n yellow,\n blue,\n cyan,\n magenta,\n white,\n gray,\n bold,\n dim,\n italic,\n underline,\n strikethrough,\n reset\n };\n }\n});\n\n// src/platform/compat/console/node.ts\nvar node_exports = {};\n__export(node_exports, {\n blue: () => blue2,\n bold: () => bold2,\n colors: () => colors2,\n cyan: () => cyan2,\n dim: () => dim2,\n gray: () => gray2,\n green: () => green2,\n initColors: () => initColors,\n italic: () => italic2,\n magenta: () => magenta2,\n red: () => red2,\n reset: () => reset2,\n strikethrough: () => strikethrough2,\n underline: () => underline2,\n white: () => white2,\n yellow: () => yellow2\n});\nasync function ensurePc() {\n if (pc)\n return pc;\n const picocolorsModule = ["npm:", "picocolors"].join("");\n const mod = await import(picocolorsModule);\n pc = mod.default;\n return pc;\n}\nasync function initColors() {\n await ensurePc();\n}\nvar pc, lazyColor, colors2, red2, green2, yellow2, blue2, cyan2, magenta2, white2, gray2, bold2, dim2, italic2, underline2, strikethrough2, reset2;\nvar init_node = __esm({\n "src/platform/compat/console/node.ts"() {\n "use strict";\n pc = null;\n lazyColor = (fn) => (s) => pc?.[fn]?.(s) ?? s;\n colors2 = {\n red: lazyColor("red"),\n green: lazyColor("green"),\n yellow: lazyColor("yellow"),\n blue: lazyColor("blue"),\n cyan: lazyColor("cyan"),\n magenta: lazyColor("magenta"),\n white: lazyColor("white"),\n gray: lazyColor("gray"),\n bold: lazyColor("bold"),\n dim: lazyColor("dim"),\n italic: lazyColor("italic"),\n underline: lazyColor("underline"),\n strikethrough: lazyColor("strikethrough"),\n reset: lazyColor("reset")\n };\n red2 = lazyColor("red");\n green2 = lazyColor("green");\n yellow2 = lazyColor("yellow");\n blue2 = lazyColor("blue");\n cyan2 = lazyColor("cyan");\n magenta2 = lazyColor("magenta");\n white2 = lazyColor("white");\n gray2 = lazyColor("gray");\n bold2 = lazyColor("bold");\n dim2 = lazyColor("dim");\n italic2 = lazyColor("italic");\n underline2 = lazyColor("underline");\n strikethrough2 = lazyColor("strikethrough");\n reset2 = lazyColor("reset");\n }\n});\n\n// src/platform/compat/console/index.ts\nasync function loadColors() {\n if (_colors)\n return _colors;\n try {\n if (isDeno) {\n const mod = await Promise.resolve().then(() => (init_deno2(), deno_exports));\n _colors = mod.colors;\n } else {\n const mod = await Promise.resolve().then(() => (init_node(), node_exports));\n _colors = mod.colors;\n }\n } catch {\n _colors = fallbackColors;\n }\n return _colors;\n}\nvar noOp, fallbackColors, _colors, colorsPromise;\nvar init_console = __esm({\n "src/platform/compat/console/index.ts"() {\n init_runtime();\n noOp = (text2) => text2;\n fallbackColors = {\n red: noOp,\n green: noOp,\n yellow: noOp,\n blue: noOp,\n cyan: noOp,\n magenta: noOp,\n white: noOp,\n gray: noOp,\n bold: noOp,\n dim: noOp,\n italic: noOp,\n underline: noOp,\n strikethrough: noOp,\n reset: noOp\n };\n _colors = null;\n colorsPromise = loadColors();\n }\n});\n\n// src/core/errors/user-friendly/error-identifier.ts\nvar init_error_identifier = __esm({\n "src/core/errors/user-friendly/error-identifier.ts"() {\n "use strict";\n }\n});\n\n// src/core/errors/user-friendly/error-formatter.ts\nvar init_error_formatter = __esm({\n "src/core/errors/user-friendly/error-formatter.ts"() {\n "use strict";\n init_console();\n init_error_catalog();\n init_error_identifier();\n }\n});\n\n// src/core/errors/user-friendly/error-wrapper.ts\nvar init_error_wrapper = __esm({\n "src/core/errors/user-friendly/error-wrapper.ts"() {\n "use strict";\n init_console();\n init_process();\n init_logger();\n init_error_formatter();\n }\n});\n\n// src/core/errors/user-friendly/index.ts\nvar init_user_friendly = __esm({\n "src/core/errors/user-friendly/index.ts"() {\n "use strict";\n init_error_catalog();\n init_error_formatter();\n init_error_identifier();\n init_error_wrapper();\n }\n});\n\n// src/core/errors/index.ts\nvar init_errors = __esm({\n "src/core/errors/index.ts"() {\n init_types();\n init_agent_errors();\n init_build_errors();\n init_runtime_errors();\n init_system_errors();\n init_error_handlers();\n init_catalog();\n init_user_friendly();\n }\n});\n\n// src/platform/adapters/deno.ts\nvar DenoFileSystemAdapter, DenoEnvironmentAdapter, DenoServerAdapter, DenoShellAdapter, DenoServer, DenoAdapter, denoAdapter;\nvar init_deno3 = __esm({\n "src/platform/adapters/deno.ts"() {\n "use strict";\n init_veryfront_error();\n init_config();\n init_utils();\n DenoFileSystemAdapter = class {\n async readFile(path) {\n return await Deno.readTextFile(path);\n }\n async readFileBytes(path) {\n return await Deno.readFile(path);\n }\n async writeFile(path, content) {\n await Deno.writeTextFile(path, content);\n }\n async exists(path) {\n try {\n await Deno.stat(path);\n return true;\n } catch (_error) {\n return false;\n }\n }\n async *readDir(path) {\n for await (const entry of Deno.readDir(path)) {\n yield {\n name: entry.name,\n isFile: entry.isFile,\n isDirectory: entry.isDirectory,\n isSymlink: entry.isSymlink\n };\n }\n }\n async stat(path) {\n const stat = await Deno.stat(path);\n return {\n size: stat.size,\n isFile: stat.isFile,\n isDirectory: stat.isDirectory,\n isSymlink: stat.isSymlink,\n mtime: stat.mtime\n };\n }\n async mkdir(path, options) {\n await Deno.mkdir(path, options);\n }\n async remove(path, options) {\n await Deno.remove(path, options);\n }\n async makeTempDir(prefix) {\n return await Deno.makeTempDir({ prefix });\n }\n watch(paths, options) {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n const watcher = Deno.watchFs(pathArray, { recursive });\n let closed = false;\n const denoIterator = watcher[Symbol.asyncIterator]();\n const mapEventKind = (kind) => {\n switch (kind) {\n case "create":\n return "create";\n case "modify":\n return "modify";\n case "remove":\n return "delete";\n default:\n return "any";\n }\n };\n const iterator = {\n async next() {\n if (closed || signal?.aborted) {\n return { done: true, value: void 0 };\n }\n try {\n const result = await denoIterator.next();\n if (result.done) {\n return { done: true, value: void 0 };\n }\n return {\n done: false,\n value: {\n kind: mapEventKind(result.value.kind),\n paths: result.value.paths\n }\n };\n } catch (error2) {\n if (closed || signal?.aborted) {\n return { done: true, value: void 0 };\n }\n throw error2;\n }\n },\n async return() {\n closed = true;\n if (denoIterator.return) {\n await denoIterator.return();\n }\n return { done: true, value: void 0 };\n }\n };\n const cleanup = () => {\n if (closed)\n return;\n closed = true;\n try {\n if ("close" in watcher && typeof watcher.close === "function") {\n watcher.close();\n }\n } catch (error2) {\n serverLogger.debug("[Deno] Filesystem watcher cleanup failed", { error: error2 });\n }\n };\n if (signal) {\n signal.addEventListener("abort", cleanup);\n }\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n close: cleanup\n };\n }\n };\n DenoEnvironmentAdapter = class {\n get(key) {\n return Deno.env.get(key);\n }\n set(key, value) {\n Deno.env.set(key, value);\n }\n toObject() {\n return Deno.env.toObject();\n }\n };\n DenoServerAdapter = class {\n upgradeWebSocket(request) {\n const { socket, response } = Deno.upgradeWebSocket(request);\n return { socket, response };\n }\n };\n DenoShellAdapter = class {\n statSync(path) {\n try {\n const stat = Deno.statSync(path);\n return {\n isFile: stat.isFile,\n isDirectory: stat.isDirectory\n };\n } catch (error2) {\n throw toError(createError({\n type: "file",\n message: `Failed to stat file: ${error2}`\n }));\n }\n }\n readFileSync(path) {\n try {\n return Deno.readTextFileSync(path);\n } catch (error2) {\n throw toError(createError({\n type: "file",\n message: `Failed to read file: ${error2}`\n }));\n }\n }\n };\n DenoServer = class {\n constructor(server, hostname, port, abortController) {\n this.server = server;\n this.hostname = hostname;\n this.port = port;\n this.abortController = abortController;\n }\n async stop() {\n try {\n if (this.abortController) {\n this.abortController.abort();\n }\n await this.server.shutdown();\n } catch (error2) {\n serverLogger.debug("[Deno] Server shutdown failed", { error: error2 });\n }\n }\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n };\n DenoAdapter = class {\n constructor() {\n this.id = "deno";\n this.name = "deno";\n /** @deprecated Use `id` instead */\n this.platform = "deno";\n this.fs = new DenoFileSystemAdapter();\n this.env = new DenoEnvironmentAdapter();\n this.server = new DenoServerAdapter();\n this.shell = new DenoShellAdapter();\n this.capabilities = {\n typescript: true,\n jsx: true,\n http2: true,\n websocket: true,\n workers: true,\n fileWatching: true,\n shell: true,\n kvStore: true,\n // Deno KV available\n writableFs: true\n };\n /** @deprecated Use `capabilities` instead */\n this.features = {\n websocket: true,\n http2: true,\n workers: true,\n jsx: true,\n typescript: true\n };\n }\n serve(handler, options = {}) {\n const { port = DEFAULT_DEV_PORT, hostname = "localhost", onListen } = options;\n const controller = new AbortController();\n const signal = options.signal || controller.signal;\n const server = Deno.serve({\n port,\n hostname,\n signal,\n handler: async (request, _info) => {\n try {\n return await handler(request);\n } catch (error2) {\n const { serverLogger: serverLogger2 } = await Promise.resolve().then(() => (init_utils(), utils_exports));\n serverLogger2.error("Request handler error:", error2);\n return new Response("Internal Server Error", { status: 500 });\n }\n },\n onListen: (params) => {\n onListen?.({ hostname: params.hostname, port: params.port });\n }\n });\n const controllerToPass = options.signal ? void 0 : controller;\n return Promise.resolve(new DenoServer(server, hostname, port, controllerToPass));\n }\n };\n denoAdapter = new DenoAdapter();\n }\n});\n\n// src/rendering/client/router.ts\ninit_utils();\nimport ReactDOM from "react-dom/client";\n\n// src/routing/matchers/pattern-route-matcher.ts\ninit_path_utils();\n\n// src/routing/matchers/index.ts\ninit_utils();\n\n// src/platform/compat/path-helper.ts\nimport nodePath2 from "node:path";\nvar pathMod = null;\nif (typeof Deno === "undefined") {\n pathMod = nodePath2;\n} else {\n Promise.resolve().then(() => (init_std_path(), std_path_exports)).then((mod) => {\n pathMod = mod;\n });\n}\nvar sep3 = nodePath2.sep;\n\n// src/routing/client/dom-utils.ts\ninit_utils();\nfunction isInternalLink(target) {\n const href = target.getAttribute("href");\n if (!href)\n return false;\n if (href.startsWith("http") || href.startsWith("mailto:"))\n return false;\n if (href.startsWith("#"))\n return false;\n if (target.getAttribute("target") === "_blank" || target.getAttribute("download")) {\n return false;\n }\n return true;\n}\nfunction findAnchorElement(element) {\n let current = element;\n while (current && current.tagName !== "A") {\n current = current.parentElement;\n }\n if (!current || !(current instanceof HTMLAnchorElement)) {\n return null;\n }\n return current;\n}\nfunction updateMetaTags(frontmatter) {\n if (frontmatter.description) {\n updateMetaTag(\'meta[name="description"]\', "name", "description", frontmatter.description);\n }\n if (frontmatter.ogTitle) {\n updateMetaTag(\'meta[property="og:title"]\', "property", "og:title", frontmatter.ogTitle);\n }\n}\nfunction updateMetaTag(selector, attributeName, attributeValue, content) {\n let metaTag = document.querySelector(selector);\n if (!metaTag) {\n metaTag = document.createElement("meta");\n metaTag.setAttribute(attributeName, attributeValue);\n document.head.appendChild(metaTag);\n }\n metaTag.setAttribute("content", content);\n}\nfunction executeScripts(container) {\n const scripts = container.querySelectorAll("script");\n scripts.forEach((oldScript) => {\n const newScript = document.createElement("script");\n Array.from(oldScript.attributes).forEach((attribute) => {\n newScript.setAttribute(attribute.name, attribute.value);\n });\n newScript.textContent = oldScript.textContent;\n oldScript.parentNode?.replaceChild(newScript, oldScript);\n });\n}\nfunction applyHeadDirectives(container) {\n const nodes = container.querySelectorAll(\'[data-veryfront-head="1"], vf-head\');\n if (nodes.length > 0) {\n cleanManagedHeadTags();\n }\n nodes.forEach((wrapper) => {\n processHeadWrapper(wrapper);\n wrapper.parentElement?.removeChild(wrapper);\n });\n}\nfunction cleanManagedHeadTags() {\n document.head.querySelectorAll(\'[data-veryfront-managed="1"]\').forEach((element) => element.parentElement?.removeChild(element));\n}\nfunction processHeadWrapper(wrapper) {\n wrapper.childNodes.forEach((node) => {\n if (!(node instanceof Element))\n return;\n const tagName = node.tagName.toLowerCase();\n if (tagName === "title") {\n document.title = node.textContent || document.title;\n return;\n }\n const clone = document.createElement(tagName);\n for (const attribute of Array.from(node.attributes)) {\n clone.setAttribute(attribute.name, attribute.value);\n }\n if (node.textContent && !clone.hasAttribute("src")) {\n clone.textContent = node.textContent;\n }\n clone.setAttribute("data-veryfront-managed", "1");\n document.head.appendChild(clone);\n });\n}\nfunction manageFocus(container) {\n try {\n const focusElement = container.querySelector("[data-router-focus]") || container.querySelector("main") || container.querySelector("h1");\n if (focusElement && focusElement instanceof HTMLElement && "focus" in focusElement) {\n focusElement.focus({ preventScroll: true });\n }\n } catch (error2) {\n rendererLogger.warn("[router] focus management failed", error2);\n }\n}\nfunction extractPageDataFromScript() {\n const pageDataScript = document.querySelector("script[data-veryfront-page]");\n if (!pageDataScript)\n return null;\n try {\n const content = pageDataScript.textContent;\n if (!content) {\n rendererLogger.warn("[dom-utils] Page data script has no content");\n return {};\n }\n return JSON.parse(content);\n } catch (error2) {\n rendererLogger.error("[dom-utils] Failed to parse page data:", error2);\n return null;\n }\n}\nfunction parsePageDataFromHTML(html3) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html3, "text/html");\n const root = doc.getElementById("root");\n let content = "";\n if (root) {\n content = root.innerHTML || "";\n } else {\n rendererLogger.warn("[dom-utils] No root element found in HTML");\n }\n const pageDataScript = doc.querySelector("script[data-veryfront-page]");\n let pageData = {};\n if (pageDataScript) {\n try {\n const content2 = pageDataScript.textContent;\n if (!content2) {\n rendererLogger.warn("[dom-utils] Page data script in HTML has no content");\n } else {\n pageData = JSON.parse(content2);\n }\n } catch (error2) {\n rendererLogger.error("[dom-utils] Failed to parse page data from HTML:", error2);\n }\n }\n return { content, pageData };\n}\n\n// src/routing/client/navigation-handlers.ts\ninit_utils();\ninit_config();\nvar NavigationHandlers = class {\n constructor(prefetchDelay = DEFAULT_PREFETCH_DELAY_MS, prefetchOptions = {}) {\n this.prefetchQueue = /* @__PURE__ */ new Set();\n this.scrollPositions = /* @__PURE__ */ new Map();\n this.isPopStateNav = false;\n this.prefetchDelay = prefetchDelay;\n this.prefetchOptions = prefetchOptions;\n }\n createClickHandler(callbacks) {\n return (event) => {\n const anchor = findAnchorElement(event.target);\n if (!anchor || !isInternalLink(anchor))\n return;\n const href = anchor.getAttribute("href");\n event.preventDefault();\n callbacks.onNavigate(href);\n };\n }\n createPopStateHandler(callbacks) {\n return (_event) => {\n const path = globalThis.location.pathname;\n this.isPopStateNav = true;\n callbacks.onNavigate(path);\n };\n }\n createMouseOverHandler(callbacks) {\n return (event) => {\n const target = event.target;\n if (target.tagName !== "A")\n return;\n const href = target.getAttribute("href");\n if (!href || href.startsWith("http") || href.startsWith("#"))\n return;\n if (!this.shouldPrefetchOnHover(target))\n return;\n if (!this.prefetchQueue.has(href)) {\n this.prefetchQueue.add(href);\n setTimeout(() => {\n callbacks.onPrefetch(href);\n this.prefetchQueue.delete(href);\n }, this.prefetchDelay);\n }\n };\n }\n shouldPrefetchOnHover(target) {\n const prefetchAttribute = target.getAttribute("data-prefetch");\n const isHoverEnabled = Boolean(this.prefetchOptions.hover);\n if (prefetchAttribute === "false")\n return false;\n return prefetchAttribute === "true" || isHoverEnabled;\n }\n saveScrollPosition(path) {\n try {\n const scrollY = globalThis.scrollY;\n if (typeof scrollY === "number") {\n this.scrollPositions.set(path, scrollY);\n } else {\n rendererLogger.debug("[router] No valid scrollY value available");\n this.scrollPositions.set(path, 0);\n }\n } catch (error2) {\n rendererLogger.warn("[router] failed to record scroll position", error2);\n }\n }\n getScrollPosition(path) {\n const position = this.scrollPositions.get(path);\n if (position === void 0) {\n rendererLogger.debug(`[router] No scroll position stored for ${path}`);\n return 0;\n }\n return position;\n }\n isPopState() {\n return this.isPopStateNav;\n }\n clearPopStateFlag() {\n this.isPopStateNav = false;\n }\n clear() {\n this.prefetchQueue.clear();\n this.scrollPositions.clear();\n this.isPopStateNav = false;\n }\n};\n\n// src/routing/client/page-loader.ts\ninit_utils();\ninit_errors();\nvar PageLoader = class {\n constructor() {\n this.cache = /* @__PURE__ */ new Map();\n }\n getCached(path) {\n return this.cache.get(path);\n }\n isCached(path) {\n return this.cache.has(path);\n }\n setCache(path, data) {\n this.cache.set(path, data);\n }\n clearCache() {\n this.cache.clear();\n }\n async fetchPageData(path) {\n const jsonData = await this.tryFetchJSON(path);\n if (jsonData)\n return jsonData;\n return this.fetchAndParseHTML(path);\n }\n async tryFetchJSON(path) {\n try {\n const response = await fetch(`/_veryfront/data${path}.json`, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (response.ok) {\n return await response.json();\n }\n } catch (error2) {\n rendererLogger.debug(`[PageLoader] RSC fetch failed for ${path}, falling back to HTML:`, error2);\n }\n return null;\n }\n async fetchAndParseHTML(path) {\n const response = await fetch(path, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (!response.ok) {\n throw new NetworkError(`Failed to fetch ${path}`, {\n status: response.status,\n path\n });\n }\n const html3 = await response.text();\n const { content, pageData } = parsePageDataFromHTML(html3);\n return {\n html: content,\n ...pageData\n };\n }\n async loadPage(path) {\n const cachedData = this.getCached(path);\n if (cachedData) {\n rendererLogger.debug(`Loading ${path} from cache`);\n return cachedData;\n }\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n return data;\n }\n async prefetch(path) {\n if (this.isCached(path))\n return;\n rendererLogger.debug(`Prefetching ${path}`);\n try {\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n } catch (error2) {\n rendererLogger.warn(`Failed to prefetch ${path}`, error2);\n }\n }\n};\n\n// src/routing/client/page-transition.ts\ninit_utils();\ninit_config();\n\n// src/security/client/html-sanitizer.ts\nvar SUSPICIOUS_PATTERNS = [\n { pattern: /<script[^>]*>[\\s\\S]*?<\\/script>/gi, name: "inline script" },\n { pattern: /javascript:/gi, name: "javascript: URL" },\n { pattern: /\\bon\\w+\\s*=/gi, name: "event handler attribute" },\n { pattern: /data:\\s*text\\/html/gi, name: "data: HTML URL" }\n];\nfunction isDevMode() {\n if (typeof globalThis !== "undefined") {\n const g = globalThis;\n return g.__VERYFRONT_DEV__ === true || g.Deno?.env?.get?.("VERYFRONT_ENV") === "development";\n }\n return false;\n}\nfunction validateTrustedHtml(html3, options = {}) {\n const { strict = false, warn = true } = options;\n for (const { pattern, name } of SUSPICIOUS_PATTERNS) {\n pattern.lastIndex = 0;\n if (pattern.test(html3)) {\n const message = `[Security] Suspicious ${name} detected in server HTML`;\n if (warn) {\n console.warn(message);\n }\n if (strict || !isDevMode()) {\n throw new Error(`Potentially unsafe HTML: ${name} detected`);\n }\n }\n }\n return html3;\n}\n\n// src/routing/client/page-transition.ts\nvar PageTransition = class {\n constructor(setupViewportPrefetch) {\n this.setupViewportPrefetch = setupViewportPrefetch;\n }\n destroy() {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n this.pendingTransitionTimeout = void 0;\n }\n }\n updatePage(data, isPopState, scrollY) {\n if (data.frontmatter?.title) {\n document.title = data.frontmatter.title;\n }\n updateMetaTags(data.frontmatter ?? {});\n const rootElement = document.getElementById("root");\n if (rootElement && (data.html ?? "") !== "") {\n this.performTransition(rootElement, data, isPopState, scrollY);\n }\n }\n performTransition(rootElement, data, isPopState, scrollY) {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n }\n rootElement.style.opacity = "0";\n this.pendingTransitionTimeout = setTimeout(() => {\n this.pendingTransitionTimeout = void 0;\n rootElement.innerHTML = validateTrustedHtml(String(data.html ?? ""));\n rootElement.style.opacity = "1";\n executeScripts(rootElement);\n applyHeadDirectives(rootElement);\n this.setupViewportPrefetch(rootElement);\n manageFocus(rootElement);\n this.handleScroll(isPopState, scrollY);\n }, PAGE_TRANSITION_DELAY_MS);\n }\n handleScroll(isPopState, scrollY) {\n try {\n globalThis.scrollTo(0, isPopState ? scrollY : 0);\n } catch (error2) {\n rendererLogger.warn("[router] scroll handling failed", error2);\n }\n }\n showError(error2) {\n const rootElement = document.getElementById("root");\n if (!rootElement)\n return;\n const errorDiv = document.createElement("div");\n errorDiv.className = "veryfront-error-page";\n const heading = document.createElement("h1");\n heading.textContent = "Oops! Something went wrong";\n const message = document.createElement("p");\n message.textContent = error2.message;\n const button = document.createElement("button");\n button.type = "button";\n button.textContent = "Reload Page";\n button.onclick = () => globalThis.location.reload();\n errorDiv.appendChild(heading);\n errorDiv.appendChild(message);\n errorDiv.appendChild(button);\n rootElement.innerHTML = "";\n rootElement.appendChild(errorDiv);\n }\n setLoadingState(loading) {\n const indicator = document.getElementById("veryfront-loading");\n if (indicator) {\n indicator.style.display = loading ? "block" : "none";\n }\n document.body.classList.toggle("veryfront-loading", loading);\n }\n};\n\n// src/routing/client/viewport-prefetch.ts\ninit_utils();\nvar ViewportPrefetch = class {\n constructor(prefetchCallback, prefetchOptions = {}) {\n this.observer = null;\n this.prefetchCallback = prefetchCallback;\n this.prefetchOptions = prefetchOptions;\n }\n setup(root) {\n try {\n if (!("IntersectionObserver" in globalThis))\n return;\n if (this.observer)\n this.observer.disconnect();\n this.createObserver();\n this.observeLinks(root);\n } catch (error2) {\n rendererLogger.debug("[router] setupViewportPrefetch failed", error2);\n }\n }\n createObserver() {\n this.observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const isAnchor = typeof HTMLAnchorElement !== "undefined" ? entry.target instanceof HTMLAnchorElement : entry.target.tagName === "A";\n if (isAnchor) {\n const href = entry.target.getAttribute("href");\n if (href) {\n this.prefetchCallback(href);\n }\n this.observer?.unobserve(entry.target);\n }\n }\n }\n },\n { rootMargin: "200px" }\n );\n }\n observeLinks(root) {\n const anchors = root.querySelectorAll?.(\'a[href]:not([target="_blank"])\') ?? document.createDocumentFragment().querySelectorAll("a");\n const isViewportEnabled = Boolean(this.prefetchOptions.viewport);\n anchors.forEach((anchor) => {\n if (this.shouldObserveAnchor(anchor, isViewportEnabled)) {\n this.observer?.observe(anchor);\n }\n });\n }\n shouldObserveAnchor(anchor, isViewportEnabled) {\n const href = anchor.getAttribute("href") || "";\n if (!href || href.startsWith("http") || href.startsWith("#") || anchor.getAttribute("download")) {\n return false;\n }\n const prefetchAttribute = anchor.getAttribute("data-prefetch");\n if (prefetchAttribute === "false")\n return false;\n return prefetchAttribute === "viewport" || isViewportEnabled;\n }\n disconnect() {\n if (this.observer) {\n try {\n this.observer.disconnect();\n } catch (error2) {\n rendererLogger.warn("[router] prefetchObserver.disconnect failed", error2);\n }\n this.observer = null;\n }\n }\n};\n\n// src/routing/api/handler.ts\ninit_utils();\ninit_std_path();\ninit_config();\n\n// src/core/utils/lru-wrapper.ts\ninit_utils();\ninit_process();\n\n// src/routing/api/handler.ts\ninit_veryfront_error();\n\n// src/security/http/response/constants.ts\nvar CONTENT_TYPES = {\n JSON: "application/json; charset=utf-8",\n HTML: "text/html; charset=utf-8",\n TEXT: "text/plain; charset=utf-8",\n JAVASCRIPT: "application/javascript; charset=utf-8",\n CSS: "text/css; charset=utf-8",\n XML: "application/xml; charset=utf-8"\n};\nvar CACHE_DURATIONS = {\n SHORT: 60,\n MEDIUM: 3600,\n LONG: 31536e3\n};\n\n// src/security/http/cors/validators.ts\ninit_logger();\n\n// src/observability/tracing/manager.ts\ninit_utils();\n\n// src/observability/tracing/config.ts\nvar DEFAULT_CONFIG2 = {\n enabled: false,\n exporter: "console",\n serviceName: "veryfront",\n sampleRate: 1,\n debug: false\n};\nfunction loadConfig(config = {}, adapter) {\n const finalConfig = { ...DEFAULT_CONFIG2, ...config };\n if (adapter?.env) {\n applyEnvFromAdapter(finalConfig, adapter.env);\n } else {\n applyEnvFromDeno(finalConfig);\n }\n return finalConfig;\n}\nfunction applyEnvFromAdapter(config, envAdapter) {\n if (!envAdapter)\n return;\n const otelEnabled = envAdapter.get("OTEL_TRACES_ENABLED");\n const veryfrontOtel = envAdapter.get("VERYFRONT_OTEL");\n const serviceName = envAdapter.get("OTEL_SERVICE_NAME");\n config.enabled = otelEnabled === "true" || veryfrontOtel === "1" || config.enabled;\n if (serviceName)\n config.serviceName = serviceName;\n const otlpEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_ENDPOINT");\n const tracesEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT");\n config.endpoint = otlpEndpoint || tracesEndpoint || config.endpoint;\n const exporterType = envAdapter.get("OTEL_TRACES_EXPORTER");\n if (isValidExporter(exporterType)) {\n config.exporter = exporterType;\n }\n}\nfunction applyEnvFromDeno(config) {\n try {\n const denoEnv = globalThis.Deno?.env;\n if (!denoEnv)\n return;\n config.enabled = denoEnv.get("OTEL_TRACES_ENABLED") === "true" || denoEnv.get("VERYFRONT_OTEL") === "1" || config.enabled;\n config.serviceName = denoEnv.get("OTEL_SERVICE_NAME") || config.serviceName;\n config.endpoint = denoEnv.get("OTEL_EXPORTER_OTLP_ENDPOINT") || denoEnv.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") || config.endpoint;\n const exporterType = denoEnv.get("OTEL_TRACES_EXPORTER");\n if (isValidExporter(exporterType)) {\n config.exporter = exporterType;\n }\n } catch {\n }\n}\nfunction isValidExporter(value) {\n return value === "jaeger" || value === "zipkin" || value === "otlp" || value === "console";\n}\n\n// src/observability/tracing/span-operations.ts\ninit_utils();\nvar SpanOperations = class {\n constructor(api, tracer2) {\n this.api = api;\n this.tracer = tracer2;\n }\n startSpan(name, options = {}) {\n try {\n const spanKind = this.mapSpanKind(options.kind);\n const span = this.tracer.startSpan(name, {\n kind: spanKind,\n attributes: options.attributes || {}\n }, options.parent);\n return span;\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to start span", { name, error: error2 });\n return null;\n }\n }\n endSpan(span, error2) {\n if (!span)\n return;\n try {\n if (error2) {\n span.recordException(error2);\n span.setStatus({\n code: this.api.SpanStatusCode.ERROR,\n message: error2.message\n });\n } else {\n span.setStatus({ code: this.api.SpanStatusCode.OK });\n }\n span.end();\n } catch (err) {\n serverLogger.debug("[tracing] Failed to end span", err);\n }\n }\n setAttributes(span, attributes) {\n if (!span)\n return;\n try {\n span.setAttributes(attributes);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to set span attributes", error2);\n }\n }\n addEvent(span, name, attributes) {\n if (!span)\n return;\n try {\n span.addEvent(name, attributes);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to add span event", error2);\n }\n }\n createChildSpan(parentSpan, name, options = {}) {\n if (!parentSpan)\n return this.startSpan(name, options);\n try {\n const parentContext = this.api.trace.setSpan(this.api.context.active(), parentSpan);\n return this.startSpan(name, { ...options, parent: parentContext });\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to create child span", error2);\n return null;\n }\n }\n mapSpanKind(kind) {\n if (!kind)\n return this.api.SpanKind.INTERNAL;\n const kindMap = {\n "internal": this.api.SpanKind.INTERNAL,\n "server": this.api.SpanKind.SERVER,\n "client": this.api.SpanKind.CLIENT,\n "producer": this.api.SpanKind.PRODUCER,\n "consumer": this.api.SpanKind.CONSUMER\n };\n return kindMap[kind.toLowerCase()] || this.api.SpanKind.INTERNAL;\n }\n};\n\n// src/observability/tracing/context-propagation.ts\ninit_utils();\nvar ContextPropagation = class {\n constructor(api, propagator) {\n this.api = api;\n this.propagator = propagator;\n }\n extractContext(headers) {\n try {\n const carrier = {};\n headers.forEach((value, key) => {\n carrier[key] = value;\n });\n return this.api.propagation.extract(this.api.context.active(), carrier);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to extract context from headers", error2);\n return void 0;\n }\n }\n injectContext(context, headers) {\n try {\n const carrier = {};\n this.api.propagation.inject(context, carrier);\n for (const [key, value] of Object.entries(carrier)) {\n headers.set(key, value);\n }\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to inject context into headers", error2);\n }\n }\n getActiveContext() {\n try {\n return this.api.context.active();\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to get active context", error2);\n return void 0;\n }\n }\n async withActiveSpan(span, fn) {\n if (!span)\n return await fn();\n return await this.api.context.with(\n this.api.trace.setSpan(this.api.context.active(), span),\n fn\n );\n }\n withSpan(name, fn, startSpan2, endSpan2) {\n const span = startSpan2(name);\n try {\n const result = fn(span);\n endSpan2(span);\n return result;\n } catch (error2) {\n endSpan2(span, error2);\n throw error2;\n }\n }\n async withSpanAsync(name, fn, startSpan2, endSpan2) {\n const span = startSpan2(name);\n try {\n const result = await fn(span);\n endSpan2(span);\n return result;\n } catch (error2) {\n endSpan2(span, error2);\n throw error2;\n }\n }\n};\n\n// src/observability/tracing/manager.ts\nvar TracingManager = class {\n constructor() {\n this.state = {\n initialized: false,\n tracer: null,\n api: null,\n propagator: null\n };\n this.spanOps = null;\n this.contextProp = null;\n }\n async initialize(config = {}, adapter) {\n if (this.state.initialized) {\n serverLogger.debug("[tracing] Already initialized");\n return;\n }\n const finalConfig = loadConfig(config, adapter);\n if (!finalConfig.enabled) {\n serverLogger.debug("[tracing] Tracing disabled");\n this.state.initialized = true;\n return;\n }\n try {\n await this.initializeTracer(finalConfig);\n this.state.initialized = true;\n serverLogger.info("[tracing] OpenTelemetry tracing initialized", {\n exporter: finalConfig.exporter,\n serviceName: finalConfig.serviceName,\n endpoint: finalConfig.endpoint\n });\n } catch (error2) {\n serverLogger.warn("[tracing] Failed to initialize OpenTelemetry tracing", error2);\n this.state.initialized = true;\n }\n }\n async initializeTracer(config) {\n const otelApiModule = ["npm:@opentelemetry/", "api@1"].join("");\n const api = await import(otelApiModule);\n this.state.api = api;\n this.state.tracer = api.trace.getTracer(config.serviceName || "veryfront", "0.1.0");\n const otelCoreModule = ["npm:@opentelemetry/", "core@1"].join("");\n const { W3CTraceContextPropagator } = await import(otelCoreModule);\n const propagator = new W3CTraceContextPropagator();\n this.state.propagator = propagator;\n api.propagation.setGlobalPropagator(propagator);\n if (this.state.api && this.state.tracer) {\n this.spanOps = new SpanOperations(this.state.api, this.state.tracer);\n }\n if (this.state.api && this.state.propagator) {\n this.contextProp = new ContextPropagation(this.state.api, this.state.propagator);\n }\n }\n isEnabled() {\n return this.state.initialized && this.state.tracer !== null;\n }\n getSpanOperations() {\n return this.spanOps;\n }\n getContextPropagation() {\n return this.contextProp;\n }\n getState() {\n return this.state;\n }\n shutdown() {\n if (!this.state.initialized)\n return;\n try {\n serverLogger.info("[tracing] Tracing shutdown initiated");\n } catch (error2) {\n serverLogger.warn("[tracing] Error during tracing shutdown", error2);\n }\n }\n};\nvar tracingManager = new TracingManager();\n\n// src/observability/metrics/manager.ts\ninit_utils();\n\n// src/observability/metrics/config.ts\nvar DEFAULT_METRICS_COLLECT_INTERVAL_MS2 = 6e4;\nvar DEFAULT_CONFIG3 = {\n enabled: false,\n exporter: "console",\n prefix: "veryfront",\n collectInterval: DEFAULT_METRICS_COLLECT_INTERVAL_MS2,\n debug: false\n};\nfunction loadConfig2(config, adapter) {\n const finalConfig = { ...DEFAULT_CONFIG3, ...config };\n if (adapter?.env) {\n const envAdapter = adapter.env;\n const otelEnabled = envAdapter.get("OTEL_METRICS_ENABLED");\n const veryfrontOtel = envAdapter.get("VERYFRONT_OTEL");\n finalConfig.enabled = otelEnabled === "true" || veryfrontOtel === "1" || finalConfig.enabled;\n const otlpEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_ENDPOINT");\n const metricsEndpoint = envAdapter.get(\n "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"\n );\n finalConfig.endpoint = otlpEndpoint || metricsEndpoint || finalConfig.endpoint;\n const exporterType = envAdapter.get("OTEL_METRICS_EXPORTER");\n if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {\n finalConfig.exporter = exporterType;\n }\n } else {\n try {\n const env = process.env;\n if (env) {\n finalConfig.enabled = env.OTEL_METRICS_ENABLED === "true" || env.VERYFRONT_OTEL === "1" || finalConfig.enabled;\n finalConfig.endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT || env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT || finalConfig.endpoint;\n const exporterType = env.OTEL_METRICS_EXPORTER;\n if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {\n finalConfig.exporter = exporterType;\n }\n }\n } catch {\n }\n }\n return finalConfig;\n}\nfunction getMemoryUsage() {\n try {\n if (process?.memoryUsage) {\n return process.memoryUsage();\n }\n return null;\n } catch {\n return null;\n }\n}\n\n// src/observability/instruments/instruments-factory.ts\ninit_utils();\n\n// src/observability/instruments/build-instruments.ts\ninit_config();\nfunction createBuildInstruments(meter, config) {\n const buildDuration = meter.createHistogram(\n `${config.prefix}.build.duration`,\n {\n description: "Build operation duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const bundleSizeHistogram = meter.createHistogram(\n `${config.prefix}.build.bundle.size`,\n {\n description: "Bundle size distribution",\n unit: "kb",\n advice: { explicitBucketBoundaries: SIZE_HISTOGRAM_BOUNDARIES_KB }\n }\n );\n const bundleCounter = meter.createCounter(\n `${config.prefix}.build.bundles`,\n {\n description: "Total number of bundles created",\n unit: "bundles"\n }\n );\n return {\n buildDuration,\n bundleSizeHistogram,\n bundleCounter\n };\n}\n\n// src/observability/instruments/cache-instruments.ts\nfunction createCacheInstruments(meter, config, runtimeState) {\n const cacheGetCounter = meter.createCounter(\n `${config.prefix}.cache.gets`,\n {\n description: "Total number of cache get operations",\n unit: "operations"\n }\n );\n const cacheHitCounter = meter.createCounter(\n `${config.prefix}.cache.hits`,\n {\n description: "Total number of cache hits",\n unit: "hits"\n }\n );\n const cacheMissCounter = meter.createCounter(\n `${config.prefix}.cache.misses`,\n {\n description: "Total number of cache misses",\n unit: "misses"\n }\n );\n const cacheSetCounter = meter.createCounter(\n `${config.prefix}.cache.sets`,\n {\n description: "Total number of cache set operations",\n unit: "operations"\n }\n );\n const cacheInvalidateCounter = meter.createCounter(\n `${config.prefix}.cache.invalidations`,\n {\n description: "Total number of cache invalidations",\n unit: "operations"\n }\n );\n const cacheSizeGauge = meter.createObservableGauge(\n `${config.prefix}.cache.size`,\n {\n description: "Current cache size",\n unit: "entries"\n }\n );\n cacheSizeGauge.addCallback((result) => {\n result.observe(runtimeState.cacheSize);\n });\n return {\n cacheGetCounter,\n cacheHitCounter,\n cacheMissCounter,\n cacheSetCounter,\n cacheInvalidateCounter,\n cacheSizeGauge\n };\n}\n\n// src/observability/instruments/data-instruments.ts\ninit_config();\nfunction createDataInstruments(meter, config) {\n const dataFetchDuration = meter.createHistogram(\n `${config.prefix}.data.fetch.duration`,\n {\n description: "Data fetch duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const dataFetchCounter = meter.createCounter(\n `${config.prefix}.data.fetch.count`,\n {\n description: "Total number of data fetches",\n unit: "fetches"\n }\n );\n const dataFetchErrorCounter = meter.createCounter(\n `${config.prefix}.data.fetch.errors`,\n {\n description: "Data fetch errors",\n unit: "errors"\n }\n );\n return {\n dataFetchDuration,\n dataFetchCounter,\n dataFetchErrorCounter\n };\n}\n\n// src/observability/instruments/http-instruments.ts\ninit_config();\nfunction createHttpInstruments(meter, config) {\n const httpRequestCounter = meter.createCounter(\n `${config.prefix}.http.requests`,\n {\n description: "Total number of HTTP requests",\n unit: "requests"\n }\n );\n const httpRequestDuration = meter.createHistogram(\n `${config.prefix}.http.request.duration`,\n {\n description: "HTTP request duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const httpActiveRequests = meter.createUpDownCounter(\n `${config.prefix}.http.requests.active`,\n {\n description: "Number of active HTTP requests",\n unit: "requests"\n }\n );\n return {\n httpRequestCounter,\n httpRequestDuration,\n httpActiveRequests\n };\n}\n\n// src/observability/instruments/memory-instruments.ts\nfunction createMemoryInstruments(meter, config) {\n const memoryUsageGauge = meter.createObservableGauge(\n `${config.prefix}.memory.usage`,\n {\n description: "Memory usage",\n unit: "bytes"\n }\n );\n memoryUsageGauge.addCallback((result) => {\n const memoryUsage = getMemoryUsage();\n if (memoryUsage) {\n result.observe(memoryUsage.rss);\n }\n });\n const heapUsageGauge = meter.createObservableGauge(\n `${config.prefix}.memory.heap`,\n {\n description: "Heap memory usage",\n unit: "bytes"\n }\n );\n heapUsageGauge.addCallback((result) => {\n const memoryUsage = getMemoryUsage();\n if (memoryUsage) {\n result.observe(memoryUsage.heapUsed);\n }\n });\n return {\n memoryUsageGauge,\n heapUsageGauge\n };\n}\n\n// src/observability/instruments/render-instruments.ts\ninit_config();\nfunction createRenderInstruments(meter, config) {\n const renderDuration = meter.createHistogram(\n `${config.prefix}.render.duration`,\n {\n description: "Page render duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const renderCounter = meter.createCounter(\n `${config.prefix}.render.count`,\n {\n description: "Total number of page renders",\n unit: "renders"\n }\n );\n const renderErrorCounter = meter.createCounter(\n `${config.prefix}.render.errors`,\n {\n description: "Total number of render errors",\n unit: "errors"\n }\n );\n return {\n renderDuration,\n renderCounter,\n renderErrorCounter\n };\n}\n\n// src/observability/instruments/rsc-instruments.ts\ninit_config();\nfunction createRscInstruments(meter, config) {\n const rscRenderDuration = meter.createHistogram(\n `${config.prefix}.rsc.render.duration`,\n {\n description: "RSC render duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const rscStreamDuration = meter.createHistogram(\n `${config.prefix}.rsc.stream.duration`,\n {\n description: "RSC stream duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const rscManifestCounter = meter.createCounter(\n `${config.prefix}.rsc.manifest`,\n {\n description: "RSC manifest requests",\n unit: "requests"\n }\n );\n const rscPageCounter = meter.createCounter(\n `${config.prefix}.rsc.page`,\n {\n description: "RSC page requests",\n unit: "requests"\n }\n );\n const rscStreamCounter = meter.createCounter(\n `${config.prefix}.rsc.stream`,\n {\n description: "RSC stream requests",\n unit: "requests"\n }\n );\n const rscActionCounter = meter.createCounter(\n `${config.prefix}.rsc.action`,\n {\n description: "RSC action requests",\n unit: "requests"\n }\n );\n const rscErrorCounter = meter.createCounter(\n `${config.prefix}.rsc.errors`,\n {\n description: "RSC errors",\n unit: "errors"\n }\n );\n return {\n rscRenderDuration,\n rscStreamDuration,\n rscManifestCounter,\n rscPageCounter,\n rscStreamCounter,\n rscActionCounter,\n rscErrorCounter\n };\n}\n\n// src/observability/instruments/instruments-factory.ts\nfunction initializeInstruments(meter, config, runtimeState) {\n const instruments = {\n httpRequestCounter: null,\n httpRequestDuration: null,\n httpActiveRequests: null,\n cacheGetCounter: null,\n cacheHitCounter: null,\n cacheMissCounter: null,\n cacheSetCounter: null,\n cacheInvalidateCounter: null,\n cacheSizeGauge: null,\n renderDuration: null,\n renderCounter: null,\n renderErrorCounter: null,\n rscRenderDuration: null,\n rscStreamDuration: null,\n rscManifestCounter: null,\n rscPageCounter: null,\n rscStreamCounter: null,\n rscActionCounter: null,\n rscErrorCounter: null,\n buildDuration: null,\n bundleSizeHistogram: null,\n bundleCounter: null,\n dataFetchDuration: null,\n dataFetchCounter: null,\n dataFetchErrorCounter: null,\n corsRejectionCounter: null,\n securityHeadersCounter: null,\n memoryUsageGauge: null,\n heapUsageGauge: null\n };\n try {\n const httpInstruments = createHttpInstruments(meter, config);\n Object.assign(instruments, httpInstruments);\n const cacheInstruments = createCacheInstruments(meter, config, runtimeState);\n Object.assign(instruments, cacheInstruments);\n const renderInstruments = createRenderInstruments(meter, config);\n Object.assign(instruments, renderInstruments);\n const rscInstruments = createRscInstruments(meter, config);\n Object.assign(instruments, rscInstruments);\n const buildInstruments = createBuildInstruments(meter, config);\n Object.assign(instruments, buildInstruments);\n const dataInstruments = createDataInstruments(meter, config);\n Object.assign(instruments, dataInstruments);\n const memoryInstruments = createMemoryInstruments(meter, config);\n Object.assign(instruments, memoryInstruments);\n } catch (error2) {\n serverLogger.warn("[metrics] Failed to initialize metric instruments", error2);\n }\n return Promise.resolve(instruments);\n}\n\n// src/observability/metrics/recorder.ts\nvar MetricsRecorder = class {\n constructor(instruments, runtimeState) {\n this.instruments = instruments;\n this.runtimeState = runtimeState;\n }\n recordHttpRequest(attributes) {\n this.instruments.httpRequestCounter?.add(1, attributes);\n this.instruments.httpActiveRequests?.add(1, attributes);\n this.runtimeState.activeRequests++;\n }\n recordHttpRequestComplete(durationMs, attributes) {\n this.instruments.httpRequestDuration?.record(durationMs, attributes);\n this.instruments.httpActiveRequests?.add(-1, attributes);\n this.runtimeState.activeRequests--;\n }\n recordCacheGet(hit, attributes) {\n this.instruments.cacheGetCounter?.add(1, attributes);\n if (hit) {\n this.instruments.cacheHitCounter?.add(1, attributes);\n } else {\n this.instruments.cacheMissCounter?.add(1, attributes);\n }\n }\n recordCacheSet(attributes) {\n this.instruments.cacheSetCounter?.add(1, attributes);\n this.runtimeState.cacheSize++;\n }\n recordCacheInvalidate(count, attributes) {\n this.instruments.cacheInvalidateCounter?.add(count, attributes);\n this.runtimeState.cacheSize = Math.max(\n 0,\n this.runtimeState.cacheSize - count\n );\n }\n setCacheSize(size) {\n this.runtimeState.cacheSize = size;\n }\n // Render Metrics\n recordRender(durationMs, attributes) {\n this.instruments.renderDuration?.record(durationMs, attributes);\n this.instruments.renderCounter?.add(1, attributes);\n }\n recordRenderError(attributes) {\n this.instruments.renderErrorCounter?.add(1, attributes);\n }\n // RSC Metrics\n recordRSCRender(durationMs, attributes) {\n this.instruments.rscRenderDuration?.record(durationMs, attributes);\n }\n recordRSCStream(durationMs, attributes) {\n this.instruments.rscStreamDuration?.record(durationMs, attributes);\n }\n recordRSCRequest(type, attributes) {\n switch (type) {\n case "manifest":\n this.instruments.rscManifestCounter?.add(1, attributes);\n break;\n case "page":\n this.instruments.rscPageCounter?.add(1, attributes);\n break;\n case "stream":\n this.instruments.rscStreamCounter?.add(1, attributes);\n break;\n case "action":\n this.instruments.rscActionCounter?.add(1, attributes);\n break;\n }\n }\n recordRSCError(attributes) {\n this.instruments.rscErrorCounter?.add(1, attributes);\n }\n // Build Metrics\n recordBuild(durationMs, attributes) {\n this.instruments.buildDuration?.record(durationMs, attributes);\n }\n recordBundle(sizeKb, attributes) {\n this.instruments.bundleSizeHistogram?.record(sizeKb, attributes);\n this.instruments.bundleCounter?.add(1, attributes);\n }\n // Data Fetching Metrics\n recordDataFetch(durationMs, attributes) {\n this.instruments.dataFetchDuration?.record(durationMs, attributes);\n this.instruments.dataFetchCounter?.add(1, attributes);\n }\n recordDataFetchError(attributes) {\n this.instruments.dataFetchErrorCounter?.add(1, attributes);\n }\n // Security Metrics\n recordCorsRejection(attributes) {\n this.instruments.corsRejectionCounter?.add(1, attributes);\n }\n recordSecurityHeaders(attributes) {\n this.instruments.securityHeadersCounter?.add(1, attributes);\n }\n};\n\n// src/observability/metrics/manager.ts\nvar MetricsManager = class {\n constructor() {\n this.initialized = false;\n this.meter = null;\n this.api = null;\n this.recorder = null;\n this.instruments = this.createEmptyInstruments();\n this.runtimeState = {\n cacheSize: 0,\n activeRequests: 0\n };\n this.recorder = new MetricsRecorder(this.instruments, this.runtimeState);\n }\n createEmptyInstruments() {\n return {\n httpRequestCounter: null,\n httpRequestDuration: null,\n httpActiveRequests: null,\n cacheGetCounter: null,\n cacheHitCounter: null,\n cacheMissCounter: null,\n cacheSetCounter: null,\n cacheInvalidateCounter: null,\n cacheSizeGauge: null,\n renderDuration: null,\n renderCounter: null,\n renderErrorCounter: null,\n rscRenderDuration: null,\n rscStreamDuration: null,\n rscManifestCounter: null,\n rscPageCounter: null,\n rscStreamCounter: null,\n rscActionCounter: null,\n rscErrorCounter: null,\n buildDuration: null,\n bundleSizeHistogram: null,\n bundleCounter: null,\n dataFetchDuration: null,\n dataFetchCounter: null,\n dataFetchErrorCounter: null,\n corsRejectionCounter: null,\n securityHeadersCounter: null,\n memoryUsageGauge: null,\n heapUsageGauge: null\n };\n }\n async initialize(config = {}, adapter) {\n if (this.initialized) {\n serverLogger.debug("[metrics] Already initialized");\n return;\n }\n const finalConfig = loadConfig2(config, adapter);\n if (!finalConfig.enabled) {\n serverLogger.debug("[metrics] Metrics collection disabled");\n this.initialized = true;\n return;\n }\n try {\n this.api = await import("npm:@opentelemetry/api@1");\n this.meter = this.api.metrics.getMeter(finalConfig.prefix, "0.1.0");\n this.instruments = await initializeInstruments(\n this.meter,\n finalConfig,\n this.runtimeState\n );\n if (this.recorder) {\n this.recorder.instruments = this.instruments;\n }\n this.initialized = true;\n serverLogger.info("[metrics] OpenTelemetry metrics initialized", {\n exporter: finalConfig.exporter,\n endpoint: finalConfig.endpoint,\n prefix: finalConfig.prefix\n });\n } catch (error2) {\n serverLogger.warn("[metrics] Failed to initialize OpenTelemetry metrics", error2);\n this.initialized = true;\n }\n }\n isEnabled() {\n return this.initialized && this.meter !== null;\n }\n getRecorder() {\n return this.recorder;\n }\n getState() {\n return {\n initialized: this.initialized,\n cacheSize: this.runtimeState.cacheSize,\n activeRequests: this.runtimeState.activeRequests\n };\n }\n shutdown() {\n if (!this.initialized)\n return;\n try {\n serverLogger.info("[metrics] Metrics shutdown initiated");\n } catch (error2) {\n serverLogger.warn("[metrics] Error during metrics shutdown", error2);\n }\n }\n};\nvar metricsManager = new MetricsManager();\n\n// src/observability/metrics/index.ts\nvar getRecorder = () => metricsManager.getRecorder();\nfunction recordCorsRejection(attributes) {\n getRecorder()?.recordCorsRejection?.(attributes);\n}\nfunction recordSecurityHeaders(attributes) {\n getRecorder()?.recordSecurityHeaders?.(attributes);\n}\n\n// src/observability/auto-instrument/orchestrator.ts\ninit_utils();\n\n// src/observability/auto-instrument/http-instrumentation.ts\ninit_utils();\nimport {\n context as otContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace\n} from "npm:@opentelemetry/api@1";\nvar tracer = trace.getTracer("veryfront-http");\n\n// src/security/http/cors/validators.ts\nasync function validateOrigin(requestOrigin, config) {\n if (!config) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (config === true) {\n const origin = requestOrigin || "*";\n return { allowedOrigin: origin, allowCredentials: false };\n }\n const corsConfig = config;\n if (!corsConfig.origin) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (!requestOrigin) {\n if (corsConfig.origin === "*") {\n return { allowedOrigin: "*", allowCredentials: false };\n }\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (corsConfig.origin === "*") {\n if (corsConfig.credentials) {\n serverLogger.warn("[CORS] Cannot use credentials with wildcard origin - denying");\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Cannot use credentials with wildcard origin"\n };\n }\n return { allowedOrigin: "*", allowCredentials: false };\n }\n if (typeof corsConfig.origin === "function") {\n try {\n const result = await corsConfig.origin(requestOrigin);\n if (typeof result === "string") {\n return {\n allowedOrigin: result,\n allowCredentials: corsConfig.credentials ?? false\n };\n }\n const allowed = result === true;\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin rejected by validation function"\n };\n } catch (error2) {\n serverLogger.error("[CORS] Origin validation function error", error2);\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Origin validation error"\n };\n }\n }\n if (Array.isArray(corsConfig.origin)) {\n const allowed = corsConfig.origin.includes(requestOrigin);\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin not in allowlist", {\n requestOrigin,\n allowedOrigins: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin not in allowlist"\n };\n }\n if (typeof corsConfig.origin === "string") {\n const allowed = corsConfig.origin === requestOrigin;\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin does not match", {\n requestOrigin,\n expectedOrigin: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin does not match"\n };\n }\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Invalid origin configuration"\n };\n}\nfunction validateOriginSync(requestOrigin, config) {\n if (!config) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (config === true) {\n const origin = requestOrigin || "*";\n return { allowedOrigin: origin, allowCredentials: false };\n }\n const corsConfig = config;\n if (!corsConfig.origin) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (!requestOrigin) {\n if (corsConfig.origin === "*") {\n return { allowedOrigin: "*", allowCredentials: false };\n }\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (corsConfig.origin === "*") {\n if (corsConfig.credentials) {\n serverLogger.warn("[CORS] Cannot use credentials with wildcard origin - denying");\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Cannot use credentials with wildcard origin"\n };\n }\n return { allowedOrigin: "*", allowCredentials: false };\n }\n if (typeof corsConfig.origin === "function") {\n try {\n const result = corsConfig.origin(requestOrigin);\n if (result instanceof Promise) {\n serverLogger.warn(\n "[CORS] Async origin validators are not supported in synchronous contexts"\n );\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Async origin validators not supported"\n };\n }\n if (typeof result === "string") {\n return {\n allowedOrigin: result,\n allowCredentials: corsConfig.credentials ?? false\n };\n }\n const allowed = result === true;\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin rejected by validation function"\n };\n } catch (error2) {\n serverLogger.error("[CORS] Origin validation function error", error2);\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Origin validation error"\n };\n }\n }\n if (Array.isArray(corsConfig.origin)) {\n const allowed = corsConfig.origin.includes(requestOrigin);\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin not in allowlist (sync)", {\n requestOrigin,\n allowedOrigins: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin not in allowlist"\n };\n }\n if (typeof corsConfig.origin === "string") {\n const allowed = corsConfig.origin === requestOrigin;\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin does not match (sync)", {\n requestOrigin,\n expectedOrigin: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin does not match"\n };\n }\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Invalid origin configuration"\n };\n}\n\n// src/security/http/cors/headers.ts\nasync function applyCORSHeaders(options) {\n const { request, response, headers: headersObj, config } = options;\n const validation = await validateOrigin(request.headers.get("origin"), config);\n if (!validation.allowedOrigin) {\n return response;\n }\n const headers = headersObj || (response ? new Headers(response.headers) : new Headers());\n headers.set("Access-Control-Allow-Origin", validation.allowedOrigin);\n if (validation.allowedOrigin !== "*") {\n const existingVary = headers.get("Vary");\n const varyValues = existingVary ? existingVary.split(",").map((v) => v.trim()) : [];\n if (!varyValues.includes("Origin")) {\n varyValues.push("Origin");\n headers.set("Vary", varyValues.join(", "));\n }\n }\n if (validation.allowCredentials && validation.allowedOrigin !== "*") {\n headers.set("Access-Control-Allow-Credentials", "true");\n }\n const corsConfig = typeof config === "object" ? config : null;\n if (corsConfig?.exposedHeaders && corsConfig.exposedHeaders.length > 0) {\n headers.set("Access-Control-Expose-Headers", corsConfig.exposedHeaders.join(", "));\n }\n if (response) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n return;\n}\nfunction applyCORSHeadersSync(options) {\n const { request, response, headers: headersObj, config } = options;\n const validation = validateOriginSync(request.headers.get("origin"), config);\n if (!validation.allowedOrigin) {\n return response;\n }\n const headers = headersObj || (response ? new Headers(response.headers) : new Headers());\n headers.set("Access-Control-Allow-Origin", validation.allowedOrigin);\n if (validation.allowedOrigin !== "*") {\n const existingVary = headers.get("Vary");\n const varyValues = existingVary ? existingVary.split(",").map((v) => v.trim()) : [];\n if (!varyValues.includes("Origin")) {\n varyValues.push("Origin");\n headers.set("Vary", varyValues.join(", "));\n }\n }\n if (validation.allowCredentials && validation.allowedOrigin !== "*") {\n headers.set("Access-Control-Allow-Credentials", "true");\n }\n const corsConfig = typeof config === "object" ? config : null;\n if (corsConfig?.exposedHeaders && corsConfig.exposedHeaders.length > 0) {\n headers.set("Access-Control-Expose-Headers", corsConfig.exposedHeaders.join(", "));\n }\n if (response) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n return;\n}\n\n// src/security/http/cors/constants.ts\ninit_config();\n\n// src/security/http/cors/preflight.ts\ninit_logger();\n\n// src/security/http/cors/middleware.ts\ninit_veryfront_error();\n\n// src/security/http/response/security-handler.ts\nfunction generateNonce() {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return btoa(String.fromCharCode(...array));\n}\nfunction buildCSP(isDev, nonce, cspUserHeader, config, adapter) {\n const envCsp = adapter?.env?.get?.("VERYFRONT_CSP");\n if (envCsp?.trim())\n return envCsp.replace(/{NONCE}/g, nonce);\n const defaultCsp = isDev ? [\n "default-src \'self\'",\n `style-src \'self\' \'unsafe-inline\' https://esm.sh https://cdnjs.cloudflare.com https://cdn.veryfront.com https://cdn.jsdelivr.net https://cdn.tailwindcss.com`,\n "img-src \'self\' data: https://cdn.veryfront.com https://cdnjs.cloudflare.com",\n `script-src \'self\' \'nonce-${nonce}\' \'unsafe-eval\' https://esm.sh https://cdn.tailwindcss.com`,\n "connect-src \'self\' https://esm.sh ws://localhost:* wss://localhost:*",\n "font-src \'self\' data: https://cdnjs.cloudflare.com"\n ].join("; ") : [\n "default-src \'self\'",\n `style-src \'self\' \'nonce-${nonce}\'`,\n "img-src \'self\' data:",\n `script-src \'self\' \'nonce-${nonce}\'`,\n "connect-src \'self\'"\n ].join("; ");\n if (cspUserHeader?.trim()) {\n return `${cspUserHeader.replace(/{NONCE}/g, nonce)}; ${defaultCsp}`;\n }\n const cfgCsp = config?.csp;\n if (cfgCsp && typeof cfgCsp === "object") {\n const pieces = [];\n for (const [k, v] of Object.entries(cfgCsp)) {\n if (v === void 0)\n continue;\n const key = String(k).replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n const val = Array.isArray(v) ? v.join(" ") : String(v);\n pieces.push(`${key} ${val}`.replace(/{NONCE}/g, nonce));\n }\n if (pieces.length > 0) {\n return `${pieces.join("; ")}; ${defaultCsp}`;\n }\n }\n return defaultCsp;\n}\nfunction getSecurityHeader(headerName, defaultValue, config, adapter) {\n const configKey = headerName.toLowerCase();\n const configValue = config?.[configKey];\n const envValue = adapter?.env?.get?.(`VERYFRONT_${headerName}`);\n return (typeof configValue === "string" ? configValue : void 0) || envValue || defaultValue;\n}\nfunction applySecurityHeaders(headers, isDev, nonce, cspUserHeader, config, adapter) {\n const getHeaderOverride = (name) => {\n const overrides = config?.headers;\n if (!overrides)\n return void 0;\n const lower = name.toLowerCase();\n for (const [key, value] of Object.entries(overrides)) {\n if (key.toLowerCase() === lower) {\n return value;\n }\n }\n return void 0;\n };\n const contentTypeOptions = getHeaderOverride("x-content-type-options") ?? "nosniff";\n headers.set("X-Content-Type-Options", contentTypeOptions);\n const frameOptions = getHeaderOverride("x-frame-options") ?? "DENY";\n headers.set("X-Frame-Options", frameOptions);\n const xssProtection = getHeaderOverride("x-xss-protection") ?? "1; mode=block";\n headers.set("X-XSS-Protection", xssProtection);\n const csp = buildCSP(isDev, nonce, cspUserHeader, config, adapter);\n if (csp) {\n headers.set("Content-Security-Policy", csp);\n }\n if (!isDev) {\n const hstsMaxAge = config?.hsts?.maxAge ?? 31536e3;\n const hstsIncludeSubDomains = config?.hsts?.includeSubDomains ?? true;\n const hstsPreload = config?.hsts?.preload ?? false;\n let hstsValue = `max-age=${hstsMaxAge}`;\n if (hstsIncludeSubDomains) {\n hstsValue += "; includeSubDomains";\n }\n if (hstsPreload) {\n hstsValue += "; preload";\n }\n const hstsOverride = getHeaderOverride("strict-transport-security");\n headers.set("Strict-Transport-Security", hstsOverride ?? hstsValue);\n }\n const coop = getSecurityHeader("COOP", "same-origin", config, adapter);\n const corp = getSecurityHeader("CORP", "same-origin", config, adapter);\n const coep = getSecurityHeader("COEP", "", config, adapter);\n headers.set("Cross-Origin-Opener-Policy", coop);\n headers.set("Cross-Origin-Resource-Policy", corp);\n if (coep) {\n headers.set("Cross-Origin-Embedder-Policy", coep);\n }\n if (config?.headers) {\n for (const [key, value] of Object.entries(config.headers)) {\n if (value === void 0)\n continue;\n headers.set(key, value);\n }\n }\n recordSecurityHeaders();\n}\n\n// src/security/http/response/cache-handler.ts\nfunction buildCacheControl(strategy) {\n let cacheControl;\n if (typeof strategy === "string") {\n switch (strategy) {\n case "no-cache":\n cacheControl = "no-cache, no-store, must-revalidate";\n break;\n case "no-store":\n cacheControl = "no-store";\n break;\n case "short":\n cacheControl = `public, max-age=${CACHE_DURATIONS.SHORT}`;\n break;\n case "medium":\n cacheControl = `public, max-age=${CACHE_DURATIONS.MEDIUM}`;\n break;\n case "long":\n cacheControl = `public, max-age=${CACHE_DURATIONS.LONG}`;\n break;\n case "immutable":\n cacheControl = `public, max-age=${CACHE_DURATIONS.LONG}, immutable`;\n break;\n case "none":\n cacheControl = "no-cache, no-store, must-revalidate";\n break;\n default:\n cacheControl = "public, max-age=0";\n }\n } else {\n const parts = [];\n parts.push(strategy.public !== false ? "public" : "private");\n parts.push(`max-age=${strategy.maxAge}`);\n if (strategy.immutable)\n parts.push("immutable");\n if (strategy.mustRevalidate)\n parts.push("must-revalidate");\n cacheControl = parts.join(", ");\n }\n return cacheControl;\n}\n\n// src/security/http/response/fluent-methods.ts\nfunction withCORS(req, corsConfig) {\n const config = corsConfig ?? this.securityConfig?.cors;\n applyCORSHeadersSync({\n request: req,\n headers: this.headers,\n config\n });\n return this;\n}\nfunction withCORSAsync(req) {\n return applyCORSHeaders({\n request: req,\n headers: this.headers,\n config: this.securityConfig?.cors\n }).then(() => this);\n}\nfunction withSecurity(config) {\n const cfg = config ?? this.securityConfig;\n applySecurityHeaders(\n this.headers,\n this.isDev,\n this.nonce,\n this.cspUserHeader,\n cfg,\n this.adapter\n );\n return this;\n}\nfunction withCache(strategy) {\n const cacheControl = buildCacheControl(strategy);\n this.headers.set("cache-control", cacheControl);\n return this;\n}\nfunction withETag(etag) {\n this.headers.set("ETag", etag);\n return this;\n}\nfunction withHeaders(headers) {\n if (headers instanceof Headers) {\n headers.forEach((value, key) => {\n this.headers.set(key, value);\n });\n } else if (Array.isArray(headers)) {\n headers.forEach(([key, value]) => {\n this.headers.set(key, value);\n });\n } else {\n Object.entries(headers).forEach(([key, value]) => {\n this.headers.set(key, value);\n });\n }\n return this;\n}\nfunction withStatus(status) {\n this.status = status;\n return this;\n}\nfunction withAllow(methods) {\n const methodStr = Array.isArray(methods) ? methods.join(", ") : methods;\n this.headers.set("Allow", methodStr);\n this.headers.set("Access-Control-Allow-Methods", methodStr);\n return this;\n}\n\n// src/security/http/response/response-methods.ts\nfunction json(data, status) {\n this.headers.set("content-type", CONTENT_TYPES.JSON);\n return new Response(JSON.stringify(data), {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction text(body, status) {\n this.headers.set("content-type", CONTENT_TYPES.TEXT);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction html(body, status) {\n this.headers.set("content-type", CONTENT_TYPES.HTML);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction javascript(code, status) {\n this.headers.set("content-type", CONTENT_TYPES.JAVASCRIPT);\n return new Response(code, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction withContentType(contentType, body, status) {\n this.headers.set("content-type", contentType);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction build(body = null, status) {\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction notModified(etag) {\n if (etag) {\n this.headers.set("ETag", etag);\n }\n return new Response(null, {\n status: 304,\n headers: this.headers\n });\n}\n\n// src/security/http/response/static-helpers.ts\ninit_veryfront_error();\nvar ResponseBuilderClass = null;\nfunction setResponseBuilderClass(builderClass) {\n ResponseBuilderClass = builderClass;\n}\nfunction error(status, message, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n const contentType = config?.contentType ?? CONTENT_TYPES.TEXT;\n if (contentType === CONTENT_TYPES.JSON) {\n return builder.json({ error: message }, status);\n } else if (contentType === CONTENT_TYPES.HTML) {\n return builder.html(message, status);\n }\n return builder.text(message, status);\n}\nfunction json2(data, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n if (config?.etag) {\n builder.withETag(config.etag);\n }\n return builder.json(data, config?.status);\n}\nfunction html2(body, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n if (config?.etag) {\n builder.withETag(config.etag);\n }\n return builder.html(body, config?.status);\n}\nfunction preflight(req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n const methods = config?.allowMethods ?? "GET,POST,PUT,PATCH,DELETE,OPTIONS";\n builder.withAllow(methods);\n const headers = config?.allowHeaders ?? req.headers.get("access-control-request-headers") ?? "Content-Type,Authorization";\n builder.headers.set(\n "Access-Control-Allow-Headers",\n Array.isArray(headers) ? headers.join(", ") : headers\n );\n return builder.build(null, 204);\n}\nfunction stream(streamData, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n const contentType = config?.contentType ?? "application/octet-stream";\n return builder.withContentType(contentType, streamData);\n}\n\n// src/security/http/response/builder.ts\nvar ResponseBuilder = class {\n constructor(config) {\n this.withCORS = withCORS;\n this.withCORSAsync = withCORSAsync;\n this.withSecurity = withSecurity;\n this.withCache = withCache;\n this.withETag = withETag;\n this.withHeaders = withHeaders;\n this.withStatus = withStatus;\n this.withAllow = withAllow;\n this.json = json;\n this.text = text;\n this.html = html;\n this.javascript = javascript;\n this.withContentType = withContentType;\n this.build = build;\n this.notModified = notModified;\n this.headers = new Headers();\n this.status = 200;\n this.securityConfig = config?.securityConfig ?? null;\n this.isDev = config?.isDev ?? false;\n this.nonce = config?.nonce ?? generateNonce();\n this.cspUserHeader = config?.cspUserHeader ?? null;\n this.adapter = config?.adapter;\n }\n};\nResponseBuilder.error = error;\nResponseBuilder.json = json2;\nResponseBuilder.html = html2;\nResponseBuilder.preflight = preflight;\nResponseBuilder.stream = stream;\nsetResponseBuilderClass(\n ResponseBuilder\n);\n\n// src/security/http/base-handler.ts\ninit_utils();\n\n// src/core/constants/index.ts\ninit_constants();\n\n// src/core/constants/buffers.ts\nvar DEFAULT_MAX_BODY_SIZE_BYTES = 1024 * 1024;\nvar DEFAULT_MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;\nvar PREFETCH_QUEUE_MAX_SIZE_BYTES = 1024 * 1024;\nvar MAX_BUNDLE_CHUNK_SIZE_BYTES = 4096 * 1024;\n\n// src/core/constants/limits.ts\nvar MAX_URL_LENGTH_FOR_VALIDATION = 2048;\n\n// src/security/input-validation/parsers.ts\nimport { z as z2 } from "zod";\n\n// src/security/input-validation/schemas.ts\nimport { z as z3 } from "zod";\nvar CommonSchemas = {\n /**\n * Valid email address (RFC-compliant, max 255 chars)\n */\n email: z3.string().email().max(255),\n /**\n * Valid UUID v4 identifier\n */\n uuid: z3.string().uuid(),\n /**\n * URL-safe slug (lowercase alphanumeric with hyphens)\n */\n slug: z3.string().regex(/^[a-z0-9-]+$/).min(1).max(100),\n /**\n * Valid HTTP/HTTPS URL (max 2048 chars)\n */\n url: z3.string().url().max(MAX_URL_LENGTH_FOR_VALIDATION),\n /**\n * International phone number (E.164 format)\n */\n phoneNumber: z3.string().regex(/^\\+?[1-9]\\d{1,14}$/),\n /**\n * Pagination parameters with defaults\n */\n pagination: z3.object({\n page: z3.coerce.number().int().positive().default(1),\n limit: z3.coerce.number().int().positive().max(100).default(10),\n sort: z3.string().optional(),\n order: z3.enum(["asc", "desc"]).optional()\n }),\n /**\n * Date range with validation\n */\n dateRange: z3.object({\n from: z3.string().datetime(),\n to: z3.string().datetime()\n }).refine((data) => new Date(data.from) <= new Date(data.to), {\n message: "From date must be before or equal to To date"\n }),\n /**\n * Strong password requirements\n * - Minimum 8 characters\n * - At least one uppercase letter\n * - At least one lowercase letter\n * - At least one number\n * - At least one special character\n */\n strongPassword: z3.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number").regex(/[^A-Za-z0-9]/, "Password must contain at least one special character")\n};\n\n// src/security/http/auth.ts\ninit_veryfront_error();\n\n// src/security/http/config.ts\ninit_config();\ninit_utils();\n\n// src/security/http/middleware/config-loader.ts\ninit_utils();\n\n// src/security/http/middleware/etag.ts\ninit_hash();\n\n// src/security/http/middleware/content-types.ts\ninit_http();\n\n// src/security/path-validation.ts\ninit_utils();\n\n// src/security/secure-fs.ts\ninit_utils();\n\n// src/routing/api/api-route-matcher.ts\ninit_process();\n\n// src/routing/api/module-loader/loader.ts\ninit_utils();\n\n// src/routing/api/module-loader/esbuild-plugin.ts\ninit_utils();\ninit_utils();\ninit_utils();\n\n// src/routing/api/module-loader/http-validator.ts\ninit_veryfront_error();\n\n// src/routing/api/module-loader/security-config.ts\ninit_utils();\ninit_utils();\n\n// src/routing/api/module-loader/loader.ts\ninit_veryfront_error();\n\n// src/platform/compat/fs.ts\ninit_veryfront_error();\ninit_runtime();\n\n// src/routing/api/route-discovery.ts\ninit_std_path();\n\n// src/core/utils/file-discovery.ts\ninit_std_path();\ninit_deno3();\n\n// src/routing/api/route-executor.ts\ninit_veryfront_error();\n\n// src/routing/api/method-validator.ts\ninit_utils();\n\n// src/routing/api/error-handler.ts\ninit_utils();\ninit_utils();\ninit_utils();\n\n// src/rendering/client/router.ts\nvar VeryfrontRouter = class {\n constructor(options = {}) {\n this.root = null;\n const globalOptions = this.loadGlobalOptions();\n this.options = { ...globalOptions, ...options };\n this.baseUrl = options.baseUrl || globalThis.location.origin;\n this.currentPath = globalThis.location.pathname;\n this.pageLoader = new PageLoader();\n this.navigationHandlers = new NavigationHandlers(\n this.options.prefetchDelay,\n this.options.prefetch\n );\n this.pageTransition = new PageTransition((root) => this.viewportPrefetch.setup(root));\n this.viewportPrefetch = new ViewportPrefetch(\n (path) => this.prefetch(path),\n this.options.prefetch\n );\n this.handleClick = this.navigationHandlers.createClickHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handlePopState = this.navigationHandlers.createPopStateHandler({\n onNavigate: (url) => this.navigate(url, false),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handleMouseOver = this.navigationHandlers.createMouseOverHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n }\n loadGlobalOptions() {\n try {\n const options = globalThis.__VERYFRONT_ROUTER_OPTS__;\n if (!options) {\n rendererLogger.debug("[router] No global options configured");\n return {};\n }\n return options;\n } catch (error2) {\n rendererLogger.error("[router] Failed to read global options:", error2);\n return {};\n }\n }\n init() {\n rendererLogger.info("Initializing client-side router");\n const rootElement = document.getElementById("root");\n if (!rootElement) {\n rendererLogger.error("Root element not found");\n return;\n }\n const ReactDOMToUse = globalThis.ReactDOM || ReactDOM;\n this.root = ReactDOMToUse.createRoot(rootElement);\n document.addEventListener("click", this.handleClick);\n globalThis.addEventListener("popstate", this.handlePopState);\n document.addEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.setup(document);\n this.cacheCurrentPage();\n }\n cacheCurrentPage() {\n const pageData = extractPageDataFromScript();\n if (pageData) {\n this.pageLoader.setCache(this.currentPath, pageData);\n }\n }\n async navigate(url, pushState = true) {\n rendererLogger.info(`Navigating to ${url}`);\n this.navigationHandlers.saveScrollPosition(this.currentPath);\n this.options.onStart?.(url);\n if (pushState) {\n globalThis.history.pushState({}, "", url);\n }\n await this.loadPage(url);\n this.options.onNavigate?.(url);\n }\n async loadPage(path, updateUI = true) {\n if (this.pageLoader.isCached(path)) {\n rendererLogger.debug(`Loading ${path} from cache`);\n const data = this.pageLoader.getCached(path);\n if (!data) {\n rendererLogger.warn(`[router] Cache entry for ${path} was unexpectedly null, fetching fresh data`);\n } else {\n if (updateUI) {\n this.updatePage(data);\n }\n return;\n }\n }\n this.pageTransition.setLoadingState(true);\n try {\n const data = await this.pageLoader.loadPage(path);\n if (updateUI) {\n this.updatePage(data);\n }\n this.currentPath = path;\n this.options.onComplete?.(path);\n } catch (error2) {\n rendererLogger.error(`Failed to load ${path}`, error2);\n this.options.onError?.(error2);\n this.pageTransition.showError(error2);\n } finally {\n this.pageTransition.setLoadingState(false);\n }\n }\n async prefetch(path) {\n await this.pageLoader.prefetch(path);\n }\n updatePage(data) {\n if (!this.root)\n return;\n const isPopState = this.navigationHandlers.isPopState();\n const scrollY = this.navigationHandlers.getScrollPosition(this.currentPath);\n this.pageTransition.updatePage(data, isPopState, scrollY);\n this.navigationHandlers.clearPopStateFlag();\n }\n destroy() {\n document.removeEventListener("click", this.handleClick);\n globalThis.removeEventListener("popstate", this.handlePopState);\n document.removeEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.disconnect();\n this.pageLoader.clearCache();\n this.navigationHandlers.clear();\n this.pageTransition.destroy();\n }\n};\nif (typeof window !== "undefined" && globalThis.document) {\n const router = new VeryfrontRouter();\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => router.init());\n } else {\n router.init();\n }\n globalThis.veryFrontRouter = router;\n}\nexport {\n VeryfrontRouter\n};\n';
14807
- CLIENT_PREFETCH_BUNDLE = '// src/rendering/client/browser-logger.ts\nvar ConditionalBrowserLogger = class {\n constructor(prefix, level) {\n this.prefix = prefix;\n this.level = level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug?.(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log?.(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn?.(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error?.(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n};\nfunction getBrowserLogLevel() {\n if (typeof window === "undefined") {\n return 2 /* WARN */;\n }\n const windowObject = window;\n const isDevelopment = windowObject.__VERYFRONT_DEV__ || windowObject.__RSC_DEV__;\n if (!isDevelopment) {\n return 2 /* WARN */;\n }\n const isDebugEnabled = windowObject.__VERYFRONT_DEBUG__ || windowObject.__RSC_DEBUG__;\n return isDebugEnabled ? 0 /* DEBUG */ : 1 /* INFO */;\n}\nvar defaultLevel = getBrowserLogLevel();\nvar rscLogger = new ConditionalBrowserLogger("RSC", defaultLevel);\nvar prefetchLogger = new ConditionalBrowserLogger("PREFETCH", defaultLevel);\nvar hydrateLogger = new ConditionalBrowserLogger("HYDRATE", defaultLevel);\nvar browserLogger = new ConditionalBrowserLogger("VERYFRONT", defaultLevel);\n\n// src/rendering/client/prefetch/link-observer.ts\nvar LinkObserver = class {\n constructor(options, prefetchedUrls) {\n this.intersectionObserver = null;\n this.mutationObserver = null;\n this.pendingTimeouts = /* @__PURE__ */ new Map();\n this.elementTimeoutMap = /* @__PURE__ */ new WeakMap();\n this.timeoutCounter = 0;\n this.options = options;\n this.prefetchedUrls = prefetchedUrls;\n }\n init() {\n this.createIntersectionObserver();\n this.observeLinks();\n this.setupMutationObserver();\n }\n createIntersectionObserver() {\n this.intersectionObserver = new IntersectionObserver(\n (entries) => this.handleIntersection(entries),\n { rootMargin: this.options.rootMargin }\n );\n }\n handleIntersection(entries) {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const target = entry.target;\n let isAnchor = false;\n if (typeof HTMLAnchorElement !== "undefined") {\n isAnchor = target instanceof HTMLAnchorElement;\n } else {\n isAnchor = target.tagName === "A";\n }\n if (!isAnchor) {\n continue;\n }\n const link = target;\n const timeoutKey = this.timeoutCounter++;\n const timeoutId = setTimeout(() => {\n this.pendingTimeouts.delete(timeoutKey);\n this.elementTimeoutMap.delete(link);\n this.options.onLinkVisible(link);\n }, this.options.delay);\n this.pendingTimeouts.set(timeoutKey, timeoutId);\n this.elementTimeoutMap.set(link, timeoutKey);\n }\n }\n }\n observeLinks() {\n const links = document.querySelectorAll(\'a[href^="/"], a[href^="./"]\');\n links.forEach((link) => {\n if (this.isValidLink(link)) {\n this.intersectionObserver?.observe(link);\n }\n });\n }\n setupMutationObserver() {\n this.mutationObserver = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type === "childList") {\n mutation.addedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n this.observeElement(node);\n }\n });\n mutation.removedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n this.clearElementTimeouts(node);\n }\n });\n }\n }\n });\n this.mutationObserver.observe(document.body, {\n childList: true,\n subtree: true\n });\n }\n clearElementTimeouts(element) {\n if (element.tagName === "A") {\n const timeoutKey = this.elementTimeoutMap.get(element);\n if (timeoutKey !== void 0) {\n const timeoutId = this.pendingTimeouts.get(timeoutKey);\n if (timeoutId) {\n clearTimeout(timeoutId);\n this.pendingTimeouts.delete(timeoutKey);\n }\n this.elementTimeoutMap.delete(element);\n }\n }\n const links = element.querySelectorAll("a");\n links.forEach((link) => {\n const timeoutKey = this.elementTimeoutMap.get(link);\n if (timeoutKey !== void 0) {\n const timeoutId = this.pendingTimeouts.get(timeoutKey);\n if (timeoutId) {\n clearTimeout(timeoutId);\n this.pendingTimeouts.delete(timeoutKey);\n }\n this.elementTimeoutMap.delete(link);\n }\n });\n }\n observeElement(element) {\n const isAnchor = typeof HTMLAnchorElement !== "undefined" ? element instanceof HTMLAnchorElement : element.tagName === "A";\n if (isAnchor && this.isValidLink(element)) {\n this.intersectionObserver?.observe(element);\n }\n const links = element.querySelectorAll(\'a[href^="/"], a[href^="./"]\');\n links.forEach((link) => {\n const isLinkAnchor = typeof HTMLAnchorElement !== "undefined" ? link instanceof HTMLAnchorElement : link.tagName === "A";\n if (isLinkAnchor && this.isValidLink(link)) {\n this.intersectionObserver?.observe(link);\n }\n });\n }\n isValidLink(link) {\n if (link.hostname !== globalThis.location.hostname)\n return false;\n if (link.hasAttribute("download"))\n return false;\n if (link.target === "_blank")\n return false;\n const url = link.href;\n if (this.prefetchedUrls.has(url))\n return false;\n if (url === globalThis.location.href)\n return false;\n if (link.hash && link.pathname === globalThis.location.pathname) {\n return false;\n }\n if (link.dataset.noPrefetch)\n return false;\n return true;\n }\n destroy() {\n for (const [_, timeoutId] of this.pendingTimeouts) {\n clearTimeout(timeoutId);\n }\n this.pendingTimeouts.clear();\n if (this.intersectionObserver) {\n this.intersectionObserver.disconnect();\n this.intersectionObserver = null;\n }\n if (this.mutationObserver) {\n this.mutationObserver.disconnect();\n this.mutationObserver = null;\n }\n }\n};\n\n// src/rendering/client/prefetch/network-utils.ts\nvar NetworkUtils = class {\n constructor(allowedNetworks = ["4g", "wifi", "ethernet"]) {\n this.allowedNetworks = allowedNetworks;\n this.networkInfo = this.getNetworkConnection();\n }\n getNavigatorWithConnection() {\n if (typeof globalThis.navigator === "undefined") {\n return null;\n }\n return globalThis.navigator;\n }\n getNetworkConnection() {\n const nav = this.getNavigatorWithConnection();\n return nav?.connection || nav?.mozConnection || nav?.webkitConnection || null;\n }\n shouldPrefetch() {\n const nav = this.getNavigatorWithConnection();\n if (nav?.connection?.saveData) {\n return false;\n }\n if (this.networkInfo) {\n const effectiveType = this.networkInfo.effectiveType;\n if (effectiveType !== void 0 && !this.allowedNetworks.includes(effectiveType)) {\n return false;\n }\n }\n return true;\n }\n onNetworkChange(callback) {\n if (this.networkInfo?.addEventListener) {\n this.networkInfo.addEventListener("change", callback);\n }\n }\n getNetworkInfo() {\n return this.networkInfo;\n }\n};\n\n// src/core/utils/constants/cache.ts\nvar SECONDS_PER_MINUTE = 60;\nvar MINUTES_PER_HOUR = 60;\nvar HOURS_PER_DAY = 24;\nvar MS_PER_SECOND = 1e3;\nvar COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\nvar ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n\n// src/core/utils/constants/http.ts\nvar KB_IN_BYTES = 1024;\nvar PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\nvar PREFETCH_DEFAULT_TIMEOUT_MS = 1e4;\nvar PREFETCH_DEFAULT_DELAY_MS = 200;\n\n// src/core/utils/constants/hmr.ts\nvar HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n\n// src/core/utils/constants/network.ts\nvar BYTES_PER_MB = 1024 * 1024;\n\n// src/core/constants/buffers.ts\nvar DEFAULT_MAX_BODY_SIZE_BYTES = 1024 * 1024;\nvar DEFAULT_MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;\nvar PREFETCH_QUEUE_MAX_SIZE_BYTES = 1024 * 1024;\nvar MAX_BUNDLE_CHUNK_SIZE_BYTES = 4096 * 1024;\n\n// src/rendering/client/prefetch/prefetch-queue.ts\nvar DEFAULT_OPTIONS = {\n maxConcurrent: 4,\n maxSize: PREFETCH_QUEUE_MAX_SIZE_BYTES,\n timeout: 5e3\n};\nfunction isAbortError(error) {\n return Boolean(\n error && typeof error === "object" && "name" in error && error.name === "AbortError"\n );\n}\nvar PrefetchQueue = class {\n constructor(options = {}, prefetchedUrls) {\n this.controllers = /* @__PURE__ */ new Map();\n this.concurrent = 0;\n this.stopped = false;\n this.options = { ...DEFAULT_OPTIONS, ...options };\n this.prefetchedUrls = prefetchedUrls ?? /* @__PURE__ */ new Set();\n }\n setResourceCallback(callback) {\n this.onResourcesFetched = callback;\n }\n enqueue(url) {\n void this.prefetch(url);\n }\n has(url) {\n return this.prefetchedUrls.has(url) || this.controllers.has(url);\n }\n get size() {\n return this.getQueueSize();\n }\n clear() {\n this.stopAll();\n this.prefetchedUrls.clear();\n }\n start() {\n this.stopped = false;\n }\n stop() {\n this.stopped = true;\n this.stopAll();\n }\n getQueueSize() {\n return this.controllers.size;\n }\n getConcurrentCount() {\n return this.concurrent;\n }\n async prefetchLink(link) {\n if (this.stopped) {\n return;\n }\n const url = link.href;\n if (!url || this.controllers.has(url) || this.prefetchedUrls.has(url)) {\n return;\n }\n if (this.concurrent >= this.options.maxConcurrent) {\n prefetchLogger.debug?.(`Prefetch queue full, skipping ${url}`);\n return;\n }\n let parsedUrl;\n try {\n parsedUrl = new URL(url);\n } catch (_error) {\n prefetchLogger.debug?.(`Invalid prefetch URL ${url}`);\n return;\n }\n const controller = new AbortController();\n this.controllers.set(url, controller);\n this.concurrent += 1;\n const timeoutId = this.options.timeout > 0 ? setTimeout(() => controller.abort(), this.options.timeout) : void 0;\n try {\n const response = await fetch(parsedUrl.toString(), {\n method: "GET",\n signal: controller.signal,\n headers: { "X-Veryfront-Prefetch": "1" }\n });\n if (!response.ok) {\n return;\n }\n if (this.isResponseTooLarge(response)) {\n prefetchLogger.debug?.(`Prefetch too large, skipping ${url}`);\n return;\n }\n this.prefetchedUrls.add(url);\n if (this.onResourcesFetched) {\n try {\n await this.onResourcesFetched(response, url);\n } catch (callbackError) {\n prefetchLogger.error?.(`Prefetch callback failed for ${url}`, callbackError);\n }\n }\n } catch (error) {\n if (!isAbortError(error)) {\n prefetchLogger.error?.(`Failed to prefetch ${url}`, error);\n }\n } finally {\n if (timeoutId !== void 0) {\n clearTimeout(timeoutId);\n }\n this.controllers.delete(url);\n this.concurrent = Math.max(0, this.concurrent - 1);\n }\n }\n async prefetch(url) {\n const link = typeof document !== "undefined" ? document.createElement("a") : { href: url };\n link.href = url;\n await this.prefetchLink(link);\n }\n stopAll() {\n for (const controller of this.controllers.values()) {\n controller.abort();\n }\n this.controllers.clear();\n this.concurrent = 0;\n }\n isResponseTooLarge(response) {\n const rawLength = response.headers.get("content-length");\n if (rawLength === null) {\n return false;\n }\n const size = Number.parseInt(rawLength, 10);\n if (!Number.isFinite(size)) {\n return false;\n }\n return size > this.options.maxSize;\n }\n};\nvar prefetchQueue = new PrefetchQueue();\n\n// src/rendering/client/prefetch/resource-hints.ts\nvar ResourceHintsManager = class {\n constructor() {\n this.appliedHints = /* @__PURE__ */ new Set();\n }\n applyResourceHints(hints) {\n for (const hint of hints) {\n const key = `${hint.type}:${hint.href}`;\n if (this.appliedHints.has(key))\n continue;\n const existing = document.querySelector(`link[rel="${hint.type}"][href="${hint.href}"]`);\n if (existing) {\n this.appliedHints.add(key);\n continue;\n }\n this.createAndAppendHint(hint);\n this.appliedHints.add(key);\n prefetchLogger.debug(`Added resource hint: ${hint.type} ${hint.href}`);\n }\n }\n createAndAppendHint(hint) {\n if (!document.head) {\n prefetchLogger.warn("document.head is not available, skipping resource hint");\n return;\n }\n const link = document.createElement("link");\n link.rel = hint.type;\n link.href = hint.href;\n if (hint.as)\n link.setAttribute("as", hint.as);\n if (hint.crossOrigin)\n link.setAttribute("crossorigin", hint.crossOrigin);\n if (hint.media)\n link.setAttribute("media", hint.media);\n document.head.appendChild(link);\n }\n extractResourceHints(html, prefetchedUrls) {\n try {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, "text/html");\n const hints = [];\n this.extractPreloadLinks(doc, prefetchedUrls, hints);\n this.extractScripts(doc, prefetchedUrls, hints);\n this.extractStylesheets(doc, prefetchedUrls, hints);\n return hints;\n } catch (error) {\n prefetchLogger.error("Failed to parse prefetched page", error);\n return [];\n }\n }\n isValidResourceHintType(rel) {\n return rel === "prefetch" || rel === "preload" || rel === "preconnect" || rel === "dns-prefetch";\n }\n extractPreloadLinks(doc, prefetchedUrls, hints) {\n doc.querySelectorAll(\'link[rel="preload"], link[rel="prefetch"]\').forEach((link) => {\n const htmlLink = link;\n const href = htmlLink.href;\n if (href && !prefetchedUrls.has(href) && this.isValidResourceHintType(htmlLink.rel)) {\n hints.push({\n type: htmlLink.rel,\n href,\n as: htmlLink.getAttribute("as") || void 0\n });\n }\n });\n }\n extractScripts(doc, prefetchedUrls, hints) {\n doc.querySelectorAll("script[src]").forEach((script) => {\n const src = script.src;\n if (src && !prefetchedUrls.has(src)) {\n hints.push({ type: "prefetch", href: src, as: "script" });\n }\n });\n }\n extractStylesheets(doc, prefetchedUrls, hints) {\n doc.querySelectorAll(\'link[rel="stylesheet"]\').forEach((link) => {\n const href = link.href;\n if (href && !prefetchedUrls.has(href)) {\n hints.push({ type: "prefetch", href, as: "style" });\n }\n });\n }\n static generateResourceHints(_route, assets) {\n const hints = [\n \'<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">\',\n \'<link rel="dns-prefetch" href="https://esm.sh">\',\n \'<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>\'\n ];\n for (const asset of assets) {\n if (asset.endsWith(".js")) {\n hints.push(`<link rel="modulepreload" href="${asset}">`);\n } else if (asset.endsWith(".css")) {\n hints.push(`<link rel="preload" as="style" href="${asset}">`);\n } else if (asset.match(/\\.(woff2?|ttf|otf)$/)) {\n hints.push(`<link rel="preload" as="font" href="${asset}" crossorigin>`);\n }\n }\n return hints.join("\\n");\n }\n};\n\n// src/core/utils/runtime-guards.ts\nfunction hasDenoRuntime(global) {\n return typeof global === "object" && global !== null && "Deno" in global && typeof global.Deno?.env?.get === "function";\n}\nfunction hasNodeProcess(global) {\n return typeof global === "object" && global !== null && "process" in global && typeof global.process?.env === "object";\n}\n\n// src/core/utils/logger/env.ts\nfunction getEnvironmentVariable(name) {\n try {\n if (typeof Deno !== "undefined" && hasDenoRuntime(globalThis)) {\n const value = globalThis.Deno?.env.get(name);\n return value === "" ? void 0 : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = globalThis.process?.env[name];\n return value === "" ? void 0 : value;\n }\n } catch {\n return void 0;\n }\n return void 0;\n}\n\n// src/core/utils/logger/logger.ts\nvar cachedLogLevel;\nfunction resolveLogLevel(force = false) {\n if (force || cachedLogLevel === void 0) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\nvar ConsoleLogger = class {\n constructor(prefix, level = resolveLogLevel()) {\n this.prefix = prefix;\n this.level = level;\n }\n setLevel(level) {\n this.level = level;\n }\n getLevel() {\n return this.level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n async time(label, fn) {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error);\n throw error;\n }\n }\n};\nfunction parseLogLevel(levelString) {\n if (!levelString)\n return void 0;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case "DEBUG":\n return 0 /* DEBUG */;\n case "WARN":\n return 2 /* WARN */;\n case "ERROR":\n return 3 /* ERROR */;\n case "INFO":\n return 1 /* INFO */;\n default:\n return void 0;\n }\n}\nvar getDefaultLevel = () => {\n const envLevel = getEnvironmentVariable("LOG_LEVEL");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== void 0)\n return parsedLevel;\n const debugFlag = getEnvironmentVariable("VERYFRONT_DEBUG");\n if (debugFlag === "1" || debugFlag === "true")\n return 0 /* DEBUG */;\n return 1 /* INFO */;\n};\nvar trackedLoggers = /* @__PURE__ */ new Set();\nfunction createLogger(prefix) {\n const logger2 = new ConsoleLogger(prefix);\n trackedLoggers.add(logger2);\n return logger2;\n}\nvar cliLogger = createLogger("CLI");\nvar serverLogger = createLogger("SERVER");\nvar rendererLogger = createLogger("RENDERER");\nvar bundlerLogger = createLogger("BUNDLER");\nvar agentLogger = createLogger("AGENT");\nvar logger = createLogger("VERYFRONT");\n\n// deno.json\nvar deno_default = {\n name: "veryfront",\n version: "0.0.31",\n nodeModulesDir: "auto",\n exports: {\n ".": "./src/index.ts",\n "./cli": "./src/cli/main.ts",\n "./server": "./src/server/index.ts",\n "./middleware": "./src/middleware/index.ts",\n "./components": "./src/react/components/index.ts",\n "./data": "./src/data/index.ts",\n "./config": "./src/core/config/index.ts",\n "./ai": "./src/ai/index.ts",\n "./ai/client": "./src/ai/client.ts",\n "./ai/react": "./src/ai/react/index.ts",\n "./ai/primitives": "./src/ai/react/primitives/index.ts",\n "./ai/components": "./src/ai/react/components/index.ts",\n "./ai/production": "./src/ai/production/index.ts",\n "./ai/dev": "./src/ai/dev/index.ts",\n "./ai/workflow": "./src/ai/workflow/index.ts",\n "./ai/workflow/react": "./src/ai/workflow/react/index.ts"\n },\n imports: {\n "@veryfront": "./src/index.ts",\n "@veryfront/": "./src/",\n "@veryfront/ai": "./src/ai/index.ts",\n "@veryfront/ai/": "./src/ai/",\n "@veryfront/platform": "./src/platform/index.ts",\n "@veryfront/platform/": "./src/platform/",\n "@veryfront/types": "./src/core/types/index.ts",\n "@veryfront/types/": "./src/core/types/",\n "@veryfront/utils": "./src/core/utils/index.ts",\n "@veryfront/utils/": "./src/core/utils/",\n "@veryfront/middleware": "./src/middleware/index.ts",\n "@veryfront/middleware/": "./src/middleware/",\n "@veryfront/errors": "./src/core/errors/index.ts",\n "@veryfront/errors/": "./src/core/errors/",\n "@veryfront/config": "./src/core/config/index.ts",\n "@veryfront/config/": "./src/core/config/",\n "@veryfront/observability": "./src/observability/index.ts",\n "@veryfront/observability/": "./src/observability/",\n "@veryfront/routing": "./src/routing/index.ts",\n "@veryfront/routing/": "./src/routing/",\n "@veryfront/transforms": "./src/build/transforms/index.ts",\n "@veryfront/transforms/": "./src/build/transforms/",\n "@veryfront/data": "./src/data/index.ts",\n "@veryfront/data/": "./src/data/",\n "@veryfront/security": "./src/security/index.ts",\n "@veryfront/security/": "./src/security/",\n "@veryfront/components": "./src/react/components/index.ts",\n "@veryfront/react": "./src/react/index.ts",\n "@veryfront/react/": "./src/react/",\n "@veryfront/html": "./src/html/index.ts",\n "@veryfront/html/": "./src/html/",\n "@veryfront/rendering": "./src/rendering/index.ts",\n "@veryfront/rendering/": "./src/rendering/",\n "@veryfront/build": "./src/build/index.ts",\n "@veryfront/build/": "./src/build/",\n "@veryfront/server": "./src/server/index.ts",\n "@veryfront/server/": "./src/server/",\n "@veryfront/modules": "./src/module-system/index.ts",\n "@veryfront/modules/": "./src/module-system/",\n "@veryfront/compat/console": "./src/platform/compat/console/index.ts",\n "@veryfront/compat/": "./src/platform/compat/",\n "std/": "https://deno.land/std@0.220.0/",\n "@std/path": "https://deno.land/std@0.220.0/path/mod.ts",\n "@std/testing/bdd.ts": "https://deno.land/std@0.220.0/testing/bdd.ts",\n "@std/expect": "https://deno.land/std@0.220.0/expect/mod.ts",\n csstype: "https://esm.sh/csstype@3.2.3",\n "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",\n "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",\n react: "https://esm.sh/react@18.3.1",\n "react-dom": "https://esm.sh/react-dom@18.3.1",\n "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",\n "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",\n "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",\n "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",\n "@mdx-js/mdx": "https://esm.sh/@mdx-js/mdx@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "@mdx-js/react": "https://esm.sh/@mdx-js/react@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "unist-util-visit": "https://esm.sh/unist-util-visit@5.0.0",\n "mdast-util-to-string": "https://esm.sh/mdast-util-to-string@4.0.0",\n "github-slugger": "https://esm.sh/github-slugger@2.0.0",\n "remark-gfm": "https://esm.sh/remark-gfm@4.0.1",\n "remark-frontmatter": "https://esm.sh/remark-frontmatter@5.0.0",\n "rehype-highlight": "https://esm.sh/rehype-highlight@7.0.2",\n "rehype-slug": "https://esm.sh/rehype-slug@6.0.0",\n esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",\n "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",\n "es-module-lexer": "https://esm.sh/es-module-lexer@1.5.0",\n zod: "https://esm.sh/zod@3.22.0",\n "mime-types": "https://esm.sh/mime-types@2.1.35",\n mdast: "https://esm.sh/@types/mdast@4.0.3",\n hast: "https://esm.sh/@types/hast@3.0.3",\n unist: "https://esm.sh/@types/unist@3.0.2",\n unified: "https://esm.sh/unified@11.0.5?dts",\n ai: "https://esm.sh/ai@5.0.76?deps=react@18.3.1,react-dom@18.3.1",\n "ai/react": "https://esm.sh/@ai-sdk/react@2.0.59?deps=react@18.3.1,react-dom@18.3.1",\n "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",\n "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.4",\n unocss: "https://esm.sh/unocss@0.59.0",\n "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",\n "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0"\n },\n compilerOptions: {\n jsx: "react-jsx",\n jsxImportSource: "react",\n strict: true,\n noImplicitAny: true,\n noUncheckedIndexedAccess: true,\n types: [],\n lib: [\n "deno.window",\n "dom",\n "dom.iterable",\n "dom.asynciterable",\n "deno.ns"\n ]\n },\n tasks: {\n setup: "deno run --allow-all scripts/setup.ts",\n dev: "deno run --allow-all --no-lock --unstable-net --unstable-worker-options src/cli/main.ts dev",\n build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",\n "build:npm": "deno run -A scripts/build-npm.ts",\n release: "deno run -A scripts/release.ts",\n test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",\n "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",\n "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",\n "test:batches": "deno run --allow-all scripts/test-batches.ts",\n "test:unsafe": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net",\n "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",\n "coverage:report": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --lcov > coverage/lcov.info && deno run --allow-read scripts/check-coverage.ts 80",\n "coverage:html": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --html",\n lint: "DENO_NO_PACKAGE_JSON=1 deno lint src/",\n fmt: "deno fmt src/",\n typecheck: "deno check src/index.ts src/cli/main.ts src/server/index.ts src/routing/api/index.ts src/rendering/index.ts src/platform/index.ts src/platform/adapters/index.ts src/build/index.ts src/build/production-build/index.ts src/build/transforms/index.ts src/core/config/index.ts src/core/utils/index.ts src/data/index.ts src/security/index.ts src/middleware/index.ts src/server/handlers/dev/index.ts src/server/handlers/request/api/index.ts src/rendering/cache/index.ts src/rendering/cache/stores/index.ts src/rendering/rsc/actions/index.ts src/html/index.ts src/module-system/index.ts",\n "docs:check-links": "deno run -A scripts/check-doc-links.ts",\n "lint:ban-console": "deno run --allow-read scripts/ban-console.ts",\n "lint:ban-deep-imports": "deno run --allow-read scripts/ban-deep-imports.ts",\n "lint:ban-internal-root-imports": "deno run --allow-read scripts/ban-internal-root-imports.ts",\n "lint:check-awaits": "deno run --allow-read scripts/check-unawaited-promises.ts",\n "check:circular": "deno run -A jsr:@cunarist/deno-circular-deps src/index.ts"\n },\n lint: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n rules: {\n tags: [\n "recommended"\n ],\n include: [\n "ban-untagged-todo"\n ],\n exclude: [\n "no-explicit-any",\n "no-process-global",\n "no-console"\n ]\n }\n },\n fmt: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n options: {\n useTabs: false,\n lineWidth: 100,\n indentWidth: 2,\n semiColons: true,\n singleQuote: false,\n proseWrap: "preserve"\n }\n }\n};\n\n// src/platform/compat/process.ts\nimport process from "node:process";\n\n// src/platform/compat/runtime.ts\nvar isDeno = typeof Deno !== "undefined";\nvar isNode = typeof globalThis.process !== "undefined" && globalThis.process?.versions?.node !== void 0;\nvar isBun = typeof globalThis.Bun !== "undefined";\nvar isCloudflare = typeof globalThis !== "undefined" && "caches" in globalThis && "WebSocketPair" in globalThis;\n\n// src/platform/compat/process.ts\nfunction getEnv(key) {\n if (isDeno) {\n return Deno.env.get(key);\n }\n return process.env[key];\n}\n\n// src/core/utils/version.ts\nvar VERSION = getEnv("VERYFRONT_VERSION") || (typeof deno_default.version === "string" ? deno_default.version : "0.0.0");\n\n// src/core/utils/bundle-manifest.ts\nvar InMemoryBundleManifestStore = class {\n constructor() {\n this.metadata = /* @__PURE__ */ new Map();\n this.code = /* @__PURE__ */ new Map();\n this.sourceIndex = /* @__PURE__ */ new Map();\n }\n getBundleMetadata(key) {\n const entry = this.metadata.get(key);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleMetadata(key, metadata, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.metadata.set(key, { value: metadata, expiry });\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, /* @__PURE__ */ new Set());\n }\n this.sourceIndex.get(metadata.source).add(key);\n return Promise.resolve();\n }\n getBundleCode(hash) {\n const entry = this.code.get(hash);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleCode(hash, code, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n async deleteBundle(key) {\n const metadata = await this.getBundleMetadata(key);\n this.metadata.delete(key);\n if (metadata) {\n this.code.delete(metadata.codeHash);\n const sourceKeys = this.sourceIndex.get(metadata.source);\n if (sourceKeys) {\n sourceKeys.delete(key);\n if (sourceKeys.size === 0) {\n this.sourceIndex.delete(metadata.source);\n }\n }\n }\n }\n async invalidateSource(source) {\n const keys = this.sourceIndex.get(source);\n if (!keys)\n return 0;\n let count = 0;\n for (const key of Array.from(keys)) {\n await this.deleteBundle(key);\n count++;\n }\n this.sourceIndex.delete(source);\n return count;\n }\n clear() {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n isAvailable() {\n return Promise.resolve(true);\n }\n getStats() {\n let totalSize = 0;\n let oldest;\n let newest;\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest)\n oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest)\n newest = value.compiledAt;\n }\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest\n });\n }\n};\nvar manifestStore = new InMemoryBundleManifestStore();\n\n// src/rendering/client/prefetch.ts\nvar PrefetchManager = class {\n constructor(options = {}) {\n this.prefetchedUrls = /* @__PURE__ */ new Set();\n this.linkObserver = null;\n this.options = {\n rootMargin: options.rootMargin || "50px",\n delay: options.delay || PREFETCH_DEFAULT_DELAY_MS,\n maxConcurrent: options.maxConcurrent || 2,\n allowedNetworks: options.allowedNetworks || ["4g", "wifi", "ethernet"],\n maxSize: options.maxSize || PREFETCH_MAX_SIZE_BYTES,\n timeout: options.timeout || PREFETCH_DEFAULT_TIMEOUT_MS\n };\n this.networkUtils = new NetworkUtils(this.options.allowedNetworks);\n this.resourceHintsManager = new ResourceHintsManager();\n this.prefetchQueue = new PrefetchQueue(\n {\n maxConcurrent: this.options.maxConcurrent,\n maxSize: this.options.maxSize,\n timeout: this.options.timeout\n },\n this.prefetchedUrls\n );\n this.prefetchQueue.setResourceCallback(\n (response, url) => this.prefetchPageResources(response, url)\n );\n }\n init() {\n prefetchLogger.info("Initializing prefetch manager");\n if (!this.networkUtils.shouldPrefetch()) {\n prefetchLogger.info("Prefetching disabled due to network conditions");\n return;\n }\n this.linkObserver = new LinkObserver(\n {\n rootMargin: this.options.rootMargin,\n delay: this.options.delay,\n onLinkVisible: (link) => this.prefetchQueue.prefetchLink(link)\n },\n this.prefetchedUrls\n );\n this.linkObserver.init();\n this.networkUtils.onNetworkChange(() => {\n if (!this.networkUtils.shouldPrefetch()) {\n this.prefetchQueue.stopAll();\n }\n });\n }\n async prefetchPageResources(response, _pageUrl) {\n const html = await response.text();\n const hints = this.resourceHintsManager.extractResourceHints(html, this.prefetchedUrls);\n this.resourceHintsManager.applyResourceHints(hints);\n }\n applyResourceHints(hints) {\n this.resourceHintsManager.applyResourceHints(hints);\n }\n async prefetch(url) {\n await this.prefetchQueue.prefetch(url);\n }\n static generateResourceHints(route, assets) {\n return ResourceHintsManager.generateResourceHints(route, assets);\n }\n destroy() {\n this.linkObserver?.destroy();\n this.prefetchQueue.stopAll();\n this.prefetchedUrls.clear();\n }\n};\nif (typeof window !== "undefined") {\n const prefetchManager = new PrefetchManager();\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => prefetchManager.init());\n } else {\n prefetchManager.init();\n }\n globalThis.veryFrontPrefetch = prefetchManager;\n}\nexport {\n PrefetchManager\n};\n';
14915
+ CLIENT_ROUTER_BUNDLE = 'var __defProp = Object.defineProperty;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __esm = (fn, res) => function __init() {\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n};\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/core/utils/runtime-guards.ts\nfunction hasDenoRuntime(global) {\n return typeof global === "object" && global !== null && "Deno" in global && typeof global.Deno?.env?.get === "function";\n}\nfunction hasNodeProcess(global) {\n return typeof global === "object" && global !== null && "process" in global && typeof global.process?.env === "object";\n}\nfunction hasBunRuntime(global) {\n return typeof global === "object" && global !== null && "Bun" in global && typeof global.Bun !== "undefined";\n}\nvar init_runtime_guards = __esm({\n "src/core/utils/runtime-guards.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/logger/env.ts\nfunction getEnvironmentVariable(name) {\n try {\n if (typeof Deno !== "undefined" && hasDenoRuntime(globalThis)) {\n const value = globalThis.Deno?.env.get(name);\n return value === "" ? void 0 : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = globalThis.process?.env[name];\n return value === "" ? void 0 : value;\n }\n } catch {\n return void 0;\n }\n return void 0;\n}\nfunction isTestEnvironment() {\n return getEnvironmentVariable("NODE_ENV") === "test";\n}\nfunction isProductionEnvironment() {\n return getEnvironmentVariable("NODE_ENV") === "production";\n}\nfunction isDevelopmentEnvironment() {\n const env = getEnvironmentVariable("NODE_ENV");\n return env === "development" || env === void 0;\n}\nvar init_env = __esm({\n "src/core/utils/logger/env.ts"() {\n "use strict";\n init_runtime_guards();\n }\n});\n\n// src/core/utils/logger/logger.ts\nfunction resolveLogLevel(force = false) {\n if (force || cachedLogLevel === void 0) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\nfunction parseLogLevel(levelString) {\n if (!levelString)\n return void 0;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case "DEBUG":\n return 0 /* DEBUG */;\n case "WARN":\n return 2 /* WARN */;\n case "ERROR":\n return 3 /* ERROR */;\n case "INFO":\n return 1 /* INFO */;\n default:\n return void 0;\n }\n}\nfunction createLogger(prefix) {\n const logger2 = new ConsoleLogger(prefix);\n trackedLoggers.add(logger2);\n return logger2;\n}\nfunction __loggerResetForTests(options = {}) {\n const updatedLevel = resolveLogLevel(true);\n for (const instance of trackedLoggers) {\n instance.setLevel(updatedLevel);\n }\n if (options.restoreConsole) {\n console.debug = originalConsole.debug;\n console.log = originalConsole.log;\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n }\n}\nvar LogLevel, originalConsole, cachedLogLevel, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, logger;\nvar init_logger = __esm({\n "src/core/utils/logger/logger.ts"() {\n "use strict";\n init_env();\n LogLevel = /* @__PURE__ */ ((LogLevel2) => {\n LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";\n LogLevel2[LogLevel2["INFO"] = 1] = "INFO";\n LogLevel2[LogLevel2["WARN"] = 2] = "WARN";\n LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";\n return LogLevel2;\n })(LogLevel || {});\n originalConsole = {\n debug: console.debug,\n log: console.log,\n warn: console.warn,\n error: console.error\n };\n ConsoleLogger = class {\n constructor(prefix, level = resolveLogLevel()) {\n this.prefix = prefix;\n this.level = level;\n }\n setLevel(level) {\n this.level = level;\n }\n getLevel() {\n return this.level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n async time(label, fn) {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error2) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error2);\n throw error2;\n }\n }\n };\n getDefaultLevel = () => {\n const envLevel = getEnvironmentVariable("LOG_LEVEL");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== void 0)\n return parsedLevel;\n const debugFlag = getEnvironmentVariable("VERYFRONT_DEBUG");\n if (debugFlag === "1" || debugFlag === "true")\n return 0 /* DEBUG */;\n return 1 /* INFO */;\n };\n trackedLoggers = /* @__PURE__ */ new Set();\n cliLogger = createLogger("CLI");\n serverLogger = createLogger("SERVER");\n rendererLogger = createLogger("RENDERER");\n bundlerLogger = createLogger("BUNDLER");\n agentLogger = createLogger("AGENT");\n logger = createLogger("VERYFRONT");\n }\n});\n\n// src/core/utils/logger/index.ts\nvar init_logger2 = __esm({\n "src/core/utils/logger/index.ts"() {\n "use strict";\n init_logger();\n init_env();\n }\n});\n\n// src/core/utils/constants/build.ts\nvar DEFAULT_BUILD_CONCURRENCY, IMAGE_OPTIMIZATION;\nvar init_build = __esm({\n "src/core/utils/constants/build.ts"() {\n "use strict";\n DEFAULT_BUILD_CONCURRENCY = 4;\n IMAGE_OPTIMIZATION = {\n DEFAULT_SIZES: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\n DEFAULT_QUALITY: 80\n };\n }\n});\n\n// src/core/utils/constants/cache.ts\nvar SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, MS_PER_SECOND, DEFAULT_LRU_MAX_ENTRIES, COMPONENT_LOADER_MAX_ENTRIES, COMPONENT_LOADER_TTL_MS, MDX_RENDERER_MAX_ENTRIES, MDX_RENDERER_TTL_MS, RENDERER_CORE_MAX_ENTRIES, RENDERER_CORE_TTL_MS, TSX_LAYOUT_MAX_ENTRIES, TSX_LAYOUT_TTL_MS, DATA_FETCHING_MAX_ENTRIES, DATA_FETCHING_TTL_MS, MDX_CACHE_TTL_PRODUCTION_MS, MDX_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_CACHE_TTL_PRODUCTION_MS, BUNDLE_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_MANIFEST_PROD_TTL_MS, BUNDLE_MANIFEST_DEV_TTL_MS, RSC_MANIFEST_CACHE_TTL_MS, SERVER_ACTION_DEFAULT_TTL_SEC, DENO_KV_SAFE_SIZE_LIMIT_BYTES, HTTP_CACHE_SHORT_MAX_AGE_SEC, HTTP_CACHE_MEDIUM_MAX_AGE_SEC, HTTP_CACHE_LONG_MAX_AGE_SEC, ONE_DAY_MS, CACHE_CLEANUP_INTERVAL_MS, LRU_DEFAULT_MAX_ENTRIES, LRU_DEFAULT_MAX_SIZE_BYTES, CLEANUP_INTERVAL_MULTIPLIER;\nvar init_cache = __esm({\n "src/core/utils/constants/cache.ts"() {\n "use strict";\n SECONDS_PER_MINUTE = 60;\n MINUTES_PER_HOUR = 60;\n HOURS_PER_DAY = 24;\n MS_PER_SECOND = 1e3;\n DEFAULT_LRU_MAX_ENTRIES = 100;\n COMPONENT_LOADER_MAX_ENTRIES = 100;\n COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_RENDERER_MAX_ENTRIES = 200;\n MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n RENDERER_CORE_MAX_ENTRIES = 100;\n RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n TSX_LAYOUT_MAX_ENTRIES = 50;\n TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n DATA_FETCHING_MAX_ENTRIES = 200;\n DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n RSC_MANIFEST_CACHE_TTL_MS = 5e3;\n SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\n DENO_KV_SAFE_SIZE_LIMIT_BYTES = 64e3;\n HTTP_CACHE_SHORT_MAX_AGE_SEC = 60;\n HTTP_CACHE_MEDIUM_MAX_AGE_SEC = 3600;\n HTTP_CACHE_LONG_MAX_AGE_SEC = 31536e3;\n ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n CACHE_CLEANUP_INTERVAL_MS = 6e4;\n LRU_DEFAULT_MAX_ENTRIES = 1e3;\n LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n CLEANUP_INTERVAL_MULTIPLIER = 2;\n }\n});\n\n// src/core/utils/constants/cdn.ts\nfunction getReactCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}`;\n}\nfunction getReactDOMCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}`;\n}\nfunction getReactDOMClientCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}/client`;\n}\nfunction getReactDOMServerCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}/server`;\n}\nfunction getReactJSXRuntimeCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}/jsx-runtime`;\n}\nfunction getReactJSXDevRuntimeCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}/jsx-dev-runtime`;\n}\nfunction getReactImportMap(version = REACT_DEFAULT_VERSION) {\n return {\n react: getReactCDNUrl(version),\n "react-dom": getReactDOMCDNUrl(version),\n "react-dom/client": getReactDOMClientCDNUrl(version),\n "react-dom/server": getReactDOMServerCDNUrl(version),\n "react/jsx-runtime": getReactJSXRuntimeCDNUrl(version),\n "react/jsx-dev-runtime": getReactJSXDevRuntimeCDNUrl(version)\n };\n}\nfunction getDenoStdNodeBase() {\n return `${DENO_STD_BASE}/std@${DENO_STD_VERSION}/node`;\n}\nfunction getUnoCSSTailwindResetUrl() {\n return `${ESM_CDN_BASE}/@unocss/reset@${UNOCSS_VERSION}/tailwind.css`;\n}\nvar ESM_CDN_BASE, JSDELIVR_CDN_BASE, DENO_STD_BASE, REACT_VERSION_17, REACT_VERSION_18_2, REACT_VERSION_18_3, REACT_VERSION_19_RC, REACT_VERSION_19, REACT_DEFAULT_VERSION, DEFAULT_ALLOWED_CDN_HOSTS, DENO_STD_VERSION, UNOCSS_VERSION;\nvar init_cdn = __esm({\n "src/core/utils/constants/cdn.ts"() {\n "use strict";\n ESM_CDN_BASE = "https://esm.sh";\n JSDELIVR_CDN_BASE = "https://cdn.jsdelivr.net";\n DENO_STD_BASE = "https://deno.land";\n REACT_VERSION_17 = "17.0.2";\n REACT_VERSION_18_2 = "18.2.0";\n REACT_VERSION_18_3 = "18.3.1";\n REACT_VERSION_19_RC = "19.0.0-rc.0";\n REACT_VERSION_19 = "19.1.1";\n REACT_DEFAULT_VERSION = REACT_VERSION_18_3;\n DEFAULT_ALLOWED_CDN_HOSTS = [ESM_CDN_BASE, DENO_STD_BASE];\n DENO_STD_VERSION = "0.220.0";\n UNOCSS_VERSION = "0.59.0";\n }\n});\n\n// src/core/utils/constants/hash.ts\nvar HASH_SEED_DJB2, HASH_SEED_FNV1A;\nvar init_hash = __esm({\n "src/core/utils/constants/hash.ts"() {\n "use strict";\n HASH_SEED_DJB2 = 5381;\n HASH_SEED_FNV1A = 2166136261;\n }\n});\n\n// src/core/utils/constants/http.ts\nvar KB_IN_BYTES, HTTP_MODULE_FETCH_TIMEOUT_MS, HMR_RECONNECT_DELAY_MS, HMR_RELOAD_DELAY_MS, HMR_FILE_WATCHER_DEBOUNCE_MS, HMR_KEEP_ALIVE_INTERVAL_MS, DASHBOARD_RECONNECT_DELAY_MS, SERVER_FUNCTION_DEFAULT_TIMEOUT_MS, PREFETCH_MAX_SIZE_BYTES, PREFETCH_DEFAULT_TIMEOUT_MS, PREFETCH_DEFAULT_DELAY_MS, HTTP_OK, HTTP_NO_CONTENT, HTTP_CREATED, HTTP_REDIRECT_FOUND, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED, HTTP_GONE, HTTP_PAYLOAD_TOO_LARGE, HTTP_URI_TOO_LONG, HTTP_TOO_MANY_REQUESTS, HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR, HTTP_BAD_GATEWAY, HTTP_NOT_IMPLEMENTED, HTTP_UNAVAILABLE, HTTP_NETWORK_CONNECT_TIMEOUT, HTTP_STATUS_SUCCESS_MIN, HTTP_STATUS_REDIRECT_MIN, HTTP_STATUS_CLIENT_ERROR_MIN, HTTP_STATUS_SERVER_ERROR_MIN, HTTP_CONTENT_TYPES, MS_PER_MINUTE, HTTP_CONTENT_TYPE_IMAGE_PNG, HTTP_CONTENT_TYPE_IMAGE_JPEG, HTTP_CONTENT_TYPE_IMAGE_WEBP, HTTP_CONTENT_TYPE_IMAGE_AVIF, HTTP_CONTENT_TYPE_IMAGE_SVG, HTTP_CONTENT_TYPE_IMAGE_GIF, HTTP_CONTENT_TYPE_IMAGE_ICO;\nvar init_http = __esm({\n "src/core/utils/constants/http.ts"() {\n "use strict";\n init_cache();\n KB_IN_BYTES = 1024;\n HTTP_MODULE_FETCH_TIMEOUT_MS = 2500;\n HMR_RECONNECT_DELAY_MS = 1e3;\n HMR_RELOAD_DELAY_MS = 1e3;\n HMR_FILE_WATCHER_DEBOUNCE_MS = 100;\n HMR_KEEP_ALIVE_INTERVAL_MS = 3e4;\n DASHBOARD_RECONNECT_DELAY_MS = 3e3;\n SERVER_FUNCTION_DEFAULT_TIMEOUT_MS = 3e4;\n PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\n PREFETCH_DEFAULT_TIMEOUT_MS = 1e4;\n PREFETCH_DEFAULT_DELAY_MS = 200;\n HTTP_OK = 200;\n HTTP_NO_CONTENT = 204;\n HTTP_CREATED = 201;\n HTTP_REDIRECT_FOUND = 302;\n HTTP_NOT_MODIFIED = 304;\n HTTP_BAD_REQUEST = 400;\n HTTP_UNAUTHORIZED = 401;\n HTTP_FORBIDDEN = 403;\n HTTP_NOT_FOUND = 404;\n HTTP_METHOD_NOT_ALLOWED = 405;\n HTTP_GONE = 410;\n HTTP_PAYLOAD_TOO_LARGE = 413;\n HTTP_URI_TOO_LONG = 414;\n HTTP_TOO_MANY_REQUESTS = 429;\n HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;\n HTTP_SERVER_ERROR = 500;\n HTTP_INTERNAL_SERVER_ERROR = 500;\n HTTP_BAD_GATEWAY = 502;\n HTTP_NOT_IMPLEMENTED = 501;\n HTTP_UNAVAILABLE = 503;\n HTTP_NETWORK_CONNECT_TIMEOUT = 599;\n HTTP_STATUS_SUCCESS_MIN = 200;\n HTTP_STATUS_REDIRECT_MIN = 300;\n HTTP_STATUS_CLIENT_ERROR_MIN = 400;\n HTTP_STATUS_SERVER_ERROR_MIN = 500;\n HTTP_CONTENT_TYPES = {\n JS: "application/javascript; charset=utf-8",\n JSON: "application/json; charset=utf-8",\n HTML: "text/html; charset=utf-8",\n CSS: "text/css; charset=utf-8",\n TEXT: "text/plain; charset=utf-8"\n };\n MS_PER_MINUTE = 6e4;\n HTTP_CONTENT_TYPE_IMAGE_PNG = "image/png";\n HTTP_CONTENT_TYPE_IMAGE_JPEG = "image/jpeg";\n HTTP_CONTENT_TYPE_IMAGE_WEBP = "image/webp";\n HTTP_CONTENT_TYPE_IMAGE_AVIF = "image/avif";\n HTTP_CONTENT_TYPE_IMAGE_SVG = "image/svg+xml";\n HTTP_CONTENT_TYPE_IMAGE_GIF = "image/gif";\n HTTP_CONTENT_TYPE_IMAGE_ICO = "image/x-icon";\n }\n});\n\n// src/core/utils/constants/hmr.ts\nfunction isValidHMRMessageType(type) {\n return Object.values(HMR_MESSAGE_TYPES).includes(\n type\n );\n}\nvar HMR_MAX_MESSAGE_SIZE_BYTES, HMR_MAX_MESSAGES_PER_MINUTE, HMR_CLIENT_RELOAD_DELAY_MS, HMR_PORT_OFFSET, HMR_RATE_LIMIT_WINDOW_MS, HMR_CLOSE_NORMAL, HMR_CLOSE_RATE_LIMIT, HMR_CLOSE_MESSAGE_TOO_LARGE, HMR_MESSAGE_TYPES;\nvar init_hmr = __esm({\n "src/core/utils/constants/hmr.ts"() {\n "use strict";\n init_http();\n HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n HMR_MAX_MESSAGES_PER_MINUTE = 100;\n HMR_CLIENT_RELOAD_DELAY_MS = 3e3;\n HMR_PORT_OFFSET = 1;\n HMR_RATE_LIMIT_WINDOW_MS = 6e4;\n HMR_CLOSE_NORMAL = 1e3;\n HMR_CLOSE_RATE_LIMIT = 1008;\n HMR_CLOSE_MESSAGE_TOO_LARGE = 1009;\n HMR_MESSAGE_TYPES = {\n CONNECTED: "connected",\n UPDATE: "update",\n RELOAD: "reload",\n PING: "ping",\n PONG: "pong"\n };\n }\n});\n\n// src/core/utils/constants/html.ts\nvar Z_INDEX_DEV_INDICATOR, Z_INDEX_ERROR_OVERLAY, BREAKPOINT_SM, BREAKPOINT_MD, BREAKPOINT_LG, BREAKPOINT_XL, PROSE_MAX_WIDTH;\nvar init_html = __esm({\n "src/core/utils/constants/html.ts"() {\n "use strict";\n Z_INDEX_DEV_INDICATOR = 9998;\n Z_INDEX_ERROR_OVERLAY = 9999;\n BREAKPOINT_SM = 640;\n BREAKPOINT_MD = 768;\n BREAKPOINT_LG = 1024;\n BREAKPOINT_XL = 1280;\n PROSE_MAX_WIDTH = "65ch";\n }\n});\n\n// src/core/utils/constants/network.ts\nvar DEFAULT_DEV_SERVER_PORT, DEFAULT_REDIS_PORT, DEFAULT_API_SERVER_PORT, DEFAULT_PREVIEW_SERVER_PORT, DEFAULT_METRICS_PORT, BYTES_PER_KB, BYTES_PER_MB, DEFAULT_IMAGE_THUMBNAIL_SIZE, DEFAULT_IMAGE_SMALL_SIZE, DEFAULT_IMAGE_LARGE_SIZE, RESPONSIVE_IMAGE_WIDTH_XS, RESPONSIVE_IMAGE_WIDTH_SM, RESPONSIVE_IMAGE_WIDTH_MD, RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS, MAX_CHUNK_SIZE_KB, MIN_PORT, MAX_PORT, DEFAULT_SERVER_PORT;\nvar init_network = __esm({\n "src/core/utils/constants/network.ts"() {\n "use strict";\n DEFAULT_DEV_SERVER_PORT = 3e3;\n DEFAULT_REDIS_PORT = 6379;\n DEFAULT_API_SERVER_PORT = 8080;\n DEFAULT_PREVIEW_SERVER_PORT = 5e3;\n DEFAULT_METRICS_PORT = 9e3;\n BYTES_PER_KB = 1024;\n BYTES_PER_MB = 1024 * 1024;\n DEFAULT_IMAGE_THUMBNAIL_SIZE = 256;\n DEFAULT_IMAGE_SMALL_SIZE = 512;\n DEFAULT_IMAGE_LARGE_SIZE = 2048;\n RESPONSIVE_IMAGE_WIDTH_XS = 320;\n RESPONSIVE_IMAGE_WIDTH_SM = 640;\n RESPONSIVE_IMAGE_WIDTH_MD = 1024;\n RESPONSIVE_IMAGE_WIDTH_LG = 1920;\n RESPONSIVE_IMAGE_WIDTHS = [\n RESPONSIVE_IMAGE_WIDTH_XS,\n RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_LG\n ];\n MAX_CHUNK_SIZE_KB = 4096;\n MIN_PORT = 1;\n MAX_PORT = 65535;\n DEFAULT_SERVER_PORT = 8e3;\n }\n});\n\n// src/core/utils/constants/security.ts\nvar MAX_PATH_TRAVERSAL_DEPTH, FORBIDDEN_PATH_PATTERNS, DIRECTORY_TRAVERSAL_PATTERN, ABSOLUTE_PATH_PATTERN, MAX_PATH_LENGTH, DEFAULT_MAX_STRING_LENGTH;\nvar init_security = __esm({\n "src/core/utils/constants/security.ts"() {\n "use strict";\n MAX_PATH_TRAVERSAL_DEPTH = 10;\n FORBIDDEN_PATH_PATTERNS = [\n /\\0/\n // Null bytes\n ];\n DIRECTORY_TRAVERSAL_PATTERN = /\\.\\.[\\/\\\\]/;\n ABSOLUTE_PATH_PATTERN = /^[\\/\\\\]/;\n MAX_PATH_LENGTH = 4096;\n DEFAULT_MAX_STRING_LENGTH = 1e3;\n }\n});\n\n// src/core/utils/constants/server.ts\nvar DEFAULT_DASHBOARD_PORT, DEV_SERVER_ENDPOINTS;\nvar init_server = __esm({\n "src/core/utils/constants/server.ts"() {\n "use strict";\n DEFAULT_DASHBOARD_PORT = 3002;\n DEV_SERVER_ENDPOINTS = {\n HMR_RUNTIME: "/_veryfront/hmr-runtime.js",\n ERROR_OVERLAY: "/_veryfront/error-overlay.js"\n };\n }\n});\n\n// src/core/utils/constants/index.ts\nvar init_constants = __esm({\n "src/core/utils/constants/index.ts"() {\n "use strict";\n init_build();\n init_cache();\n init_cdn();\n init_hash();\n init_hmr();\n init_html();\n init_http();\n init_network();\n init_security();\n init_server();\n }\n});\n\n// deno.json\nvar deno_default;\nvar init_deno = __esm({\n "deno.json"() {\n deno_default = {\n name: "veryfront",\n version: "0.0.33",\n exclude: [\n "npm/",\n "dist/",\n "coverage/",\n "scripts/",\n "examples/",\n "tests/"\n ],\n exports: {\n ".": "./src/index.ts",\n "./cli": "./src/cli/main.ts",\n "./server": "./src/server/index.ts",\n "./middleware": "./src/middleware/index.ts",\n "./components": "./src/react/components/index.ts",\n "./data": "./src/data/index.ts",\n "./config": "./src/core/config/index.ts",\n "./ai": "./src/ai/index.ts",\n "./ai/client": "./src/ai/client.ts",\n "./ai/react": "./src/ai/react/index.ts",\n "./ai/primitives": "./src/ai/react/primitives/index.ts",\n "./ai/components": "./src/ai/react/components/index.ts",\n "./ai/production": "./src/ai/production/index.ts",\n "./ai/dev": "./src/ai/dev/index.ts",\n "./ai/workflow": "./src/ai/workflow/index.ts",\n "./ai/workflow/react": "./src/ai/workflow/react/index.ts"\n },\n imports: {\n "@veryfront": "./src/index.ts",\n "@veryfront/": "./src/",\n "@veryfront/ai": "./src/ai/index.ts",\n "@veryfront/ai/": "./src/ai/",\n "@veryfront/platform": "./src/platform/index.ts",\n "@veryfront/platform/": "./src/platform/",\n "@veryfront/types": "./src/core/types/index.ts",\n "@veryfront/types/": "./src/core/types/",\n "@veryfront/utils": "./src/core/utils/index.ts",\n "@veryfront/utils/": "./src/core/utils/",\n "@veryfront/middleware": "./src/middleware/index.ts",\n "@veryfront/middleware/": "./src/middleware/",\n "@veryfront/errors": "./src/core/errors/index.ts",\n "@veryfront/errors/": "./src/core/errors/",\n "@veryfront/config": "./src/core/config/index.ts",\n "@veryfront/config/": "./src/core/config/",\n "@veryfront/observability": "./src/observability/index.ts",\n "@veryfront/observability/": "./src/observability/",\n "@veryfront/routing": "./src/routing/index.ts",\n "@veryfront/routing/": "./src/routing/",\n "@veryfront/transforms": "./src/build/transforms/index.ts",\n "@veryfront/transforms/": "./src/build/transforms/",\n "@veryfront/data": "./src/data/index.ts",\n "@veryfront/data/": "./src/data/",\n "@veryfront/security": "./src/security/index.ts",\n "@veryfront/security/": "./src/security/",\n "@veryfront/components": "./src/react/components/index.ts",\n "@veryfront/react": "./src/react/index.ts",\n "@veryfront/react/": "./src/react/",\n "@veryfront/html": "./src/html/index.ts",\n "@veryfront/html/": "./src/html/",\n "@veryfront/rendering": "./src/rendering/index.ts",\n "@veryfront/rendering/": "./src/rendering/",\n "@veryfront/build": "./src/build/index.ts",\n "@veryfront/build/": "./src/build/",\n "@veryfront/server": "./src/server/index.ts",\n "@veryfront/server/": "./src/server/",\n "@veryfront/modules": "./src/module-system/index.ts",\n "@veryfront/modules/": "./src/module-system/",\n "@veryfront/compat/console": "./src/platform/compat/console/index.ts",\n "@veryfront/compat/": "./src/platform/compat/",\n "std/": "https://deno.land/std@0.220.0/",\n "@std/path": "https://deno.land/std@0.220.0/path/mod.ts",\n "@std/testing/bdd.ts": "https://deno.land/std@0.220.0/testing/bdd.ts",\n "@std/expect": "https://deno.land/std@0.220.0/expect/mod.ts",\n csstype: "https://esm.sh/csstype@3.2.3",\n "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",\n "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",\n react: "https://esm.sh/react@18.3.1",\n "react-dom": "https://esm.sh/react-dom@18.3.1",\n "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",\n "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",\n "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",\n "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",\n "@mdx-js/mdx": "https://esm.sh/@mdx-js/mdx@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "@mdx-js/react": "https://esm.sh/@mdx-js/react@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "unist-util-visit": "https://esm.sh/unist-util-visit@5.0.0",\n "mdast-util-to-string": "https://esm.sh/mdast-util-to-string@4.0.0",\n "github-slugger": "https://esm.sh/github-slugger@2.0.0",\n "remark-gfm": "https://esm.sh/remark-gfm@4.0.1",\n "remark-frontmatter": "https://esm.sh/remark-frontmatter@5.0.0",\n "rehype-highlight": "https://esm.sh/rehype-highlight@7.0.2",\n "rehype-slug": "https://esm.sh/rehype-slug@6.0.0",\n esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",\n "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",\n "es-module-lexer": "https://esm.sh/es-module-lexer@1.5.0",\n zod: "https://esm.sh/zod@3.22.0",\n "mime-types": "https://esm.sh/mime-types@2.1.35",\n mdast: "https://esm.sh/@types/mdast@4.0.3",\n hast: "https://esm.sh/@types/hast@3.0.3",\n unist: "https://esm.sh/@types/unist@3.0.2",\n unified: "https://esm.sh/unified@11.0.5?dts",\n ai: "https://esm.sh/ai@5.0.76?deps=react@18.3.1,react-dom@18.3.1",\n "ai/react": "https://esm.sh/@ai-sdk/react@2.0.59?deps=react@18.3.1,react-dom@18.3.1",\n "@ai-sdk/react": "https://esm.sh/@ai-sdk/react@2.0.59?deps=react@18.3.1,react-dom@18.3.1",\n "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",\n "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.4",\n unocss: "https://esm.sh/unocss@0.59.0",\n "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",\n "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0",\n redis: "npm:redis"\n },\n compilerOptions: {\n jsx: "react-jsx",\n jsxImportSource: "react",\n strict: true,\n noImplicitAny: true,\n noUncheckedIndexedAccess: true,\n types: [],\n lib: [\n "deno.window",\n "dom",\n "dom.iterable",\n "dom.asynciterable",\n "deno.ns"\n ]\n },\n tasks: {\n setup: "deno run --allow-all scripts/setup.ts",\n dev: "deno run --allow-all --no-lock --unstable-net --unstable-worker-options src/cli/main.ts dev",\n build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",\n "build:npm": "deno run -A scripts/build-npm.ts",\n release: "deno run -A scripts/release.ts",\n test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",\n "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",\n "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",\n "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",\n "coverage:report": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --lcov > coverage/lcov.info && deno run --allow-read scripts/check-coverage.ts 80",\n "coverage:html": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --html",\n lint: "DENO_NO_PACKAGE_JSON=1 deno lint src/",\n fmt: "deno fmt src/",\n typecheck: "deno check src/index.ts src/cli/main.ts src/server/index.ts src/routing/api/index.ts src/rendering/index.ts src/platform/index.ts src/platform/adapters/index.ts src/build/index.ts src/build/production-build/index.ts src/build/transforms/index.ts src/core/config/index.ts src/core/utils/index.ts src/data/index.ts src/security/index.ts src/middleware/index.ts src/server/handlers/dev/index.ts src/server/handlers/request/api/index.ts src/rendering/cache/index.ts src/rendering/cache/stores/index.ts src/rendering/rsc/actions/index.ts src/html/index.ts src/module-system/index.ts",\n "docs:check-links": "deno run -A scripts/check-doc-links.ts",\n "lint:ban-console": "deno run --allow-read scripts/ban-console.ts",\n "lint:ban-deep-imports": "deno run --allow-read scripts/ban-deep-imports.ts",\n "lint:ban-internal-root-imports": "deno run --allow-read scripts/ban-internal-root-imports.ts",\n "lint:check-awaits": "deno run --allow-read scripts/check-unawaited-promises.ts",\n "lint:platform": "deno run --allow-read scripts/lint-platform-agnostic.ts",\n "check:circular": "deno run -A jsr:@cunarist/deno-circular-deps src/index.ts"\n },\n lint: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n rules: {\n tags: [\n "recommended"\n ],\n include: [\n "ban-untagged-todo"\n ],\n exclude: [\n "no-explicit-any",\n "no-process-global",\n "no-console"\n ]\n }\n },\n fmt: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n options: {\n useTabs: false,\n lineWidth: 100,\n indentWidth: 2,\n semiColons: true,\n singleQuote: false,\n proseWrap: "preserve"\n }\n }\n };\n }\n});\n\n// src/platform/compat/runtime.ts\nvar isDeno, isNode, isBun, isCloudflare;\nvar init_runtime = __esm({\n "src/platform/compat/runtime.ts"() {\n "use strict";\n isDeno = typeof Deno !== "undefined";\n isNode = typeof globalThis.process !== "undefined" && globalThis.process?.versions?.node !== void 0;\n isBun = typeof globalThis.Bun !== "undefined";\n isCloudflare = typeof globalThis !== "undefined" && "caches" in globalThis && "WebSocketPair" in globalThis;\n }\n});\n\n// src/platform/compat/process.ts\nfunction getEnv(key) {\n if (isDeno) {\n return Deno.env.get(key);\n }\n if (hasNodeProcess2) {\n return nodeProcess.env[key];\n }\n return void 0;\n}\nfunction memoryUsage() {\n if (isDeno) {\n const usage2 = Deno.memoryUsage();\n return {\n rss: usage2.rss,\n heapTotal: usage2.heapTotal,\n heapUsed: usage2.heapUsed,\n external: usage2.external\n };\n }\n if (!hasNodeProcess2) {\n throw new Error("memoryUsage() is not supported in this runtime");\n }\n const usage = nodeProcess.memoryUsage();\n return {\n rss: usage.rss,\n heapTotal: usage.heapTotal,\n heapUsed: usage.heapUsed,\n external: usage.external || 0\n };\n}\nfunction execPath() {\n if (isDeno) {\n return Deno.execPath();\n }\n if (hasNodeProcess2) {\n return nodeProcess.execPath;\n }\n return "";\n}\nvar nodeProcess, hasNodeProcess2;\nvar init_process = __esm({\n "src/platform/compat/process.ts"() {\n "use strict";\n init_runtime();\n nodeProcess = globalThis.process;\n hasNodeProcess2 = !!nodeProcess?.versions?.node;\n }\n});\n\n// src/core/utils/version.ts\nvar VERSION;\nvar init_version = __esm({\n "src/core/utils/version.ts"() {\n "use strict";\n init_deno();\n init_process();\n VERSION = getEnv("VERYFRONT_VERSION") || (typeof deno_default.version === "string" ? deno_default.version : "0.0.0");\n }\n});\n\n// src/core/utils/paths.ts\nvar PATHS, VERYFRONT_PATHS, FILE_EXTENSIONS;\nvar init_paths = __esm({\n "src/core/utils/paths.ts"() {\n "use strict";\n PATHS = {\n PAGES_DIR: "pages",\n COMPONENTS_DIR: "components",\n PUBLIC_DIR: "public",\n STYLES_DIR: "styles",\n DIST_DIR: "dist",\n CONFIG_FILE: "veryfront.config.js"\n };\n VERYFRONT_PATHS = {\n INTERNAL_PREFIX: "/_veryfront",\n BUILD_DIR: "_veryfront",\n CHUNKS_DIR: "_veryfront/chunks",\n DATA_DIR: "_veryfront/data",\n ASSETS_DIR: "_veryfront/assets",\n HMR_RUNTIME: "/_veryfront/hmr-runtime.js",\n CLIENT_JS: "/_veryfront/client.js",\n ROUTER_JS: "/_veryfront/router.js",\n ERROR_OVERLAY: "/_veryfront/error-overlay.js"\n };\n FILE_EXTENSIONS = {\n MDX: [".mdx", ".md"],\n SCRIPT: [".tsx", ".ts", ".jsx", ".js"],\n STYLE: [".css", ".scss", ".sass"],\n ALL: [".mdx", ".md", ".tsx", ".ts", ".jsx", ".js", ".css"]\n };\n }\n});\n\n// src/core/utils/hash-utils.ts\nasync function computeHash(content) {\n const encoder = new TextEncoder();\n const data = encoder.encode(content);\n const hashBuffer = await crypto.subtle.digest("SHA-256", data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");\n}\nfunction getContentHash(content) {\n return computeHash(content);\n}\nfunction computeContentHash(content) {\n return computeHash(content);\n}\nfunction computeCodeHash(code) {\n const combined = code.code + (code.css || "") + (code.sourceMap || "");\n return computeHash(combined);\n}\nfunction simpleHash(str) {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n return Math.abs(hash);\n}\nasync function shortHash(content) {\n const fullHash = await computeHash(content);\n return fullHash.slice(0, 8);\n}\nvar init_hash_utils = __esm({\n "src/core/utils/hash-utils.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/memoize.ts\nfunction memoizeAsync(fn, keyHasher) {\n const cache = new MemoCache();\n return async (...args) => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = await fn(...args);\n cache.set(key, result);\n return result;\n };\n}\nfunction memoize(fn, keyHasher) {\n const cache = new MemoCache();\n return (...args) => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = fn(...args);\n cache.set(key, result);\n return result;\n };\n}\nfunction simpleHash2(...values) {\n const FNV_OFFSET_BASIS = 2166136261;\n const FNV_PRIME = 16777619;\n let hash = FNV_OFFSET_BASIS;\n for (const value of values) {\n const str = typeof value === "string" ? value : String(value);\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = Math.imul(hash, FNV_PRIME);\n }\n }\n return (hash >>> 0).toString(36);\n}\nvar MemoCache;\nvar init_memoize = __esm({\n "src/core/utils/memoize.ts"() {\n "use strict";\n MemoCache = class {\n constructor() {\n this.cache = /* @__PURE__ */ new Map();\n }\n get(key) {\n return this.cache.get(key);\n }\n set(key, value) {\n this.cache.set(key, value);\n }\n has(key) {\n return this.cache.has(key);\n }\n clear() {\n this.cache.clear();\n }\n size() {\n return this.cache.size;\n }\n };\n }\n});\n\n// src/core/utils/path-utils.ts\nfunction normalizePath(pathname) {\n pathname = pathname.replace(/\\\\+/g, "/").replace(/\\/\\.+\\//g, "/");\n if (pathname !== "/" && pathname.endsWith("/")) {\n pathname = pathname.slice(0, -1);\n }\n return pathname;\n}\nfunction joinPath(a, b) {\n return `${a.replace(/\\/$/, "")}/${b.replace(/^\\//, "")}`;\n}\nfunction isWithinDirectory(root, target) {\n const normalizedRoot = normalizePath(root);\n const normalizedTarget = normalizePath(target);\n return normalizedTarget.startsWith(`${normalizedRoot}/`) || normalizedTarget === normalizedRoot;\n}\nfunction getExtension(path) {\n const lastDot = path.lastIndexOf(".");\n if (lastDot === -1 || lastDot === path.length - 1) {\n return "";\n }\n return path.slice(lastDot);\n}\nfunction getDirectory(path) {\n const normalized = normalizePath(path);\n const lastSlash = normalized.lastIndexOf("/");\n return lastSlash <= 0 ? "/" : normalized.slice(0, lastSlash);\n}\nfunction hasHashedFilename(path) {\n return /\\.[a-f0-9]{8,}\\./.test(path);\n}\nfunction isAbsolutePath(path) {\n return path.startsWith("/") || /^[A-Za-z]:[\\\\/]/.test(path);\n}\nfunction toBase64Url(s) {\n const b64 = btoa(s);\n return b64.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");\n}\nfunction fromBase64Url(encoded) {\n const b64 = encoded.replaceAll("-", "+").replaceAll("_", "/");\n const pad = b64.length % 4 === 2 ? "==" : b64.length % 4 === 3 ? "=" : "";\n try {\n return atob(b64 + pad);\n } catch (error2) {\n logger.debug(`Failed to decode base64url string "${encoded}":`, error2);\n return "";\n }\n}\nvar init_path_utils = __esm({\n "src/core/utils/path-utils.ts"() {\n "use strict";\n init_logger();\n }\n});\n\n// src/core/utils/format-utils.ts\nfunction formatBytes(bytes) {\n if (bytes === 0)\n return "0 Bytes";\n const absBytes = Math.abs(bytes);\n if (absBytes < 1) {\n return `${absBytes} Bytes`;\n }\n const k = 1024;\n const sizes = ["Bytes", "KB", "MB", "GB", "TB"];\n const i = Math.floor(Math.log(absBytes) / Math.log(k));\n const index = Math.max(0, Math.min(i, sizes.length - 1));\n return `${parseFloat((absBytes / Math.pow(k, index)).toFixed(2))} ${sizes[index]}`;\n}\nfunction estimateSize(value) {\n if (value === null || value === void 0)\n return 8;\n switch (typeof value) {\n case "boolean":\n return 4;\n case "number":\n return 8;\n case "string":\n return value.length * 2;\n case "function":\n return 0;\n case "object":\n return estimateObjectSize(value);\n default:\n return 32;\n }\n}\nfunction estimateSizeWithCircularHandling(value) {\n const seen = /* @__PURE__ */ new WeakSet();\n const encoder = new TextEncoder();\n const json3 = JSON.stringify(value, (_key, val) => {\n if (typeof val === "object" && val !== null) {\n if (seen.has(val))\n return void 0;\n seen.add(val);\n if (val instanceof Map) {\n return { __type: "Map", entries: Array.from(val.entries()) };\n }\n if (val instanceof Set) {\n return { __type: "Set", values: Array.from(val.values()) };\n }\n }\n if (typeof val === "function")\n return void 0;\n if (val instanceof Uint8Array) {\n return { __type: "Uint8Array", length: val.length };\n }\n return val;\n });\n return encoder.encode(json3 ?? "").length;\n}\nfunction estimateObjectSize(value) {\n if (value instanceof ArrayBuffer)\n return value.byteLength;\n if (value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Uint32Array || value instanceof Int8Array || value instanceof Int16Array || value instanceof Int32Array) {\n return value.byteLength;\n }\n try {\n return JSON.stringify(value).length * 2;\n } catch (error2) {\n logger.debug("Failed to estimate size of non-serializable object:", error2);\n return 1024;\n }\n}\nfunction formatDuration(ms) {\n if (ms < 1e3)\n return `${ms}ms`;\n if (ms < 6e4)\n return `${(ms / 1e3).toFixed(1)}s`;\n if (ms < 36e5)\n return `${Math.floor(ms / 6e4)}m ${Math.floor(ms % 6e4 / 1e3)}s`;\n return `${Math.floor(ms / 36e5)}h ${Math.floor(ms % 36e5 / 6e4)}m`;\n}\nfunction formatNumber(num) {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ",");\n}\nfunction truncateString(str, maxLength) {\n if (str.length <= maxLength)\n return str;\n return str.slice(0, maxLength - 3) + "...";\n}\nvar init_format_utils = __esm({\n "src/core/utils/format-utils.ts"() {\n "use strict";\n init_logger();\n }\n});\n\n// src/core/utils/bundle-manifest.ts\nfunction setBundleManifestStore(store) {\n manifestStore = store;\n serverLogger.info("[bundle-manifest] Bundle manifest store configured", {\n type: store.constructor.name\n });\n}\nfunction getBundleManifestStore() {\n return manifestStore;\n}\nvar InMemoryBundleManifestStore, manifestStore;\nvar init_bundle_manifest = __esm({\n "src/core/utils/bundle-manifest.ts"() {\n "use strict";\n init_logger2();\n init_hash_utils();\n InMemoryBundleManifestStore = class {\n constructor() {\n this.metadata = /* @__PURE__ */ new Map();\n this.code = /* @__PURE__ */ new Map();\n this.sourceIndex = /* @__PURE__ */ new Map();\n }\n getBundleMetadata(key) {\n const entry = this.metadata.get(key);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleMetadata(key, metadata, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.metadata.set(key, { value: metadata, expiry });\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, /* @__PURE__ */ new Set());\n }\n this.sourceIndex.get(metadata.source).add(key);\n return Promise.resolve();\n }\n getBundleCode(hash) {\n const entry = this.code.get(hash);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleCode(hash, code, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n async deleteBundle(key) {\n const metadata = await this.getBundleMetadata(key);\n this.metadata.delete(key);\n if (metadata) {\n this.code.delete(metadata.codeHash);\n const sourceKeys = this.sourceIndex.get(metadata.source);\n if (sourceKeys) {\n sourceKeys.delete(key);\n if (sourceKeys.size === 0) {\n this.sourceIndex.delete(metadata.source);\n }\n }\n }\n }\n async invalidateSource(source) {\n const keys = this.sourceIndex.get(source);\n if (!keys)\n return 0;\n let count = 0;\n for (const key of Array.from(keys)) {\n await this.deleteBundle(key);\n count++;\n }\n this.sourceIndex.delete(source);\n return count;\n }\n clear() {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n isAvailable() {\n return Promise.resolve(true);\n }\n getStats() {\n let totalSize = 0;\n let oldest;\n let newest;\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest)\n oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest)\n newest = value.compiledAt;\n }\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest\n });\n }\n };\n manifestStore = new InMemoryBundleManifestStore();\n }\n});\n\n// src/core/utils/bundle-manifest-init.ts\nasync function initializeBundleManifest(config, mode, adapter) {\n const manifestConfig = config.cache?.bundleManifest;\n const enabled = manifestConfig?.enabled ?? mode === "production";\n if (!enabled) {\n serverLogger.info("[bundle-manifest] Bundle manifest disabled");\n setBundleManifestStore(new InMemoryBundleManifestStore());\n return;\n }\n const envType = adapter?.env.get("VERYFRONT_BUNDLE_MANIFEST_TYPE");\n const storeType = manifestConfig?.type || envType || "memory";\n serverLogger.info("[bundle-manifest] Initializing bundle manifest", {\n type: storeType,\n mode\n });\n try {\n let store;\n switch (storeType) {\n case "redis": {\n const { RedisBundleManifestStore } = await import("./bundle-manifest-redis.ts");\n const redisUrl = manifestConfig?.redisUrl || adapter?.env.get("VERYFRONT_BUNDLE_MANIFEST_REDIS_URL");\n store = new RedisBundleManifestStore(\n {\n url: redisUrl,\n keyPrefix: manifestConfig?.keyPrefix\n },\n adapter\n );\n const available = await store.isAvailable();\n if (!available) {\n serverLogger.warn("[bundle-manifest] Redis not available, falling back to in-memory");\n store = new InMemoryBundleManifestStore();\n } else {\n serverLogger.info("[bundle-manifest] Redis store initialized");\n }\n break;\n }\n case "kv": {\n const { KVBundleManifestStore } = await import("./bundle-manifest-kv.ts");\n store = new KVBundleManifestStore({\n keyPrefix: manifestConfig?.keyPrefix\n });\n const available = await store.isAvailable();\n if (!available) {\n serverLogger.warn("[bundle-manifest] KV not available, falling back to in-memory");\n store = new InMemoryBundleManifestStore();\n } else {\n serverLogger.info("[bundle-manifest] KV store initialized");\n }\n break;\n }\n case "memory":\n default: {\n store = new InMemoryBundleManifestStore();\n serverLogger.info("[bundle-manifest] In-memory store initialized");\n break;\n }\n }\n setBundleManifestStore(store);\n try {\n const stats = await store.getStats();\n serverLogger.info("[bundle-manifest] Store statistics", stats);\n } catch (error2) {\n serverLogger.debug("[bundle-manifest] Failed to get stats", { error: error2 });\n }\n } catch (error2) {\n serverLogger.error("[bundle-manifest] Failed to initialize store, using in-memory fallback", {\n error: error2\n });\n setBundleManifestStore(new InMemoryBundleManifestStore());\n }\n}\nfunction getBundleManifestTTL(config, mode) {\n const manifestConfig = config.cache?.bundleManifest;\n if (manifestConfig?.ttl) {\n return manifestConfig.ttl;\n }\n if (mode === "production") {\n return BUNDLE_MANIFEST_PROD_TTL_MS;\n } else {\n return BUNDLE_MANIFEST_DEV_TTL_MS;\n }\n}\nasync function warmupBundleManifest(store, keys) {\n serverLogger.info("[bundle-manifest] Warming up cache", { keys: keys.length });\n let loaded = 0;\n let failed = 0;\n for (const key of keys) {\n try {\n const metadata = await store.getBundleMetadata(key);\n if (metadata) {\n await store.getBundleCode(metadata.codeHash);\n loaded++;\n }\n } catch (error2) {\n serverLogger.debug("[bundle-manifest] Failed to warm up key", { key, error: error2 });\n failed++;\n }\n }\n serverLogger.info("[bundle-manifest] Cache warmup complete", { loaded, failed });\n}\nvar init_bundle_manifest_init = __esm({\n "src/core/utils/bundle-manifest-init.ts"() {\n "use strict";\n init_logger2();\n init_bundle_manifest();\n init_cache();\n }\n});\n\n// src/core/utils/feature-flags.ts\nfunction isRSCEnabled(config) {\n if (config?.experimental?.rsc !== void 0) {\n return config.experimental.rsc;\n }\n return getEnv("VERYFRONT_EXPERIMENTAL_RSC") === "1";\n}\nvar init_feature_flags = __esm({\n "src/core/utils/feature-flags.ts"() {\n "use strict";\n init_process();\n }\n});\n\n// src/core/utils/platform.ts\nfunction isCompiledBinary() {\n if (!isDeno)\n return false;\n try {\n const path = execPath();\n return path.includes("veryfront");\n } catch {\n return false;\n }\n}\nvar init_platform = __esm({\n "src/core/utils/platform.ts"() {\n "use strict";\n init_runtime();\n init_process();\n }\n});\n\n// src/core/utils/index.ts\nvar utils_exports = {};\n__export(utils_exports, {\n ABSOLUTE_PATH_PATTERN: () => ABSOLUTE_PATH_PATTERN,\n BREAKPOINT_LG: () => BREAKPOINT_LG,\n BREAKPOINT_MD: () => BREAKPOINT_MD,\n BREAKPOINT_SM: () => BREAKPOINT_SM,\n BREAKPOINT_XL: () => BREAKPOINT_XL,\n BUNDLE_CACHE_TTL_DEVELOPMENT_MS: () => BUNDLE_CACHE_TTL_DEVELOPMENT_MS,\n BUNDLE_CACHE_TTL_PRODUCTION_MS: () => BUNDLE_CACHE_TTL_PRODUCTION_MS,\n BUNDLE_MANIFEST_DEV_TTL_MS: () => BUNDLE_MANIFEST_DEV_TTL_MS,\n BUNDLE_MANIFEST_PROD_TTL_MS: () => BUNDLE_MANIFEST_PROD_TTL_MS,\n BYTES_PER_KB: () => BYTES_PER_KB,\n BYTES_PER_MB: () => BYTES_PER_MB,\n CACHE_CLEANUP_INTERVAL_MS: () => CACHE_CLEANUP_INTERVAL_MS,\n CLEANUP_INTERVAL_MULTIPLIER: () => CLEANUP_INTERVAL_MULTIPLIER,\n COMPONENT_LOADER_MAX_ENTRIES: () => COMPONENT_LOADER_MAX_ENTRIES,\n COMPONENT_LOADER_TTL_MS: () => COMPONENT_LOADER_TTL_MS,\n DASHBOARD_RECONNECT_DELAY_MS: () => DASHBOARD_RECONNECT_DELAY_MS,\n DATA_FETCHING_MAX_ENTRIES: () => DATA_FETCHING_MAX_ENTRIES,\n DATA_FETCHING_TTL_MS: () => DATA_FETCHING_TTL_MS,\n DEFAULT_ALLOWED_CDN_HOSTS: () => DEFAULT_ALLOWED_CDN_HOSTS,\n DEFAULT_API_SERVER_PORT: () => DEFAULT_API_SERVER_PORT,\n DEFAULT_BUILD_CONCURRENCY: () => DEFAULT_BUILD_CONCURRENCY,\n DEFAULT_DASHBOARD_PORT: () => DEFAULT_DASHBOARD_PORT,\n DEFAULT_DEV_SERVER_PORT: () => DEFAULT_DEV_SERVER_PORT,\n DEFAULT_IMAGE_LARGE_SIZE: () => DEFAULT_IMAGE_LARGE_SIZE,\n DEFAULT_IMAGE_SMALL_SIZE: () => DEFAULT_IMAGE_SMALL_SIZE,\n DEFAULT_IMAGE_THUMBNAIL_SIZE: () => DEFAULT_IMAGE_THUMBNAIL_SIZE,\n DEFAULT_LRU_MAX_ENTRIES: () => DEFAULT_LRU_MAX_ENTRIES,\n DEFAULT_MAX_STRING_LENGTH: () => DEFAULT_MAX_STRING_LENGTH,\n DEFAULT_METRICS_PORT: () => DEFAULT_METRICS_PORT,\n DEFAULT_PREVIEW_SERVER_PORT: () => DEFAULT_PREVIEW_SERVER_PORT,\n DEFAULT_REDIS_PORT: () => DEFAULT_REDIS_PORT,\n DEFAULT_SERVER_PORT: () => DEFAULT_SERVER_PORT,\n DENO_KV_SAFE_SIZE_LIMIT_BYTES: () => DENO_KV_SAFE_SIZE_LIMIT_BYTES,\n DENO_STD_BASE: () => DENO_STD_BASE,\n DENO_STD_VERSION: () => DENO_STD_VERSION,\n DEV_SERVER_ENDPOINTS: () => DEV_SERVER_ENDPOINTS,\n DIRECTORY_TRAVERSAL_PATTERN: () => DIRECTORY_TRAVERSAL_PATTERN,\n ESM_CDN_BASE: () => ESM_CDN_BASE,\n FILE_EXTENSIONS: () => FILE_EXTENSIONS,\n FORBIDDEN_PATH_PATTERNS: () => FORBIDDEN_PATH_PATTERNS,\n HASH_SEED_DJB2: () => HASH_SEED_DJB2,\n HASH_SEED_FNV1A: () => HASH_SEED_FNV1A,\n HMR_CLIENT_RELOAD_DELAY_MS: () => HMR_CLIENT_RELOAD_DELAY_MS,\n HMR_CLOSE_MESSAGE_TOO_LARGE: () => HMR_CLOSE_MESSAGE_TOO_LARGE,\n HMR_CLOSE_NORMAL: () => HMR_CLOSE_NORMAL,\n HMR_CLOSE_RATE_LIMIT: () => HMR_CLOSE_RATE_LIMIT,\n HMR_FILE_WATCHER_DEBOUNCE_MS: () => HMR_FILE_WATCHER_DEBOUNCE_MS,\n HMR_KEEP_ALIVE_INTERVAL_MS: () => HMR_KEEP_ALIVE_INTERVAL_MS,\n HMR_MAX_MESSAGES_PER_MINUTE: () => HMR_MAX_MESSAGES_PER_MINUTE,\n HMR_MAX_MESSAGE_SIZE_BYTES: () => HMR_MAX_MESSAGE_SIZE_BYTES,\n HMR_MESSAGE_TYPES: () => HMR_MESSAGE_TYPES,\n HMR_PORT_OFFSET: () => HMR_PORT_OFFSET,\n HMR_RATE_LIMIT_WINDOW_MS: () => HMR_RATE_LIMIT_WINDOW_MS,\n HMR_RECONNECT_DELAY_MS: () => HMR_RECONNECT_DELAY_MS,\n HMR_RELOAD_DELAY_MS: () => HMR_RELOAD_DELAY_MS,\n HOURS_PER_DAY: () => HOURS_PER_DAY,\n HTTP_BAD_GATEWAY: () => HTTP_BAD_GATEWAY,\n HTTP_BAD_REQUEST: () => HTTP_BAD_REQUEST,\n HTTP_CACHE_LONG_MAX_AGE_SEC: () => HTTP_CACHE_LONG_MAX_AGE_SEC,\n HTTP_CACHE_MEDIUM_MAX_AGE_SEC: () => HTTP_CACHE_MEDIUM_MAX_AGE_SEC,\n HTTP_CACHE_SHORT_MAX_AGE_SEC: () => HTTP_CACHE_SHORT_MAX_AGE_SEC,\n HTTP_CONTENT_TYPES: () => HTTP_CONTENT_TYPES,\n HTTP_CONTENT_TYPE_IMAGE_AVIF: () => HTTP_CONTENT_TYPE_IMAGE_AVIF,\n HTTP_CONTENT_TYPE_IMAGE_GIF: () => HTTP_CONTENT_TYPE_IMAGE_GIF,\n HTTP_CONTENT_TYPE_IMAGE_ICO: () => HTTP_CONTENT_TYPE_IMAGE_ICO,\n HTTP_CONTENT_TYPE_IMAGE_JPEG: () => HTTP_CONTENT_TYPE_IMAGE_JPEG,\n HTTP_CONTENT_TYPE_IMAGE_PNG: () => HTTP_CONTENT_TYPE_IMAGE_PNG,\n HTTP_CONTENT_TYPE_IMAGE_SVG: () => HTTP_CONTENT_TYPE_IMAGE_SVG,\n HTTP_CONTENT_TYPE_IMAGE_WEBP: () => HTTP_CONTENT_TYPE_IMAGE_WEBP,\n HTTP_CREATED: () => HTTP_CREATED,\n HTTP_FORBIDDEN: () => HTTP_FORBIDDEN,\n HTTP_GONE: () => HTTP_GONE,\n HTTP_INTERNAL_SERVER_ERROR: () => HTTP_INTERNAL_SERVER_ERROR,\n HTTP_METHOD_NOT_ALLOWED: () => HTTP_METHOD_NOT_ALLOWED,\n HTTP_MODULE_FETCH_TIMEOUT_MS: () => HTTP_MODULE_FETCH_TIMEOUT_MS,\n HTTP_NETWORK_CONNECT_TIMEOUT: () => HTTP_NETWORK_CONNECT_TIMEOUT,\n HTTP_NOT_FOUND: () => HTTP_NOT_FOUND,\n HTTP_NOT_IMPLEMENTED: () => HTTP_NOT_IMPLEMENTED,\n HTTP_NOT_MODIFIED: () => HTTP_NOT_MODIFIED,\n HTTP_NO_CONTENT: () => HTTP_NO_CONTENT,\n HTTP_OK: () => HTTP_OK,\n HTTP_PAYLOAD_TOO_LARGE: () => HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REDIRECT_FOUND: () => HTTP_REDIRECT_FOUND,\n HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: () => HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,\n HTTP_SERVER_ERROR: () => HTTP_SERVER_ERROR,\n HTTP_STATUS_CLIENT_ERROR_MIN: () => HTTP_STATUS_CLIENT_ERROR_MIN,\n HTTP_STATUS_REDIRECT_MIN: () => HTTP_STATUS_REDIRECT_MIN,\n HTTP_STATUS_SERVER_ERROR_MIN: () => HTTP_STATUS_SERVER_ERROR_MIN,\n HTTP_STATUS_SUCCESS_MIN: () => HTTP_STATUS_SUCCESS_MIN,\n HTTP_TOO_MANY_REQUESTS: () => HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED: () => HTTP_UNAUTHORIZED,\n HTTP_UNAVAILABLE: () => HTTP_UNAVAILABLE,\n HTTP_URI_TOO_LONG: () => HTTP_URI_TOO_LONG,\n IMAGE_OPTIMIZATION: () => IMAGE_OPTIMIZATION,\n InMemoryBundleManifestStore: () => InMemoryBundleManifestStore,\n JSDELIVR_CDN_BASE: () => JSDELIVR_CDN_BASE,\n KB_IN_BYTES: () => KB_IN_BYTES,\n LRU_DEFAULT_MAX_ENTRIES: () => LRU_DEFAULT_MAX_ENTRIES,\n LRU_DEFAULT_MAX_SIZE_BYTES: () => LRU_DEFAULT_MAX_SIZE_BYTES,\n LogLevel: () => LogLevel,\n MAX_CHUNK_SIZE_KB: () => MAX_CHUNK_SIZE_KB,\n MAX_PATH_LENGTH: () => MAX_PATH_LENGTH,\n MAX_PATH_TRAVERSAL_DEPTH: () => MAX_PATH_TRAVERSAL_DEPTH,\n MAX_PORT: () => MAX_PORT,\n MDX_CACHE_TTL_DEVELOPMENT_MS: () => MDX_CACHE_TTL_DEVELOPMENT_MS,\n MDX_CACHE_TTL_PRODUCTION_MS: () => MDX_CACHE_TTL_PRODUCTION_MS,\n MDX_RENDERER_MAX_ENTRIES: () => MDX_RENDERER_MAX_ENTRIES,\n MDX_RENDERER_TTL_MS: () => MDX_RENDERER_TTL_MS,\n MINUTES_PER_HOUR: () => MINUTES_PER_HOUR,\n MIN_PORT: () => MIN_PORT,\n MS_PER_MINUTE: () => MS_PER_MINUTE,\n MS_PER_SECOND: () => MS_PER_SECOND,\n MemoCache: () => MemoCache,\n ONE_DAY_MS: () => ONE_DAY_MS,\n PATHS: () => PATHS,\n PREFETCH_DEFAULT_DELAY_MS: () => PREFETCH_DEFAULT_DELAY_MS,\n PREFETCH_DEFAULT_TIMEOUT_MS: () => PREFETCH_DEFAULT_TIMEOUT_MS,\n PREFETCH_MAX_SIZE_BYTES: () => PREFETCH_MAX_SIZE_BYTES,\n PROSE_MAX_WIDTH: () => PROSE_MAX_WIDTH,\n REACT_DEFAULT_VERSION: () => REACT_DEFAULT_VERSION,\n REACT_VERSION_17: () => REACT_VERSION_17,\n REACT_VERSION_18_2: () => REACT_VERSION_18_2,\n REACT_VERSION_18_3: () => REACT_VERSION_18_3,\n REACT_VERSION_19: () => REACT_VERSION_19,\n REACT_VERSION_19_RC: () => REACT_VERSION_19_RC,\n RENDERER_CORE_MAX_ENTRIES: () => RENDERER_CORE_MAX_ENTRIES,\n RENDERER_CORE_TTL_MS: () => RENDERER_CORE_TTL_MS,\n RESPONSIVE_IMAGE_WIDTHS: () => RESPONSIVE_IMAGE_WIDTHS,\n RESPONSIVE_IMAGE_WIDTH_LG: () => RESPONSIVE_IMAGE_WIDTH_LG,\n RESPONSIVE_IMAGE_WIDTH_MD: () => RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_SM: () => RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_XS: () => RESPONSIVE_IMAGE_WIDTH_XS,\n RSC_MANIFEST_CACHE_TTL_MS: () => RSC_MANIFEST_CACHE_TTL_MS,\n SECONDS_PER_MINUTE: () => SECONDS_PER_MINUTE,\n SERVER_ACTION_DEFAULT_TTL_SEC: () => SERVER_ACTION_DEFAULT_TTL_SEC,\n SERVER_FUNCTION_DEFAULT_TIMEOUT_MS: () => SERVER_FUNCTION_DEFAULT_TIMEOUT_MS,\n TSX_LAYOUT_MAX_ENTRIES: () => TSX_LAYOUT_MAX_ENTRIES,\n TSX_LAYOUT_TTL_MS: () => TSX_LAYOUT_TTL_MS,\n UNOCSS_VERSION: () => UNOCSS_VERSION,\n VERSION: () => VERSION,\n VERYFRONT_PATHS: () => VERYFRONT_PATHS,\n Z_INDEX_DEV_INDICATOR: () => Z_INDEX_DEV_INDICATOR,\n Z_INDEX_ERROR_OVERLAY: () => Z_INDEX_ERROR_OVERLAY,\n __loggerResetForTests: () => __loggerResetForTests,\n agentLogger: () => agentLogger,\n bundlerLogger: () => bundlerLogger,\n cliLogger: () => cliLogger,\n computeCodeHash: () => computeCodeHash,\n computeContentHash: () => computeContentHash,\n computeHash: () => computeHash,\n estimateSize: () => estimateSize,\n estimateSizeWithCircularHandling: () => estimateSizeWithCircularHandling,\n formatBytes: () => formatBytes,\n formatDuration: () => formatDuration,\n formatNumber: () => formatNumber,\n fromBase64Url: () => fromBase64Url,\n getBundleManifestStore: () => getBundleManifestStore,\n getBundleManifestTTL: () => getBundleManifestTTL,\n getContentHash: () => getContentHash,\n getDenoStdNodeBase: () => getDenoStdNodeBase,\n getDirectory: () => getDirectory,\n getEnvironmentVariable: () => getEnvironmentVariable,\n getExtension: () => getExtension,\n getReactCDNUrl: () => getReactCDNUrl,\n getReactDOMCDNUrl: () => getReactDOMCDNUrl,\n getReactDOMClientCDNUrl: () => getReactDOMClientCDNUrl,\n getReactDOMServerCDNUrl: () => getReactDOMServerCDNUrl,\n getReactImportMap: () => getReactImportMap,\n getReactJSXDevRuntimeCDNUrl: () => getReactJSXDevRuntimeCDNUrl,\n getReactJSXRuntimeCDNUrl: () => getReactJSXRuntimeCDNUrl,\n getUnoCSSTailwindResetUrl: () => getUnoCSSTailwindResetUrl,\n hasBunRuntime: () => hasBunRuntime,\n hasDenoRuntime: () => hasDenoRuntime,\n hasHashedFilename: () => hasHashedFilename,\n hasNodeProcess: () => hasNodeProcess,\n initializeBundleManifest: () => initializeBundleManifest,\n isAbsolutePath: () => isAbsolutePath,\n isCompiledBinary: () => isCompiledBinary,\n isDevelopmentEnvironment: () => isDevelopmentEnvironment,\n isProductionEnvironment: () => isProductionEnvironment,\n isRSCEnabled: () => isRSCEnabled,\n isTestEnvironment: () => isTestEnvironment,\n isValidHMRMessageType: () => isValidHMRMessageType,\n isWithinDirectory: () => isWithinDirectory,\n joinPath: () => joinPath,\n logger: () => logger,\n memoize: () => memoize,\n memoizeAsync: () => memoizeAsync,\n memoizeHash: () => simpleHash2,\n normalizePath: () => normalizePath,\n numericHash: () => simpleHash,\n rendererLogger: () => rendererLogger,\n serverLogger: () => serverLogger,\n setBundleManifestStore: () => setBundleManifestStore,\n shortHash: () => shortHash,\n simpleHash: () => simpleHash,\n toBase64Url: () => toBase64Url,\n truncateString: () => truncateString,\n warmupBundleManifest: () => warmupBundleManifest\n});\nvar init_utils = __esm({\n "src/core/utils/index.ts"() {\n init_runtime_guards();\n init_logger2();\n init_constants();\n init_version();\n init_paths();\n init_hash_utils();\n init_memoize();\n init_path_utils();\n init_format_utils();\n init_bundle_manifest();\n init_bundle_manifest_init();\n init_feature_flags();\n init_platform();\n }\n});\n\n// src/_shims/std-path.ts\nvar std_path_exports = {};\n__export(std_path_exports, {\n SEPARATOR: () => SEPARATOR,\n SEPARATOR_PATTERN: () => SEPARATOR_PATTERN,\n basename: () => basename2,\n delimiter: () => delimiter2,\n dirname: () => dirname2,\n extname: () => extname2,\n format: () => format2,\n fromFileUrl: () => fromFileUrl,\n isAbsolute: () => isAbsolute2,\n join: () => join2,\n normalize: () => normalize2,\n parse: () => parse2,\n relative: () => relative2,\n resolve: () => resolve2,\n sep: () => sep2,\n toFileUrl: () => toFileUrl\n});\nimport * as nodeUrl from "node:url";\nimport * as nodePath from "node:path";\nfunction fromFileUrl(url) {\n return nodeUrl.fileURLToPath(url);\n}\nfunction toFileUrl(path) {\n return nodeUrl.pathToFileURL(path);\n}\nvar basename2, dirname2, extname2, join2, resolve2, relative2, isAbsolute2, normalize2, parse2, format2, sep2, delimiter2, SEPARATOR, SEPARATOR_PATTERN;\nvar init_std_path = __esm({\n "src/_shims/std-path.ts"() {\n basename2 = nodePath.basename;\n dirname2 = nodePath.dirname;\n extname2 = nodePath.extname;\n join2 = nodePath.join;\n resolve2 = nodePath.resolve;\n relative2 = nodePath.relative;\n isAbsolute2 = nodePath.isAbsolute;\n normalize2 = nodePath.normalize;\n parse2 = nodePath.parse;\n format2 = nodePath.format;\n sep2 = nodePath.sep;\n delimiter2 = nodePath.delimiter;\n SEPARATOR = nodePath.sep;\n SEPARATOR_PATTERN = nodePath.sep === "/" ? /\\/+/ : /[\\\\/]+/;\n }\n});\n\n// src/core/errors/veryfront-error.ts\nfunction createError(error2) {\n return error2;\n}\nfunction toError(veryfrontError) {\n const error2 = new Error(veryfrontError.message);\n error2.name = `VeryfrontError[${veryfrontError.type}]`;\n Object.defineProperty(error2, "context", {\n value: veryfrontError,\n enumerable: false,\n configurable: true\n });\n return error2;\n}\nvar init_veryfront_error = __esm({\n "src/core/errors/veryfront-error.ts"() {\n "use strict";\n }\n});\n\n// src/core/config/schema.ts\nimport { z } from "zod";\nvar corsSchema, veryfrontConfigSchema;\nvar init_schema = __esm({\n "src/core/config/schema.ts"() {\n "use strict";\n init_veryfront_error();\n corsSchema = z.union([z.boolean(), z.object({ origin: z.string().optional() }).strict()]);\n veryfrontConfigSchema = z.object({\n title: z.string().optional(),\n description: z.string().optional(),\n experimental: z.object({\n esmLayouts: z.boolean().optional(),\n precompileMDX: z.boolean().optional()\n }).partial().optional(),\n router: z.enum(["app", "pages"]).optional(),\n defaultLayout: z.string().optional(),\n theme: z.object({ colors: z.record(z.string()).optional() }).partial().optional(),\n build: z.object({\n outDir: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n esbuild: z.object({\n wasmURL: z.string().url().optional(),\n worker: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n cache: z.object({\n dir: z.string().optional(),\n bundleManifest: z.object({\n type: z.enum(["redis", "kv", "memory"]).optional(),\n redisUrl: z.string().optional(),\n keyPrefix: z.string().optional(),\n ttl: z.number().int().positive().optional(),\n enabled: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n dev: z.object({\n port: z.number().int().positive().optional(),\n host: z.string().optional(),\n open: z.boolean().optional(),\n hmr: z.boolean().optional(),\n components: z.array(z.string()).optional()\n }).partial().optional(),\n resolve: z.object({\n importMap: z.object({\n imports: z.record(z.string()).optional(),\n scopes: z.record(z.record(z.string())).optional()\n }).partial().optional()\n }).partial().optional(),\n security: z.object({\n csp: z.record(z.array(z.string())).optional(),\n remoteHosts: z.array(z.string().url()).optional(),\n cors: corsSchema.optional(),\n coop: z.enum(["same-origin", "same-origin-allow-popups", "unsafe-none"]).optional(),\n corp: z.enum(["same-origin", "same-site", "cross-origin"]).optional(),\n coep: z.enum(["require-corp", "unsafe-none"]).optional()\n }).partial().optional(),\n middleware: z.object({\n custom: z.array(z.function()).optional()\n }).partial().optional(),\n theming: z.object({\n brandName: z.string().optional(),\n logoHtml: z.string().optional()\n }).partial().optional(),\n assetPipeline: z.object({\n images: z.object({\n enabled: z.boolean().optional(),\n formats: z.array(z.enum(["webp", "avif", "jpeg", "png"])).optional(),\n sizes: z.array(z.number().int().positive()).optional(),\n quality: z.number().int().min(1).max(100).optional(),\n inputDir: z.string().optional(),\n outputDir: z.string().optional(),\n preserveOriginal: z.boolean().optional()\n }).partial().optional(),\n css: z.object({\n enabled: z.boolean().optional(),\n minify: z.boolean().optional(),\n autoprefixer: z.boolean().optional(),\n purge: z.boolean().optional(),\n criticalCSS: z.boolean().optional(),\n inputDir: z.string().optional(),\n outputDir: z.string().optional(),\n browsers: z.array(z.string()).optional(),\n purgeContent: z.array(z.string()).optional(),\n sourceMap: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n observability: z.object({\n tracing: z.object({\n enabled: z.boolean().optional(),\n exporter: z.enum(["jaeger", "zipkin", "otlp", "console"]).optional(),\n endpoint: z.string().optional(),\n serviceName: z.string().optional(),\n sampleRate: z.number().min(0).max(1).optional()\n }).partial().optional(),\n metrics: z.object({\n enabled: z.boolean().optional(),\n exporter: z.enum(["prometheus", "otlp", "console"]).optional(),\n endpoint: z.string().optional(),\n prefix: z.string().optional(),\n collectInterval: z.number().int().positive().optional()\n }).partial().optional()\n }).partial().optional(),\n fs: z.object({\n type: z.enum(["local", "veryfront-api", "memory"]).optional(),\n local: z.object({\n baseDir: z.string().optional()\n }).partial().optional(),\n veryfront: z.object({\n apiBaseUrl: z.string().url(),\n apiToken: z.string(),\n projectSlug: z.string(),\n cache: z.object({\n enabled: z.boolean().optional(),\n ttl: z.number().int().positive().optional(),\n maxSize: z.number().int().positive().optional()\n }).partial().optional(),\n retry: z.object({\n maxRetries: z.number().int().min(0).optional(),\n initialDelay: z.number().int().positive().optional(),\n maxDelay: z.number().int().positive().optional()\n }).partial().optional()\n }).partial().optional(),\n memory: z.object({\n files: z.record(z.union([z.string(), z.instanceof(Uint8Array)])).optional()\n }).partial().optional()\n }).partial().optional(),\n client: z.object({\n moduleResolution: z.enum(["cdn", "self-hosted", "bundled"]).optional(),\n cdn: z.object({\n provider: z.enum(["esm.sh", "unpkg", "jsdelivr"]).optional(),\n versions: z.union([\n z.literal("auto"),\n z.object({\n react: z.string().optional(),\n veryfront: z.string().optional()\n })\n ]).optional()\n }).partial().optional()\n }).partial().optional()\n }).partial();\n }\n});\n\n// src/core/config/loader.ts\nfunction getDefaultImportMapForConfig() {\n return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };\n}\nvar DEFAULT_CONFIG;\nvar init_loader = __esm({\n "src/core/config/loader.ts"() {\n "use strict";\n init_schema();\n init_std_path();\n init_logger();\n init_cdn();\n DEFAULT_CONFIG = {\n title: "Veryfront App",\n description: "Built with Veryfront",\n experimental: {\n esmLayouts: true\n },\n router: void 0,\n defaultLayout: void 0,\n theme: {\n colors: {\n primary: "#3B82F6"\n }\n },\n build: {\n outDir: "dist",\n trailingSlash: false,\n esbuild: {\n wasmURL: "https://deno.land/x/esbuild@v0.20.1/esbuild.wasm",\n worker: false\n }\n },\n cache: {\n dir: ".veryfront/cache",\n render: {\n type: "memory",\n ttl: void 0,\n maxEntries: 500,\n kvPath: void 0,\n redisUrl: void 0,\n redisKeyPrefix: void 0\n }\n },\n dev: {\n port: 3002,\n host: "localhost",\n open: false\n },\n resolve: {\n importMap: getDefaultImportMapForConfig()\n },\n client: {\n moduleResolution: "cdn",\n cdn: {\n provider: "esm.sh",\n versions: "auto"\n }\n }\n };\n }\n});\n\n// src/core/config/define-config.ts\nvar init_define_config = __esm({\n "src/core/config/define-config.ts"() {\n "use strict";\n init_veryfront_error();\n init_process();\n }\n});\n\n// src/core/config/defaults.ts\nvar DEFAULT_DEV_PORT, DEFAULT_PREFETCH_DELAY_MS, DURATION_HISTOGRAM_BOUNDARIES_MS, SIZE_HISTOGRAM_BOUNDARIES_KB, PAGE_TRANSITION_DELAY_MS;\nvar init_defaults = __esm({\n "src/core/config/defaults.ts"() {\n "use strict";\n DEFAULT_DEV_PORT = 3e3;\n DEFAULT_PREFETCH_DELAY_MS = 100;\n DURATION_HISTOGRAM_BOUNDARIES_MS = [\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1e3,\n 2500,\n 5e3,\n 7500,\n 1e4\n ];\n SIZE_HISTOGRAM_BOUNDARIES_KB = [\n 1,\n 5,\n 10,\n 25,\n 50,\n 100,\n 250,\n 500,\n 1e3,\n 2500,\n 5e3,\n 1e4\n ];\n PAGE_TRANSITION_DELAY_MS = 150;\n }\n});\n\n// src/core/config/network-defaults.ts\nvar init_network_defaults = __esm({\n "src/core/config/network-defaults.ts"() {\n "use strict";\n }\n});\n\n// src/core/config/index.ts\nvar init_config = __esm({\n "src/core/config/index.ts"() {\n init_loader();\n init_define_config();\n init_schema();\n init_defaults();\n init_network_defaults();\n }\n});\n\n// src/core/errors/types.ts\nvar VeryfrontError;\nvar init_types = __esm({\n "src/core/errors/types.ts"() {\n "use strict";\n VeryfrontError = class extends Error {\n constructor(message, code, context) {\n super(message);\n this.name = "VeryfrontError";\n this.code = code;\n this.context = context;\n }\n };\n }\n});\n\n// src/core/errors/agent-errors.ts\nvar init_agent_errors = __esm({\n "src/core/errors/agent-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/build-errors.ts\nvar init_build_errors = __esm({\n "src/core/errors/build-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/runtime-errors.ts\nvar init_runtime_errors = __esm({\n "src/core/errors/runtime-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/system-errors.ts\nvar NetworkError;\nvar init_system_errors = __esm({\n "src/core/errors/system-errors.ts"() {\n "use strict";\n init_types();\n NetworkError = class extends VeryfrontError {\n constructor(message, context) {\n super(message, "NETWORK_ERROR" /* NETWORK_ERROR */, context);\n this.name = "NetworkError";\n }\n };\n }\n});\n\n// src/core/errors/error-handlers.ts\nvar init_error_handlers = __esm({\n "src/core/errors/error-handlers.ts"() {\n "use strict";\n init_logger();\n init_types();\n }\n});\n\n// src/core/errors/error-codes.ts\nfunction getErrorDocsUrl(code) {\n return `https://veryfront.com/docs/errors/${code}`;\n}\nvar ErrorCode2;\nvar init_error_codes = __esm({\n "src/core/errors/error-codes.ts"() {\n "use strict";\n ErrorCode2 = {\n CONFIG_NOT_FOUND: "VF001",\n CONFIG_INVALID: "VF002",\n CONFIG_PARSE_ERROR: "VF003",\n CONFIG_VALIDATION_ERROR: "VF004",\n CONFIG_TYPE_ERROR: "VF005",\n IMPORT_MAP_INVALID: "VF006",\n CORS_CONFIG_INVALID: "VF007",\n BUILD_FAILED: "VF100",\n BUNDLE_ERROR: "VF101",\n TYPESCRIPT_ERROR: "VF102",\n MDX_COMPILE_ERROR: "VF103",\n ASSET_OPTIMIZATION_ERROR: "VF104",\n SSG_GENERATION_ERROR: "VF105",\n SOURCEMAP_ERROR: "VF106",\n HYDRATION_MISMATCH: "VF200",\n RENDER_ERROR: "VF201",\n COMPONENT_ERROR: "VF202",\n LAYOUT_NOT_FOUND: "VF203",\n PAGE_NOT_FOUND: "VF204",\n API_ERROR: "VF205",\n MIDDLEWARE_ERROR: "VF206",\n ROUTE_CONFLICT: "VF300",\n INVALID_ROUTE_FILE: "VF301",\n ROUTE_HANDLER_INVALID: "VF302",\n DYNAMIC_ROUTE_ERROR: "VF303",\n ROUTE_PARAMS_ERROR: "VF304",\n API_ROUTE_ERROR: "VF305",\n MODULE_NOT_FOUND: "VF400",\n IMPORT_RESOLUTION_ERROR: "VF401",\n CIRCULAR_DEPENDENCY: "VF402",\n INVALID_IMPORT: "VF403",\n DEPENDENCY_MISSING: "VF404",\n VERSION_MISMATCH: "VF405",\n PORT_IN_USE: "VF500",\n SERVER_START_ERROR: "VF501",\n HMR_ERROR: "VF502",\n CACHE_ERROR: "VF503",\n FILE_WATCH_ERROR: "VF504",\n REQUEST_ERROR: "VF505",\n CLIENT_BOUNDARY_VIOLATION: "VF600",\n SERVER_ONLY_IN_CLIENT: "VF601",\n CLIENT_ONLY_IN_SERVER: "VF602",\n INVALID_USE_CLIENT: "VF603",\n INVALID_USE_SERVER: "VF604",\n RSC_PAYLOAD_ERROR: "VF605",\n DEV_SERVER_ERROR: "VF700",\n FAST_REFRESH_ERROR: "VF701",\n ERROR_OVERLAY_ERROR: "VF702",\n SOURCE_MAP_ERROR: "VF703",\n DEPLOYMENT_ERROR: "VF800",\n PLATFORM_ERROR: "VF801",\n ENV_VAR_MISSING: "VF802",\n PRODUCTION_BUILD_REQUIRED: "VF803",\n UNKNOWN_ERROR: "VF900",\n PERMISSION_DENIED: "VF901",\n FILE_NOT_FOUND: "VF902",\n INVALID_ARGUMENT: "VF903",\n TIMEOUT_ERROR: "VF904"\n };\n }\n});\n\n// src/core/errors/catalog/factory.ts\nfunction createErrorSolution(code, config) {\n return {\n code,\n ...config,\n docs: config.docs ?? getErrorDocsUrl(code)\n };\n}\nfunction createSimpleError(code, title, message, steps) {\n return createErrorSolution(code, { title, message, steps });\n}\nvar init_factory = __esm({\n "src/core/errors/catalog/factory.ts"() {\n "use strict";\n init_error_codes();\n }\n});\n\n// src/core/errors/catalog/config-errors.ts\nvar CONFIG_ERROR_CATALOG;\nvar init_config_errors = __esm({\n "src/core/errors/catalog/config-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n CONFIG_ERROR_CATALOG = {\n [ErrorCode2.CONFIG_NOT_FOUND]: createErrorSolution(ErrorCode2.CONFIG_NOT_FOUND, {\n title: "Configuration file not found",\n message: "Veryfront could not find veryfront.config.js in your project root.",\n steps: [\n "Create veryfront.config.js in your project root directory",\n "Run \'veryfront init\' to generate a default configuration",\n "Or copy from an example project"\n ],\n example: `// veryfront.config.js\nexport default {\n title: "My App",\n dev: { port: 3002 }\n}`,\n tips: ["You can use .ts or .mjs extensions too", "Config is optional for simple projects"]\n }),\n [ErrorCode2.CONFIG_INVALID]: createErrorSolution(ErrorCode2.CONFIG_INVALID, {\n title: "Invalid configuration",\n message: "Your configuration file has invalid values or structure.",\n steps: [\n "Check that the config exports a default object",\n "Ensure all values are valid JavaScript types",\n "Remove any trailing commas",\n "Verify property names match the schema"\n ],\n example: `// \\u2713 Valid config\nexport default {\n title: "My App",\n dev: {\n port: 3002,\n open: true\n }\n}`\n }),\n [ErrorCode2.CONFIG_PARSE_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_PARSE_ERROR,\n "Configuration parse error",\n "Failed to parse your configuration file.",\n [\n "Check for syntax errors (missing brackets, quotes, etc.)",\n "Ensure the file has valid JavaScript/TypeScript syntax",\n "Look for the specific parse error in the output above"\n ]\n ),\n [ErrorCode2.CONFIG_VALIDATION_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_VALIDATION_ERROR,\n "Configuration validation failed",\n "Configuration values do not pass validation.",\n [\n "Check that port numbers are between 1-65535",\n "Ensure boolean flags are true/false (not strings)",\n "Verify URLs are properly formatted",\n "Check array/object structures match expected format"\n ]\n ),\n [ErrorCode2.CONFIG_TYPE_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_TYPE_ERROR,\n "Configuration type error",\n "A configuration value has the wrong type.",\n [\n "Check that numbers are not in quotes",\n \'Ensure booleans are true/false, not "true"/"false"\',\n "Verify arrays use [] brackets",\n "Check objects use {} braces"\n ]\n ),\n [ErrorCode2.IMPORT_MAP_INVALID]: createErrorSolution(ErrorCode2.IMPORT_MAP_INVALID, {\n title: "Invalid import map",\n message: "The import map in your configuration is invalid.",\n steps: [\n "Check import map structure: { imports: {}, scopes: {} }",\n "Ensure URLs are valid and accessible",\n "Verify package names are correct"\n ],\n example: `resolve: {\n importMap: {\n imports: {\n "react": "https://esm.sh/react@19",\n "@/utils": "./src/utils/index.ts"\n }\n }\n}`\n }),\n [ErrorCode2.CORS_CONFIG_INVALID]: createErrorSolution(ErrorCode2.CORS_CONFIG_INVALID, {\n title: "Invalid CORS configuration",\n message: "The CORS configuration is invalid.",\n steps: [\n "Use true for default CORS settings",\n "Or provide an object with origin, methods, headers",\n "Ensure origin is a string, not an array"\n ],\n example: `security: {\n cors: true // or { origin: "https://example.com" }\n}`\n })\n };\n }\n});\n\n// src/core/errors/catalog/build-errors.ts\nvar BUILD_ERROR_CATALOG;\nvar init_build_errors2 = __esm({\n "src/core/errors/catalog/build-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n BUILD_ERROR_CATALOG = {\n [ErrorCode2.BUILD_FAILED]: createErrorSolution(ErrorCode2.BUILD_FAILED, {\n title: "Build failed",\n message: "The build process encountered errors.",\n steps: [\n "Check the error messages above for specific issues",\n "Fix any TypeScript or syntax errors",\n "Ensure all imports can be resolved",\n "Run \'veryfront doctor\' to check your environment"\n ],\n tips: ["Try running with --verbose for more details", "Check build logs for warnings"]\n }),\n [ErrorCode2.BUNDLE_ERROR]: createSimpleError(\n ErrorCode2.BUNDLE_ERROR,\n "Bundle generation failed",\n "Failed to generate JavaScript bundles.",\n [\n "Check for circular dependencies",\n "Ensure all imports are valid",\n "Try clearing cache: veryfront clean"\n ]\n ),\n [ErrorCode2.TYPESCRIPT_ERROR]: createSimpleError(\n ErrorCode2.TYPESCRIPT_ERROR,\n "TypeScript compilation error",\n "TypeScript found errors in your code.",\n [\n "Fix the TypeScript errors shown above",\n "Check your tsconfig.json configuration",\n "Ensure all types are properly imported"\n ]\n ),\n [ErrorCode2.MDX_COMPILE_ERROR]: createErrorSolution(ErrorCode2.MDX_COMPILE_ERROR, {\n title: "MDX compilation failed",\n message: "Failed to compile MDX file.",\n steps: [\n "Check for syntax errors in your MDX file",\n "Ensure frontmatter YAML is valid",\n "Verify JSX components are properly imported",\n "Check for unclosed tags or brackets"\n ],\n example: `---\ntitle: My Post\n---\n\nimport Button from \'./components/Button.jsx\'\n\n# Hello World\n\n<Button>Click me</Button>`\n }),\n [ErrorCode2.ASSET_OPTIMIZATION_ERROR]: createSimpleError(\n ErrorCode2.ASSET_OPTIMIZATION_ERROR,\n "Asset optimization failed",\n "Failed to optimize assets (images, CSS, etc.).",\n [\n "Check that asset files are valid",\n "Ensure file paths are correct",\n "Try disabling optimization temporarily"\n ]\n ),\n [ErrorCode2.SSG_GENERATION_ERROR]: createSimpleError(\n ErrorCode2.SSG_GENERATION_ERROR,\n "Static site generation failed",\n "Failed to generate static pages.",\n [\n "Check that all routes are valid",\n "Ensure getStaticData functions return correctly",\n "Verify no dynamic content requires runtime"\n ]\n ),\n [ErrorCode2.SOURCEMAP_ERROR]: createSimpleError(\n ErrorCode2.SOURCEMAP_ERROR,\n "Source map generation failed",\n "Failed to generate source maps.",\n [\n "Try disabling source maps temporarily",\n "Check for very large files that might cause issues"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/runtime-errors.ts\nvar RUNTIME_ERROR_CATALOG;\nvar init_runtime_errors2 = __esm({\n "src/core/errors/catalog/runtime-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n RUNTIME_ERROR_CATALOG = {\n [ErrorCode2.HYDRATION_MISMATCH]: createErrorSolution(ErrorCode2.HYDRATION_MISMATCH, {\n title: "Hydration mismatch",\n message: "Client-side HTML does not match server-rendered HTML.",\n steps: [\n "Check for random values or timestamps in render",\n "Ensure Date() calls are consistent",\n "Avoid using browser-only APIs during SSR",\n "Check for white space or formatting differences"\n ],\n example: `// \\u274C Wrong - random on each render\n<div>{Math.random()}</div>\n\nconst [random, setRandom] = useState(0)\nuseEffect(() => setRandom(Math.random()), [])\n<div>{random}</div>`,\n relatedErrors: [ErrorCode2.RENDER_ERROR]\n }),\n [ErrorCode2.RENDER_ERROR]: createSimpleError(\n ErrorCode2.RENDER_ERROR,\n "Render error",\n "Failed to render component.",\n [\n "Check the component for errors",\n "Ensure all props are valid",\n "Look for null/undefined access",\n "Check error boundaries"\n ]\n ),\n [ErrorCode2.COMPONENT_ERROR]: createSimpleError(\n ErrorCode2.COMPONENT_ERROR,\n "Component error",\n "Error in component lifecycle or render.",\n [\n "Check component code for errors",\n "Ensure hooks follow Rules of Hooks",\n "Verify props are passed correctly"\n ]\n ),\n [ErrorCode2.LAYOUT_NOT_FOUND]: createErrorSolution(ErrorCode2.LAYOUT_NOT_FOUND, {\n title: "Layout file not found",\n message: "Required layout file is missing.",\n steps: [\n "Create app/layout.tsx in App Router",\n "Or create layouts/default.mdx for Pages Router",\n "Check file path and name are correct"\n ],\n example: `// app/layout.tsx\nexport default function RootLayout({ children }) {\n return (\n <html lang="en">\n <body>{children}</body>\n </html>\n )\n}`\n }),\n [ErrorCode2.PAGE_NOT_FOUND]: createSimpleError(\n ErrorCode2.PAGE_NOT_FOUND,\n "Page not found",\n "The requested page does not exist.",\n [\n "Check that the page file exists",\n "Verify file name matches route",\n "Ensure file extension is correct (.tsx, .jsx, .mdx)"\n ]\n ),\n [ErrorCode2.API_ERROR]: createSimpleError(\n ErrorCode2.API_ERROR,\n "API handler error",\n "Error in API route handler.",\n [\n "Check API handler code for errors",\n "Ensure proper error handling",\n "Verify request/response format"\n ]\n ),\n [ErrorCode2.MIDDLEWARE_ERROR]: createSimpleError(\n ErrorCode2.MIDDLEWARE_ERROR,\n "Middleware error",\n "Error in middleware execution.",\n [\n "Check middleware code for errors",\n "Ensure middleware returns Response",\n "Verify middleware is properly exported"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/route-errors.ts\nvar ROUTE_ERROR_CATALOG;\nvar init_route_errors = __esm({\n "src/core/errors/catalog/route-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n ROUTE_ERROR_CATALOG = {\n [ErrorCode2.ROUTE_CONFLICT]: createSimpleError(\n ErrorCode2.ROUTE_CONFLICT,\n "Route conflict",\n "Multiple files are trying to handle the same route.",\n [\n "Check for duplicate route files",\n "Remove conflicting routes",\n "Use dynamic routes [id] carefully"\n ]\n ),\n [ErrorCode2.INVALID_ROUTE_FILE]: createErrorSolution(ErrorCode2.INVALID_ROUTE_FILE, {\n title: "Invalid route file",\n message: "Route file has invalid structure or exports.",\n steps: [\n "API routes must export GET, POST, etc. functions",\n "Page routes must export default component",\n "Check for syntax errors"\n ],\n example: `// app/api/users/route.ts\nexport async function GET() {\n return Response.json({ users: [] })\n}`\n }),\n [ErrorCode2.ROUTE_HANDLER_INVALID]: createSimpleError(\n ErrorCode2.ROUTE_HANDLER_INVALID,\n "Invalid route handler",\n "Route handler does not return Response.",\n [\n "Ensure handler returns Response object",\n "Use Response.json() for JSON responses",\n "Check for missing return statement"\n ]\n ),\n [ErrorCode2.DYNAMIC_ROUTE_ERROR]: createSimpleError(\n ErrorCode2.DYNAMIC_ROUTE_ERROR,\n "Dynamic route error",\n "Error in dynamic route handling.",\n [\n "Check [param] syntax is correct",\n "Ensure params are accessed properly",\n "Verify dynamic segment names"\n ]\n ),\n [ErrorCode2.ROUTE_PARAMS_ERROR]: createSimpleError(\n ErrorCode2.ROUTE_PARAMS_ERROR,\n "Route parameters error",\n "Error accessing route parameters.",\n [\n "Check params object structure",\n "Ensure parameter names match route",\n "Verify params are strings"\n ]\n ),\n [ErrorCode2.API_ROUTE_ERROR]: createSimpleError(\n ErrorCode2.API_ROUTE_ERROR,\n "API route error",\n "Error in API route execution.",\n [\n "Check API handler code",\n "Ensure proper error handling",\n "Verify request parsing"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/module-errors.ts\nvar MODULE_ERROR_CATALOG;\nvar init_module_errors = __esm({\n "src/core/errors/catalog/module-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n MODULE_ERROR_CATALOG = {\n [ErrorCode2.MODULE_NOT_FOUND]: createErrorSolution(ErrorCode2.MODULE_NOT_FOUND, {\n title: "Module not found",\n message: "Cannot find the imported module.",\n steps: [\n "Check that the file path is correct",\n "Ensure the module is installed or exists",\n "Add missing module to import map",\n "Check for typos in import statement"\n ],\n example: `// Add to veryfront.config.js\nresolve: {\n importMap: {\n imports: {\n "missing-lib": "https://esm.sh/missing-lib@1.0.0"\n }\n }\n}`\n }),\n [ErrorCode2.IMPORT_RESOLUTION_ERROR]: createSimpleError(\n ErrorCode2.IMPORT_RESOLUTION_ERROR,\n "Import resolution failed",\n "Failed to resolve import specifier.",\n [\n "Check import paths are correct",\n "Ensure modules are in import map",\n "Verify network connectivity for remote imports"\n ]\n ),\n [ErrorCode2.CIRCULAR_DEPENDENCY]: createSimpleError(\n ErrorCode2.CIRCULAR_DEPENDENCY,\n "Circular dependency detected",\n "Files are importing each other in a circle.",\n [\n "Identify the circular import chain",\n "Extract shared code to separate file",\n "Use dependency injection or lazy imports"\n ]\n ),\n [ErrorCode2.INVALID_IMPORT]: createSimpleError(\n ErrorCode2.INVALID_IMPORT,\n "Invalid import statement",\n "Import statement has invalid syntax.",\n [\n \'Check import syntax: import X from "y"\',\n "Ensure quotes are properly closed",\n "Verify export exists in target module"\n ]\n ),\n [ErrorCode2.DEPENDENCY_MISSING]: createErrorSolution(ErrorCode2.DEPENDENCY_MISSING, {\n title: "Required dependency not found",\n message: "A required dependency is missing.",\n steps: [\n "Add React to your import map",\n "Ensure all peer dependencies are included",\n "Run \'veryfront doctor\' to verify setup"\n ],\n example: `// Minimum required imports\nresolve: {\n importMap: {\n imports: {\n "react": "https://esm.sh/react@19",\n "react-dom": "https://esm.sh/react-dom@19"\n }\n }\n}`\n }),\n [ErrorCode2.VERSION_MISMATCH]: createSimpleError(\n ErrorCode2.VERSION_MISMATCH,\n "Dependency version mismatch",\n "Incompatible versions of dependencies detected.",\n [\n "Ensure React and React-DOM versions match",\n "Check for multiple React instances",\n "Update dependencies to compatible versions"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/server-errors.ts\nvar SERVER_ERROR_CATALOG;\nvar init_server_errors = __esm({\n "src/core/errors/catalog/server-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n SERVER_ERROR_CATALOG = {\n [ErrorCode2.PORT_IN_USE]: createErrorSolution(ErrorCode2.PORT_IN_USE, {\n title: "Port already in use",\n message: "Another process is using the specified port.",\n steps: [\n "Stop the other process: lsof -i :PORT",\n "Use a different port: veryfront dev --port 3003",\n "Add port to config file"\n ],\n example: `// veryfront.config.js\ndev: {\n port: 3003\n}`\n }),\n [ErrorCode2.SERVER_START_ERROR]: createSimpleError(\n ErrorCode2.SERVER_START_ERROR,\n "Server failed to start",\n "Development server could not start.",\n [\n "Check for port conflicts",\n "Ensure file permissions are correct",\n "Verify configuration is valid"\n ]\n ),\n [ErrorCode2.HMR_ERROR]: createSimpleError(\n ErrorCode2.HMR_ERROR,\n "Hot Module Replacement error",\n "HMR failed to update module.",\n [\n "Try refreshing the page",\n "Check for syntax errors",\n "Restart dev server if persistent"\n ]\n ),\n [ErrorCode2.CACHE_ERROR]: createSimpleError(\n ErrorCode2.CACHE_ERROR,\n "Cache operation failed",\n "Error reading or writing cache.",\n [\n "Clear cache: veryfront clean --cache",\n "Check disk space",\n "Verify file permissions"\n ]\n ),\n [ErrorCode2.FILE_WATCH_ERROR]: createSimpleError(\n ErrorCode2.FILE_WATCH_ERROR,\n "File watching failed",\n "Could not watch files for changes.",\n [\n "Check system file watch limits",\n "Reduce number of watched files",\n "Try restarting dev server"\n ]\n ),\n [ErrorCode2.REQUEST_ERROR]: createSimpleError(\n ErrorCode2.REQUEST_ERROR,\n "Request handling error",\n "Error processing HTTP request.",\n [\n "Check request format and headers",\n "Verify route handler code",\n "Check for middleware errors"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/rsc-errors.ts\nvar RSC_ERROR_CATALOG;\nvar init_rsc_errors = __esm({\n "src/core/errors/catalog/rsc-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n RSC_ERROR_CATALOG = {\n [ErrorCode2.CLIENT_BOUNDARY_VIOLATION]: createErrorSolution(\n ErrorCode2.CLIENT_BOUNDARY_VIOLATION,\n {\n title: "Client/Server boundary violation",\n message: "Server-only code used in Client Component.",\n steps: [\n "Move server-only imports to Server Components",\n "Use \'use server\' for server actions",\n "Split component into server and client parts"\n ],\n example: `// \\u2713 Correct pattern\nimport { db } from \'./database\'\nexport default async function ServerComponent() {\n const data = await db.query(\'...\')\n return <ClientComponent data={data} />\n}\n\n\'use client\'\nexport default function ClientComponent({ data }) {\n return <div>{data}</div>\n}`\n }\n ),\n [ErrorCode2.SERVER_ONLY_IN_CLIENT]: createSimpleError(\n ErrorCode2.SERVER_ONLY_IN_CLIENT,\n "Server-only module in Client Component",\n "Cannot use server-only module in client code.",\n [\n "Move server logic to Server Component",\n "Use API routes for client data fetching",\n "Pass data as props from server"\n ]\n ),\n [ErrorCode2.CLIENT_ONLY_IN_SERVER]: createSimpleError(\n ErrorCode2.CLIENT_ONLY_IN_SERVER,\n "Client-only code in Server Component",\n "Cannot use browser APIs in Server Component.",\n [\n "Add \'use client\' directive",\n "Move client-only code to Client Component",\n "Use useEffect for client-side logic"\n ]\n ),\n [ErrorCode2.INVALID_USE_CLIENT]: createErrorSolution(ErrorCode2.INVALID_USE_CLIENT, {\n title: "Invalid \'use client\' directive",\n message: "\'use client\' directive is not properly placed.",\n steps: [\n "Place \'use client\' at the very top of file",\n "Must be before any imports",\n \'Use exact string: "use client"\'\n ],\n example: `\'use client\' // Must be first line\n\nimport React from \'react\'`\n }),\n [ErrorCode2.INVALID_USE_SERVER]: createSimpleError(\n ErrorCode2.INVALID_USE_SERVER,\n "Invalid \'use server\' directive",\n "\'use server\' directive is not properly placed.",\n [\n "Place \'use server\' at top of function",\n "Or at top of file for all functions",\n \'Use exact string: "use server"\'\n ]\n ),\n [ErrorCode2.RSC_PAYLOAD_ERROR]: createSimpleError(\n ErrorCode2.RSC_PAYLOAD_ERROR,\n "RSC payload error",\n "Error serializing Server Component payload.",\n [\n "Ensure props are JSON-serializable",\n "Avoid passing functions as props",\n "Check for circular references"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/dev-errors.ts\nvar DEV_ERROR_CATALOG;\nvar init_dev_errors = __esm({\n "src/core/errors/catalog/dev-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n DEV_ERROR_CATALOG = {\n [ErrorCode2.DEV_SERVER_ERROR]: createSimpleError(\n ErrorCode2.DEV_SERVER_ERROR,\n "Development server error",\n "Error in development server.",\n [\n "Check server logs for details",\n "Try restarting dev server",\n "Clear cache and restart"\n ]\n ),\n [ErrorCode2.FAST_REFRESH_ERROR]: createSimpleError(\n ErrorCode2.FAST_REFRESH_ERROR,\n "Fast Refresh error",\n "React Fast Refresh failed.",\n [\n "Check for syntax errors",\n "Ensure components follow Fast Refresh rules",\n "Try full page refresh"\n ]\n ),\n [ErrorCode2.ERROR_OVERLAY_ERROR]: createSimpleError(\n ErrorCode2.ERROR_OVERLAY_ERROR,\n "Error overlay failed",\n "Could not display error overlay.",\n [\n "Check browser console for details",\n "Try disabling browser extensions",\n "Refresh the page"\n ]\n ),\n [ErrorCode2.SOURCE_MAP_ERROR]: createSimpleError(\n ErrorCode2.SOURCE_MAP_ERROR,\n "Source map error",\n "Error loading or parsing source map.",\n [\n "Check that source maps are enabled",\n "Try rebuilding the project",\n "Check for corrupted build files"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/deployment-errors.ts\nvar DEPLOYMENT_ERROR_CATALOG;\nvar init_deployment_errors = __esm({\n "src/core/errors/catalog/deployment-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n DEPLOYMENT_ERROR_CATALOG = {\n [ErrorCode2.DEPLOYMENT_ERROR]: createSimpleError(\n ErrorCode2.DEPLOYMENT_ERROR,\n "Deployment failed",\n "Failed to deploy application.",\n [\n "Check deployment logs for details",\n "Verify platform credentials",\n "Ensure build succeeded first"\n ]\n ),\n [ErrorCode2.PLATFORM_ERROR]: createSimpleError(\n ErrorCode2.PLATFORM_ERROR,\n "Platform error",\n "Deployment platform returned an error.",\n [\n "Check platform status page",\n "Verify API keys and credentials",\n "Try deploying again"\n ]\n ),\n [ErrorCode2.ENV_VAR_MISSING]: createSimpleError(\n ErrorCode2.ENV_VAR_MISSING,\n "Environment variable missing",\n "Required environment variable is not set.",\n [\n "Add variable to .env file",\n "Set variable in deployment platform",\n "Check variable name is correct"\n ]\n ),\n [ErrorCode2.PRODUCTION_BUILD_REQUIRED]: createSimpleError(\n ErrorCode2.PRODUCTION_BUILD_REQUIRED,\n "Production build required",\n "Must build project before deploying.",\n [\n "Run \'veryfront build\' first",\n "Check that dist/ directory exists",\n "Verify build completed successfully"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/general-errors.ts\nvar GENERAL_ERROR_CATALOG;\nvar init_general_errors = __esm({\n "src/core/errors/catalog/general-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n GENERAL_ERROR_CATALOG = {\n [ErrorCode2.UNKNOWN_ERROR]: createSimpleError(\n ErrorCode2.UNKNOWN_ERROR,\n "Unknown error",\n "An unexpected error occurred.",\n [\n "Check error details above",\n "Run \'veryfront doctor\' to diagnose",\n "Try restarting the operation",\n "Check GitHub issues for similar problems"\n ]\n ),\n [ErrorCode2.PERMISSION_DENIED]: createSimpleError(\n ErrorCode2.PERMISSION_DENIED,\n "Permission denied",\n "Insufficient permissions to perform operation.",\n [\n "Check file/directory permissions",\n "Run with appropriate permissions",\n "Verify user has write access"\n ]\n ),\n [ErrorCode2.FILE_NOT_FOUND]: createSimpleError(\n ErrorCode2.FILE_NOT_FOUND,\n "File not found",\n "Required file does not exist.",\n [\n "Check that file path is correct",\n "Verify file exists in project",\n "Check for typos in file name"\n ]\n ),\n [ErrorCode2.INVALID_ARGUMENT]: createSimpleError(\n ErrorCode2.INVALID_ARGUMENT,\n "Invalid argument",\n "Command received invalid argument.",\n [\n "Check command syntax",\n "Verify argument values",\n "Run \'veryfront help <command>\' for usage"\n ]\n ),\n [ErrorCode2.TIMEOUT_ERROR]: createSimpleError(\n ErrorCode2.TIMEOUT_ERROR,\n "Operation timed out",\n "Operation took too long to complete.",\n [\n "Check network connectivity",\n "Try increasing timeout if available",\n "Check for very large files"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/index.ts\nvar ERROR_CATALOG;\nvar init_catalog = __esm({\n "src/core/errors/catalog/index.ts"() {\n "use strict";\n init_config_errors();\n init_build_errors2();\n init_runtime_errors2();\n init_route_errors();\n init_module_errors();\n init_server_errors();\n init_rsc_errors();\n init_dev_errors();\n init_deployment_errors();\n init_general_errors();\n init_factory();\n ERROR_CATALOG = {\n ...CONFIG_ERROR_CATALOG,\n ...BUILD_ERROR_CATALOG,\n ...RUNTIME_ERROR_CATALOG,\n ...ROUTE_ERROR_CATALOG,\n ...MODULE_ERROR_CATALOG,\n ...SERVER_ERROR_CATALOG,\n ...RSC_ERROR_CATALOG,\n ...DEV_ERROR_CATALOG,\n ...DEPLOYMENT_ERROR_CATALOG,\n ...GENERAL_ERROR_CATALOG\n };\n }\n});\n\n// src/core/errors/user-friendly/error-catalog.ts\nvar init_error_catalog = __esm({\n "src/core/errors/user-friendly/error-catalog.ts"() {\n "use strict";\n }\n});\n\n// src/platform/compat/console/ansi.ts\nvar ansi, red, green, yellow, blue, magenta, cyan, white, gray, bold, dim, italic, underline, strikethrough, reset;\nvar init_ansi = __esm({\n "src/platform/compat/console/ansi.ts"() {\n ansi = (open, close) => (text2) => `\\x1B[${open}m${text2}\\x1B[${close}m`;\n red = ansi(31, 39);\n green = ansi(32, 39);\n yellow = ansi(33, 39);\n blue = ansi(34, 39);\n magenta = ansi(35, 39);\n cyan = ansi(36, 39);\n white = ansi(37, 39);\n gray = ansi(90, 39);\n bold = ansi(1, 22);\n dim = ansi(2, 22);\n italic = ansi(3, 23);\n underline = ansi(4, 24);\n strikethrough = ansi(9, 29);\n reset = (text2) => `\\x1B[0m${text2}`;\n }\n});\n\n// src/platform/compat/console/deno.ts\nvar deno_exports = {};\n__export(deno_exports, {\n blue: () => blue,\n bold: () => bold,\n colors: () => colors,\n cyan: () => cyan,\n dim: () => dim,\n gray: () => gray,\n green: () => green,\n italic: () => italic,\n magenta: () => magenta,\n red: () => red,\n reset: () => reset,\n strikethrough: () => strikethrough,\n underline: () => underline,\n white: () => white,\n yellow: () => yellow\n});\nvar colors;\nvar init_deno2 = __esm({\n "src/platform/compat/console/deno.ts"() {\n "use strict";\n init_ansi();\n colors = {\n red,\n green,\n yellow,\n blue,\n cyan,\n magenta,\n white,\n gray,\n bold,\n dim,\n italic,\n underline,\n strikethrough,\n reset\n };\n }\n});\n\n// src/platform/compat/console/node.ts\nvar node_exports = {};\n__export(node_exports, {\n blue: () => blue2,\n bold: () => bold2,\n colors: () => colors2,\n cyan: () => cyan2,\n dim: () => dim2,\n gray: () => gray2,\n green: () => green2,\n initColors: () => initColors,\n italic: () => italic2,\n magenta: () => magenta2,\n red: () => red2,\n reset: () => reset2,\n strikethrough: () => strikethrough2,\n underline: () => underline2,\n white: () => white2,\n yellow: () => yellow2\n});\nasync function ensurePc() {\n if (pc)\n return pc;\n const picocolorsModule = ["npm:", "picocolors"].join("");\n const mod = await import(picocolorsModule);\n pc = mod.default;\n return pc;\n}\nasync function initColors() {\n await ensurePc();\n}\nvar pc, lazyColor, colors2, red2, green2, yellow2, blue2, cyan2, magenta2, white2, gray2, bold2, dim2, italic2, underline2, strikethrough2, reset2;\nvar init_node = __esm({\n "src/platform/compat/console/node.ts"() {\n "use strict";\n pc = null;\n lazyColor = (fn) => (s) => pc?.[fn]?.(s) ?? s;\n colors2 = {\n red: lazyColor("red"),\n green: lazyColor("green"),\n yellow: lazyColor("yellow"),\n blue: lazyColor("blue"),\n cyan: lazyColor("cyan"),\n magenta: lazyColor("magenta"),\n white: lazyColor("white"),\n gray: lazyColor("gray"),\n bold: lazyColor("bold"),\n dim: lazyColor("dim"),\n italic: lazyColor("italic"),\n underline: lazyColor("underline"),\n strikethrough: lazyColor("strikethrough"),\n reset: lazyColor("reset")\n };\n red2 = lazyColor("red");\n green2 = lazyColor("green");\n yellow2 = lazyColor("yellow");\n blue2 = lazyColor("blue");\n cyan2 = lazyColor("cyan");\n magenta2 = lazyColor("magenta");\n white2 = lazyColor("white");\n gray2 = lazyColor("gray");\n bold2 = lazyColor("bold");\n dim2 = lazyColor("dim");\n italic2 = lazyColor("italic");\n underline2 = lazyColor("underline");\n strikethrough2 = lazyColor("strikethrough");\n reset2 = lazyColor("reset");\n }\n});\n\n// src/platform/compat/console/index.ts\nasync function loadColors() {\n if (_colors)\n return _colors;\n try {\n if (isDeno) {\n const mod = await Promise.resolve().then(() => (init_deno2(), deno_exports));\n _colors = mod.colors;\n } else {\n const mod = await Promise.resolve().then(() => (init_node(), node_exports));\n _colors = mod.colors;\n }\n } catch {\n _colors = fallbackColors;\n }\n return _colors;\n}\nvar noOp, fallbackColors, _colors, colorsPromise;\nvar init_console = __esm({\n "src/platform/compat/console/index.ts"() {\n init_runtime();\n noOp = (text2) => text2;\n fallbackColors = {\n red: noOp,\n green: noOp,\n yellow: noOp,\n blue: noOp,\n cyan: noOp,\n magenta: noOp,\n white: noOp,\n gray: noOp,\n bold: noOp,\n dim: noOp,\n italic: noOp,\n underline: noOp,\n strikethrough: noOp,\n reset: noOp\n };\n _colors = null;\n colorsPromise = loadColors();\n }\n});\n\n// src/core/errors/user-friendly/error-identifier.ts\nvar init_error_identifier = __esm({\n "src/core/errors/user-friendly/error-identifier.ts"() {\n "use strict";\n }\n});\n\n// src/core/errors/user-friendly/error-formatter.ts\nvar init_error_formatter = __esm({\n "src/core/errors/user-friendly/error-formatter.ts"() {\n "use strict";\n init_console();\n init_error_catalog();\n init_error_identifier();\n }\n});\n\n// src/core/errors/user-friendly/error-wrapper.ts\nvar init_error_wrapper = __esm({\n "src/core/errors/user-friendly/error-wrapper.ts"() {\n "use strict";\n init_console();\n init_process();\n init_logger();\n init_error_formatter();\n }\n});\n\n// src/core/errors/user-friendly/index.ts\nvar init_user_friendly = __esm({\n "src/core/errors/user-friendly/index.ts"() {\n "use strict";\n init_error_catalog();\n init_error_formatter();\n init_error_identifier();\n init_error_wrapper();\n }\n});\n\n// src/core/errors/index.ts\nvar init_errors = __esm({\n "src/core/errors/index.ts"() {\n init_types();\n init_agent_errors();\n init_build_errors();\n init_runtime_errors();\n init_system_errors();\n init_error_handlers();\n init_catalog();\n init_user_friendly();\n }\n});\n\n// src/platform/adapters/deno.ts\nvar DenoFileSystemAdapter, DenoEnvironmentAdapter, DenoServerAdapter, DenoShellAdapter, DenoServer, DenoAdapter, denoAdapter;\nvar init_deno3 = __esm({\n "src/platform/adapters/deno.ts"() {\n "use strict";\n init_veryfront_error();\n init_config();\n init_utils();\n DenoFileSystemAdapter = class {\n async readFile(path) {\n return await Deno.readTextFile(path);\n }\n async readFileBytes(path) {\n return await Deno.readFile(path);\n }\n async writeFile(path, content) {\n await Deno.writeTextFile(path, content);\n }\n async exists(path) {\n try {\n await Deno.stat(path);\n return true;\n } catch (_error) {\n return false;\n }\n }\n async *readDir(path) {\n for await (const entry of Deno.readDir(path)) {\n yield {\n name: entry.name,\n isFile: entry.isFile,\n isDirectory: entry.isDirectory,\n isSymlink: entry.isSymlink\n };\n }\n }\n async stat(path) {\n const stat = await Deno.stat(path);\n return {\n size: stat.size,\n isFile: stat.isFile,\n isDirectory: stat.isDirectory,\n isSymlink: stat.isSymlink,\n mtime: stat.mtime\n };\n }\n async mkdir(path, options) {\n await Deno.mkdir(path, options);\n }\n async remove(path, options) {\n await Deno.remove(path, options);\n }\n async makeTempDir(prefix) {\n return await Deno.makeTempDir({ prefix });\n }\n watch(paths, options) {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n const watcher = Deno.watchFs(pathArray, { recursive });\n let closed = false;\n const denoIterator = watcher[Symbol.asyncIterator]();\n const mapEventKind = (kind) => {\n switch (kind) {\n case "create":\n return "create";\n case "modify":\n return "modify";\n case "remove":\n return "delete";\n default:\n return "any";\n }\n };\n const iterator = {\n async next() {\n if (closed || signal?.aborted) {\n return { done: true, value: void 0 };\n }\n try {\n const result = await denoIterator.next();\n if (result.done) {\n return { done: true, value: void 0 };\n }\n return {\n done: false,\n value: {\n kind: mapEventKind(result.value.kind),\n paths: result.value.paths\n }\n };\n } catch (error2) {\n if (closed || signal?.aborted) {\n return { done: true, value: void 0 };\n }\n throw error2;\n }\n },\n async return() {\n closed = true;\n if (denoIterator.return) {\n await denoIterator.return();\n }\n return { done: true, value: void 0 };\n }\n };\n const cleanup = () => {\n if (closed)\n return;\n closed = true;\n try {\n if ("close" in watcher && typeof watcher.close === "function") {\n watcher.close();\n }\n } catch (error2) {\n serverLogger.debug("[Deno] Filesystem watcher cleanup failed", { error: error2 });\n }\n };\n if (signal) {\n signal.addEventListener("abort", cleanup);\n }\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n close: cleanup\n };\n }\n };\n DenoEnvironmentAdapter = class {\n get(key) {\n return Deno.env.get(key);\n }\n set(key, value) {\n Deno.env.set(key, value);\n }\n toObject() {\n return Deno.env.toObject();\n }\n };\n DenoServerAdapter = class {\n upgradeWebSocket(request) {\n const { socket, response } = Deno.upgradeWebSocket(request);\n return { socket, response };\n }\n };\n DenoShellAdapter = class {\n statSync(path) {\n try {\n const stat = Deno.statSync(path);\n return {\n isFile: stat.isFile,\n isDirectory: stat.isDirectory\n };\n } catch (error2) {\n throw toError(createError({\n type: "file",\n message: `Failed to stat file: ${error2}`\n }));\n }\n }\n readFileSync(path) {\n try {\n return Deno.readTextFileSync(path);\n } catch (error2) {\n throw toError(createError({\n type: "file",\n message: `Failed to read file: ${error2}`\n }));\n }\n }\n };\n DenoServer = class {\n constructor(server, hostname, port, abortController) {\n this.server = server;\n this.hostname = hostname;\n this.port = port;\n this.abortController = abortController;\n }\n async stop() {\n try {\n if (this.abortController) {\n this.abortController.abort();\n }\n await this.server.shutdown();\n } catch (error2) {\n serverLogger.debug("[Deno] Server shutdown failed", { error: error2 });\n }\n }\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n };\n DenoAdapter = class {\n constructor() {\n this.id = "deno";\n this.name = "deno";\n /** @deprecated Use `id` instead */\n this.platform = "deno";\n this.fs = new DenoFileSystemAdapter();\n this.env = new DenoEnvironmentAdapter();\n this.server = new DenoServerAdapter();\n this.shell = new DenoShellAdapter();\n this.capabilities = {\n typescript: true,\n jsx: true,\n http2: true,\n websocket: true,\n workers: true,\n fileWatching: true,\n shell: true,\n kvStore: true,\n // Deno KV available\n writableFs: true\n };\n /** @deprecated Use `capabilities` instead */\n this.features = {\n websocket: true,\n http2: true,\n workers: true,\n jsx: true,\n typescript: true\n };\n }\n serve(handler, options = {}) {\n const { port = DEFAULT_DEV_PORT, hostname = "localhost", onListen } = options;\n const controller = new AbortController();\n const signal = options.signal || controller.signal;\n const server = Deno.serve({\n port,\n hostname,\n signal,\n handler: async (request, _info) => {\n try {\n return await handler(request);\n } catch (error2) {\n const { serverLogger: serverLogger2 } = await Promise.resolve().then(() => (init_utils(), utils_exports));\n serverLogger2.error("Request handler error:", error2);\n return new Response("Internal Server Error", { status: 500 });\n }\n },\n onListen: (params) => {\n onListen?.({ hostname: params.hostname, port: params.port });\n }\n });\n const controllerToPass = options.signal ? void 0 : controller;\n return Promise.resolve(new DenoServer(server, hostname, port, controllerToPass));\n }\n };\n denoAdapter = new DenoAdapter();\n }\n});\n\n// src/rendering/client/router.ts\ninit_utils();\nimport ReactDOM from "react-dom/client";\n\n// src/routing/matchers/pattern-route-matcher.ts\ninit_path_utils();\n\n// src/routing/matchers/index.ts\ninit_utils();\n\n// src/platform/compat/path-helper.ts\nimport nodePath2 from "node:path";\nvar pathMod = null;\nif (typeof Deno === "undefined") {\n pathMod = nodePath2;\n} else {\n Promise.resolve().then(() => (init_std_path(), std_path_exports)).then((mod) => {\n pathMod = mod;\n });\n}\nvar sep3 = nodePath2.sep;\n\n// src/routing/client/dom-utils.ts\ninit_utils();\nfunction isInternalLink(target) {\n const href = target.getAttribute("href");\n if (!href)\n return false;\n if (href.startsWith("http") || href.startsWith("mailto:"))\n return false;\n if (href.startsWith("#"))\n return false;\n if (target.getAttribute("target") === "_blank" || target.getAttribute("download")) {\n return false;\n }\n return true;\n}\nfunction findAnchorElement(element) {\n let current = element;\n while (current && current.tagName !== "A") {\n current = current.parentElement;\n }\n if (!current || !(current instanceof HTMLAnchorElement)) {\n return null;\n }\n return current;\n}\nfunction updateMetaTags(frontmatter) {\n if (frontmatter.description) {\n updateMetaTag(\'meta[name="description"]\', "name", "description", frontmatter.description);\n }\n if (frontmatter.ogTitle) {\n updateMetaTag(\'meta[property="og:title"]\', "property", "og:title", frontmatter.ogTitle);\n }\n}\nfunction updateMetaTag(selector, attributeName, attributeValue, content) {\n let metaTag = document.querySelector(selector);\n if (!metaTag) {\n metaTag = document.createElement("meta");\n metaTag.setAttribute(attributeName, attributeValue);\n document.head.appendChild(metaTag);\n }\n metaTag.setAttribute("content", content);\n}\nfunction executeScripts(container) {\n const scripts = container.querySelectorAll("script");\n scripts.forEach((oldScript) => {\n const newScript = document.createElement("script");\n Array.from(oldScript.attributes).forEach((attribute) => {\n newScript.setAttribute(attribute.name, attribute.value);\n });\n newScript.textContent = oldScript.textContent;\n oldScript.parentNode?.replaceChild(newScript, oldScript);\n });\n}\nfunction applyHeadDirectives(container) {\n const nodes = container.querySelectorAll(\'[data-veryfront-head="1"], vf-head\');\n if (nodes.length > 0) {\n cleanManagedHeadTags();\n }\n nodes.forEach((wrapper) => {\n processHeadWrapper(wrapper);\n wrapper.parentElement?.removeChild(wrapper);\n });\n}\nfunction cleanManagedHeadTags() {\n document.head.querySelectorAll(\'[data-veryfront-managed="1"]\').forEach((element) => element.parentElement?.removeChild(element));\n}\nfunction processHeadWrapper(wrapper) {\n wrapper.childNodes.forEach((node) => {\n if (!(node instanceof Element))\n return;\n const tagName = node.tagName.toLowerCase();\n if (tagName === "title") {\n document.title = node.textContent || document.title;\n return;\n }\n const clone = document.createElement(tagName);\n for (const attribute of Array.from(node.attributes)) {\n clone.setAttribute(attribute.name, attribute.value);\n }\n if (node.textContent && !clone.hasAttribute("src")) {\n clone.textContent = node.textContent;\n }\n clone.setAttribute("data-veryfront-managed", "1");\n document.head.appendChild(clone);\n });\n}\nfunction manageFocus(container) {\n try {\n const focusElement = container.querySelector("[data-router-focus]") || container.querySelector("main") || container.querySelector("h1");\n if (focusElement && focusElement instanceof HTMLElement && "focus" in focusElement) {\n focusElement.focus({ preventScroll: true });\n }\n } catch (error2) {\n rendererLogger.warn("[router] focus management failed", error2);\n }\n}\nfunction extractPageDataFromScript() {\n const pageDataScript = document.querySelector("script[data-veryfront-page]");\n if (!pageDataScript)\n return null;\n try {\n const content = pageDataScript.textContent;\n if (!content) {\n rendererLogger.warn("[dom-utils] Page data script has no content");\n return {};\n }\n return JSON.parse(content);\n } catch (error2) {\n rendererLogger.error("[dom-utils] Failed to parse page data:", error2);\n return null;\n }\n}\nfunction parsePageDataFromHTML(html3) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html3, "text/html");\n const root = doc.getElementById("root");\n let content = "";\n if (root) {\n content = root.innerHTML || "";\n } else {\n rendererLogger.warn("[dom-utils] No root element found in HTML");\n }\n const pageDataScript = doc.querySelector("script[data-veryfront-page]");\n let pageData = {};\n if (pageDataScript) {\n try {\n const content2 = pageDataScript.textContent;\n if (!content2) {\n rendererLogger.warn("[dom-utils] Page data script in HTML has no content");\n } else {\n pageData = JSON.parse(content2);\n }\n } catch (error2) {\n rendererLogger.error("[dom-utils] Failed to parse page data from HTML:", error2);\n }\n }\n return { content, pageData };\n}\n\n// src/routing/client/navigation-handlers.ts\ninit_utils();\ninit_config();\nvar NavigationHandlers = class {\n constructor(prefetchDelay = DEFAULT_PREFETCH_DELAY_MS, prefetchOptions = {}) {\n this.prefetchQueue = /* @__PURE__ */ new Set();\n this.scrollPositions = /* @__PURE__ */ new Map();\n this.isPopStateNav = false;\n this.prefetchDelay = prefetchDelay;\n this.prefetchOptions = prefetchOptions;\n }\n createClickHandler(callbacks) {\n return (event) => {\n const anchor = findAnchorElement(event.target);\n if (!anchor || !isInternalLink(anchor))\n return;\n const href = anchor.getAttribute("href");\n event.preventDefault();\n callbacks.onNavigate(href);\n };\n }\n createPopStateHandler(callbacks) {\n return (_event) => {\n const path = globalThis.location.pathname;\n this.isPopStateNav = true;\n callbacks.onNavigate(path);\n };\n }\n createMouseOverHandler(callbacks) {\n return (event) => {\n const target = event.target;\n if (target.tagName !== "A")\n return;\n const href = target.getAttribute("href");\n if (!href || href.startsWith("http") || href.startsWith("#"))\n return;\n if (!this.shouldPrefetchOnHover(target))\n return;\n if (!this.prefetchQueue.has(href)) {\n this.prefetchQueue.add(href);\n setTimeout(() => {\n callbacks.onPrefetch(href);\n this.prefetchQueue.delete(href);\n }, this.prefetchDelay);\n }\n };\n }\n shouldPrefetchOnHover(target) {\n const prefetchAttribute = target.getAttribute("data-prefetch");\n const isHoverEnabled = Boolean(this.prefetchOptions.hover);\n if (prefetchAttribute === "false")\n return false;\n return prefetchAttribute === "true" || isHoverEnabled;\n }\n saveScrollPosition(path) {\n try {\n const scrollY = globalThis.scrollY;\n if (typeof scrollY === "number") {\n this.scrollPositions.set(path, scrollY);\n } else {\n rendererLogger.debug("[router] No valid scrollY value available");\n this.scrollPositions.set(path, 0);\n }\n } catch (error2) {\n rendererLogger.warn("[router] failed to record scroll position", error2);\n }\n }\n getScrollPosition(path) {\n const position = this.scrollPositions.get(path);\n if (position === void 0) {\n rendererLogger.debug(`[router] No scroll position stored for ${path}`);\n return 0;\n }\n return position;\n }\n isPopState() {\n return this.isPopStateNav;\n }\n clearPopStateFlag() {\n this.isPopStateNav = false;\n }\n clear() {\n this.prefetchQueue.clear();\n this.scrollPositions.clear();\n this.isPopStateNav = false;\n }\n};\n\n// src/routing/client/page-loader.ts\ninit_utils();\ninit_errors();\nvar PageLoader = class {\n constructor() {\n this.cache = /* @__PURE__ */ new Map();\n }\n getCached(path) {\n return this.cache.get(path);\n }\n isCached(path) {\n return this.cache.has(path);\n }\n setCache(path, data) {\n this.cache.set(path, data);\n }\n clearCache() {\n this.cache.clear();\n }\n async fetchPageData(path) {\n const jsonData = await this.tryFetchJSON(path);\n if (jsonData)\n return jsonData;\n return this.fetchAndParseHTML(path);\n }\n async tryFetchJSON(path) {\n try {\n const response = await fetch(`/_veryfront/data${path}.json`, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (response.ok) {\n return await response.json();\n }\n } catch (error2) {\n rendererLogger.debug(`[PageLoader] RSC fetch failed for ${path}, falling back to HTML:`, error2);\n }\n return null;\n }\n async fetchAndParseHTML(path) {\n const response = await fetch(path, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (!response.ok) {\n throw new NetworkError(`Failed to fetch ${path}`, {\n status: response.status,\n path\n });\n }\n const html3 = await response.text();\n const { content, pageData } = parsePageDataFromHTML(html3);\n return {\n html: content,\n ...pageData\n };\n }\n async loadPage(path) {\n const cachedData = this.getCached(path);\n if (cachedData) {\n rendererLogger.debug(`Loading ${path} from cache`);\n return cachedData;\n }\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n return data;\n }\n async prefetch(path) {\n if (this.isCached(path))\n return;\n rendererLogger.debug(`Prefetching ${path}`);\n try {\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n } catch (error2) {\n rendererLogger.warn(`Failed to prefetch ${path}`, error2);\n }\n }\n};\n\n// src/routing/client/page-transition.ts\ninit_utils();\ninit_config();\n\n// src/security/client/html-sanitizer.ts\nvar SUSPICIOUS_PATTERNS = [\n { pattern: /<script[^>]*>[\\s\\S]*?<\\/script>/gi, name: "inline script" },\n { pattern: /javascript:/gi, name: "javascript: URL" },\n { pattern: /\\bon\\w+\\s*=/gi, name: "event handler attribute" },\n { pattern: /data:\\s*text\\/html/gi, name: "data: HTML URL" }\n];\nfunction isDevMode() {\n if (typeof globalThis !== "undefined") {\n const g = globalThis;\n return g.__VERYFRONT_DEV__ === true || g.Deno?.env?.get?.("VERYFRONT_ENV") === "development";\n }\n return false;\n}\nfunction validateTrustedHtml(html3, options = {}) {\n const { strict = false, warn = true } = options;\n for (const { pattern, name } of SUSPICIOUS_PATTERNS) {\n pattern.lastIndex = 0;\n if (pattern.test(html3)) {\n const message = `[Security] Suspicious ${name} detected in server HTML`;\n if (warn) {\n console.warn(message);\n }\n if (strict || !isDevMode()) {\n throw new Error(`Potentially unsafe HTML: ${name} detected`);\n }\n }\n }\n return html3;\n}\n\n// src/routing/client/page-transition.ts\nvar PageTransition = class {\n constructor(setupViewportPrefetch) {\n this.setupViewportPrefetch = setupViewportPrefetch;\n }\n destroy() {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n this.pendingTransitionTimeout = void 0;\n }\n }\n updatePage(data, isPopState, scrollY) {\n if (data.frontmatter?.title) {\n document.title = data.frontmatter.title;\n }\n updateMetaTags(data.frontmatter ?? {});\n const rootElement = document.getElementById("root");\n if (rootElement && (data.html ?? "") !== "") {\n this.performTransition(rootElement, data, isPopState, scrollY);\n }\n }\n performTransition(rootElement, data, isPopState, scrollY) {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n }\n rootElement.style.opacity = "0";\n this.pendingTransitionTimeout = setTimeout(() => {\n this.pendingTransitionTimeout = void 0;\n rootElement.innerHTML = validateTrustedHtml(String(data.html ?? ""));\n rootElement.style.opacity = "1";\n executeScripts(rootElement);\n applyHeadDirectives(rootElement);\n this.setupViewportPrefetch(rootElement);\n manageFocus(rootElement);\n this.handleScroll(isPopState, scrollY);\n }, PAGE_TRANSITION_DELAY_MS);\n }\n handleScroll(isPopState, scrollY) {\n try {\n globalThis.scrollTo(0, isPopState ? scrollY : 0);\n } catch (error2) {\n rendererLogger.warn("[router] scroll handling failed", error2);\n }\n }\n showError(error2) {\n const rootElement = document.getElementById("root");\n if (!rootElement)\n return;\n const errorDiv = document.createElement("div");\n errorDiv.className = "veryfront-error-page";\n const heading = document.createElement("h1");\n heading.textContent = "Oops! Something went wrong";\n const message = document.createElement("p");\n message.textContent = error2.message;\n const button = document.createElement("button");\n button.type = "button";\n button.textContent = "Reload Page";\n button.onclick = () => globalThis.location.reload();\n errorDiv.appendChild(heading);\n errorDiv.appendChild(message);\n errorDiv.appendChild(button);\n rootElement.innerHTML = "";\n rootElement.appendChild(errorDiv);\n }\n setLoadingState(loading) {\n const indicator = document.getElementById("veryfront-loading");\n if (indicator) {\n indicator.style.display = loading ? "block" : "none";\n }\n document.body.classList.toggle("veryfront-loading", loading);\n }\n};\n\n// src/routing/client/viewport-prefetch.ts\ninit_utils();\nvar ViewportPrefetch = class {\n constructor(prefetchCallback, prefetchOptions = {}) {\n this.observer = null;\n this.prefetchCallback = prefetchCallback;\n this.prefetchOptions = prefetchOptions;\n }\n setup(root) {\n try {\n if (!("IntersectionObserver" in globalThis))\n return;\n if (this.observer)\n this.observer.disconnect();\n this.createObserver();\n this.observeLinks(root);\n } catch (error2) {\n rendererLogger.debug("[router] setupViewportPrefetch failed", error2);\n }\n }\n createObserver() {\n this.observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const isAnchor = typeof HTMLAnchorElement !== "undefined" ? entry.target instanceof HTMLAnchorElement : entry.target.tagName === "A";\n if (isAnchor) {\n const href = entry.target.getAttribute("href");\n if (href) {\n this.prefetchCallback(href);\n }\n this.observer?.unobserve(entry.target);\n }\n }\n }\n },\n { rootMargin: "200px" }\n );\n }\n observeLinks(root) {\n const anchors = root.querySelectorAll?.(\'a[href]:not([target="_blank"])\') ?? document.createDocumentFragment().querySelectorAll("a");\n const isViewportEnabled = Boolean(this.prefetchOptions.viewport);\n anchors.forEach((anchor) => {\n if (this.shouldObserveAnchor(anchor, isViewportEnabled)) {\n this.observer?.observe(anchor);\n }\n });\n }\n shouldObserveAnchor(anchor, isViewportEnabled) {\n const href = anchor.getAttribute("href") || "";\n if (!href || href.startsWith("http") || href.startsWith("#") || anchor.getAttribute("download")) {\n return false;\n }\n const prefetchAttribute = anchor.getAttribute("data-prefetch");\n if (prefetchAttribute === "false")\n return false;\n return prefetchAttribute === "viewport" || isViewportEnabled;\n }\n disconnect() {\n if (this.observer) {\n try {\n this.observer.disconnect();\n } catch (error2) {\n rendererLogger.warn("[router] prefetchObserver.disconnect failed", error2);\n }\n this.observer = null;\n }\n }\n};\n\n// src/routing/api/handler.ts\ninit_utils();\ninit_std_path();\ninit_config();\n\n// src/core/utils/lru-wrapper.ts\ninit_utils();\ninit_process();\n\n// src/routing/api/handler.ts\ninit_veryfront_error();\n\n// src/security/http/response/constants.ts\nvar CONTENT_TYPES = {\n JSON: "application/json; charset=utf-8",\n HTML: "text/html; charset=utf-8",\n TEXT: "text/plain; charset=utf-8",\n JAVASCRIPT: "application/javascript; charset=utf-8",\n CSS: "text/css; charset=utf-8",\n XML: "application/xml; charset=utf-8"\n};\nvar CACHE_DURATIONS = {\n SHORT: 60,\n MEDIUM: 3600,\n LONG: 31536e3\n};\n\n// src/security/http/cors/validators.ts\ninit_logger();\n\n// src/observability/tracing/manager.ts\ninit_utils();\n\n// src/observability/tracing/config.ts\ninit_process();\nvar DEFAULT_CONFIG2 = {\n enabled: false,\n exporter: "console",\n serviceName: "veryfront",\n sampleRate: 1,\n debug: false\n};\nfunction loadConfig(config = {}, adapter) {\n const finalConfig = { ...DEFAULT_CONFIG2, ...config };\n if (adapter?.env) {\n applyEnvFromAdapter(finalConfig, adapter.env);\n } else {\n applyEnvFromDeno(finalConfig);\n }\n return finalConfig;\n}\nfunction applyEnvFromAdapter(config, envAdapter) {\n if (!envAdapter)\n return;\n const otelEnabled = envAdapter.get("OTEL_TRACES_ENABLED");\n const veryfrontOtel = envAdapter.get("VERYFRONT_OTEL");\n const serviceName = envAdapter.get("OTEL_SERVICE_NAME");\n config.enabled = otelEnabled === "true" || veryfrontOtel === "1" || config.enabled;\n if (serviceName)\n config.serviceName = serviceName;\n const otlpEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_ENDPOINT");\n const tracesEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT");\n config.endpoint = otlpEndpoint || tracesEndpoint || config.endpoint;\n const exporterType = envAdapter.get("OTEL_TRACES_EXPORTER");\n if (isValidExporter(exporterType)) {\n config.exporter = exporterType;\n }\n}\nfunction applyEnvFromDeno(config) {\n try {\n config.enabled = getEnv("OTEL_TRACES_ENABLED") === "true" || getEnv("VERYFRONT_OTEL") === "1" || config.enabled;\n config.serviceName = getEnv("OTEL_SERVICE_NAME") || config.serviceName;\n config.endpoint = getEnv("OTEL_EXPORTER_OTLP_ENDPOINT") || getEnv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") || config.endpoint;\n const exporterType = getEnv("OTEL_TRACES_EXPORTER");\n if (isValidExporter(exporterType)) {\n config.exporter = exporterType;\n }\n } catch {\n }\n}\nfunction isValidExporter(value) {\n return value === "jaeger" || value === "zipkin" || value === "otlp" || value === "console";\n}\n\n// src/observability/tracing/span-operations.ts\ninit_utils();\nvar SpanOperations = class {\n constructor(api, tracer2) {\n this.api = api;\n this.tracer = tracer2;\n }\n startSpan(name, options = {}) {\n try {\n const spanKind = this.mapSpanKind(options.kind);\n const span = this.tracer.startSpan(name, {\n kind: spanKind,\n attributes: options.attributes || {}\n }, options.parent);\n return span;\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to start span", { name, error: error2 });\n return null;\n }\n }\n endSpan(span, error2) {\n if (!span)\n return;\n try {\n if (error2) {\n span.recordException(error2);\n span.setStatus({\n code: this.api.SpanStatusCode.ERROR,\n message: error2.message\n });\n } else {\n span.setStatus({ code: this.api.SpanStatusCode.OK });\n }\n span.end();\n } catch (err) {\n serverLogger.debug("[tracing] Failed to end span", err);\n }\n }\n setAttributes(span, attributes) {\n if (!span)\n return;\n try {\n span.setAttributes(attributes);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to set span attributes", error2);\n }\n }\n addEvent(span, name, attributes) {\n if (!span)\n return;\n try {\n span.addEvent(name, attributes);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to add span event", error2);\n }\n }\n createChildSpan(parentSpan, name, options = {}) {\n if (!parentSpan)\n return this.startSpan(name, options);\n try {\n const parentContext = this.api.trace.setSpan(this.api.context.active(), parentSpan);\n return this.startSpan(name, { ...options, parent: parentContext });\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to create child span", error2);\n return null;\n }\n }\n mapSpanKind(kind) {\n if (!kind)\n return this.api.SpanKind.INTERNAL;\n const kindMap = {\n "internal": this.api.SpanKind.INTERNAL,\n "server": this.api.SpanKind.SERVER,\n "client": this.api.SpanKind.CLIENT,\n "producer": this.api.SpanKind.PRODUCER,\n "consumer": this.api.SpanKind.CONSUMER\n };\n return kindMap[kind.toLowerCase()] || this.api.SpanKind.INTERNAL;\n }\n};\n\n// src/observability/tracing/context-propagation.ts\ninit_utils();\nvar ContextPropagation = class {\n constructor(api, propagator) {\n this.api = api;\n this.propagator = propagator;\n }\n extractContext(headers) {\n try {\n const carrier = {};\n headers.forEach((value, key) => {\n carrier[key] = value;\n });\n return this.api.propagation.extract(this.api.context.active(), carrier);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to extract context from headers", error2);\n return void 0;\n }\n }\n injectContext(context, headers) {\n try {\n const carrier = {};\n this.api.propagation.inject(context, carrier);\n for (const [key, value] of Object.entries(carrier)) {\n headers.set(key, value);\n }\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to inject context into headers", error2);\n }\n }\n getActiveContext() {\n try {\n return this.api.context.active();\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to get active context", error2);\n return void 0;\n }\n }\n async withActiveSpan(span, fn) {\n if (!span)\n return await fn();\n return await this.api.context.with(\n this.api.trace.setSpan(this.api.context.active(), span),\n fn\n );\n }\n withSpan(name, fn, startSpan2, endSpan2) {\n const span = startSpan2(name);\n try {\n const result = fn(span);\n endSpan2(span);\n return result;\n } catch (error2) {\n endSpan2(span, error2);\n throw error2;\n }\n }\n async withSpanAsync(name, fn, startSpan2, endSpan2) {\n const span = startSpan2(name);\n try {\n const result = await fn(span);\n endSpan2(span);\n return result;\n } catch (error2) {\n endSpan2(span, error2);\n throw error2;\n }\n }\n};\n\n// src/observability/tracing/manager.ts\nvar TracingManager = class {\n constructor() {\n this.state = {\n initialized: false,\n tracer: null,\n api: null,\n propagator: null\n };\n this.spanOps = null;\n this.contextProp = null;\n }\n async initialize(config = {}, adapter) {\n if (this.state.initialized) {\n serverLogger.debug("[tracing] Already initialized");\n return;\n }\n const finalConfig = loadConfig(config, adapter);\n if (!finalConfig.enabled) {\n serverLogger.debug("[tracing] Tracing disabled");\n this.state.initialized = true;\n return;\n }\n try {\n await this.initializeTracer(finalConfig);\n this.state.initialized = true;\n serverLogger.info("[tracing] OpenTelemetry tracing initialized", {\n exporter: finalConfig.exporter,\n serviceName: finalConfig.serviceName,\n endpoint: finalConfig.endpoint\n });\n } catch (error2) {\n serverLogger.warn("[tracing] Failed to initialize OpenTelemetry tracing", error2);\n this.state.initialized = true;\n }\n }\n async initializeTracer(config) {\n const otelApiModule = ["npm:@opentelemetry/", "api@1"].join("");\n const api = await import(otelApiModule);\n this.state.api = api;\n this.state.tracer = api.trace.getTracer(config.serviceName || "veryfront", "0.1.0");\n const otelCoreModule = ["npm:@opentelemetry/", "core@1"].join("");\n const { W3CTraceContextPropagator } = await import(otelCoreModule);\n const propagator = new W3CTraceContextPropagator();\n this.state.propagator = propagator;\n api.propagation.setGlobalPropagator(propagator);\n if (this.state.api && this.state.tracer) {\n this.spanOps = new SpanOperations(this.state.api, this.state.tracer);\n }\n if (this.state.api && this.state.propagator) {\n this.contextProp = new ContextPropagation(this.state.api, this.state.propagator);\n }\n }\n isEnabled() {\n return this.state.initialized && this.state.tracer !== null;\n }\n getSpanOperations() {\n return this.spanOps;\n }\n getContextPropagation() {\n return this.contextProp;\n }\n getState() {\n return this.state;\n }\n shutdown() {\n if (!this.state.initialized)\n return;\n try {\n serverLogger.info("[tracing] Tracing shutdown initiated");\n } catch (error2) {\n serverLogger.warn("[tracing] Error during tracing shutdown", error2);\n }\n }\n};\nvar tracingManager = new TracingManager();\n\n// src/observability/metrics/manager.ts\ninit_utils();\n\n// src/observability/metrics/config.ts\ninit_process();\ninit_process();\nvar DEFAULT_METRICS_COLLECT_INTERVAL_MS2 = 6e4;\nvar DEFAULT_CONFIG3 = {\n enabled: false,\n exporter: "console",\n prefix: "veryfront",\n collectInterval: DEFAULT_METRICS_COLLECT_INTERVAL_MS2,\n debug: false\n};\nfunction loadConfig2(config, adapter) {\n const finalConfig = { ...DEFAULT_CONFIG3, ...config };\n if (adapter?.env) {\n const envAdapter = adapter.env;\n const otelEnabled = envAdapter.get("OTEL_METRICS_ENABLED");\n const veryfrontOtel = envAdapter.get("VERYFRONT_OTEL");\n finalConfig.enabled = otelEnabled === "true" || veryfrontOtel === "1" || finalConfig.enabled;\n const otlpEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_ENDPOINT");\n const metricsEndpoint = envAdapter.get(\n "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"\n );\n finalConfig.endpoint = otlpEndpoint || metricsEndpoint || finalConfig.endpoint;\n const exporterType = envAdapter.get("OTEL_METRICS_EXPORTER");\n if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {\n finalConfig.exporter = exporterType;\n }\n } else {\n try {\n finalConfig.enabled = getEnv("OTEL_METRICS_ENABLED") === "true" || getEnv("VERYFRONT_OTEL") === "1" || finalConfig.enabled;\n finalConfig.endpoint = getEnv("OTEL_EXPORTER_OTLP_ENDPOINT") || getEnv("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT") || finalConfig.endpoint;\n const exporterType = getEnv("OTEL_METRICS_EXPORTER");\n if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {\n finalConfig.exporter = exporterType;\n }\n } catch {\n }\n }\n return finalConfig;\n}\nfunction getMemoryUsage() {\n try {\n return memoryUsage();\n } catch {\n return null;\n }\n}\n\n// src/observability/instruments/instruments-factory.ts\ninit_utils();\n\n// src/observability/instruments/build-instruments.ts\ninit_config();\nfunction createBuildInstruments(meter, config) {\n const buildDuration = meter.createHistogram(\n `${config.prefix}.build.duration`,\n {\n description: "Build operation duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const bundleSizeHistogram = meter.createHistogram(\n `${config.prefix}.build.bundle.size`,\n {\n description: "Bundle size distribution",\n unit: "kb",\n advice: { explicitBucketBoundaries: SIZE_HISTOGRAM_BOUNDARIES_KB }\n }\n );\n const bundleCounter = meter.createCounter(\n `${config.prefix}.build.bundles`,\n {\n description: "Total number of bundles created",\n unit: "bundles"\n }\n );\n return {\n buildDuration,\n bundleSizeHistogram,\n bundleCounter\n };\n}\n\n// src/observability/instruments/cache-instruments.ts\nfunction createCacheInstruments(meter, config, runtimeState) {\n const cacheGetCounter = meter.createCounter(\n `${config.prefix}.cache.gets`,\n {\n description: "Total number of cache get operations",\n unit: "operations"\n }\n );\n const cacheHitCounter = meter.createCounter(\n `${config.prefix}.cache.hits`,\n {\n description: "Total number of cache hits",\n unit: "hits"\n }\n );\n const cacheMissCounter = meter.createCounter(\n `${config.prefix}.cache.misses`,\n {\n description: "Total number of cache misses",\n unit: "misses"\n }\n );\n const cacheSetCounter = meter.createCounter(\n `${config.prefix}.cache.sets`,\n {\n description: "Total number of cache set operations",\n unit: "operations"\n }\n );\n const cacheInvalidateCounter = meter.createCounter(\n `${config.prefix}.cache.invalidations`,\n {\n description: "Total number of cache invalidations",\n unit: "operations"\n }\n );\n const cacheSizeGauge = meter.createObservableGauge(\n `${config.prefix}.cache.size`,\n {\n description: "Current cache size",\n unit: "entries"\n }\n );\n cacheSizeGauge.addCallback((result) => {\n result.observe(runtimeState.cacheSize);\n });\n return {\n cacheGetCounter,\n cacheHitCounter,\n cacheMissCounter,\n cacheSetCounter,\n cacheInvalidateCounter,\n cacheSizeGauge\n };\n}\n\n// src/observability/instruments/data-instruments.ts\ninit_config();\nfunction createDataInstruments(meter, config) {\n const dataFetchDuration = meter.createHistogram(\n `${config.prefix}.data.fetch.duration`,\n {\n description: "Data fetch duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const dataFetchCounter = meter.createCounter(\n `${config.prefix}.data.fetch.count`,\n {\n description: "Total number of data fetches",\n unit: "fetches"\n }\n );\n const dataFetchErrorCounter = meter.createCounter(\n `${config.prefix}.data.fetch.errors`,\n {\n description: "Data fetch errors",\n unit: "errors"\n }\n );\n return {\n dataFetchDuration,\n dataFetchCounter,\n dataFetchErrorCounter\n };\n}\n\n// src/observability/instruments/http-instruments.ts\ninit_config();\nfunction createHttpInstruments(meter, config) {\n const httpRequestCounter = meter.createCounter(\n `${config.prefix}.http.requests`,\n {\n description: "Total number of HTTP requests",\n unit: "requests"\n }\n );\n const httpRequestDuration = meter.createHistogram(\n `${config.prefix}.http.request.duration`,\n {\n description: "HTTP request duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const httpActiveRequests = meter.createUpDownCounter(\n `${config.prefix}.http.requests.active`,\n {\n description: "Number of active HTTP requests",\n unit: "requests"\n }\n );\n return {\n httpRequestCounter,\n httpRequestDuration,\n httpActiveRequests\n };\n}\n\n// src/observability/instruments/memory-instruments.ts\nfunction createMemoryInstruments(meter, config) {\n const memoryUsageGauge = meter.createObservableGauge(\n `${config.prefix}.memory.usage`,\n {\n description: "Memory usage",\n unit: "bytes"\n }\n );\n memoryUsageGauge.addCallback((result) => {\n const memoryUsage2 = getMemoryUsage();\n if (memoryUsage2) {\n result.observe(memoryUsage2.rss);\n }\n });\n const heapUsageGauge = meter.createObservableGauge(\n `${config.prefix}.memory.heap`,\n {\n description: "Heap memory usage",\n unit: "bytes"\n }\n );\n heapUsageGauge.addCallback((result) => {\n const memoryUsage2 = getMemoryUsage();\n if (memoryUsage2) {\n result.observe(memoryUsage2.heapUsed);\n }\n });\n return {\n memoryUsageGauge,\n heapUsageGauge\n };\n}\n\n// src/observability/instruments/render-instruments.ts\ninit_config();\nfunction createRenderInstruments(meter, config) {\n const renderDuration = meter.createHistogram(\n `${config.prefix}.render.duration`,\n {\n description: "Page render duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const renderCounter = meter.createCounter(\n `${config.prefix}.render.count`,\n {\n description: "Total number of page renders",\n unit: "renders"\n }\n );\n const renderErrorCounter = meter.createCounter(\n `${config.prefix}.render.errors`,\n {\n description: "Total number of render errors",\n unit: "errors"\n }\n );\n return {\n renderDuration,\n renderCounter,\n renderErrorCounter\n };\n}\n\n// src/observability/instruments/rsc-instruments.ts\ninit_config();\nfunction createRscInstruments(meter, config) {\n const rscRenderDuration = meter.createHistogram(\n `${config.prefix}.rsc.render.duration`,\n {\n description: "RSC render duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const rscStreamDuration = meter.createHistogram(\n `${config.prefix}.rsc.stream.duration`,\n {\n description: "RSC stream duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const rscManifestCounter = meter.createCounter(\n `${config.prefix}.rsc.manifest`,\n {\n description: "RSC manifest requests",\n unit: "requests"\n }\n );\n const rscPageCounter = meter.createCounter(\n `${config.prefix}.rsc.page`,\n {\n description: "RSC page requests",\n unit: "requests"\n }\n );\n const rscStreamCounter = meter.createCounter(\n `${config.prefix}.rsc.stream`,\n {\n description: "RSC stream requests",\n unit: "requests"\n }\n );\n const rscActionCounter = meter.createCounter(\n `${config.prefix}.rsc.action`,\n {\n description: "RSC action requests",\n unit: "requests"\n }\n );\n const rscErrorCounter = meter.createCounter(\n `${config.prefix}.rsc.errors`,\n {\n description: "RSC errors",\n unit: "errors"\n }\n );\n return {\n rscRenderDuration,\n rscStreamDuration,\n rscManifestCounter,\n rscPageCounter,\n rscStreamCounter,\n rscActionCounter,\n rscErrorCounter\n };\n}\n\n// src/observability/instruments/instruments-factory.ts\nfunction initializeInstruments(meter, config, runtimeState) {\n const instruments = {\n httpRequestCounter: null,\n httpRequestDuration: null,\n httpActiveRequests: null,\n cacheGetCounter: null,\n cacheHitCounter: null,\n cacheMissCounter: null,\n cacheSetCounter: null,\n cacheInvalidateCounter: null,\n cacheSizeGauge: null,\n renderDuration: null,\n renderCounter: null,\n renderErrorCounter: null,\n rscRenderDuration: null,\n rscStreamDuration: null,\n rscManifestCounter: null,\n rscPageCounter: null,\n rscStreamCounter: null,\n rscActionCounter: null,\n rscErrorCounter: null,\n buildDuration: null,\n bundleSizeHistogram: null,\n bundleCounter: null,\n dataFetchDuration: null,\n dataFetchCounter: null,\n dataFetchErrorCounter: null,\n corsRejectionCounter: null,\n securityHeadersCounter: null,\n memoryUsageGauge: null,\n heapUsageGauge: null\n };\n try {\n const httpInstruments = createHttpInstruments(meter, config);\n Object.assign(instruments, httpInstruments);\n const cacheInstruments = createCacheInstruments(meter, config, runtimeState);\n Object.assign(instruments, cacheInstruments);\n const renderInstruments = createRenderInstruments(meter, config);\n Object.assign(instruments, renderInstruments);\n const rscInstruments = createRscInstruments(meter, config);\n Object.assign(instruments, rscInstruments);\n const buildInstruments = createBuildInstruments(meter, config);\n Object.assign(instruments, buildInstruments);\n const dataInstruments = createDataInstruments(meter, config);\n Object.assign(instruments, dataInstruments);\n const memoryInstruments = createMemoryInstruments(meter, config);\n Object.assign(instruments, memoryInstruments);\n } catch (error2) {\n serverLogger.warn("[metrics] Failed to initialize metric instruments", error2);\n }\n return Promise.resolve(instruments);\n}\n\n// src/observability/metrics/recorder.ts\nvar MetricsRecorder = class {\n constructor(instruments, runtimeState) {\n this.instruments = instruments;\n this.runtimeState = runtimeState;\n }\n recordHttpRequest(attributes) {\n this.instruments.httpRequestCounter?.add(1, attributes);\n this.instruments.httpActiveRequests?.add(1, attributes);\n this.runtimeState.activeRequests++;\n }\n recordHttpRequestComplete(durationMs, attributes) {\n this.instruments.httpRequestDuration?.record(durationMs, attributes);\n this.instruments.httpActiveRequests?.add(-1, attributes);\n this.runtimeState.activeRequests--;\n }\n recordCacheGet(hit, attributes) {\n this.instruments.cacheGetCounter?.add(1, attributes);\n if (hit) {\n this.instruments.cacheHitCounter?.add(1, attributes);\n } else {\n this.instruments.cacheMissCounter?.add(1, attributes);\n }\n }\n recordCacheSet(attributes) {\n this.instruments.cacheSetCounter?.add(1, attributes);\n this.runtimeState.cacheSize++;\n }\n recordCacheInvalidate(count, attributes) {\n this.instruments.cacheInvalidateCounter?.add(count, attributes);\n this.runtimeState.cacheSize = Math.max(\n 0,\n this.runtimeState.cacheSize - count\n );\n }\n setCacheSize(size) {\n this.runtimeState.cacheSize = size;\n }\n // Render Metrics\n recordRender(durationMs, attributes) {\n this.instruments.renderDuration?.record(durationMs, attributes);\n this.instruments.renderCounter?.add(1, attributes);\n }\n recordRenderError(attributes) {\n this.instruments.renderErrorCounter?.add(1, attributes);\n }\n // RSC Metrics\n recordRSCRender(durationMs, attributes) {\n this.instruments.rscRenderDuration?.record(durationMs, attributes);\n }\n recordRSCStream(durationMs, attributes) {\n this.instruments.rscStreamDuration?.record(durationMs, attributes);\n }\n recordRSCRequest(type, attributes) {\n switch (type) {\n case "manifest":\n this.instruments.rscManifestCounter?.add(1, attributes);\n break;\n case "page":\n this.instruments.rscPageCounter?.add(1, attributes);\n break;\n case "stream":\n this.instruments.rscStreamCounter?.add(1, attributes);\n break;\n case "action":\n this.instruments.rscActionCounter?.add(1, attributes);\n break;\n }\n }\n recordRSCError(attributes) {\n this.instruments.rscErrorCounter?.add(1, attributes);\n }\n // Build Metrics\n recordBuild(durationMs, attributes) {\n this.instruments.buildDuration?.record(durationMs, attributes);\n }\n recordBundle(sizeKb, attributes) {\n this.instruments.bundleSizeHistogram?.record(sizeKb, attributes);\n this.instruments.bundleCounter?.add(1, attributes);\n }\n // Data Fetching Metrics\n recordDataFetch(durationMs, attributes) {\n this.instruments.dataFetchDuration?.record(durationMs, attributes);\n this.instruments.dataFetchCounter?.add(1, attributes);\n }\n recordDataFetchError(attributes) {\n this.instruments.dataFetchErrorCounter?.add(1, attributes);\n }\n // Security Metrics\n recordCorsRejection(attributes) {\n this.instruments.corsRejectionCounter?.add(1, attributes);\n }\n recordSecurityHeaders(attributes) {\n this.instruments.securityHeadersCounter?.add(1, attributes);\n }\n};\n\n// src/observability/metrics/manager.ts\nvar MetricsManager = class {\n constructor() {\n this.initialized = false;\n this.meter = null;\n this.api = null;\n this.recorder = null;\n this.instruments = this.createEmptyInstruments();\n this.runtimeState = {\n cacheSize: 0,\n activeRequests: 0\n };\n this.recorder = new MetricsRecorder(this.instruments, this.runtimeState);\n }\n createEmptyInstruments() {\n return {\n httpRequestCounter: null,\n httpRequestDuration: null,\n httpActiveRequests: null,\n cacheGetCounter: null,\n cacheHitCounter: null,\n cacheMissCounter: null,\n cacheSetCounter: null,\n cacheInvalidateCounter: null,\n cacheSizeGauge: null,\n renderDuration: null,\n renderCounter: null,\n renderErrorCounter: null,\n rscRenderDuration: null,\n rscStreamDuration: null,\n rscManifestCounter: null,\n rscPageCounter: null,\n rscStreamCounter: null,\n rscActionCounter: null,\n rscErrorCounter: null,\n buildDuration: null,\n bundleSizeHistogram: null,\n bundleCounter: null,\n dataFetchDuration: null,\n dataFetchCounter: null,\n dataFetchErrorCounter: null,\n corsRejectionCounter: null,\n securityHeadersCounter: null,\n memoryUsageGauge: null,\n heapUsageGauge: null\n };\n }\n async initialize(config = {}, adapter) {\n if (this.initialized) {\n serverLogger.debug("[metrics] Already initialized");\n return;\n }\n const finalConfig = loadConfig2(config, adapter);\n if (!finalConfig.enabled) {\n serverLogger.debug("[metrics] Metrics collection disabled");\n this.initialized = true;\n return;\n }\n try {\n this.api = await import("npm:@opentelemetry/api@1");\n this.meter = this.api.metrics.getMeter(finalConfig.prefix, "0.1.0");\n this.instruments = await initializeInstruments(\n this.meter,\n finalConfig,\n this.runtimeState\n );\n if (this.recorder) {\n this.recorder.instruments = this.instruments;\n }\n this.initialized = true;\n serverLogger.info("[metrics] OpenTelemetry metrics initialized", {\n exporter: finalConfig.exporter,\n endpoint: finalConfig.endpoint,\n prefix: finalConfig.prefix\n });\n } catch (error2) {\n serverLogger.warn("[metrics] Failed to initialize OpenTelemetry metrics", error2);\n this.initialized = true;\n }\n }\n isEnabled() {\n return this.initialized && this.meter !== null;\n }\n getRecorder() {\n return this.recorder;\n }\n getState() {\n return {\n initialized: this.initialized,\n cacheSize: this.runtimeState.cacheSize,\n activeRequests: this.runtimeState.activeRequests\n };\n }\n shutdown() {\n if (!this.initialized)\n return;\n try {\n serverLogger.info("[metrics] Metrics shutdown initiated");\n } catch (error2) {\n serverLogger.warn("[metrics] Error during metrics shutdown", error2);\n }\n }\n};\nvar metricsManager = new MetricsManager();\n\n// src/observability/metrics/index.ts\nvar getRecorder = () => metricsManager.getRecorder();\nfunction recordCorsRejection(attributes) {\n getRecorder()?.recordCorsRejection?.(attributes);\n}\nfunction recordSecurityHeaders(attributes) {\n getRecorder()?.recordSecurityHeaders?.(attributes);\n}\n\n// src/observability/auto-instrument/orchestrator.ts\ninit_utils();\n\n// src/observability/auto-instrument/http-instrumentation.ts\ninit_utils();\nimport {\n context as otContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace\n} from "npm:@opentelemetry/api@1";\nvar tracer = trace.getTracer("veryfront-http");\n\n// src/security/http/cors/validators.ts\nasync function validateOrigin(requestOrigin, config) {\n if (!config) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (config === true) {\n const origin = requestOrigin || "*";\n return { allowedOrigin: origin, allowCredentials: false };\n }\n const corsConfig = config;\n if (!corsConfig.origin) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (!requestOrigin) {\n if (corsConfig.origin === "*") {\n return { allowedOrigin: "*", allowCredentials: false };\n }\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (corsConfig.origin === "*") {\n if (corsConfig.credentials) {\n serverLogger.warn("[CORS] Cannot use credentials with wildcard origin - denying");\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Cannot use credentials with wildcard origin"\n };\n }\n return { allowedOrigin: "*", allowCredentials: false };\n }\n if (typeof corsConfig.origin === "function") {\n try {\n const result = await corsConfig.origin(requestOrigin);\n if (typeof result === "string") {\n return {\n allowedOrigin: result,\n allowCredentials: corsConfig.credentials ?? false\n };\n }\n const allowed = result === true;\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin rejected by validation function"\n };\n } catch (error2) {\n serverLogger.error("[CORS] Origin validation function error", error2);\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Origin validation error"\n };\n }\n }\n if (Array.isArray(corsConfig.origin)) {\n const allowed = corsConfig.origin.includes(requestOrigin);\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin not in allowlist", {\n requestOrigin,\n allowedOrigins: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin not in allowlist"\n };\n }\n if (typeof corsConfig.origin === "string") {\n const allowed = corsConfig.origin === requestOrigin;\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin does not match", {\n requestOrigin,\n expectedOrigin: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin does not match"\n };\n }\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Invalid origin configuration"\n };\n}\nfunction validateOriginSync(requestOrigin, config) {\n if (!config) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (config === true) {\n const origin = requestOrigin || "*";\n return { allowedOrigin: origin, allowCredentials: false };\n }\n const corsConfig = config;\n if (!corsConfig.origin) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (!requestOrigin) {\n if (corsConfig.origin === "*") {\n return { allowedOrigin: "*", allowCredentials: false };\n }\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (corsConfig.origin === "*") {\n if (corsConfig.credentials) {\n serverLogger.warn("[CORS] Cannot use credentials with wildcard origin - denying");\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Cannot use credentials with wildcard origin"\n };\n }\n return { allowedOrigin: "*", allowCredentials: false };\n }\n if (typeof corsConfig.origin === "function") {\n try {\n const result = corsConfig.origin(requestOrigin);\n if (result instanceof Promise) {\n serverLogger.warn(\n "[CORS] Async origin validators are not supported in synchronous contexts"\n );\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Async origin validators not supported"\n };\n }\n if (typeof result === "string") {\n return {\n allowedOrigin: result,\n allowCredentials: corsConfig.credentials ?? false\n };\n }\n const allowed = result === true;\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin rejected by validation function"\n };\n } catch (error2) {\n serverLogger.error("[CORS] Origin validation function error", error2);\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Origin validation error"\n };\n }\n }\n if (Array.isArray(corsConfig.origin)) {\n const allowed = corsConfig.origin.includes(requestOrigin);\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin not in allowlist (sync)", {\n requestOrigin,\n allowedOrigins: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin not in allowlist"\n };\n }\n if (typeof corsConfig.origin === "string") {\n const allowed = corsConfig.origin === requestOrigin;\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin does not match (sync)", {\n requestOrigin,\n expectedOrigin: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin does not match"\n };\n }\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Invalid origin configuration"\n };\n}\n\n// src/security/http/cors/headers.ts\nasync function applyCORSHeaders(options) {\n const { request, response, headers: headersObj, config } = options;\n const validation = await validateOrigin(request.headers.get("origin"), config);\n if (!validation.allowedOrigin) {\n return response;\n }\n const headers = headersObj || (response ? new Headers(response.headers) : new Headers());\n headers.set("Access-Control-Allow-Origin", validation.allowedOrigin);\n if (validation.allowedOrigin !== "*") {\n const existingVary = headers.get("Vary");\n const varyValues = existingVary ? existingVary.split(",").map((v) => v.trim()) : [];\n if (!varyValues.includes("Origin")) {\n varyValues.push("Origin");\n headers.set("Vary", varyValues.join(", "));\n }\n }\n if (validation.allowCredentials && validation.allowedOrigin !== "*") {\n headers.set("Access-Control-Allow-Credentials", "true");\n }\n const corsConfig = typeof config === "object" ? config : null;\n if (corsConfig?.exposedHeaders && corsConfig.exposedHeaders.length > 0) {\n headers.set("Access-Control-Expose-Headers", corsConfig.exposedHeaders.join(", "));\n }\n if (response) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n return;\n}\nfunction applyCORSHeadersSync(options) {\n const { request, response, headers: headersObj, config } = options;\n const validation = validateOriginSync(request.headers.get("origin"), config);\n if (!validation.allowedOrigin) {\n return response;\n }\n const headers = headersObj || (response ? new Headers(response.headers) : new Headers());\n headers.set("Access-Control-Allow-Origin", validation.allowedOrigin);\n if (validation.allowedOrigin !== "*") {\n const existingVary = headers.get("Vary");\n const varyValues = existingVary ? existingVary.split(",").map((v) => v.trim()) : [];\n if (!varyValues.includes("Origin")) {\n varyValues.push("Origin");\n headers.set("Vary", varyValues.join(", "));\n }\n }\n if (validation.allowCredentials && validation.allowedOrigin !== "*") {\n headers.set("Access-Control-Allow-Credentials", "true");\n }\n const corsConfig = typeof config === "object" ? config : null;\n if (corsConfig?.exposedHeaders && corsConfig.exposedHeaders.length > 0) {\n headers.set("Access-Control-Expose-Headers", corsConfig.exposedHeaders.join(", "));\n }\n if (response) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n return;\n}\n\n// src/security/http/cors/constants.ts\ninit_config();\ninit_process();\n\n// src/security/http/cors/preflight.ts\ninit_logger();\n\n// src/security/http/cors/middleware.ts\ninit_veryfront_error();\n\n// src/security/http/response/security-handler.ts\nfunction generateNonce() {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return btoa(String.fromCharCode(...array));\n}\nfunction buildCSP(isDev, nonce, cspUserHeader, config, adapter) {\n const envCsp = adapter?.env?.get?.("VERYFRONT_CSP");\n if (envCsp?.trim())\n return envCsp.replace(/{NONCE}/g, nonce);\n const defaultCsp = isDev ? [\n "default-src \'self\'",\n `style-src \'self\' \'unsafe-inline\' https://esm.sh https://cdnjs.cloudflare.com https://cdn.veryfront.com https://cdn.jsdelivr.net https://cdn.tailwindcss.com`,\n "img-src \'self\' data: https://cdn.veryfront.com https://cdnjs.cloudflare.com",\n `script-src \'self\' \'nonce-${nonce}\' \'unsafe-eval\' https://esm.sh https://cdn.tailwindcss.com`,\n "connect-src \'self\' https://esm.sh ws://localhost:* wss://localhost:*",\n "font-src \'self\' data: https://cdnjs.cloudflare.com"\n ].join("; ") : [\n "default-src \'self\'",\n `style-src \'self\' \'nonce-${nonce}\'`,\n "img-src \'self\' data:",\n `script-src \'self\' \'nonce-${nonce}\'`,\n "connect-src \'self\'"\n ].join("; ");\n if (cspUserHeader?.trim()) {\n return `${cspUserHeader.replace(/{NONCE}/g, nonce)}; ${defaultCsp}`;\n }\n const cfgCsp = config?.csp;\n if (cfgCsp && typeof cfgCsp === "object") {\n const pieces = [];\n for (const [k, v] of Object.entries(cfgCsp)) {\n if (v === void 0)\n continue;\n const key = String(k).replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n const val = Array.isArray(v) ? v.join(" ") : String(v);\n pieces.push(`${key} ${val}`.replace(/{NONCE}/g, nonce));\n }\n if (pieces.length > 0) {\n return `${pieces.join("; ")}; ${defaultCsp}`;\n }\n }\n return defaultCsp;\n}\nfunction getSecurityHeader(headerName, defaultValue, config, adapter) {\n const configKey = headerName.toLowerCase();\n const configValue = config?.[configKey];\n const envValue = adapter?.env?.get?.(`VERYFRONT_${headerName}`);\n return (typeof configValue === "string" ? configValue : void 0) || envValue || defaultValue;\n}\nfunction applySecurityHeaders(headers, isDev, nonce, cspUserHeader, config, adapter) {\n const getHeaderOverride = (name) => {\n const overrides = config?.headers;\n if (!overrides)\n return void 0;\n const lower = name.toLowerCase();\n for (const [key, value] of Object.entries(overrides)) {\n if (key.toLowerCase() === lower) {\n return value;\n }\n }\n return void 0;\n };\n const contentTypeOptions = getHeaderOverride("x-content-type-options") ?? "nosniff";\n headers.set("X-Content-Type-Options", contentTypeOptions);\n const frameOptions = getHeaderOverride("x-frame-options") ?? "DENY";\n headers.set("X-Frame-Options", frameOptions);\n const xssProtection = getHeaderOverride("x-xss-protection") ?? "1; mode=block";\n headers.set("X-XSS-Protection", xssProtection);\n const csp = buildCSP(isDev, nonce, cspUserHeader, config, adapter);\n if (csp) {\n headers.set("Content-Security-Policy", csp);\n }\n if (!isDev) {\n const hstsMaxAge = config?.hsts?.maxAge ?? 31536e3;\n const hstsIncludeSubDomains = config?.hsts?.includeSubDomains ?? true;\n const hstsPreload = config?.hsts?.preload ?? false;\n let hstsValue = `max-age=${hstsMaxAge}`;\n if (hstsIncludeSubDomains) {\n hstsValue += "; includeSubDomains";\n }\n if (hstsPreload) {\n hstsValue += "; preload";\n }\n const hstsOverride = getHeaderOverride("strict-transport-security");\n headers.set("Strict-Transport-Security", hstsOverride ?? hstsValue);\n }\n const coop = getSecurityHeader("COOP", "same-origin", config, adapter);\n const corp = getSecurityHeader("CORP", "same-origin", config, adapter);\n const coep = getSecurityHeader("COEP", "", config, adapter);\n headers.set("Cross-Origin-Opener-Policy", coop);\n headers.set("Cross-Origin-Resource-Policy", corp);\n if (coep) {\n headers.set("Cross-Origin-Embedder-Policy", coep);\n }\n if (config?.headers) {\n for (const [key, value] of Object.entries(config.headers)) {\n if (value === void 0)\n continue;\n headers.set(key, value);\n }\n }\n recordSecurityHeaders();\n}\n\n// src/security/http/response/cache-handler.ts\nfunction buildCacheControl(strategy) {\n let cacheControl;\n if (typeof strategy === "string") {\n switch (strategy) {\n case "no-cache":\n cacheControl = "no-cache, no-store, must-revalidate";\n break;\n case "no-store":\n cacheControl = "no-store";\n break;\n case "short":\n cacheControl = `public, max-age=${CACHE_DURATIONS.SHORT}`;\n break;\n case "medium":\n cacheControl = `public, max-age=${CACHE_DURATIONS.MEDIUM}`;\n break;\n case "long":\n cacheControl = `public, max-age=${CACHE_DURATIONS.LONG}`;\n break;\n case "immutable":\n cacheControl = `public, max-age=${CACHE_DURATIONS.LONG}, immutable`;\n break;\n case "none":\n cacheControl = "no-cache, no-store, must-revalidate";\n break;\n default:\n cacheControl = "public, max-age=0";\n }\n } else {\n const parts = [];\n parts.push(strategy.public !== false ? "public" : "private");\n parts.push(`max-age=${strategy.maxAge}`);\n if (strategy.immutable)\n parts.push("immutable");\n if (strategy.mustRevalidate)\n parts.push("must-revalidate");\n cacheControl = parts.join(", ");\n }\n return cacheControl;\n}\n\n// src/security/http/response/fluent-methods.ts\nfunction withCORS(req, corsConfig) {\n const config = corsConfig ?? this.securityConfig?.cors;\n applyCORSHeadersSync({\n request: req,\n headers: this.headers,\n config\n });\n return this;\n}\nfunction withCORSAsync(req) {\n return applyCORSHeaders({\n request: req,\n headers: this.headers,\n config: this.securityConfig?.cors\n }).then(() => this);\n}\nfunction withSecurity(config) {\n const cfg = config ?? this.securityConfig;\n applySecurityHeaders(\n this.headers,\n this.isDev,\n this.nonce,\n this.cspUserHeader,\n cfg,\n this.adapter\n );\n return this;\n}\nfunction withCache(strategy) {\n const cacheControl = buildCacheControl(strategy);\n this.headers.set("cache-control", cacheControl);\n return this;\n}\nfunction withETag(etag) {\n this.headers.set("ETag", etag);\n return this;\n}\nfunction withHeaders(headers) {\n if (headers instanceof Headers) {\n headers.forEach((value, key) => {\n this.headers.set(key, value);\n });\n } else if (Array.isArray(headers)) {\n headers.forEach(([key, value]) => {\n this.headers.set(key, value);\n });\n } else {\n Object.entries(headers).forEach(([key, value]) => {\n this.headers.set(key, value);\n });\n }\n return this;\n}\nfunction withStatus(status) {\n this.status = status;\n return this;\n}\nfunction withAllow(methods) {\n const methodStr = Array.isArray(methods) ? methods.join(", ") : methods;\n this.headers.set("Allow", methodStr);\n this.headers.set("Access-Control-Allow-Methods", methodStr);\n return this;\n}\n\n// src/security/http/response/response-methods.ts\nfunction json(data, status) {\n this.headers.set("content-type", CONTENT_TYPES.JSON);\n return new Response(JSON.stringify(data), {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction text(body, status) {\n this.headers.set("content-type", CONTENT_TYPES.TEXT);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction html(body, status) {\n this.headers.set("content-type", CONTENT_TYPES.HTML);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction javascript(code, status) {\n this.headers.set("content-type", CONTENT_TYPES.JAVASCRIPT);\n return new Response(code, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction withContentType(contentType, body, status) {\n this.headers.set("content-type", contentType);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction build(body = null, status) {\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction notModified(etag) {\n if (etag) {\n this.headers.set("ETag", etag);\n }\n return new Response(null, {\n status: 304,\n headers: this.headers\n });\n}\n\n// src/security/http/response/static-helpers.ts\ninit_veryfront_error();\nvar ResponseBuilderClass = null;\nfunction setResponseBuilderClass(builderClass) {\n ResponseBuilderClass = builderClass;\n}\nfunction error(status, message, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n const contentType = config?.contentType ?? CONTENT_TYPES.TEXT;\n if (contentType === CONTENT_TYPES.JSON) {\n return builder.json({ error: message }, status);\n } else if (contentType === CONTENT_TYPES.HTML) {\n return builder.html(message, status);\n }\n return builder.text(message, status);\n}\nfunction json2(data, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n if (config?.etag) {\n builder.withETag(config.etag);\n }\n return builder.json(data, config?.status);\n}\nfunction html2(body, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n if (config?.etag) {\n builder.withETag(config.etag);\n }\n return builder.html(body, config?.status);\n}\nfunction preflight(req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n const methods = config?.allowMethods ?? "GET,POST,PUT,PATCH,DELETE,OPTIONS";\n builder.withAllow(methods);\n const headers = config?.allowHeaders ?? req.headers.get("access-control-request-headers") ?? "Content-Type,Authorization";\n builder.headers.set(\n "Access-Control-Allow-Headers",\n Array.isArray(headers) ? headers.join(", ") : headers\n );\n return builder.build(null, 204);\n}\nfunction stream(streamData, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n const contentType = config?.contentType ?? "application/octet-stream";\n return builder.withContentType(contentType, streamData);\n}\n\n// src/security/http/response/builder.ts\nvar ResponseBuilder = class {\n constructor(config) {\n this.withCORS = withCORS;\n this.withCORSAsync = withCORSAsync;\n this.withSecurity = withSecurity;\n this.withCache = withCache;\n this.withETag = withETag;\n this.withHeaders = withHeaders;\n this.withStatus = withStatus;\n this.withAllow = withAllow;\n this.json = json;\n this.text = text;\n this.html = html;\n this.javascript = javascript;\n this.withContentType = withContentType;\n this.build = build;\n this.notModified = notModified;\n this.headers = new Headers();\n this.status = 200;\n this.securityConfig = config?.securityConfig ?? null;\n this.isDev = config?.isDev ?? false;\n this.nonce = config?.nonce ?? generateNonce();\n this.cspUserHeader = config?.cspUserHeader ?? null;\n this.adapter = config?.adapter;\n }\n};\nResponseBuilder.error = error;\nResponseBuilder.json = json2;\nResponseBuilder.html = html2;\nResponseBuilder.preflight = preflight;\nResponseBuilder.stream = stream;\nsetResponseBuilderClass(\n ResponseBuilder\n);\n\n// src/security/http/base-handler.ts\ninit_utils();\n\n// src/core/constants/index.ts\ninit_constants();\n\n// src/core/constants/buffers.ts\nvar DEFAULT_MAX_BODY_SIZE_BYTES = 1024 * 1024;\nvar DEFAULT_MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;\nvar PREFETCH_QUEUE_MAX_SIZE_BYTES = 1024 * 1024;\nvar MAX_BUNDLE_CHUNK_SIZE_BYTES = 4096 * 1024;\n\n// src/core/constants/limits.ts\nvar MAX_URL_LENGTH_FOR_VALIDATION = 2048;\n\n// src/security/input-validation/parsers.ts\nimport { z as z2 } from "zod";\n\n// src/security/input-validation/schemas.ts\nimport { z as z3 } from "zod";\nvar CommonSchemas = {\n /**\n * Valid email address (RFC-compliant, max 255 chars)\n */\n email: z3.string().email().max(255),\n /**\n * Valid UUID v4 identifier\n */\n uuid: z3.string().uuid(),\n /**\n * URL-safe slug (lowercase alphanumeric with hyphens)\n */\n slug: z3.string().regex(/^[a-z0-9-]+$/).min(1).max(100),\n /**\n * Valid HTTP/HTTPS URL (max 2048 chars)\n */\n url: z3.string().url().max(MAX_URL_LENGTH_FOR_VALIDATION),\n /**\n * International phone number (E.164 format)\n */\n phoneNumber: z3.string().regex(/^\\+?[1-9]\\d{1,14}$/),\n /**\n * Pagination parameters with defaults\n */\n pagination: z3.object({\n page: z3.coerce.number().int().positive().default(1),\n limit: z3.coerce.number().int().positive().max(100).default(10),\n sort: z3.string().optional(),\n order: z3.enum(["asc", "desc"]).optional()\n }),\n /**\n * Date range with validation\n */\n dateRange: z3.object({\n from: z3.string().datetime(),\n to: z3.string().datetime()\n }).refine((data) => new Date(data.from) <= new Date(data.to), {\n message: "From date must be before or equal to To date"\n }),\n /**\n * Strong password requirements\n * - Minimum 8 characters\n * - At least one uppercase letter\n * - At least one lowercase letter\n * - At least one number\n * - At least one special character\n */\n strongPassword: z3.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number").regex(/[^A-Za-z0-9]/, "Password must contain at least one special character")\n};\n\n// src/security/http/auth.ts\ninit_veryfront_error();\n\n// src/security/http/config.ts\ninit_config();\ninit_utils();\n\n// src/security/http/middleware/config-loader.ts\ninit_utils();\n\n// src/security/http/middleware/etag.ts\ninit_hash();\n\n// src/security/http/middleware/content-types.ts\ninit_http();\n\n// src/security/path-validation.ts\ninit_utils();\n\n// src/security/secure-fs.ts\ninit_utils();\n\n// src/routing/api/api-route-matcher.ts\ninit_process();\n\n// src/routing/api/module-loader/loader.ts\ninit_utils();\n\n// src/routing/api/module-loader/esbuild-plugin.ts\ninit_utils();\ninit_utils();\ninit_utils();\n\n// src/routing/api/module-loader/http-validator.ts\ninit_veryfront_error();\n\n// src/routing/api/module-loader/security-config.ts\ninit_utils();\ninit_utils();\n\n// src/routing/api/module-loader/loader.ts\ninit_veryfront_error();\n\n// src/platform/compat/fs.ts\ninit_veryfront_error();\ninit_runtime();\n\n// src/routing/api/module-loader/loader.ts\ninit_runtime();\n\n// src/routing/api/route-discovery.ts\ninit_std_path();\n\n// src/core/utils/file-discovery.ts\ninit_std_path();\ninit_deno3();\n\n// src/routing/api/route-executor.ts\ninit_veryfront_error();\n\n// src/routing/api/method-validator.ts\ninit_utils();\n\n// src/routing/api/error-handler.ts\ninit_utils();\ninit_utils();\ninit_utils();\n\n// src/rendering/client/router.ts\nvar VeryfrontRouter = class {\n constructor(options = {}) {\n this.root = null;\n const globalOptions = this.loadGlobalOptions();\n this.options = { ...globalOptions, ...options };\n this.baseUrl = options.baseUrl || globalThis.location.origin;\n this.currentPath = globalThis.location.pathname;\n this.pageLoader = new PageLoader();\n this.navigationHandlers = new NavigationHandlers(\n this.options.prefetchDelay,\n this.options.prefetch\n );\n this.pageTransition = new PageTransition((root) => this.viewportPrefetch.setup(root));\n this.viewportPrefetch = new ViewportPrefetch(\n (path) => this.prefetch(path),\n this.options.prefetch\n );\n this.handleClick = this.navigationHandlers.createClickHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handlePopState = this.navigationHandlers.createPopStateHandler({\n onNavigate: (url) => this.navigate(url, false),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handleMouseOver = this.navigationHandlers.createMouseOverHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n }\n loadGlobalOptions() {\n try {\n const options = globalThis.__VERYFRONT_ROUTER_OPTS__;\n if (!options) {\n rendererLogger.debug("[router] No global options configured");\n return {};\n }\n return options;\n } catch (error2) {\n rendererLogger.error("[router] Failed to read global options:", error2);\n return {};\n }\n }\n init() {\n rendererLogger.info("Initializing client-side router");\n const rootElement = document.getElementById("root");\n if (!rootElement) {\n rendererLogger.error("Root element not found");\n return;\n }\n const ReactDOMToUse = globalThis.ReactDOM || ReactDOM;\n this.root = ReactDOMToUse.createRoot(rootElement);\n document.addEventListener("click", this.handleClick);\n globalThis.addEventListener("popstate", this.handlePopState);\n document.addEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.setup(document);\n this.cacheCurrentPage();\n }\n cacheCurrentPage() {\n const pageData = extractPageDataFromScript();\n if (pageData) {\n this.pageLoader.setCache(this.currentPath, pageData);\n }\n }\n async navigate(url, pushState = true) {\n rendererLogger.info(`Navigating to ${url}`);\n this.navigationHandlers.saveScrollPosition(this.currentPath);\n this.options.onStart?.(url);\n if (pushState) {\n globalThis.history.pushState({}, "", url);\n }\n await this.loadPage(url);\n this.options.onNavigate?.(url);\n }\n async loadPage(path, updateUI = true) {\n if (this.pageLoader.isCached(path)) {\n rendererLogger.debug(`Loading ${path} from cache`);\n const data = this.pageLoader.getCached(path);\n if (!data) {\n rendererLogger.warn(`[router] Cache entry for ${path} was unexpectedly null, fetching fresh data`);\n } else {\n if (updateUI) {\n this.updatePage(data);\n }\n return;\n }\n }\n this.pageTransition.setLoadingState(true);\n try {\n const data = await this.pageLoader.loadPage(path);\n if (updateUI) {\n this.updatePage(data);\n }\n this.currentPath = path;\n this.options.onComplete?.(path);\n } catch (error2) {\n rendererLogger.error(`Failed to load ${path}`, error2);\n this.options.onError?.(error2);\n this.pageTransition.showError(error2);\n } finally {\n this.pageTransition.setLoadingState(false);\n }\n }\n async prefetch(path) {\n await this.pageLoader.prefetch(path);\n }\n updatePage(data) {\n if (!this.root)\n return;\n const isPopState = this.navigationHandlers.isPopState();\n const scrollY = this.navigationHandlers.getScrollPosition(this.currentPath);\n this.pageTransition.updatePage(data, isPopState, scrollY);\n this.navigationHandlers.clearPopStateFlag();\n }\n destroy() {\n document.removeEventListener("click", this.handleClick);\n globalThis.removeEventListener("popstate", this.handlePopState);\n document.removeEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.disconnect();\n this.pageLoader.clearCache();\n this.navigationHandlers.clear();\n this.pageTransition.destroy();\n }\n};\nif (typeof window !== "undefined" && globalThis.document) {\n const router = new VeryfrontRouter();\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => router.init());\n } else {\n router.init();\n }\n globalThis.veryFrontRouter = router;\n}\nexport {\n VeryfrontRouter\n};\n';
14916
+ CLIENT_PREFETCH_BUNDLE = '// src/rendering/client/browser-logger.ts\nvar ConditionalBrowserLogger = class {\n constructor(prefix, level) {\n this.prefix = prefix;\n this.level = level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug?.(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log?.(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn?.(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error?.(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n};\nfunction getBrowserLogLevel() {\n if (typeof window === "undefined") {\n return 2 /* WARN */;\n }\n const windowObject = window;\n const isDevelopment = windowObject.__VERYFRONT_DEV__ || windowObject.__RSC_DEV__;\n if (!isDevelopment) {\n return 2 /* WARN */;\n }\n const isDebugEnabled = windowObject.__VERYFRONT_DEBUG__ || windowObject.__RSC_DEBUG__;\n return isDebugEnabled ? 0 /* DEBUG */ : 1 /* INFO */;\n}\nvar defaultLevel = getBrowserLogLevel();\nvar rscLogger = new ConditionalBrowserLogger("RSC", defaultLevel);\nvar prefetchLogger = new ConditionalBrowserLogger("PREFETCH", defaultLevel);\nvar hydrateLogger = new ConditionalBrowserLogger("HYDRATE", defaultLevel);\nvar browserLogger = new ConditionalBrowserLogger("VERYFRONT", defaultLevel);\n\n// src/rendering/client/prefetch/link-observer.ts\nvar LinkObserver = class {\n constructor(options, prefetchedUrls) {\n this.intersectionObserver = null;\n this.mutationObserver = null;\n this.pendingTimeouts = /* @__PURE__ */ new Map();\n this.elementTimeoutMap = /* @__PURE__ */ new WeakMap();\n this.timeoutCounter = 0;\n this.options = options;\n this.prefetchedUrls = prefetchedUrls;\n }\n init() {\n this.createIntersectionObserver();\n this.observeLinks();\n this.setupMutationObserver();\n }\n createIntersectionObserver() {\n this.intersectionObserver = new IntersectionObserver(\n (entries) => this.handleIntersection(entries),\n { rootMargin: this.options.rootMargin }\n );\n }\n handleIntersection(entries) {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const target = entry.target;\n let isAnchor = false;\n if (typeof HTMLAnchorElement !== "undefined") {\n isAnchor = target instanceof HTMLAnchorElement;\n } else {\n isAnchor = target.tagName === "A";\n }\n if (!isAnchor) {\n continue;\n }\n const link = target;\n const timeoutKey = this.timeoutCounter++;\n const timeoutId = setTimeout(() => {\n this.pendingTimeouts.delete(timeoutKey);\n this.elementTimeoutMap.delete(link);\n this.options.onLinkVisible(link);\n }, this.options.delay);\n this.pendingTimeouts.set(timeoutKey, timeoutId);\n this.elementTimeoutMap.set(link, timeoutKey);\n }\n }\n }\n observeLinks() {\n const links = document.querySelectorAll(\'a[href^="/"], a[href^="./"]\');\n links.forEach((link) => {\n if (this.isValidLink(link)) {\n this.intersectionObserver?.observe(link);\n }\n });\n }\n setupMutationObserver() {\n this.mutationObserver = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type === "childList") {\n mutation.addedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n this.observeElement(node);\n }\n });\n mutation.removedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n this.clearElementTimeouts(node);\n }\n });\n }\n }\n });\n this.mutationObserver.observe(document.body, {\n childList: true,\n subtree: true\n });\n }\n clearElementTimeouts(element) {\n if (element.tagName === "A") {\n const timeoutKey = this.elementTimeoutMap.get(element);\n if (timeoutKey !== void 0) {\n const timeoutId = this.pendingTimeouts.get(timeoutKey);\n if (timeoutId) {\n clearTimeout(timeoutId);\n this.pendingTimeouts.delete(timeoutKey);\n }\n this.elementTimeoutMap.delete(element);\n }\n }\n const links = element.querySelectorAll("a");\n links.forEach((link) => {\n const timeoutKey = this.elementTimeoutMap.get(link);\n if (timeoutKey !== void 0) {\n const timeoutId = this.pendingTimeouts.get(timeoutKey);\n if (timeoutId) {\n clearTimeout(timeoutId);\n this.pendingTimeouts.delete(timeoutKey);\n }\n this.elementTimeoutMap.delete(link);\n }\n });\n }\n observeElement(element) {\n const isAnchor = typeof HTMLAnchorElement !== "undefined" ? element instanceof HTMLAnchorElement : element.tagName === "A";\n if (isAnchor && this.isValidLink(element)) {\n this.intersectionObserver?.observe(element);\n }\n const links = element.querySelectorAll(\'a[href^="/"], a[href^="./"]\');\n links.forEach((link) => {\n const isLinkAnchor = typeof HTMLAnchorElement !== "undefined" ? link instanceof HTMLAnchorElement : link.tagName === "A";\n if (isLinkAnchor && this.isValidLink(link)) {\n this.intersectionObserver?.observe(link);\n }\n });\n }\n isValidLink(link) {\n if (link.hostname !== globalThis.location.hostname)\n return false;\n if (link.hasAttribute("download"))\n return false;\n if (link.target === "_blank")\n return false;\n const url = link.href;\n if (this.prefetchedUrls.has(url))\n return false;\n if (url === globalThis.location.href)\n return false;\n if (link.hash && link.pathname === globalThis.location.pathname) {\n return false;\n }\n if (link.dataset.noPrefetch)\n return false;\n return true;\n }\n destroy() {\n for (const [_, timeoutId] of this.pendingTimeouts) {\n clearTimeout(timeoutId);\n }\n this.pendingTimeouts.clear();\n if (this.intersectionObserver) {\n this.intersectionObserver.disconnect();\n this.intersectionObserver = null;\n }\n if (this.mutationObserver) {\n this.mutationObserver.disconnect();\n this.mutationObserver = null;\n }\n }\n};\n\n// src/rendering/client/prefetch/network-utils.ts\nvar NetworkUtils = class {\n constructor(allowedNetworks = ["4g", "wifi", "ethernet"]) {\n this.allowedNetworks = allowedNetworks;\n this.networkInfo = this.getNetworkConnection();\n }\n getNavigatorWithConnection() {\n if (typeof globalThis.navigator === "undefined") {\n return null;\n }\n return globalThis.navigator;\n }\n getNetworkConnection() {\n const nav = this.getNavigatorWithConnection();\n return nav?.connection || nav?.mozConnection || nav?.webkitConnection || null;\n }\n shouldPrefetch() {\n const nav = this.getNavigatorWithConnection();\n if (nav?.connection?.saveData) {\n return false;\n }\n if (this.networkInfo) {\n const effectiveType = this.networkInfo.effectiveType;\n if (effectiveType !== void 0 && !this.allowedNetworks.includes(effectiveType)) {\n return false;\n }\n }\n return true;\n }\n onNetworkChange(callback) {\n if (this.networkInfo?.addEventListener) {\n this.networkInfo.addEventListener("change", callback);\n }\n }\n getNetworkInfo() {\n return this.networkInfo;\n }\n};\n\n// src/core/utils/constants/cache.ts\nvar SECONDS_PER_MINUTE = 60;\nvar MINUTES_PER_HOUR = 60;\nvar HOURS_PER_DAY = 24;\nvar MS_PER_SECOND = 1e3;\nvar COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\nvar ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n\n// src/core/utils/constants/http.ts\nvar KB_IN_BYTES = 1024;\nvar PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\nvar PREFETCH_DEFAULT_TIMEOUT_MS = 1e4;\nvar PREFETCH_DEFAULT_DELAY_MS = 200;\n\n// src/core/utils/constants/hmr.ts\nvar HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n\n// src/core/utils/constants/network.ts\nvar BYTES_PER_MB = 1024 * 1024;\n\n// src/core/constants/buffers.ts\nvar DEFAULT_MAX_BODY_SIZE_BYTES = 1024 * 1024;\nvar DEFAULT_MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;\nvar PREFETCH_QUEUE_MAX_SIZE_BYTES = 1024 * 1024;\nvar MAX_BUNDLE_CHUNK_SIZE_BYTES = 4096 * 1024;\n\n// src/rendering/client/prefetch/prefetch-queue.ts\nvar DEFAULT_OPTIONS = {\n maxConcurrent: 4,\n maxSize: PREFETCH_QUEUE_MAX_SIZE_BYTES,\n timeout: 5e3\n};\nfunction isAbortError(error) {\n return Boolean(\n error && typeof error === "object" && "name" in error && error.name === "AbortError"\n );\n}\nvar PrefetchQueue = class {\n constructor(options = {}, prefetchedUrls) {\n this.controllers = /* @__PURE__ */ new Map();\n this.concurrent = 0;\n this.stopped = false;\n this.options = { ...DEFAULT_OPTIONS, ...options };\n this.prefetchedUrls = prefetchedUrls ?? /* @__PURE__ */ new Set();\n }\n setResourceCallback(callback) {\n this.onResourcesFetched = callback;\n }\n enqueue(url) {\n void this.prefetch(url);\n }\n has(url) {\n return this.prefetchedUrls.has(url) || this.controllers.has(url);\n }\n get size() {\n return this.getQueueSize();\n }\n clear() {\n this.stopAll();\n this.prefetchedUrls.clear();\n }\n start() {\n this.stopped = false;\n }\n stop() {\n this.stopped = true;\n this.stopAll();\n }\n getQueueSize() {\n return this.controllers.size;\n }\n getConcurrentCount() {\n return this.concurrent;\n }\n async prefetchLink(link) {\n if (this.stopped) {\n return;\n }\n const url = link.href;\n if (!url || this.controllers.has(url) || this.prefetchedUrls.has(url)) {\n return;\n }\n if (this.concurrent >= this.options.maxConcurrent) {\n prefetchLogger.debug?.(`Prefetch queue full, skipping ${url}`);\n return;\n }\n let parsedUrl;\n try {\n parsedUrl = new URL(url);\n } catch (_error) {\n prefetchLogger.debug?.(`Invalid prefetch URL ${url}`);\n return;\n }\n const controller = new AbortController();\n this.controllers.set(url, controller);\n this.concurrent += 1;\n const timeoutId = this.options.timeout > 0 ? setTimeout(() => controller.abort(), this.options.timeout) : void 0;\n try {\n const response = await fetch(parsedUrl.toString(), {\n method: "GET",\n signal: controller.signal,\n headers: { "X-Veryfront-Prefetch": "1" }\n });\n if (!response.ok) {\n return;\n }\n if (this.isResponseTooLarge(response)) {\n prefetchLogger.debug?.(`Prefetch too large, skipping ${url}`);\n return;\n }\n this.prefetchedUrls.add(url);\n if (this.onResourcesFetched) {\n try {\n await this.onResourcesFetched(response, url);\n } catch (callbackError) {\n prefetchLogger.error?.(`Prefetch callback failed for ${url}`, callbackError);\n }\n }\n } catch (error) {\n if (!isAbortError(error)) {\n prefetchLogger.error?.(`Failed to prefetch ${url}`, error);\n }\n } finally {\n if (timeoutId !== void 0) {\n clearTimeout(timeoutId);\n }\n this.controllers.delete(url);\n this.concurrent = Math.max(0, this.concurrent - 1);\n }\n }\n async prefetch(url) {\n const link = typeof document !== "undefined" ? document.createElement("a") : { href: url };\n link.href = url;\n await this.prefetchLink(link);\n }\n stopAll() {\n for (const controller of this.controllers.values()) {\n controller.abort();\n }\n this.controllers.clear();\n this.concurrent = 0;\n }\n isResponseTooLarge(response) {\n const rawLength = response.headers.get("content-length");\n if (rawLength === null) {\n return false;\n }\n const size = Number.parseInt(rawLength, 10);\n if (!Number.isFinite(size)) {\n return false;\n }\n return size > this.options.maxSize;\n }\n};\nvar prefetchQueue = new PrefetchQueue();\n\n// src/rendering/client/prefetch/resource-hints.ts\nvar ResourceHintsManager = class {\n constructor() {\n this.appliedHints = /* @__PURE__ */ new Set();\n }\n applyResourceHints(hints) {\n for (const hint of hints) {\n const key = `${hint.type}:${hint.href}`;\n if (this.appliedHints.has(key))\n continue;\n const existing = document.querySelector(`link[rel="${hint.type}"][href="${hint.href}"]`);\n if (existing) {\n this.appliedHints.add(key);\n continue;\n }\n this.createAndAppendHint(hint);\n this.appliedHints.add(key);\n prefetchLogger.debug(`Added resource hint: ${hint.type} ${hint.href}`);\n }\n }\n createAndAppendHint(hint) {\n if (!document.head) {\n prefetchLogger.warn("document.head is not available, skipping resource hint");\n return;\n }\n const link = document.createElement("link");\n link.rel = hint.type;\n link.href = hint.href;\n if (hint.as)\n link.setAttribute("as", hint.as);\n if (hint.crossOrigin)\n link.setAttribute("crossorigin", hint.crossOrigin);\n if (hint.media)\n link.setAttribute("media", hint.media);\n document.head.appendChild(link);\n }\n extractResourceHints(html, prefetchedUrls) {\n try {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, "text/html");\n const hints = [];\n this.extractPreloadLinks(doc, prefetchedUrls, hints);\n this.extractScripts(doc, prefetchedUrls, hints);\n this.extractStylesheets(doc, prefetchedUrls, hints);\n return hints;\n } catch (error) {\n prefetchLogger.error("Failed to parse prefetched page", error);\n return [];\n }\n }\n isValidResourceHintType(rel) {\n return rel === "prefetch" || rel === "preload" || rel === "preconnect" || rel === "dns-prefetch";\n }\n extractPreloadLinks(doc, prefetchedUrls, hints) {\n doc.querySelectorAll(\'link[rel="preload"], link[rel="prefetch"]\').forEach((link) => {\n const htmlLink = link;\n const href = htmlLink.href;\n if (href && !prefetchedUrls.has(href) && this.isValidResourceHintType(htmlLink.rel)) {\n hints.push({\n type: htmlLink.rel,\n href,\n as: htmlLink.getAttribute("as") || void 0\n });\n }\n });\n }\n extractScripts(doc, prefetchedUrls, hints) {\n doc.querySelectorAll("script[src]").forEach((script) => {\n const src = script.src;\n if (src && !prefetchedUrls.has(src)) {\n hints.push({ type: "prefetch", href: src, as: "script" });\n }\n });\n }\n extractStylesheets(doc, prefetchedUrls, hints) {\n doc.querySelectorAll(\'link[rel="stylesheet"]\').forEach((link) => {\n const href = link.href;\n if (href && !prefetchedUrls.has(href)) {\n hints.push({ type: "prefetch", href, as: "style" });\n }\n });\n }\n static generateResourceHints(_route, assets) {\n const hints = [\n \'<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">\',\n \'<link rel="dns-prefetch" href="https://esm.sh">\',\n \'<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>\'\n ];\n for (const asset of assets) {\n if (asset.endsWith(".js")) {\n hints.push(`<link rel="modulepreload" href="${asset}">`);\n } else if (asset.endsWith(".css")) {\n hints.push(`<link rel="preload" as="style" href="${asset}">`);\n } else if (asset.match(/\\.(woff2?|ttf|otf)$/)) {\n hints.push(`<link rel="preload" as="font" href="${asset}" crossorigin>`);\n }\n }\n return hints.join("\\n");\n }\n};\n\n// src/core/utils/runtime-guards.ts\nfunction hasDenoRuntime(global) {\n return typeof global === "object" && global !== null && "Deno" in global && typeof global.Deno?.env?.get === "function";\n}\nfunction hasNodeProcess(global) {\n return typeof global === "object" && global !== null && "process" in global && typeof global.process?.env === "object";\n}\n\n// src/core/utils/logger/env.ts\nfunction getEnvironmentVariable(name) {\n try {\n if (typeof Deno !== "undefined" && hasDenoRuntime(globalThis)) {\n const value = globalThis.Deno?.env.get(name);\n return value === "" ? void 0 : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = globalThis.process?.env[name];\n return value === "" ? void 0 : value;\n }\n } catch {\n return void 0;\n }\n return void 0;\n}\n\n// src/core/utils/logger/logger.ts\nvar cachedLogLevel;\nfunction resolveLogLevel(force = false) {\n if (force || cachedLogLevel === void 0) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\nvar ConsoleLogger = class {\n constructor(prefix, level = resolveLogLevel()) {\n this.prefix = prefix;\n this.level = level;\n }\n setLevel(level) {\n this.level = level;\n }\n getLevel() {\n return this.level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n async time(label, fn) {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error);\n throw error;\n }\n }\n};\nfunction parseLogLevel(levelString) {\n if (!levelString)\n return void 0;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case "DEBUG":\n return 0 /* DEBUG */;\n case "WARN":\n return 2 /* WARN */;\n case "ERROR":\n return 3 /* ERROR */;\n case "INFO":\n return 1 /* INFO */;\n default:\n return void 0;\n }\n}\nvar getDefaultLevel = () => {\n const envLevel = getEnvironmentVariable("LOG_LEVEL");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== void 0)\n return parsedLevel;\n const debugFlag = getEnvironmentVariable("VERYFRONT_DEBUG");\n if (debugFlag === "1" || debugFlag === "true")\n return 0 /* DEBUG */;\n return 1 /* INFO */;\n};\nvar trackedLoggers = /* @__PURE__ */ new Set();\nfunction createLogger(prefix) {\n const logger2 = new ConsoleLogger(prefix);\n trackedLoggers.add(logger2);\n return logger2;\n}\nvar cliLogger = createLogger("CLI");\nvar serverLogger = createLogger("SERVER");\nvar rendererLogger = createLogger("RENDERER");\nvar bundlerLogger = createLogger("BUNDLER");\nvar agentLogger = createLogger("AGENT");\nvar logger = createLogger("VERYFRONT");\n\n// deno.json\nvar deno_default = {\n name: "veryfront",\n version: "0.0.33",\n exclude: [\n "npm/",\n "dist/",\n "coverage/",\n "scripts/",\n "examples/",\n "tests/"\n ],\n exports: {\n ".": "./src/index.ts",\n "./cli": "./src/cli/main.ts",\n "./server": "./src/server/index.ts",\n "./middleware": "./src/middleware/index.ts",\n "./components": "./src/react/components/index.ts",\n "./data": "./src/data/index.ts",\n "./config": "./src/core/config/index.ts",\n "./ai": "./src/ai/index.ts",\n "./ai/client": "./src/ai/client.ts",\n "./ai/react": "./src/ai/react/index.ts",\n "./ai/primitives": "./src/ai/react/primitives/index.ts",\n "./ai/components": "./src/ai/react/components/index.ts",\n "./ai/production": "./src/ai/production/index.ts",\n "./ai/dev": "./src/ai/dev/index.ts",\n "./ai/workflow": "./src/ai/workflow/index.ts",\n "./ai/workflow/react": "./src/ai/workflow/react/index.ts"\n },\n imports: {\n "@veryfront": "./src/index.ts",\n "@veryfront/": "./src/",\n "@veryfront/ai": "./src/ai/index.ts",\n "@veryfront/ai/": "./src/ai/",\n "@veryfront/platform": "./src/platform/index.ts",\n "@veryfront/platform/": "./src/platform/",\n "@veryfront/types": "./src/core/types/index.ts",\n "@veryfront/types/": "./src/core/types/",\n "@veryfront/utils": "./src/core/utils/index.ts",\n "@veryfront/utils/": "./src/core/utils/",\n "@veryfront/middleware": "./src/middleware/index.ts",\n "@veryfront/middleware/": "./src/middleware/",\n "@veryfront/errors": "./src/core/errors/index.ts",\n "@veryfront/errors/": "./src/core/errors/",\n "@veryfront/config": "./src/core/config/index.ts",\n "@veryfront/config/": "./src/core/config/",\n "@veryfront/observability": "./src/observability/index.ts",\n "@veryfront/observability/": "./src/observability/",\n "@veryfront/routing": "./src/routing/index.ts",\n "@veryfront/routing/": "./src/routing/",\n "@veryfront/transforms": "./src/build/transforms/index.ts",\n "@veryfront/transforms/": "./src/build/transforms/",\n "@veryfront/data": "./src/data/index.ts",\n "@veryfront/data/": "./src/data/",\n "@veryfront/security": "./src/security/index.ts",\n "@veryfront/security/": "./src/security/",\n "@veryfront/components": "./src/react/components/index.ts",\n "@veryfront/react": "./src/react/index.ts",\n "@veryfront/react/": "./src/react/",\n "@veryfront/html": "./src/html/index.ts",\n "@veryfront/html/": "./src/html/",\n "@veryfront/rendering": "./src/rendering/index.ts",\n "@veryfront/rendering/": "./src/rendering/",\n "@veryfront/build": "./src/build/index.ts",\n "@veryfront/build/": "./src/build/",\n "@veryfront/server": "./src/server/index.ts",\n "@veryfront/server/": "./src/server/",\n "@veryfront/modules": "./src/module-system/index.ts",\n "@veryfront/modules/": "./src/module-system/",\n "@veryfront/compat/console": "./src/platform/compat/console/index.ts",\n "@veryfront/compat/": "./src/platform/compat/",\n "std/": "https://deno.land/std@0.220.0/",\n "@std/path": "https://deno.land/std@0.220.0/path/mod.ts",\n "@std/testing/bdd.ts": "https://deno.land/std@0.220.0/testing/bdd.ts",\n "@std/expect": "https://deno.land/std@0.220.0/expect/mod.ts",\n csstype: "https://esm.sh/csstype@3.2.3",\n "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",\n "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",\n react: "https://esm.sh/react@18.3.1",\n "react-dom": "https://esm.sh/react-dom@18.3.1",\n "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",\n "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",\n "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",\n "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",\n "@mdx-js/mdx": "https://esm.sh/@mdx-js/mdx@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "@mdx-js/react": "https://esm.sh/@mdx-js/react@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "unist-util-visit": "https://esm.sh/unist-util-visit@5.0.0",\n "mdast-util-to-string": "https://esm.sh/mdast-util-to-string@4.0.0",\n "github-slugger": "https://esm.sh/github-slugger@2.0.0",\n "remark-gfm": "https://esm.sh/remark-gfm@4.0.1",\n "remark-frontmatter": "https://esm.sh/remark-frontmatter@5.0.0",\n "rehype-highlight": "https://esm.sh/rehype-highlight@7.0.2",\n "rehype-slug": "https://esm.sh/rehype-slug@6.0.0",\n esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",\n "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",\n "es-module-lexer": "https://esm.sh/es-module-lexer@1.5.0",\n zod: "https://esm.sh/zod@3.22.0",\n "mime-types": "https://esm.sh/mime-types@2.1.35",\n mdast: "https://esm.sh/@types/mdast@4.0.3",\n hast: "https://esm.sh/@types/hast@3.0.3",\n unist: "https://esm.sh/@types/unist@3.0.2",\n unified: "https://esm.sh/unified@11.0.5?dts",\n ai: "https://esm.sh/ai@5.0.76?deps=react@18.3.1,react-dom@18.3.1",\n "ai/react": "https://esm.sh/@ai-sdk/react@2.0.59?deps=react@18.3.1,react-dom@18.3.1",\n "@ai-sdk/react": "https://esm.sh/@ai-sdk/react@2.0.59?deps=react@18.3.1,react-dom@18.3.1",\n "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",\n "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.4",\n unocss: "https://esm.sh/unocss@0.59.0",\n "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",\n "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0",\n redis: "npm:redis"\n },\n compilerOptions: {\n jsx: "react-jsx",\n jsxImportSource: "react",\n strict: true,\n noImplicitAny: true,\n noUncheckedIndexedAccess: true,\n types: [],\n lib: [\n "deno.window",\n "dom",\n "dom.iterable",\n "dom.asynciterable",\n "deno.ns"\n ]\n },\n tasks: {\n setup: "deno run --allow-all scripts/setup.ts",\n dev: "deno run --allow-all --no-lock --unstable-net --unstable-worker-options src/cli/main.ts dev",\n build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",\n "build:npm": "deno run -A scripts/build-npm.ts",\n release: "deno run -A scripts/release.ts",\n test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",\n "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",\n "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",\n "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",\n "coverage:report": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --lcov > coverage/lcov.info && deno run --allow-read scripts/check-coverage.ts 80",\n "coverage:html": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --html",\n lint: "DENO_NO_PACKAGE_JSON=1 deno lint src/",\n fmt: "deno fmt src/",\n typecheck: "deno check src/index.ts src/cli/main.ts src/server/index.ts src/routing/api/index.ts src/rendering/index.ts src/platform/index.ts src/platform/adapters/index.ts src/build/index.ts src/build/production-build/index.ts src/build/transforms/index.ts src/core/config/index.ts src/core/utils/index.ts src/data/index.ts src/security/index.ts src/middleware/index.ts src/server/handlers/dev/index.ts src/server/handlers/request/api/index.ts src/rendering/cache/index.ts src/rendering/cache/stores/index.ts src/rendering/rsc/actions/index.ts src/html/index.ts src/module-system/index.ts",\n "docs:check-links": "deno run -A scripts/check-doc-links.ts",\n "lint:ban-console": "deno run --allow-read scripts/ban-console.ts",\n "lint:ban-deep-imports": "deno run --allow-read scripts/ban-deep-imports.ts",\n "lint:ban-internal-root-imports": "deno run --allow-read scripts/ban-internal-root-imports.ts",\n "lint:check-awaits": "deno run --allow-read scripts/check-unawaited-promises.ts",\n "lint:platform": "deno run --allow-read scripts/lint-platform-agnostic.ts",\n "check:circular": "deno run -A jsr:@cunarist/deno-circular-deps src/index.ts"\n },\n lint: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n rules: {\n tags: [\n "recommended"\n ],\n include: [\n "ban-untagged-todo"\n ],\n exclude: [\n "no-explicit-any",\n "no-process-global",\n "no-console"\n ]\n }\n },\n fmt: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n options: {\n useTabs: false,\n lineWidth: 100,\n indentWidth: 2,\n semiColons: true,\n singleQuote: false,\n proseWrap: "preserve"\n }\n }\n};\n\n// src/platform/compat/runtime.ts\nvar isDeno = typeof Deno !== "undefined";\nvar isNode = typeof globalThis.process !== "undefined" && globalThis.process?.versions?.node !== void 0;\nvar isBun = typeof globalThis.Bun !== "undefined";\nvar isCloudflare = typeof globalThis !== "undefined" && "caches" in globalThis && "WebSocketPair" in globalThis;\n\n// src/platform/compat/process.ts\nvar nodeProcess = globalThis.process;\nvar hasNodeProcess2 = !!nodeProcess?.versions?.node;\nfunction getEnv(key) {\n if (isDeno) {\n return Deno.env.get(key);\n }\n if (hasNodeProcess2) {\n return nodeProcess.env[key];\n }\n return void 0;\n}\n\n// src/core/utils/version.ts\nvar VERSION = getEnv("VERYFRONT_VERSION") || (typeof deno_default.version === "string" ? deno_default.version : "0.0.0");\n\n// src/core/utils/bundle-manifest.ts\nvar InMemoryBundleManifestStore = class {\n constructor() {\n this.metadata = /* @__PURE__ */ new Map();\n this.code = /* @__PURE__ */ new Map();\n this.sourceIndex = /* @__PURE__ */ new Map();\n }\n getBundleMetadata(key) {\n const entry = this.metadata.get(key);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleMetadata(key, metadata, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.metadata.set(key, { value: metadata, expiry });\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, /* @__PURE__ */ new Set());\n }\n this.sourceIndex.get(metadata.source).add(key);\n return Promise.resolve();\n }\n getBundleCode(hash) {\n const entry = this.code.get(hash);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleCode(hash, code, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n async deleteBundle(key) {\n const metadata = await this.getBundleMetadata(key);\n this.metadata.delete(key);\n if (metadata) {\n this.code.delete(metadata.codeHash);\n const sourceKeys = this.sourceIndex.get(metadata.source);\n if (sourceKeys) {\n sourceKeys.delete(key);\n if (sourceKeys.size === 0) {\n this.sourceIndex.delete(metadata.source);\n }\n }\n }\n }\n async invalidateSource(source) {\n const keys = this.sourceIndex.get(source);\n if (!keys)\n return 0;\n let count = 0;\n for (const key of Array.from(keys)) {\n await this.deleteBundle(key);\n count++;\n }\n this.sourceIndex.delete(source);\n return count;\n }\n clear() {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n isAvailable() {\n return Promise.resolve(true);\n }\n getStats() {\n let totalSize = 0;\n let oldest;\n let newest;\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest)\n oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest)\n newest = value.compiledAt;\n }\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest\n });\n }\n};\nvar manifestStore = new InMemoryBundleManifestStore();\n\n// src/rendering/client/prefetch.ts\nvar PrefetchManager = class {\n constructor(options = {}) {\n this.prefetchedUrls = /* @__PURE__ */ new Set();\n this.linkObserver = null;\n this.options = {\n rootMargin: options.rootMargin || "50px",\n delay: options.delay || PREFETCH_DEFAULT_DELAY_MS,\n maxConcurrent: options.maxConcurrent || 2,\n allowedNetworks: options.allowedNetworks || ["4g", "wifi", "ethernet"],\n maxSize: options.maxSize || PREFETCH_MAX_SIZE_BYTES,\n timeout: options.timeout || PREFETCH_DEFAULT_TIMEOUT_MS\n };\n this.networkUtils = new NetworkUtils(this.options.allowedNetworks);\n this.resourceHintsManager = new ResourceHintsManager();\n this.prefetchQueue = new PrefetchQueue(\n {\n maxConcurrent: this.options.maxConcurrent,\n maxSize: this.options.maxSize,\n timeout: this.options.timeout\n },\n this.prefetchedUrls\n );\n this.prefetchQueue.setResourceCallback(\n (response, url) => this.prefetchPageResources(response, url)\n );\n }\n init() {\n prefetchLogger.info("Initializing prefetch manager");\n if (!this.networkUtils.shouldPrefetch()) {\n prefetchLogger.info("Prefetching disabled due to network conditions");\n return;\n }\n this.linkObserver = new LinkObserver(\n {\n rootMargin: this.options.rootMargin,\n delay: this.options.delay,\n onLinkVisible: (link) => this.prefetchQueue.prefetchLink(link)\n },\n this.prefetchedUrls\n );\n this.linkObserver.init();\n this.networkUtils.onNetworkChange(() => {\n if (!this.networkUtils.shouldPrefetch()) {\n this.prefetchQueue.stopAll();\n }\n });\n }\n async prefetchPageResources(response, _pageUrl) {\n const html = await response.text();\n const hints = this.resourceHintsManager.extractResourceHints(html, this.prefetchedUrls);\n this.resourceHintsManager.applyResourceHints(hints);\n }\n applyResourceHints(hints) {\n this.resourceHintsManager.applyResourceHints(hints);\n }\n async prefetch(url) {\n await this.prefetchQueue.prefetch(url);\n }\n static generateResourceHints(route, assets) {\n return ResourceHintsManager.generateResourceHints(route, assets);\n }\n destroy() {\n this.linkObserver?.destroy();\n this.prefetchQueue.stopAll();\n this.prefetchedUrls.clear();\n }\n};\nif (typeof window !== "undefined") {\n const prefetchManager = new PrefetchManager();\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => prefetchManager.init());\n } else {\n prefetchManager.init();\n }\n globalThis.veryFrontPrefetch = prefetchManager;\n}\nexport {\n PrefetchManager\n};\n';
14808
14917
  }
14809
14918
  });
14810
14919
 
@@ -14931,22 +15040,18 @@ var init_hooks_adapter = __esm({
14931
15040
 
14932
15041
  // src/react/compat/ssr-adapter/server-loader.ts
14933
15042
  import * as React3 from "react";
14934
- function isNodeRuntime2() {
14935
- const g67 = globalThis;
14936
- return typeof Deno === "undefined" && typeof g67.process?.versions?.node !== "undefined";
14937
- }
14938
15043
  async function canResolveReactFromProject() {
14939
15044
  if (useProjectReact !== null) {
14940
15045
  return useProjectReact;
14941
15046
  }
14942
- if (!isNodeRuntime2()) {
15047
+ if (!isNode) {
14943
15048
  useProjectReact = false;
14944
15049
  return false;
14945
15050
  }
14946
15051
  try {
14947
15052
  const { createRequire: createRequire2 } = await import("node:module");
14948
15053
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
14949
- const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
15054
+ const projectRequire = createRequire2(pathToFileURL2(cwd() + "/").href);
14950
15055
  const reactPath = projectRequire.resolve("react");
14951
15056
  const reactDomPath = projectRequire.resolve("react-dom/server");
14952
15057
  rendererLogger.debug("Project has both react and react-dom", {
@@ -14973,7 +15078,7 @@ async function getProjectReact() {
14973
15078
  try {
14974
15079
  const { createRequire: createRequire2 } = await import("node:module");
14975
15080
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
14976
- const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
15081
+ const projectRequire = createRequire2(pathToFileURL2(cwd() + "/").href);
14977
15082
  const reactPath = projectRequire.resolve("react");
14978
15083
  rendererLogger.debug("Resolved react from project", { path: reactPath });
14979
15084
  const projectReact = await import(pathToFileURL2(reactPath).href);
@@ -14992,7 +15097,7 @@ async function importReactDOMServerFromProject() {
14992
15097
  try {
14993
15098
  const { createRequire: createRequire2 } = await import("node:module");
14994
15099
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
14995
- const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
15100
+ const projectRequire = createRequire2(pathToFileURL2(cwd() + "/").href);
14996
15101
  const reactDomServerPath = projectRequire.resolve("react-dom/server");
14997
15102
  rendererLogger.debug("Resolved react-dom/server from project", { path: reactDomServerPath });
14998
15103
  return await import(pathToFileURL2(reactDomServerPath).href);
@@ -15029,6 +15134,8 @@ var init_server_loader = __esm({
15029
15134
  "use strict";
15030
15135
  init_utils();
15031
15136
  init_version_detector();
15137
+ init_runtime();
15138
+ init_process();
15032
15139
  projectReactCache = null;
15033
15140
  useProjectReact = null;
15034
15141
  }
@@ -15066,7 +15173,7 @@ var init_string_renderer = __esm({
15066
15173
  // src/react/compat/ssr-adapter/stream-renderer.ts
15067
15174
  async function renderToReadableStreamImpl(element, options, server) {
15068
15175
  const debug = Boolean(
15069
- globalThis.__VERYFRONT_DEBUG__ || process.env?.VERYFRONT_DEBUG === "1"
15176
+ globalThis.__VERYFRONT_DEBUG__ || getEnv("VERYFRONT_DEBUG") === "1"
15070
15177
  );
15071
15178
  if (!server.renderToReadableStream) {
15072
15179
  throw toError(createError({
@@ -15126,7 +15233,7 @@ function renderToPipeableStreamImpl(element, options, server) {
15126
15233
  }));
15127
15234
  }
15128
15235
  const renderFn = server.renderToPipeableStream;
15129
- return new Promise((resolve5, reject) => {
15236
+ return new Promise((resolve6, reject) => {
15130
15237
  try {
15131
15238
  const { pipe, abort } = renderFn(element, {
15132
15239
  bootstrapScripts: options.bootstrapScripts,
@@ -15145,7 +15252,7 @@ function renderToPipeableStreamImpl(element, options, server) {
15145
15252
  onShellReady: () => {
15146
15253
  rendererLogger.debug("React pipeable stream: shell ready");
15147
15254
  options.onShellReady?.();
15148
- resolve5({ pipe, abort });
15255
+ resolve6({ pipe, abort });
15149
15256
  },
15150
15257
  onShellError: (error2) => {
15151
15258
  rendererLogger.error("React pipeable stream shell error", error2);
@@ -15171,7 +15278,7 @@ function renderToPipeableStreamImpl(element, options, server) {
15171
15278
  }
15172
15279
  async function renderToStreamAdapter(element, options = {}) {
15173
15280
  const debug = Boolean(
15174
- globalThis.__VERYFRONT_DEBUG__ || process.env?.VERYFRONT_DEBUG === "1"
15281
+ globalThis.__VERYFRONT_DEBUG__ || getEnv("VERYFRONT_DEBUG") === "1"
15175
15282
  );
15176
15283
  const versionInfo = getReactVersionInfo();
15177
15284
  const server = await getReactDOMServer();
@@ -15203,6 +15310,7 @@ var init_stream_renderer = __esm({
15203
15310
  init_server_loader();
15204
15311
  init_string_renderer();
15205
15312
  init_veryfront_error();
15313
+ init_process();
15206
15314
  }
15207
15315
  });
15208
15316
 
@@ -15553,9 +15661,9 @@ async function loadModuleESM(compiledProgramCode, context2) {
15553
15661
  const { getAdapter: getAdapter2 } = await Promise.resolve().then(() => (init_detect(), detect_exports));
15554
15662
  const adapter = await getAdapter2();
15555
15663
  if (!context2.esmCacheDir) {
15556
- if (IS_NODE) {
15664
+ if (isNode) {
15557
15665
  const projectCacheDir = join2(
15558
- _global.process.cwd(),
15666
+ cwd(),
15559
15667
  "node_modules",
15560
15668
  ".cache",
15561
15669
  "veryfront-mdx"
@@ -15567,7 +15675,7 @@ async function loadModuleESM(compiledProgramCode, context2) {
15567
15675
  }
15568
15676
  }
15569
15677
  let rewritten;
15570
- if (IS_NODE) {
15678
+ if (isNode) {
15571
15679
  rewritten = compiledProgramCode;
15572
15680
  } else {
15573
15681
  rewritten = transformImportsWithMap(
@@ -15622,7 +15730,7 @@ ${transformed}`;
15622
15730
  if (/\bconst\s+MDXLayout\b/.test(rewritten) && !/export\s+\{[^}]*MDXLayout/.test(rewritten)) {
15623
15731
  rewritten += "\nexport { MDXLayout as __vfLayout };\n";
15624
15732
  }
15625
- if (IS_NODE && HTTP_IMPORT_PATTERN.test(rewritten)) {
15733
+ if (isNode && HTTP_IMPORT_PATTERN.test(rewritten)) {
15626
15734
  rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Bundling HTTP imports via esbuild for Node.js`);
15627
15735
  const { build: build3 } = await import("esbuild");
15628
15736
  const tempSourcePath = join2(context2.esmCacheDir, `temp-${hashString(rewritten)}.mjs`);
@@ -15710,7 +15818,7 @@ ${transformed}`;
15710
15818
  throw error2;
15711
15819
  }
15712
15820
  }
15713
- var _global, IS_NODE, LOG_PREFIX_MDX_LOADER, LOG_PREFIX_MDX_RENDERER, JSX_IMPORT_PATTERN, REACT_IMPORT_PATTERN, HTTP_IMPORT_PATTERN, ESBUILD_JSX_FACTORY, ESBUILD_JSX_FRAGMENT, HTTP_MODULE_FETCH_TIMEOUT_MS2;
15821
+ var LOG_PREFIX_MDX_LOADER, LOG_PREFIX_MDX_RENDERER, JSX_IMPORT_PATTERN, REACT_IMPORT_PATTERN, HTTP_IMPORT_PATTERN, ESBUILD_JSX_FACTORY, ESBUILD_JSX_FRAGMENT, HTTP_MODULE_FETCH_TIMEOUT_MS2;
15714
15822
  var init_esm_module_loader = __esm({
15715
15823
  "src/build/transforms/mdx/esm-module-loader.ts"() {
15716
15824
  "use strict";
@@ -15718,8 +15826,8 @@ var init_esm_module_loader = __esm({
15718
15826
  init_namespace();
15719
15827
  init_import_map();
15720
15828
  init_std_path();
15721
- _global = globalThis;
15722
- IS_NODE = typeof Deno === "undefined" && typeof _global.process !== "undefined" && _global.process?.versions?.node;
15829
+ init_runtime();
15830
+ init_process();
15723
15831
  LOG_PREFIX_MDX_LOADER = "[mdx-loader]";
15724
15832
  LOG_PREFIX_MDX_RENDERER = "[mdx-renderer]";
15725
15833
  JSX_IMPORT_PATTERN = /import\s+([^'"]+)\s+from\s+['"]file:\/\/([^'"]+\.(jsx|tsx))['"];?/g;
@@ -16393,9 +16501,9 @@ var init_transform_utils = __esm({
16393
16501
  });
16394
16502
 
16395
16503
  // ../../../../node_modules/es-module-lexer/dist/lexer.js
16396
- function parse4(E56, g67 = "@") {
16504
+ function parse5(E56, g67 = "@") {
16397
16505
  if (!C)
16398
- return init.then(() => parse4(E56));
16506
+ return init.then(() => parse5(E56));
16399
16507
  const I56 = E56.length + 1, w62 = (C.__heap_base.value || C.__heap_base) + 4 * I56 - C.memory.buffer.byteLength;
16400
16508
  w62 > 0 && C.memory.grow(Math.ceil(w62 / 65536));
16401
16509
  const o45 = C.sa(I56 - 1);
@@ -16456,7 +16564,7 @@ async function initLexer() {
16456
16564
  }
16457
16565
  async function parseImports(code) {
16458
16566
  await initLexer();
16459
- return parse4(code)[0];
16567
+ return parse5(code)[0];
16460
16568
  }
16461
16569
  async function replaceSpecifiers(code, replacer) {
16462
16570
  const imports = await parseImports(code);
@@ -16503,22 +16611,18 @@ var init_lexer2 = __esm({
16503
16611
  });
16504
16612
 
16505
16613
  // src/build/transforms/esm/react-imports.ts
16506
- function isNodeRuntime3() {
16507
- const _global2 = globalThis;
16508
- return typeof Deno === "undefined" && typeof _global2.process !== "undefined" && !!_global2.process?.versions?.node;
16509
- }
16510
16614
  async function checkProjectHasReactDom() {
16511
16615
  if (projectHasReactDom !== null) {
16512
16616
  return projectHasReactDom;
16513
16617
  }
16514
- if (!isNodeRuntime3()) {
16618
+ if (!isNodeRuntime()) {
16515
16619
  projectHasReactDom = false;
16516
16620
  return false;
16517
16621
  }
16518
16622
  try {
16519
16623
  const { createRequire: createRequire2 } = await import("node:module");
16520
16624
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
16521
- const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
16625
+ const projectRequire = createRequire2(pathToFileURL2(cwd() + "/").href);
16522
16626
  projectRequire.resolve("react");
16523
16627
  projectRequire.resolve("react-dom/server");
16524
16628
  projectHasReactDom = true;
@@ -16529,7 +16633,7 @@ async function checkProjectHasReactDom() {
16529
16633
  }
16530
16634
  }
16531
16635
  async function getBundledReactPath(subpath = "") {
16532
- if (!isNodeRuntime3()) {
16636
+ if (!isNodeRuntime()) {
16533
16637
  return null;
16534
16638
  }
16535
16639
  try {
@@ -16542,13 +16646,14 @@ async function getBundledReactPath(subpath = "") {
16542
16646
  }
16543
16647
  }
16544
16648
  async function resolveReactImports(code, forSSR = false) {
16545
- if (isNodeRuntime3() && forSSR) {
16649
+ const isNode2 = isNodeRuntime();
16650
+ if (isNode2 && forSSR) {
16546
16651
  const hasReactDom = await checkProjectHasReactDom();
16547
16652
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
16548
16653
  if (hasReactDom) {
16549
16654
  try {
16550
16655
  const { createRequire: createRequire2 } = await import("node:module");
16551
- const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
16656
+ const projectRequire = createRequire2(pathToFileURL2(cwd() + "/").href);
16552
16657
  const projectImports = {
16553
16658
  "react/jsx-runtime": pathToFileURL2(projectRequire.resolve("react/jsx-runtime")).href,
16554
16659
  "react/jsx-dev-runtime": pathToFileURL2(projectRequire.resolve("react/jsx-dev-runtime")).href,
@@ -16575,7 +16680,7 @@ async function resolveReactImports(code, forSSR = false) {
16575
16680
  }
16576
16681
  return code;
16577
16682
  }
16578
- if (isNodeRuntime3()) {
16683
+ if (isNode2) {
16579
16684
  return code;
16580
16685
  }
16581
16686
  const reactImports = {
@@ -16591,7 +16696,7 @@ async function resolveReactImports(code, forSSR = false) {
16591
16696
  });
16592
16697
  }
16593
16698
  function addDepsToEsmShUrls(code) {
16594
- if (isNodeRuntime3()) {
16699
+ if (isNodeRuntime()) {
16595
16700
  return Promise.resolve(code);
16596
16701
  }
16597
16702
  return Promise.resolve(replaceSpecifiers(code, (specifier) => {
@@ -16607,6 +16712,8 @@ var init_react_imports = __esm({
16607
16712
  "use strict";
16608
16713
  init_lexer2();
16609
16714
  init_cdn();
16715
+ init_runtime();
16716
+ init_process();
16610
16717
  projectHasReactDom = null;
16611
16718
  }
16612
16719
  });
@@ -35254,7 +35361,7 @@ async function transformToESM(source, filePath, projectDir, _adapter, options) {
35254
35361
  code = await addDepsToEsmShUrls(code);
35255
35362
  code = await resolvePathAliases(code, filePath, projectDir);
35256
35363
  if (ssr) {
35257
- if (isNodeRuntime3()) {
35364
+ if (isNode) {
35258
35365
  code = await resolveVeryfrontImports(code);
35259
35366
  code = await resolveRelativeImportsForNodeSSR(code);
35260
35367
  } else {
@@ -35276,6 +35383,7 @@ var init_transform_core = __esm({
35276
35383
  init_transform_cache();
35277
35384
  init_transform_utils();
35278
35385
  init_react_imports();
35386
+ init_runtime();
35279
35387
  init_path_resolver();
35280
35388
  init_import_rewriter();
35281
35389
  init_mdx_compiler();
@@ -35342,14 +35450,10 @@ var component_loader_exports = {};
35342
35450
  __export(component_loader_exports, {
35343
35451
  loadComponentFromSource: () => loadComponentFromSource
35344
35452
  });
35345
- function isNodeRuntime4() {
35346
- const _global2 = globalThis;
35347
- return typeof Deno === "undefined" && typeof _global2.process !== "undefined" && !!_global2.process?.versions?.node;
35348
- }
35349
35453
  async function loadComponentFromSource(source, filePath, projectDir, adapter, options) {
35350
35454
  const projectId = options?.projectId || projectDir;
35351
35455
  const dev = options?.dev ?? true;
35352
- const isNode2 = isNodeRuntime4();
35456
+ const isNode2 = isNodeRuntime();
35353
35457
  const ssr = isNode2 ? true : options?.ssr ?? false;
35354
35458
  const moduleServerUrl = isNode2 ? void 0 : options?.moduleServerUrl ?? "/_vf_modules";
35355
35459
  const vendorBundleHash = isNode2 ? void 0 : options?.vendorBundleHash;
@@ -35405,12 +35509,14 @@ function extractComponent(mod, filePath) {
35405
35509
  }
35406
35510
  var init_component_loader = __esm({
35407
35511
  "src/module-system/react-loader/component-loader.ts"() {
35512
+ "use strict";
35408
35513
  init_std_path();
35409
35514
  init_transform_core();
35410
35515
  init_temp_directory();
35411
35516
  init_path_resolver2();
35412
35517
  init_veryfront_error();
35413
35518
  init_fs();
35519
+ init_runtime();
35414
35520
  }
35415
35521
  });
35416
35522
 
@@ -39722,9 +39828,9 @@ async function resolveExistingFiles(candidates, adapter) {
39722
39828
  }
39723
39829
  return existing;
39724
39830
  }
39725
- function addLayoutsFromFiles(files, nestedLayouts, extname5) {
39831
+ function addLayoutsFromFiles(files, nestedLayouts, extname6) {
39726
39832
  for (const file of files) {
39727
- const ext = extname5(file).toLowerCase();
39833
+ const ext = extname6(file).toLowerCase();
39728
39834
  if (ext === ".mdx") {
39729
39835
  nestedLayouts.push({ kind: "mdx", path: file });
39730
39836
  } else if (ext === ".tsx" || ext === ".jsx") {
@@ -39738,11 +39844,11 @@ function addLayoutsFromFiles(files, nestedLayouts, extname5) {
39738
39844
  }
39739
39845
  }
39740
39846
  }
39741
- async function addMissedAncestorLayouts(pageFilePath, rootDir, existing, nestedLayouts, adapter, pathJoin, dirname7) {
39847
+ async function addMissedAncestorLayouts(pageFilePath, rootDir, existing, nestedLayouts, adapter, pathJoin, dirname8) {
39742
39848
  try {
39743
39849
  const included = new Set(existing);
39744
39850
  const candidates = [];
39745
- let dir = dirname7(pageFilePath);
39851
+ let dir = dirname8(pageFilePath);
39746
39852
  while (dir.startsWith(rootDir)) {
39747
39853
  const tsx = pathJoin(dir, "layout.tsx");
39748
39854
  const jsx10 = pathJoin(dir, "layout.jsx");
@@ -39750,7 +39856,7 @@ async function addMissedAncestorLayouts(pageFilePath, rootDir, existing, nestedL
39750
39856
  candidates.push(tsx);
39751
39857
  if (!included.has(jsx10))
39752
39858
  candidates.push(jsx10);
39753
- const parent = dirname7(dir);
39859
+ const parent = dirname8(dir);
39754
39860
  if (parent === dir)
39755
39861
  break;
39756
39862
  dir = parent;
@@ -39995,6 +40101,7 @@ function extractParams(pattern, slug) {
39995
40101
  }
39996
40102
  var init_dynamic_route_matcher = __esm({
39997
40103
  "src/routing/slug-mapper/dynamic-route-matcher.ts"() {
40104
+ "use strict";
39998
40105
  }
39999
40106
  });
40000
40107
 
@@ -40834,11 +40941,11 @@ __export(app_reserved_exports, {
40834
40941
  });
40835
40942
  import * as BundledReact from "react";
40836
40943
  function collectAncestorDirs(segmentDir, appRootDir) {
40837
- const normalize3 = (p70) => p70.replace(/\\+/g, "/").replace(/\/\.+\//g, "/");
40838
- const getDirname = (p70) => normalize3(p70).replace(/\/?[^/]+\/?$/, "");
40944
+ const normalize4 = (p70) => p70.replace(/\\+/g, "/").replace(/\/\.+\//g, "/");
40945
+ const getDirname = (p70) => normalize4(p70).replace(/\/?[^/]+\/?$/, "");
40839
40946
  const dirs = [];
40840
- let current = normalize3(segmentDir);
40841
- const root = normalize3(appRootDir);
40947
+ let current = normalize4(segmentDir);
40948
+ const root = normalize4(appRootDir);
40842
40949
  while (current.startsWith(root)) {
40843
40950
  dirs.push(current);
40844
40951
  const parent = getDirname(current) || "/";
@@ -40873,11 +40980,11 @@ function createErrorBoundary(ErrorComponent, React11 = BundledReact) {
40873
40980
  };
40874
40981
  }
40875
40982
  async function tryLoadReservedInDirs(dirs, which, projectDir, _mode, adapter) {
40876
- const join13 = (a56, b70) => `${a56.replace(/\/$/, "")}/${b70.replace(/^\//, "")}`;
40983
+ const join14 = (a56, b70) => `${a56.replace(/\/$/, "")}/${b70.replace(/^\//, "")}`;
40877
40984
  const candidateName = RESERVED_COMPONENTS[which];
40878
40985
  for (const dir of dirs) {
40879
40986
  for (const ext of [".tsx", ".jsx"]) {
40880
- const file = join13(dir, candidateName.replace(/\.tsx$/, ext));
40987
+ const file = join14(dir, candidateName.replace(/\.tsx$/, ext));
40881
40988
  try {
40882
40989
  const src = await adapter.fs.readFile(file);
40883
40990
  const { loadComponentFromSource: loadComponentFromSource2 } = await Promise.resolve().then(() => (init_component_loader(), component_loader_exports));
@@ -47168,14 +47275,14 @@ var init_element_validator = __esm({
47168
47275
  async function pipeToString(pipeFn) {
47169
47276
  const { PassThrough } = await import("node:stream");
47170
47277
  const { Buffer: Buffer2 } = await import("node:buffer");
47171
- return new Promise((resolve5, reject) => {
47278
+ return new Promise((resolve6, reject) => {
47172
47279
  const chunks = [];
47173
47280
  const passThrough = new PassThrough();
47174
47281
  passThrough.on("data", (chunk) => {
47175
47282
  chunks.push(chunk);
47176
47283
  });
47177
47284
  passThrough.on("end", () => {
47178
- resolve5(Buffer2.concat(chunks).toString("utf-8"));
47285
+ resolve6(Buffer2.concat(chunks).toString("utf-8"));
47179
47286
  });
47180
47287
  passThrough.on("error", (err) => {
47181
47288
  reject(err);
@@ -47808,7 +47915,7 @@ function isLruIntervalDisabled3() {
47808
47915
  return true;
47809
47916
  }
47810
47917
  try {
47811
- return process.env.VF_DISABLE_LRU_INTERVAL === "1";
47918
+ return getEnv("VF_DISABLE_LRU_INTERVAL") === "1";
47812
47919
  } catch {
47813
47920
  return false;
47814
47921
  }
@@ -47819,6 +47926,7 @@ var init_data_fetching_cache = __esm({
47819
47926
  "use strict";
47820
47927
  init_lru_wrapper();
47821
47928
  init_cache();
47929
+ init_process();
47822
47930
  CacheManager = class {
47823
47931
  constructor() {
47824
47932
  this.cache = new LRUCache({
@@ -49340,8 +49448,8 @@ async function compileMDXToJS(mdxPath, mdxContent, options) {
49340
49448
  const _match = mdxContent.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
49341
49449
  if (_match && _match[1]) {
49342
49450
  try {
49343
- const { parse: parse5 } = await import("yaml");
49344
- const parsed = parse5(_match[1]);
49451
+ const { parse: parse6 } = await import("yaml");
49452
+ const parsed = parse6(_match[1]);
49345
49453
  frontmatter = parsed && typeof parsed === "object" ? parsed : {};
49346
49454
  if (!_match[2]) {
49347
49455
  throw toError(createError({
@@ -50098,8 +50206,8 @@ async function parseManually(content) {
50098
50206
  return null;
50099
50207
  }
50100
50208
  try {
50101
- const { parse: parse5 } = await import("yaml");
50102
- const parsed = parse5(match[1]);
50209
+ const { parse: parse6 } = await import("yaml");
50210
+ const parsed = parse6(match[1]);
50103
50211
  const frontmatter = parsed && typeof parsed === "object" ? parsed : {};
50104
50212
  if (!match[2]) {
50105
50213
  throw toError(createError({
@@ -97162,8 +97270,8 @@ var init_image_finder = __esm({
97162
97270
  });
97163
97271
 
97164
97272
  // src/build/asset-pipeline/image-optimizer/format-processor.ts
97165
- function processFormat(image, format3, quality) {
97166
- return FORMAT_PROCESSORS[format3].process(image, quality);
97273
+ function processFormat(image, format4, quality) {
97274
+ return FORMAT_PROCESSORS[format4].process(image, quality);
97167
97275
  }
97168
97276
  var WebpProcessor, AvifProcessor, JpegProcessor, PngProcessor, FORMAT_PROCESSORS;
97169
97277
  var init_format_processor = __esm({
@@ -97199,13 +97307,13 @@ var init_format_processor = __esm({
97199
97307
  });
97200
97308
 
97201
97309
  // src/build/utils/asset-utils.ts
97202
- function getVariantPath(outputDir, relPath, format3, size) {
97310
+ function getVariantPath(outputDir, relPath, format4, size) {
97203
97311
  const dir = dirname2(relPath);
97204
97312
  const name = basename2(relPath, extname2(relPath));
97205
- return join2(outputDir, dir, `${name}-${size}w.${format3}`);
97313
+ return join2(outputDir, dir, `${name}-${size}w.${format4}`);
97206
97314
  }
97207
- function generateSrcSet2(_imagePath, metadata, outputDir, format3) {
97208
- const targetFormat = format3 || metadata.defaultFormat;
97315
+ function generateSrcSet2(_imagePath, metadata, outputDir, format4) {
97316
+ const targetFormat = format4 || metadata.defaultFormat;
97209
97317
  const variants = metadata.variants.filter((v62) => v62.format === targetFormat);
97210
97318
  return variants.map((v62) => `/${join2(outputDir, v62.path)} ${v62.width}w`).join(", ");
97211
97319
  }
@@ -97224,21 +97332,21 @@ var init_asset_utils = __esm({
97224
97332
  });
97225
97333
 
97226
97334
  // src/build/asset-pipeline/image-optimizer/variant-generator.ts
97227
- async function generateVariant(sharp, image, relPath, format3, width, metadata, quality, outputDir) {
97335
+ async function generateVariant(sharp, image, relPath, format4, width, metadata, quality, outputDir) {
97228
97336
  const fs15 = createFileSystem();
97229
97337
  try {
97230
- const outputPath = getVariantPath(outputDir, relPath, format3, width);
97338
+ const outputPath = getVariantPath(outputDir, relPath, format4, width);
97231
97339
  await fs15.mkdir(dirname2(outputPath), { recursive: true });
97232
97340
  const processor = image.clone().resize(width, null, {
97233
97341
  fit: "inside",
97234
97342
  withoutEnlargement: true
97235
97343
  });
97236
- const formattedProcessor = processFormat(processor, format3, quality);
97344
+ const formattedProcessor = processFormat(processor, format4, quality);
97237
97345
  const buffer = await formattedProcessor.toBuffer();
97238
97346
  await fs15.writeFile(outputPath, buffer);
97239
97347
  const processedMetadata = await sharp(buffer).metadata();
97240
97348
  return {
97241
- format: format3,
97349
+ format: format4,
97242
97350
  size: width,
97243
97351
  width: processedMetadata.width || width,
97244
97352
  height: processedMetadata.height || Math.round(
@@ -97248,7 +97356,7 @@ async function generateVariant(sharp, image, relPath, format3, width, metadata,
97248
97356
  fileSize: buffer.length
97249
97357
  };
97250
97358
  } catch (error2) {
97251
- logger.error(`Failed to generate ${format3} variant at ${width}px`, {
97359
+ logger.error(`Failed to generate ${format4} variant at ${width}px`, {
97252
97360
  error: error2 instanceof Error ? error2.message : String(error2)
97253
97361
  });
97254
97362
  return null;
@@ -97260,12 +97368,12 @@ async function generateImageVariants(sharp, image, relPath, metadata, formats, s
97260
97368
  if (metadata.width && metadata.width < size) {
97261
97369
  continue;
97262
97370
  }
97263
- for (const format3 of formats) {
97371
+ for (const format4 of formats) {
97264
97372
  const variant = await generateVariant(
97265
97373
  sharp,
97266
97374
  image,
97267
97375
  relPath,
97268
- format3,
97376
+ format4,
97269
97377
  size,
97270
97378
  metadata,
97271
97379
  quality,
@@ -97276,12 +97384,12 @@ async function generateImageVariants(sharp, image, relPath, metadata, formats, s
97276
97384
  }
97277
97385
  }
97278
97386
  }
97279
- for (const format3 of formats) {
97387
+ for (const format4 of formats) {
97280
97388
  const variant = await generateVariant(
97281
97389
  sharp,
97282
97390
  image,
97283
97391
  relPath,
97284
- format3,
97392
+ format4,
97285
97393
  metadata.width || 1920,
97286
97394
  metadata,
97287
97395
  quality,
@@ -97430,12 +97538,12 @@ var init_optimizer_core = __esm({
97430
97538
  getImageMetadata(imagePath) {
97431
97539
  return this.imageManifest.get(imagePath) || null;
97432
97540
  }
97433
- generateSrcSet(imagePath, format3) {
97541
+ generateSrcSet(imagePath, format4) {
97434
97542
  const metadata = this.imageManifest.get(imagePath);
97435
97543
  if (!metadata) {
97436
97544
  return "";
97437
97545
  }
97438
- return generateSrcSet2(imagePath, metadata, this.options.outputDir, format3);
97546
+ return generateSrcSet2(imagePath, metadata, this.options.outputDir, format4);
97439
97547
  }
97440
97548
  getTotalVariants() {
97441
97549
  return Array.from(this.imageManifest.values()).reduce(
@@ -98315,7 +98423,7 @@ async function isNotFoundError2(error2, path) {
98315
98423
  if (error2.code === "ENOENT") {
98316
98424
  return true;
98317
98425
  }
98318
- if (typeof Deno !== "undefined" && error2 instanceof Deno.errors.NotFound) {
98426
+ if (isDeno && error2 instanceof Deno.errors.NotFound) {
98319
98427
  return true;
98320
98428
  }
98321
98429
  }
@@ -98438,6 +98546,7 @@ var init_env_loader = __esm({
98438
98546
  init_utils();
98439
98547
  init_process();
98440
98548
  init_fs();
98549
+ init_runtime();
98441
98550
  _fs = null;
98442
98551
  }
98443
98552
  });
@@ -98947,7 +99056,7 @@ async function closeAllConnections(clients, rateLimiter) {
98947
99056
  }
98948
99057
  for (let i48 = 0; i48 < 10; i48++) {
98949
99058
  await Promise.resolve();
98950
- await new Promise((resolve5) => setTimeout(resolve5, 50));
99059
+ await new Promise((resolve6) => setTimeout(resolve6, 50));
98951
99060
  }
98952
99061
  for (const client of clients) {
98953
99062
  rateLimiter.cleanup(client);
@@ -100375,6 +100484,7 @@ var init_metrics3 = __esm({
100375
100484
  init_simple_metrics();
100376
100485
  init_security2();
100377
100486
  init_constants4();
100487
+ init_process();
100378
100488
  MetricsHandler = class extends BaseHandler {
100379
100489
  constructor() {
100380
100490
  super(...arguments);
@@ -100395,41 +100505,24 @@ var init_metrics3 = __esm({
100395
100505
  }
100396
100506
  try {
100397
100507
  const snap = metrics.snapshot();
100398
- const global = globalThis;
100399
- const D50 = global.Deno;
100400
- const P49 = global.process;
100401
100508
  const memory = (() => {
100402
100509
  try {
100403
- if (D50?.memoryUsage)
100404
- return D50.memoryUsage();
100405
- } catch (err) {
100406
- this.logDebug("Failed to get Deno memory usage", { error: err }, ctx);
100407
- }
100408
- try {
100409
- if (P49?.memoryUsage)
100410
- return P49.memoryUsage();
100510
+ return memoryUsage();
100411
100511
  } catch (err) {
100412
- this.logDebug("Failed to get process memory usage", { error: err }, ctx);
100512
+ this.logDebug("Failed to get memory usage", { error: err }, ctx);
100513
+ return void 0;
100413
100514
  }
100414
- return void 0;
100415
100515
  })();
100416
- const uptime = (() => {
100417
- try {
100418
- if (D50?.osUptime)
100419
- return D50.osUptime();
100420
- } catch (err) {
100421
- this.logDebug("Failed to get Deno uptime", { error: err }, ctx);
100422
- }
100516
+ const uptimeValue = (() => {
100423
100517
  try {
100424
- if (P49?.uptime)
100425
- return P49.uptime();
100518
+ return uptime();
100426
100519
  } catch (err) {
100427
- this.logDebug("Failed to get process uptime", { error: err }, ctx);
100520
+ this.logDebug("Failed to get uptime", { error: err }, ctx);
100521
+ return void 0;
100428
100522
  }
100429
- return void 0;
100430
100523
  })();
100431
100524
  const response = ResponseBuilder.json(
100432
- { counters: snap, memory, uptime },
100525
+ { counters: snap, memory, uptime: uptimeValue },
100433
100526
  req,
100434
100527
  {
100435
100528
  securityConfig: ctx.securityConfig ?? void 0,
@@ -102315,12 +102408,7 @@ var init_component_resolver = __esm({
102315
102408
  // src/server/handlers/request/rsc/handlers/environment.ts
102316
102409
  function isProductionMode2() {
102317
102410
  try {
102318
- if (typeof Deno !== "undefined" && hasDenoRuntime(globalThis)) {
102319
- return globalThis.Deno?.env.get("DENO_ENV") === "production";
102320
- }
102321
- if (typeof process !== "undefined" && process.env) {
102322
- return process.env.DENO_ENV === "production";
102323
- }
102411
+ return getEnv("DENO_ENV") === "production" || getEnv("NODE_ENV") === "production";
102324
102412
  } catch {
102325
102413
  }
102326
102414
  return false;
@@ -102328,7 +102416,7 @@ function isProductionMode2() {
102328
102416
  var init_environment2 = __esm({
102329
102417
  "src/server/handlers/request/rsc/handlers/environment.ts"() {
102330
102418
  "use strict";
102331
- init_runtime_guards();
102419
+ init_process();
102332
102420
  }
102333
102421
  });
102334
102422
 
@@ -102447,7 +102535,7 @@ var init_render_handler = __esm({
102447
102535
 
102448
102536
  // src/server/handlers/request/rsc/handlers/stream-handler.ts
102449
102537
  function sleep(ms) {
102450
- return new Promise((resolve5) => setTimeout(resolve5, ms));
102538
+ return new Promise((resolve6) => setTimeout(resolve6, ms));
102451
102539
  }
102452
102540
  function streamSlot(controller, encoder, slot) {
102453
102541
  controller.enqueue(encoder.encode(`${JSON.stringify(slot)}
@@ -102857,6 +102945,12 @@ async function handleRSCEndpoint({ req, pathname, projectDir, adapter, config })
102857
102945
  if (sub === "dom.js") {
102858
102946
  return handleDomScript(adapter);
102859
102947
  }
102948
+ if (sub === "flight_page") {
102949
+ return new Response(
102950
+ "Flight endpoint removed. Use custom RSC endpoints.",
102951
+ { status: 410 }
102952
+ );
102953
+ }
102860
102954
  if (!isRSCEnabled(config)) {
102861
102955
  return null;
102862
102956
  }
@@ -102924,11 +103018,6 @@ async function handleRSCEndpoint({ req, pathname, projectDir, adapter, config })
102924
103018
  case "stream":
102925
103019
  metrics.recordRSC("stream");
102926
103020
  return handleStreamEndpoint(url.searchParams);
102927
- case "flight_page":
102928
- return new Response(
102929
- "Flight endpoint removed. Use custom RSC endpoints.",
102930
- { status: 410 }
102931
- );
102932
103021
  default:
102933
103022
  if (sub.startsWith("render/")) {
102934
103023
  const componentPath = sub.replace("render/", "");
@@ -103218,7 +103307,8 @@ var init_rsc = __esm({
103218
103307
  }
103219
103308
  const sub = pathname.replace("/_veryfront/rsc/", "");
103220
103309
  const isHydrationScript = sub === "client.js" || sub === "dom.js";
103221
- if (!isRSCEnabled(ctx.config) && !isHydrationScript) {
103310
+ const isDeprecatedEndpoint = sub === "flight_page";
103311
+ if (!isRSCEnabled(ctx.config) && !isHydrationScript && !isDeprecatedEndpoint) {
103222
103312
  return this.respond(new Response("Not Found", { status: HTTP_NOT_FOUND }));
103223
103313
  }
103224
103314
  const res = await handleRSCEndpoint({
@@ -103738,8 +103828,8 @@ var init_etag_handler = __esm({
103738
103828
  // src/server/handlers/request/ssr/not-found-fallback.ts
103739
103829
  async function tryNotFoundFallback(req, slug, ctx, builder) {
103740
103830
  try {
103741
- const isDeno3 = "name" in ctx.adapter && ctx.adapter.name === "deno";
103742
- if (!isDeno3)
103831
+ const isDeno4 = "name" in ctx.adapter && ctx.adapter.name === "deno";
103832
+ if (!isDeno4)
103743
103833
  return null;
103744
103834
  const appRoot = join2(ctx.projectDir, "app");
103745
103835
  try {
@@ -104870,8 +104960,8 @@ var init_server3 = __esm({
104870
104960
  constructor(options) {
104871
104961
  this.options = options;
104872
104962
  this._isReady = false;
104873
- this.ready = new Promise((resolve5) => {
104874
- this._resolveReady = resolve5;
104963
+ this.ready = new Promise((resolve6) => {
104964
+ this._resolveReady = resolve6;
104875
104965
  });
104876
104966
  this.router = new DynamicRouter();
104877
104967
  this.pipeline = new MiddlewarePipeline();
@@ -105038,7 +105128,7 @@ async function startUniversalServer(options) {
105038
105128
  mode
105039
105129
  });
105040
105130
  let onListenResolve = null;
105041
- const listenReady = new Promise((resolve5) => onListenResolve = resolve5);
105131
+ const listenReady = new Promise((resolve6) => onListenResolve = resolve6);
105042
105132
  const ready = Promise.all([
105043
105133
  listenReady,
105044
105134
  handler.ready ?? Promise.resolve()
@@ -105074,12 +105164,12 @@ var init_production_server = __esm({
105074
105164
  init_detect();
105075
105165
  await init_universal_handler();
105076
105166
  init_bootstrap();
105167
+ init_process();
105077
105168
  if (import.meta.main) {
105078
105169
  try {
105079
- const { cwd: cwd2 } = await import("../runtime/compat/process.ts");
105080
105170
  const adapter = await getAdapter();
105081
105171
  const shutdownController = new AbortController();
105082
- const projectDir = cwd2();
105172
+ const projectDir = cwd();
105083
105173
  const port = Number(
105084
105174
  adapter.env.get("PORT") ?? adapter.env.get("VERYFRONT_PORT") ?? 3e3
105085
105175
  );
@@ -105106,18 +105196,8 @@ var init_production_server = __esm({
105106
105196
  serverLogger.warn("Error while shutting down production server:", error2);
105107
105197
  }
105108
105198
  };
105109
- const signals = ["SIGINT", "SIGTERM"];
105110
- for (const signal of signals) {
105111
- if (typeof Deno !== "undefined" && "addSignalListener" in Deno) {
105112
- Deno.addSignalListener(signal, () => {
105113
- void shutdown(signal);
105114
- });
105115
- } else if (typeof process !== "undefined" && typeof process.on === "function") {
105116
- process.on(signal, () => {
105117
- void shutdown(signal);
105118
- });
105119
- }
105120
- }
105199
+ onSignal("SIGINT", () => void shutdown("SIGINT"));
105200
+ onSignal("SIGTERM", () => void shutdown("SIGTERM"));
105121
105201
  } catch (e25) {
105122
105202
  serverLogger.error("Failed to start production server:", e25);
105123
105203
  }
@@ -105935,7 +106015,7 @@ async function createPackageJson(projectDir, projectName) {
105935
106015
  dependencies: {
105936
106016
  react: "^19.0.0",
105937
106017
  "react-dom": "^19.0.0",
105938
- veryfront: "^0.0.31",
106018
+ veryfront: "^0.0.33",
105939
106019
  zod: "^3.24.0"
105940
106020
  }
105941
106021
  };
@@ -106134,34 +106214,67 @@ async function createRscDemoSample(projectDir) {
106134
106214
  init_process();
106135
106215
  init_fs();
106136
106216
 
106217
+ // src/platform/compat/path/runtime.ts
106218
+ var globalProcess = globalThis.process;
106219
+ var hasNodeApis = !!globalProcess?.versions?.node || "Bun" in globalThis;
106220
+ var isDeno3 = typeof Deno !== "undefined";
106221
+ var nodePath4 = null;
106222
+ if (hasNodeApis) {
106223
+ nodePath4 = await import("node:path");
106224
+ }
106225
+ var sep4 = nodePath4 ? nodePath4.sep : "/";
106226
+ var delimiter3 = nodePath4 ? nodePath4.delimiter : ":";
106227
+ var hasNodePath = nodePath4 !== null;
106228
+
106229
+ // src/platform/compat/path/basic-operations.ts
106230
+ function join6(...paths) {
106231
+ if (!isDeno3 && hasNodePath) {
106232
+ return nodePath4.join(...paths);
106233
+ }
106234
+ return paths.filter((p70) => p70.length > 0).join("/").replace(/\/+/g, "/").replace(/\/$/, "") || "/";
106235
+ }
106236
+
106237
+ // src/platform/compat/path/security.ts
106238
+ init_utils();
106239
+
106137
106240
  // src/cli/utils/package-manager.ts
106138
- init_std_path();
106139
106241
  init_utils();
106140
106242
  init_fs();
106243
+ init_runtime();
106244
+ function isWindows() {
106245
+ if (isDeno) {
106246
+ return Deno.build.os === "windows";
106247
+ }
106248
+ if (isNode) {
106249
+ const nodeProcess2 = globalThis.process;
106250
+ return nodeProcess2?.platform === "win32";
106251
+ }
106252
+ return false;
106253
+ }
106141
106254
  async function executeCommand(cmd, args, cwd2, silent) {
106142
- if (typeof Deno !== "undefined" && Deno.Command) {
106143
- const process6 = new Deno.Command(cmd, {
106255
+ if (isDeno) {
106256
+ const process3 = new Deno.Command(cmd, {
106144
106257
  args,
106145
106258
  cwd: cwd2,
106146
106259
  stdout: silent ? "null" : "inherit",
106147
106260
  stderr: silent ? "null" : "inherit"
106148
106261
  });
106149
- const { code } = await process6.output();
106262
+ const { code } = await process3.output();
106150
106263
  return code;
106151
106264
  }
106152
106265
  const { spawn } = await import("node:child_process");
106153
- return new Promise((resolve5, reject) => {
106266
+ return new Promise((resolve6, reject) => {
106154
106267
  const child = spawn(cmd, args, {
106155
106268
  cwd: cwd2,
106156
106269
  stdio: silent ? "ignore" : "inherit",
106157
- shell: process.platform === "win32"
106270
+ shell: isWindows()
106158
106271
  // Use shell on Windows for .cmd files
106159
106272
  });
106160
106273
  child.on("error", (error2) => {
106161
106274
  reject(error2);
106162
106275
  });
106163
106276
  child.on("close", (code) => {
106164
- resolve5(code ?? 1);
106277
+ resolve6(code ?? 1);
106165
106278
  });
106166
106279
  });
106167
106280
  }
@@ -106177,15 +106290,15 @@ async function detectPackageManager(projectDir, preference) {
106177
106290
  { file: "package-lock.json", pm: "npm" }
106178
106291
  ];
106179
106292
  for (const { file, pm } of lockfiles) {
106180
- const lockPath = join2(projectDir, file);
106293
+ const lockPath = join6(projectDir, file);
106181
106294
  if (await fs15.exists(lockPath)) {
106182
106295
  cliLogger.debug(`Detected ${pm} from ${file}`);
106183
106296
  return pm;
106184
106297
  }
106185
106298
  }
106186
- const parentDir = join2(projectDir, "..");
106299
+ const parentDir = join6(projectDir, "..");
106187
106300
  for (const { file, pm } of lockfiles) {
106188
- const lockPath = join2(parentDir, file);
106301
+ const lockPath = join6(parentDir, file);
106189
106302
  if (await fs15.exists(lockPath)) {
106190
106303
  cliLogger.debug(`Detected ${pm} from parent directory ${file}`);
106191
106304
  return pm;
@@ -106311,10 +106424,10 @@ async function promptUser(message) {
106311
106424
  input: process.stdin,
106312
106425
  output: process.stdout
106313
106426
  });
106314
- return new Promise((resolve5) => {
106427
+ return new Promise((resolve6) => {
106315
106428
  rl.question("", (answer) => {
106316
106429
  rl.close();
106317
- resolve5(answer.trim());
106430
+ resolve6(answer.trim());
106318
106431
  });
106319
106432
  });
106320
106433
  }
@@ -106495,7 +106608,9 @@ async function initCommand(options) {
106495
106608
  if (["blog", "docs", "app", "minimal", "ai"].includes(template)) {
106496
106609
  const { getTemplate: getTemplate2, getTemplateConfig: getTemplateConfig2 } = await Promise.resolve().then(() => (init_templates(), templates_exports));
106497
106610
  const templateFiles = getTemplate2(template);
106498
- const templateConfig = getTemplateConfig2(template);
106611
+ const templateConfig = getTemplateConfig2(
106612
+ template
106613
+ );
106499
106614
  if (!templateFiles) {
106500
106615
  throw toError(createError({
106501
106616
  type: "config",
@@ -106683,7 +106798,7 @@ init_utils();
106683
106798
  init_std_fs();
106684
106799
  init_templates2();
106685
106800
  init_fs();
106686
- import { dirname as dirname4, join as join6, relative as relative3 } from "node:path";
106801
+ import { dirname as dirname5, join as join7, relative as relative4 } from "node:path";
106687
106802
  function isNotFoundError(error2) {
106688
106803
  if (!error2 || typeof error2 !== "object")
106689
106804
  return false;
@@ -106746,7 +106861,7 @@ async function ensureDirPath(path, adapter) {
106746
106861
  }
106747
106862
  async function copyStaticAssets(adapter, projectDir, outputDir, dryRun = false) {
106748
106863
  const stats = { assets: 0, totalSize: 0 };
106749
- const publicDir = join6(projectDir, "public");
106864
+ const publicDir = join7(projectDir, "public");
106750
106865
  let publicDirInfo;
106751
106866
  try {
106752
106867
  publicDirInfo = await statPath(publicDir, adapter);
@@ -106775,17 +106890,13 @@ async function copyStaticAssets(adapter, projectDir, outputDir, dryRun = false)
106775
106890
  };
106776
106891
  if (!dryRun) {
106777
106892
  await ensureDirPath(destinationRoot, adapter);
106778
- const testFilePath = join6(destinationRoot, ".vf_write_test.tmp");
106893
+ const testFilePath = join7(destinationRoot, ".vf_write_test.tmp");
106779
106894
  const testBytes = new Uint8Array([0]);
106780
106895
  try {
106781
106896
  await writeFileBytes(testFilePath, testBytes);
106782
106897
  try {
106783
- if (typeof Deno !== "undefined" && typeof Deno.remove === "function") {
106784
- await Deno.remove(testFilePath);
106785
- } else {
106786
- const fs15 = await import("node:fs/promises");
106787
- await fs15.rm(testFilePath, { force: true });
106788
- }
106898
+ const fs15 = createFileSystem();
106899
+ await fs15.remove(testFilePath);
106789
106900
  } catch (_error) {
106790
106901
  }
106791
106902
  } catch (error2) {
@@ -106793,11 +106904,11 @@ async function copyStaticAssets(adapter, projectDir, outputDir, dryRun = false)
106793
106904
  }
106794
106905
  }
106795
106906
  for await (const entry of walk(publicDir, { followSymlinks: true, includeDirs: true })) {
106796
- const relativePath = relative3(publicDir, entry.path);
106907
+ const relativePath = relative4(publicDir, entry.path);
106797
106908
  if (!relativePath || relativePath === "" || relativePath.startsWith("..")) {
106798
106909
  continue;
106799
106910
  }
106800
- const destinationPath = join6(destinationRoot, relativePath);
106911
+ const destinationPath = join7(destinationRoot, relativePath);
106801
106912
  if (entry.isDirectory) {
106802
106913
  if (!dryRun) {
106803
106914
  await ensureDirPath(destinationPath, adapter);
@@ -106812,7 +106923,7 @@ async function copyStaticAssets(adapter, projectDir, outputDir, dryRun = false)
106812
106923
  stats.assets += 1;
106813
106924
  stats.totalSize += fileInfo.size;
106814
106925
  if (!dryRun) {
106815
- await ensureDirPath(dirname4(destinationPath), adapter);
106926
+ await ensureDirPath(dirname5(destinationPath), adapter);
106816
106927
  const bytes = await readFileBytes(entry.path);
106817
106928
  await writeFileBytes(destinationPath, bytes);
106818
106929
  }
@@ -106833,7 +106944,7 @@ init_std_path();
106833
106944
  init_utils();
106834
106945
  init_veryfront_error();
106835
106946
  init_fs();
106836
- import { dirname as dirname5, extname as extname4, isAbsolute as isAbsolute4, join as join7, resolve as resolve4 } from "node:path";
106947
+ import { dirname as dirname6, extname as extname5, isAbsolute as isAbsolute5, join as join8, resolve as resolve5 } from "node:path";
106837
106948
  var CLIENT_ROUTER_BUNDLE2;
106838
106949
  var CLIENT_PREFETCH_BUNDLE2;
106839
106950
  try {
@@ -106855,8 +106966,8 @@ async function readTextFile(path) {
106855
106966
  const fs15 = createFileSystem();
106856
106967
  return await fs15.readTextFile(path);
106857
106968
  }
106858
- var moduleDir = dirname5(fromFileUrl(import.meta.url));
106859
- var packageRoot = join7(moduleDir, "..", "..", "..");
106969
+ var moduleDir = dirname6(fromFileUrl(import.meta.url));
106970
+ var packageRoot = join8(moduleDir, "..", "..", "..");
106860
106971
  var vfSrcPrefix = "@vf-src/";
106861
106972
  var moduleExtensions = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".mts", ".cjs", ".cts"];
106862
106973
  var externalSpecifier = /^(std\/|@std\/|node:|deno:|https?:)/;
@@ -106944,7 +107055,7 @@ function createPathResolverPlugin() {
106944
107055
  return { path: args.path, external: true };
106945
107056
  }
106946
107057
  if (specifier.startsWith(vfSrcPrefix)) {
106947
- const lookupBase = resolve4(packageRoot, specifier.slice(vfSrcPrefix.length));
107058
+ const lookupBase = resolve5(packageRoot, specifier.slice(vfSrcPrefix.length));
106948
107059
  const resolved = await resolveFromCandidates(lookupBase);
106949
107060
  if (resolved) {
106950
107061
  return { path: resolved };
@@ -106953,7 +107064,7 @@ function createPathResolverPlugin() {
106953
107064
  }
106954
107065
  if (relativeSpecifier.test(specifier)) {
106955
107066
  const importerDir = determineImporterDir(args);
106956
- const lookupBase = resolve4(importerDir, specifier);
107067
+ const lookupBase = resolve5(importerDir, specifier);
106957
107068
  const resolved = await resolveFromCandidates(lookupBase);
106958
107069
  if (resolved) {
106959
107070
  return { path: resolved };
@@ -106967,17 +107078,17 @@ function createPathResolverPlugin() {
106967
107078
  }
106968
107079
  function determineImporterDir(args) {
106969
107080
  if (args.resolveDir) {
106970
- if (isAbsolute4(args.resolveDir)) {
107081
+ if (isAbsolute5(args.resolveDir)) {
106971
107082
  return args.resolveDir;
106972
107083
  }
106973
- return resolve4(packageRoot, args.resolveDir);
107084
+ return resolve5(packageRoot, args.resolveDir);
106974
107085
  }
106975
107086
  if (args.importer) {
106976
107087
  if (args.importer.startsWith("file://")) {
106977
- return dirname5(fromFileUrl(new URL(args.importer)));
107088
+ return dirname6(fromFileUrl(new URL(args.importer)));
106978
107089
  }
106979
- if (isAbsolute4(args.importer)) {
106980
- return dirname5(args.importer);
107090
+ if (isAbsolute5(args.importer)) {
107091
+ return dirname6(args.importer);
106981
107092
  }
106982
107093
  }
106983
107094
  return packageRoot;
@@ -106999,12 +107110,12 @@ function buildCandidatePaths(basePath) {
106999
107110
  }
107000
107111
  const withExtensions = moduleExtensions.map((extension) => `${normalizedBase}${extension}`);
107001
107112
  const indexCandidates = moduleExtensions.map(
107002
- (extension) => join7(normalizedBase, `index${extension}`)
107113
+ (extension) => join8(normalizedBase, `index${extension}`)
107003
107114
  );
107004
107115
  return [...withExtensions, ...indexCandidates];
107005
107116
  }
107006
107117
  function hasSupportedExtension(filePath) {
107007
- const extension = extname4(filePath);
107118
+ const extension = extname5(filePath);
107008
107119
  return extension.length > 0 && moduleExtensions.includes(extension);
107009
107120
  }
107010
107121
  function stripTrailingSeparator(path) {
@@ -107023,7 +107134,7 @@ function createFsLoaderPlugin() {
107023
107134
  build3.onLoad({ filter: /.*/ }, async (args) => {
107024
107135
  try {
107025
107136
  const contents = await readTextFile(args.path);
107026
- const ext = extname4(args.path).toLowerCase();
107137
+ const ext = extname5(args.path).toLowerCase();
107027
107138
  let loader = "js";
107028
107139
  if (ext === ".ts")
107029
107140
  loader = "ts";
@@ -107049,7 +107160,7 @@ async function bundleClientEntry(entryRelative) {
107049
107160
  const entryUrl = new URL(entryRelative, import.meta.url);
107050
107161
  const shimUrl = new URL("../../rendering/client/browser-stubs/logger.ts", import.meta.url);
107051
107162
  const entryPath = fromFileUrl(entryUrl);
107052
- const entryDir = dirname5(entryPath);
107163
+ const entryDir = dirname6(entryPath);
107053
107164
  const shimPath = fromFileUrl(shimUrl);
107054
107165
  const source = await readTextFile(entryPath);
107055
107166
  const loader = entryPath.endsWith(".tsx") ? "tsx" : "ts";
@@ -107179,7 +107290,7 @@ function generateRedirects() {
107179
107290
  // src/build/production-build/static-generation.ts
107180
107291
  init_utils();
107181
107292
  import { mkdir as mkdir2 } from "node:fs/promises";
107182
- import { dirname as dirname6, join as join8 } from "node:path";
107293
+ import { dirname as dirname7, join as join9 } from "node:path";
107183
107294
 
107184
107295
  // src/server/build-app-route-renderer.ts
107185
107296
  init_utils();
@@ -107457,8 +107568,8 @@ ${clientStyles}
107457
107568
  </head>`
107458
107569
  );
107459
107570
  enhancedHtml = enhancedHtml.replace("</body>", generateClientRuntime(route, result, baseUrl));
107460
- const outputPath = route.slug === "index" ? join8(outputDir, "index.html") : join8(outputDir, route.slug, "index.html");
107461
- await mkdir2(dirname6(outputPath), { recursive: true });
107571
+ const outputPath = route.slug === "index" ? join9(outputDir, "index.html") : join9(outputDir, route.slug, "index.html");
107572
+ await mkdir2(dirname7(outputPath), { recursive: true });
107462
107573
  if (!dryRun) {
107463
107574
  await traceStep(`write:${route.slug}`, () => adapter.fs.writeFile(outputPath, enhancedHtml));
107464
107575
  }
@@ -107473,12 +107584,12 @@ ${clientStyles}
107473
107584
  // Include rendered HTML for client navigation
107474
107585
  };
107475
107586
  if (!dryRun) {
107476
- const dataPath = join8(outputDir, "_veryfront/data", `${route.slug}.json`);
107477
- await mkdir2(dirname6(dataPath), { recursive: true });
107587
+ const dataPath = join9(outputDir, "_veryfront/data", `${route.slug}.json`);
107588
+ await mkdir2(dirname7(dataPath), { recursive: true });
107478
107589
  await traceStep(`data:${route.slug}`, () => adapter.fs.writeFile(dataPath, JSON.stringify(pageData)));
107479
107590
  if (result.pageModule?.code) {
107480
- const modulePath = join8(outputDir, "_veryfront/pages", `${route.slug}.js`);
107481
- await mkdir2(dirname6(modulePath), { recursive: true });
107591
+ const modulePath = join9(outputDir, "_veryfront/pages", `${route.slug}.js`);
107592
+ await mkdir2(dirname7(modulePath), { recursive: true });
107482
107593
  await traceStep(`module:${route.slug}`, () => adapter.fs.writeFile(modulePath, result.pageModule.code));
107483
107594
  }
107484
107595
  }
@@ -107514,9 +107625,9 @@ async function buildAppRoutes(appRoutes, options) {
107514
107625
  routePath: route.path,
107515
107626
  pageFile: route.pageFile
107516
107627
  }));
107517
- const outputPath = route.path === "/" ? join8(outputDir, "index.html") : join8(outputDir, route.path.slice(1), "index.html");
107628
+ const outputPath = route.path === "/" ? join9(outputDir, "index.html") : join9(outputDir, route.path.slice(1), "index.html");
107518
107629
  if (!dryRun) {
107519
- await mkdir2(dirname6(outputPath), { recursive: true });
107630
+ await mkdir2(dirname7(outputPath), { recursive: true });
107520
107631
  await traceStep(`write:${route.path}`, () => adapter.fs.writeFile(outputPath, html3));
107521
107632
  }
107522
107633
  stats.ssgPaths.push(route.path);
@@ -107622,7 +107733,7 @@ async function executeBuild(pagesRoutes, appRoutes, options) {
107622
107733
  init_adapters();
107623
107734
  init_config();
107624
107735
  await init_rendering();
107625
- import { join as join9 } from "node:path";
107736
+ import { join as join10 } from "node:path";
107626
107737
  async function initializeBuildContext(options) {
107627
107738
  const adapter = await getAdapter();
107628
107739
  const config = await getConfig(options.projectDir, adapter);
@@ -107648,7 +107759,7 @@ async function initializeBuildContext(options) {
107648
107759
  };
107649
107760
  }
107650
107761
  function normalizeBuildOptions(options) {
107651
- const defaultOutputDir = join9(options.projectDir, ".veryfront", "output");
107762
+ const defaultOutputDir = join10(options.projectDir, ".veryfront", "output");
107652
107763
  return {
107653
107764
  projectDir: options.projectDir,
107654
107765
  outputDir: options.outputDir ?? defaultOutputDir,
@@ -107666,7 +107777,7 @@ function normalizeBuildOptions(options) {
107666
107777
  init_utils();
107667
107778
  init_errors();
107668
107779
  init_fs();
107669
- import { join as join10 } from "node:path";
107780
+ import { join as join11 } from "node:path";
107670
107781
  async function setupBuildDirectories(adapter, outputDir, dryRun) {
107671
107782
  serverLogger.info("Setting up build directories...");
107672
107783
  await handleErrorWithFallback(
@@ -107678,10 +107789,10 @@ async function setupBuildDirectories(adapter, outputDir, dryRun) {
107678
107789
  const fs15 = createFileSystem();
107679
107790
  const dirs = [
107680
107791
  outputDir,
107681
- join10(outputDir, "_veryfront"),
107682
- join10(outputDir, "_veryfront/chunks"),
107683
- join10(outputDir, "_veryfront/data"),
107684
- join10(outputDir, "assets")
107792
+ join11(outputDir, "_veryfront"),
107793
+ join11(outputDir, "_veryfront/chunks"),
107794
+ join11(outputDir, "_veryfront/data"),
107795
+ join11(outputDir, "assets")
107685
107796
  ];
107686
107797
  for (const dir of dirs) {
107687
107798
  try {
@@ -107699,7 +107810,7 @@ async function setupBuildDirectories(adapter, outputDir, dryRun) {
107699
107810
 
107700
107811
  // src/build/production-build/build/code-splitter-orchestrator.ts
107701
107812
  init_utils();
107702
- import { join as join11 } from "node:path";
107813
+ import { join as join12 } from "node:path";
107703
107814
 
107704
107815
  // src/build/bundler/index.ts
107705
107816
  init_code_splitter();
@@ -107717,7 +107828,7 @@ async function runCodeSplitting(projectDir, outputDir, routes, enableSplitting,
107717
107828
  serverLogger.info("Running code splitter...");
107718
107829
  const splitter = createCodeSplitter({
107719
107830
  projectDir,
107720
- outDir: join11(outputDir, "_veryfront/chunks"),
107831
+ outDir: join12(outputDir, "_veryfront/chunks"),
107721
107832
  mode: "production",
107722
107833
  routes: routes.map((r41) => ({
107723
107834
  path: r41.path,
@@ -107738,7 +107849,7 @@ async function runCodeSplitting(projectDir, outputDir, routes, enableSplitting,
107738
107849
 
107739
107850
  // src/build/production-build/build/output-generator.ts
107740
107851
  init_utils();
107741
- import { join as join12 } from "node:path";
107852
+ import { join as join13 } from "node:path";
107742
107853
 
107743
107854
  // src/server/build-service-worker.ts
107744
107855
  function sanitizeCacheKey(value) {
@@ -107930,17 +108041,17 @@ self.addEventListener('message', (event) => {
107930
108041
  async function generateClientScripts(adapter, outputDir, dryRun) {
107931
108042
  serverLogger.info("Copying client scripts...");
107932
108043
  if (!dryRun) {
107933
- await adapter.fs.writeFile(join12(outputDir, "_veryfront/app.js"), generateAppModule());
108044
+ await adapter.fs.writeFile(join13(outputDir, "_veryfront/app.js"), generateAppModule());
107934
108045
  await adapter.fs.writeFile(
107935
- join12(outputDir, "_veryfront/client.js"),
108046
+ join13(outputDir, "_veryfront/client.js"),
107936
108047
  await generateClientModule()
107937
108048
  );
107938
108049
  await adapter.fs.writeFile(
107939
- join12(outputDir, "_veryfront/router.js"),
108050
+ join13(outputDir, "_veryfront/router.js"),
107940
108051
  await generateRouterScript(adapter)
107941
108052
  );
107942
108053
  await adapter.fs.writeFile(
107943
- join12(outputDir, "_veryfront/prefetch.js"),
108054
+ join13(outputDir, "_veryfront/prefetch.js"),
107944
108055
  await generatePrefetchScript(adapter)
107945
108056
  );
107946
108057
  }
@@ -107957,16 +108068,16 @@ async function generateManifestAndServiceWorker(adapter, outputDir, routes, appR
107957
108068
  });
107958
108069
  if (!dryRun) {
107959
108070
  await adapter.fs.writeFile(
107960
- join12(outputDir, "_veryfront/manifest.json"),
108071
+ join13(outputDir, "_veryfront/manifest.json"),
107961
108072
  JSON.stringify(manifest, null, 2)
107962
108073
  );
107963
108074
  const sw3 = generateServiceWorker(manifest);
107964
- await adapter.fs.writeFile(join12(outputDir, "sw.js"), sw3);
108075
+ await adapter.fs.writeFile(join13(outputDir, "sw.js"), sw3);
107965
108076
  }
107966
108077
  }
107967
108078
  async function generateRedirectsFile(adapter, outputDir, dryRun) {
107968
108079
  if (!dryRun) {
107969
- await adapter.fs.writeFile(join12(outputDir, "_redirects"), generateRedirects());
108080
+ await adapter.fs.writeFile(join13(outputDir, "_redirects"), generateRedirects());
107970
108081
  }
107971
108082
  }
107972
108083
  async function copyAssets(adapter, projectDir, outputDir, dryRun) {
@@ -108066,12 +108177,12 @@ function isForceDynamic(source) {
108066
108177
  return /export\s+const\s+dynamic\s*=\s*["']force-dynamic["']/.test(source);
108067
108178
  }
108068
108179
  async function walkAppSSG(adapter, dir, segs, segDirs, collected) {
108069
- const { join: join13 } = await Promise.resolve().then(() => (init_std_path(), std_path_exports));
108180
+ const { join: join14 } = await Promise.resolve().then(() => (init_std_path(), std_path_exports));
108070
108181
  const baseName = dir.split("/").pop() || "";
108071
108182
  if (isDynamicSegment3(baseName)) {
108072
108183
  return;
108073
108184
  }
108074
- const candidates = PAGE_CANDIDATES.map((n48) => join13(dir, n48));
108185
+ const candidates = PAGE_CANDIDATES.map((n48) => join14(dir, n48));
108075
108186
  for (const f53 of candidates) {
108076
108187
  try {
108077
108188
  const st9 = await adapter.fs.stat(f53);
@@ -108096,9 +108207,9 @@ async function walkAppSSG(adapter, dir, segs, segDirs, collected) {
108096
108207
  continue;
108097
108208
  await walkAppSSG(
108098
108209
  adapter,
108099
- join13(dir, e25.name),
108210
+ join14(dir, e25.name),
108100
108211
  e25.name === "app" ? [] : [...segs, e25.name],
108101
- [...segDirs, join13(dir, e25.name)],
108212
+ [...segDirs, join14(dir, e25.name)],
108102
108213
  collected
108103
108214
  );
108104
108215
  }
@@ -108237,9 +108348,11 @@ function displayBuildStart() {
108237
108348
  init_console();
108238
108349
  init_utils();
108239
108350
  init_process();
108240
- import process5 from "node:process";
108241
108351
  function handleBuildError(error2) {
108242
- process5.stdout.write(`\r${" ".repeat(80)}\r`);
108352
+ const stdout = getStdout();
108353
+ if (stdout?.write) {
108354
+ stdout.write(`\r${" ".repeat(80)}\r`);
108355
+ }
108243
108356
  cliLogger.error(`
108244
108357
  ${red3("\u2717")}${bold3(red3(" Build failed!\n"))}`);
108245
108358
  if (error2 instanceof Error) {
@@ -108345,9 +108458,9 @@ async function handleBuildCommand(args) {
108345
108458
  }
108346
108459
  async function handleEmbeddedBuild(projectDir, outputDir) {
108347
108460
  const { bold: bold4, cyan: cyan4, dim: dim4, green: green4, yellow: yellow4 } = await Promise.resolve().then(() => (init_ansi(), ansi_exports));
108348
- const { join: join13 } = await Promise.resolve().then(() => (init_std_path(), std_path_exports));
108461
+ const { join: join14 } = await Promise.resolve().then(() => (init_std_path(), std_path_exports));
108349
108462
  const { buildEmbeddedPreset: buildEmbeddedPreset2 } = await Promise.resolve().then(() => (init_build2(), build_exports));
108350
- const finalOutput = outputDir ?? join13(projectDir, "dist");
108463
+ const finalOutput = outputDir ?? join14(projectDir, "dist");
108351
108464
  cliLogger.info(bold4(cyan4("\n\u{1F517} Veryfront Embedded Preset Build\n")));
108352
108465
  cliLogger.info("Starting embedded preset build");
108353
108466
  cliLogger.info(yellow4("\nBuild Configuration:"));
@@ -108446,8 +108559,8 @@ function detectPlatform() {
108446
108559
  if (typeof caches !== "undefined" && typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") {
108447
108560
  return "cloudflare-workers";
108448
108561
  }
108449
- const globalProcess = globalThis.process;
108450
- if (typeof globalProcess !== "undefined" && globalProcess.versions?.node) {
108562
+ const globalProcess2 = globalThis.process;
108563
+ if (typeof globalProcess2 !== "undefined" && globalProcess2.versions?.node) {
108451
108564
  return "node";
108452
108565
  }
108453
108566
  return "unknown";
@@ -108636,7 +108749,9 @@ var ToolRegistryClass = class {
108636
108749
  return Array.from(this.tools.values()).map(toolToProviderDefinition);
108637
108750
  }
108638
108751
  };
108639
- var toolRegistry = new ToolRegistryClass();
108752
+ var TOOL_REGISTRY_KEY = "__veryfront_tool_registry__";
108753
+ var _globalTool = globalThis;
108754
+ var toolRegistry = _globalTool[TOOL_REGISTRY_KEY] ||= new ToolRegistryClass();
108640
108755
  function toolToProviderDefinition(tool) {
108641
108756
  const jsonSchema = tool.inputSchemaJson || zodToJsonSchema(tool.inputSchema);
108642
108757
  agentLogger.info(
@@ -108716,7 +108831,9 @@ var ResourceRegistryClass = class {
108716
108831
  this.resources.clear();
108717
108832
  }
108718
108833
  };
108719
- var resourceRegistry = new ResourceRegistryClass();
108834
+ var RESOURCE_REGISTRY_KEY = "__veryfront_resource_registry__";
108835
+ var _globalResource = globalThis;
108836
+ var resourceRegistry = _globalResource[RESOURCE_REGISTRY_KEY] ||= new ResourceRegistryClass();
108720
108837
 
108721
108838
  // src/ai/mcp/prompt.ts
108722
108839
  init_logger();
@@ -108766,7 +108883,9 @@ var PromptRegistryClass = class {
108766
108883
  this.prompts.clear();
108767
108884
  }
108768
108885
  };
108769
- var promptRegistry = new PromptRegistryClass();
108886
+ var PROMPT_REGISTRY_KEY = "__veryfront_prompt_registry__";
108887
+ var _globalPrompt = globalThis;
108888
+ var promptRegistry = _globalPrompt[PROMPT_REGISTRY_KEY] ||= new PromptRegistryClass();
108770
108889
 
108771
108890
  // src/ai/mcp/registry.ts
108772
108891
  function registerTool(id, tool) {
@@ -108780,25 +108899,56 @@ function registerPrompt(id, promptInstance) {
108780
108899
  }
108781
108900
 
108782
108901
  // src/ai/agent/composition.ts
108902
+ init_logger();
108783
108903
  import { z as z41 } from "zod";
108784
108904
  var AgentRegistryClass = class {
108785
108905
  constructor() {
108786
108906
  this.agents = /* @__PURE__ */ new Map();
108787
108907
  }
108908
+ /**
108909
+ * Register an agent
108910
+ */
108788
108911
  register(id, agent) {
108912
+ if (this.agents.has(id)) {
108913
+ agentLogger.warn(`Agent "${id}" is already registered. Overwriting.`);
108914
+ }
108789
108915
  this.agents.set(id, agent);
108916
+ agentLogger.debug(`Registered agent: ${id}`);
108790
108917
  }
108918
+ /**
108919
+ * Get an agent by ID
108920
+ */
108791
108921
  get(id) {
108792
108922
  return this.agents.get(id);
108793
108923
  }
108924
+ /**
108925
+ * Check if an agent exists
108926
+ */
108927
+ has(id) {
108928
+ return this.agents.has(id);
108929
+ }
108930
+ /**
108931
+ * Get all agent IDs
108932
+ */
108933
+ getAllIds() {
108934
+ return Array.from(this.agents.keys());
108935
+ }
108936
+ /**
108937
+ * Get all agents as a Map
108938
+ */
108794
108939
  getAll() {
108795
108940
  return new Map(this.agents);
108796
108941
  }
108942
+ /**
108943
+ * Clear all agents (for testing)
108944
+ */
108797
108945
  clear() {
108798
108946
  this.agents.clear();
108799
108947
  }
108800
108948
  };
108801
- var agentRegistry = new AgentRegistryClass();
108949
+ var AGENT_REGISTRY_KEY = "__veryfront_agent_registry__";
108950
+ var _globalAgent = globalThis;
108951
+ var agentRegistry = _globalAgent[AGENT_REGISTRY_KEY] ||= new AgentRegistryClass();
108802
108952
  function registerAgent(id, agent) {
108803
108953
  agentRegistry.register(id, agent);
108804
108954
  }
@@ -108899,6 +109049,7 @@ async function discoverAgents(dir, result, context2, verbose) {
108899
109049
  const id = agent.id || filenameToId(file);
108900
109050
  registerAgent(id, agent);
108901
109051
  result.agents.set(id, agent);
109052
+ trackAgentPath(id, file);
108902
109053
  if (verbose) {
108903
109054
  agentLogger.info(`[Discovery] Registered agent: ${id}`);
108904
109055
  }
@@ -109054,6 +109205,10 @@ function filePathToPattern(filePath, baseDir) {
109054
109205
  pattern = "/" + pattern;
109055
109206
  return pattern;
109056
109207
  }
109208
+ var discoveredAgentPaths = /* @__PURE__ */ new Map();
109209
+ function trackAgentPath(id, filePath) {
109210
+ discoveredAgentPaths.set(id, filePath);
109211
+ }
109057
109212
 
109058
109213
  // src/cli/commands/dev.ts
109059
109214
  async function getLocalIP() {