veryfront 0.0.73 → 0.0.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,12 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require2 = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined")
7
+ return require.apply(this, arguments);
8
+ throw Error('Dynamic require of "' + x + '" is not supported');
9
+ });
3
10
  var __esm = (fn, res) => function __init() {
4
11
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
12
  };
@@ -89,6 +96,47 @@ function resolveLogLevel(force = false) {
89
96
  }
90
97
  return cachedLogLevel;
91
98
  }
99
+ function resolveLogFormat(force = false) {
100
+ if (force || cachedLogFormat === void 0) {
101
+ cachedLogFormat = getDefaultFormat();
102
+ }
103
+ return cachedLogFormat;
104
+ }
105
+ function getDefaultFormat() {
106
+ const envFormat = getEnvironmentVariable("LOG_FORMAT");
107
+ if (envFormat === "json" || envFormat === "text") {
108
+ return envFormat;
109
+ }
110
+ return isProductionEnvironment() ? "json" : "text";
111
+ }
112
+ function serializeError(err) {
113
+ if (err instanceof Error) {
114
+ return {
115
+ name: err.name,
116
+ message: err.message,
117
+ stack: err.stack
118
+ };
119
+ }
120
+ if (err !== void 0 && err !== null) {
121
+ return {
122
+ name: "UnknownError",
123
+ message: String(err)
124
+ };
125
+ }
126
+ return void 0;
127
+ }
128
+ function extractContext(args) {
129
+ let context;
130
+ let error;
131
+ for (const arg of args) {
132
+ if (arg instanceof Error) {
133
+ error = serializeError(arg);
134
+ } else if (typeof arg === "object" && arg !== null && !Array.isArray(arg)) {
135
+ context = { ...context, ...arg };
136
+ }
137
+ }
138
+ return { context, error };
139
+ }
92
140
  function parseLogLevel(levelString) {
93
141
  if (!levelString)
94
142
  return void 0;
@@ -113,8 +161,10 @@ function createLogger(prefix) {
113
161
  }
114
162
  function __loggerResetForTests(options = {}) {
115
163
  const updatedLevel = resolveLogLevel(true);
164
+ const updatedFormat = resolveLogFormat(true);
116
165
  for (const instance of trackedLoggers) {
117
166
  instance.setLevel(updatedLevel);
167
+ instance.setFormat(updatedFormat);
118
168
  }
119
169
  if (options.restoreConsole) {
120
170
  console.debug = originalConsole.debug;
@@ -123,7 +173,10 @@ function __loggerResetForTests(options = {}) {
123
173
  console.error = originalConsole.error;
124
174
  }
125
175
  }
126
- var LogLevel, originalConsole, cachedLogLevel, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, logger;
176
+ function createRequestLogger(baseLogger, requestContext) {
177
+ return baseLogger.child(requestContext);
178
+ }
179
+ var LogLevel, originalConsole, cachedLogLevel, cachedLogFormat, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, proxyLogger, logger;
127
180
  var init_logger = __esm({
128
181
  "src/core/utils/logger/logger.ts"() {
129
182
  init_deno_env();
@@ -141,47 +194,104 @@ var init_logger = __esm({
141
194
  warn: console.warn,
142
195
  error: console.error
143
196
  };
144
- ConsoleLogger = class {
145
- constructor(prefix, level = resolveLogLevel()) {
197
+ ConsoleLogger = class _ConsoleLogger {
198
+ constructor(prefix, level = resolveLogLevel(), format = resolveLogFormat(), boundContext) {
146
199
  this.prefix = prefix;
147
200
  this.level = level;
201
+ this.format = format;
202
+ if (boundContext) {
203
+ this.boundContext = boundContext;
204
+ }
148
205
  }
206
+ boundContext = {};
149
207
  setLevel(level) {
150
208
  this.level = level;
151
209
  }
152
210
  getLevel() {
153
211
  return this.level;
154
212
  }
155
- debug(message, ...args) {
156
- if (this.level <= 0 /* DEBUG */) {
157
- console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);
213
+ setFormat(format) {
214
+ this.format = format;
215
+ }
216
+ getFormat() {
217
+ return this.format;
218
+ }
219
+ /**
220
+ * Create a child logger with additional bound context.
221
+ */
222
+ child(context) {
223
+ return new _ConsoleLogger(this.prefix, this.level, this.format, {
224
+ ...this.boundContext,
225
+ ...context
226
+ });
227
+ }
228
+ formatJson(level, message, args) {
229
+ const { context, error } = extractContext(args);
230
+ const entry = {
231
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
232
+ level,
233
+ service: this.prefix.toLowerCase(),
234
+ message
235
+ };
236
+ const mergedContext = { ...this.boundContext, ...context };
237
+ if (Object.keys(mergedContext).length > 0) {
238
+ if ("requestId" in mergedContext) {
239
+ entry.requestId = String(mergedContext.requestId);
240
+ delete mergedContext.requestId;
241
+ }
242
+ if ("traceId" in mergedContext) {
243
+ entry.traceId = String(mergedContext.traceId);
244
+ delete mergedContext.traceId;
245
+ }
246
+ if ("projectSlug" in mergedContext) {
247
+ entry.projectSlug = String(mergedContext.projectSlug);
248
+ delete mergedContext.projectSlug;
249
+ }
250
+ if ("durationMs" in mergedContext) {
251
+ entry.durationMs = Number(mergedContext.durationMs);
252
+ delete mergedContext.durationMs;
253
+ }
254
+ if (Object.keys(mergedContext).length > 0) {
255
+ entry.context = mergedContext;
256
+ }
257
+ }
258
+ if (error) {
259
+ entry.error = error;
158
260
  }
261
+ return JSON.stringify(entry);
159
262
  }
160
- info(message, ...args) {
161
- if (this.level <= 1 /* INFO */) {
162
- console.log(`[${this.prefix}] ${message}`, ...args);
263
+ log(level, logLevel, consoleFn, message, args) {
264
+ if (this.level > logLevel)
265
+ return;
266
+ if (this.format === "json") {
267
+ consoleFn(this.formatJson(level, message, args));
268
+ } else {
269
+ const prefix = level === "info" ? "" : ` ${level.toUpperCase()}:`;
270
+ consoleFn(`[${this.prefix}]${prefix} ${message}`, ...args);
163
271
  }
164
272
  }
273
+ debug(message, ...args) {
274
+ this.log("debug", 0 /* DEBUG */, console.debug, message, args);
275
+ }
276
+ info(message, ...args) {
277
+ this.log("info", 1 /* INFO */, console.log, message, args);
278
+ }
165
279
  warn(message, ...args) {
166
- if (this.level <= 2 /* WARN */) {
167
- console.warn(`[${this.prefix}] WARN: ${message}`, ...args);
168
- }
280
+ this.log("warn", 2 /* WARN */, console.warn, message, args);
169
281
  }
170
282
  error(message, ...args) {
171
- if (this.level <= 3 /* ERROR */) {
172
- console.error(`[${this.prefix}] ERROR: ${message}`, ...args);
173
- }
283
+ this.log("error", 3 /* ERROR */, console.error, message, args);
174
284
  }
175
285
  async time(label, fn) {
176
286
  const start = performance.now();
177
287
  try {
178
288
  const result = await fn();
179
- const end = performance.now();
180
- this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);
289
+ const durationMs = performance.now() - start;
290
+ this.debug(`${label} completed`, { durationMs: Math.round(durationMs) });
181
291
  return result;
182
292
  } catch (error) {
183
- const end = performance.now();
184
- this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error);
293
+ const durationMs = performance.now() - start;
294
+ this.error(`${label} failed`, { durationMs: Math.round(durationMs) }, error);
185
295
  throw error;
186
296
  }
187
297
  }
@@ -202,6 +312,7 @@ var init_logger = __esm({
202
312
  rendererLogger = createLogger("RENDERER");
203
313
  bundlerLogger = createLogger("BUNDLER");
204
314
  agentLogger = createLogger("AGENT");
315
+ proxyLogger = createLogger("PROXY");
205
316
  logger = createLogger("VERYFRONT");
206
317
  }
207
318
  });
@@ -274,7 +385,7 @@ var init_deno = __esm({
274
385
  "deno.json"() {
275
386
  deno_default = {
276
387
  name: "veryfront",
277
- version: "0.0.73",
388
+ version: "0.0.75",
278
389
  nodeModulesDir: "auto",
279
390
  exclude: [
280
391
  "npm/",
@@ -306,7 +417,11 @@ var init_deno = __esm({
306
417
  "./oauth": "./src/core/oauth/index.ts",
307
418
  "./oauth/providers": "./src/core/oauth/providers/index.ts",
308
419
  "./oauth/handlers": "./src/core/oauth/handlers/index.ts",
309
- "./oauth/token-store": "./src/core/oauth/token-store/index.ts"
420
+ "./oauth/token-store": "./src/core/oauth/token-store/index.ts",
421
+ "./head": "./src/exports/head.ts",
422
+ "./router": "./src/exports/router.ts",
423
+ "./context": "./src/exports/context.ts",
424
+ "./fonts": "./src/exports/fonts.ts"
310
425
  },
311
426
  imports: {
312
427
  "@veryfront": "./src/index.ts",
@@ -359,12 +474,12 @@ var init_deno = __esm({
359
474
  csstype: "https://esm.sh/csstype@3.2.3",
360
475
  "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",
361
476
  "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",
362
- react: "https://esm.sh/react@18.3.1",
363
- "react-dom": "https://esm.sh/react-dom@18.3.1",
364
- "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",
365
- "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",
366
- "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",
367
- "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",
477
+ react: "npm:react@18.3.1",
478
+ "react-dom": "npm:react-dom@18.3.1",
479
+ "react-dom/server": "npm:react-dom@18.3.1/server",
480
+ "react-dom/client": "npm:react-dom@18.3.1/client",
481
+ "react/jsx-runtime": "npm:react@18.3.1/jsx-runtime",
482
+ "react/jsx-dev-runtime": "npm:react@18.3.1/jsx-dev-runtime",
368
483
  "@mdx-js/mdx": "npm:@mdx-js/mdx@3.0.0",
369
484
  "@mdx-js/react": "npm:@mdx-js/react@3.0.0",
370
485
  "unist-util-visit": "npm:unist-util-visit@5.0.0",
@@ -374,27 +489,36 @@ var init_deno = __esm({
374
489
  "remark-frontmatter": "npm:remark-frontmatter@5.0.0",
375
490
  "rehype-highlight": "npm:rehype-highlight@7.0.2",
376
491
  "rehype-slug": "npm:rehype-slug@6.0.0",
377
- esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",
378
- "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",
492
+ esbuild: "npm:esbuild@0.20.2",
493
+ "esbuild/mod.js": "npm:esbuild@0.20.2",
379
494
  "es-module-lexer": "npm:es-module-lexer@1.5.0",
380
- zod: "npm:zod@3.23.8",
495
+ zod: "npm:zod@3.25.76",
381
496
  "mime-types": "npm:mime-types@2.1.35",
382
497
  mdast: "npm:@types/mdast@4.0.3",
383
498
  hast: "npm:@types/hast@3.0.3",
384
499
  unist: "npm:@types/unist@3.0.2",
385
500
  unified: "npm:unified@11.0.5",
386
- ai: "https://esm.sh/ai@5.0.76?deps=react@18.3.1,react-dom@18.3.1",
387
- "ai/react": "https://esm.sh/@ai-sdk/react@2.0.1?deps=react@18.3.1,react-dom@18.3.1",
388
- "@ai-sdk/react": "https://esm.sh/@ai-sdk/react@2.0.1?deps=react@18.3.1,react-dom@18.3.1",
501
+ ai: "npm:ai@5.0.76",
502
+ "ai/react": "npm:@ai-sdk/react@2.0.1",
503
+ "@ai-sdk/react": "npm:@ai-sdk/react@2.0.1",
389
504
  "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",
390
505
  "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.1",
391
506
  unocss: "https://esm.sh/unocss@0.59.0",
392
507
  "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",
393
508
  "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0",
509
+ "next-themes": "npm:next-themes@0.4",
394
510
  redis: "npm:redis",
395
511
  pg: "npm:pg",
396
512
  "@opentelemetry/api": "npm:@opentelemetry/api@1",
397
- "@opentelemetry/core": "npm:@opentelemetry/core@1"
513
+ "@opentelemetry/core": "npm:@opentelemetry/core@1",
514
+ "@opentelemetry/sdk-trace-base": "npm:@opentelemetry/sdk-trace-base@1",
515
+ "@opentelemetry/exporter-trace-otlp-http": "npm:@opentelemetry/exporter-trace-otlp-http@0.57",
516
+ "@opentelemetry/resources": "npm:@opentelemetry/resources@1",
517
+ "@opentelemetry/semantic-conventions": "npm:@opentelemetry/semantic-conventions@1",
518
+ "@babel/parser": "npm:@babel/parser@7.26.3",
519
+ "@babel/traverse": "npm:@babel/traverse@7.26.3",
520
+ "@babel/generator": "npm:@babel/generator@7.26.3",
521
+ "@babel/types": "npm:@babel/types@7.26.3"
398
522
  },
399
523
  compilerOptions: {
400
524
  jsx: "react-jsx",
@@ -402,7 +526,7 @@ var init_deno = __esm({
402
526
  strict: true,
403
527
  noImplicitAny: true,
404
528
  noUncheckedIndexedAccess: true,
405
- types: [],
529
+ types: ["npm:@types/react@18"],
406
530
  lib: [
407
531
  "deno.window",
408
532
  "dom",
@@ -417,9 +541,9 @@ var init_deno = __esm({
417
541
  build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",
418
542
  "build:npm": "deno run -A scripts/build-npm.ts",
419
543
  release: "deno run -A scripts/release.ts",
420
- test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",
421
- "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",
422
- "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",
544
+ test: "VF_DISABLE_LRU_INTERVAL=1 DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",
545
+ "test:unit": "VF_DISABLE_LRU_INTERVAL=1 DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests,src/ai/workflow/__tests__ --unstable-worker-options --unstable-net",
546
+ "test:integration": "VF_DISABLE_LRU_INTERVAL=1 DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",
423
547
  "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",
424
548
  "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",
425
549
  "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",
@@ -532,13 +656,14 @@ var init_process = __esm({
532
656
  });
533
657
 
534
658
  // src/core/utils/version.ts
535
- var VERSION;
659
+ var VERSION, SERVER_START_TIME;
536
660
  var init_version = __esm({
537
661
  "src/core/utils/version.ts"() {
538
662
  init_deno_env();
539
663
  init_deno();
540
664
  init_process();
541
665
  VERSION = getEnv("VERYFRONT_VERSION") || (typeof deno_default.version === "string" ? deno_default.version : "0.0.0");
666
+ SERVER_START_TIME = Date.now();
542
667
  }
543
668
  });
544
669
 
@@ -577,7 +702,7 @@ function getDenoStdNodeBase() {
577
702
  function getUnoCSSTailwindResetUrl() {
578
703
  return `${ESM_CDN_BASE}/@unocss/reset@${UNOCSS_VERSION}/tailwind.css`;
579
704
  }
580
- 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;
705
+ 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, TAILWIND_VERSION, UNOCSS_VERSION;
581
706
  var init_cdn = __esm({
582
707
  "src/core/utils/constants/cdn.ts"() {
583
708
  init_deno_env();
@@ -593,6 +718,7 @@ var init_cdn = __esm({
593
718
  REACT_DEFAULT_VERSION = REACT_VERSION_18_3;
594
719
  DEFAULT_ALLOWED_CDN_HOSTS = [ESM_CDN_BASE, DENO_STD_BASE];
595
720
  DENO_STD_VERSION = "0.220.0";
721
+ TAILWIND_VERSION = "4.1.8";
596
722
  UNOCSS_VERSION = "0.59.0";
597
723
  }
598
724
  });
@@ -1312,8 +1438,8 @@ var init_bundle_manifest = __esm({
1312
1438
  // src/core/utils/bundle-manifest-init.ts
1313
1439
  async function initializeBundleManifest(config, mode, adapter) {
1314
1440
  const manifestConfig = config.cache?.bundleManifest;
1315
- const enabled = manifestConfig?.enabled ?? mode === "production";
1316
- if (!enabled) {
1441
+ const enabled2 = manifestConfig?.enabled ?? mode === "production";
1442
+ if (!enabled2) {
1317
1443
  serverLogger.info("[bundle-manifest] Bundle manifest disabled");
1318
1444
  setBundleManifestStore(new InMemoryBundleManifestStore());
1319
1445
  return;
@@ -1452,6 +1578,376 @@ var init_platform = __esm({
1452
1578
  }
1453
1579
  });
1454
1580
 
1581
+ // src/core/utils/import-lockfile.ts
1582
+ function createEmptyLockfile() {
1583
+ return {
1584
+ version: LOCKFILE_VERSION,
1585
+ imports: {}
1586
+ };
1587
+ }
1588
+ async function computeIntegrity(content) {
1589
+ const hash = await computeHash(content);
1590
+ return `sha256-${hash}`;
1591
+ }
1592
+ function verifyIntegrity(content, integrity) {
1593
+ return computeIntegrity(content).then((computed) => computed === integrity);
1594
+ }
1595
+ function createNodeFSAdapter() {
1596
+ const fs = globalThis.Deno ? null : __require2("fs/promises");
1597
+ return {
1598
+ readFile(path) {
1599
+ if (globalThis.Deno) {
1600
+ return Deno.readTextFile(path);
1601
+ }
1602
+ return fs.readFile(path, "utf-8");
1603
+ },
1604
+ async writeFile(path, content) {
1605
+ if (globalThis.Deno) {
1606
+ await Deno.writeTextFile(path, content);
1607
+ return;
1608
+ }
1609
+ await fs.writeFile(path, content, "utf-8");
1610
+ },
1611
+ async exists(path) {
1612
+ try {
1613
+ if (globalThis.Deno) {
1614
+ await Deno.stat(path);
1615
+ return true;
1616
+ }
1617
+ await fs.access(path);
1618
+ return true;
1619
+ } catch {
1620
+ return false;
1621
+ }
1622
+ },
1623
+ async remove(path) {
1624
+ if (globalThis.Deno) {
1625
+ await Deno.remove(path);
1626
+ return;
1627
+ }
1628
+ await fs.unlink(path);
1629
+ }
1630
+ };
1631
+ }
1632
+ function createLockfileManager(projectDir, fsAdapter) {
1633
+ const fs = fsAdapter || createNodeFSAdapter();
1634
+ const lockfilePath = `${projectDir}/${LOCKFILE_NAME}`;
1635
+ let cache = null;
1636
+ let dirty = false;
1637
+ const read = async () => {
1638
+ if (cache)
1639
+ return cache;
1640
+ try {
1641
+ if (await fs.exists(lockfilePath)) {
1642
+ const content = await fs.readFile(lockfilePath);
1643
+ cache = JSON.parse(content);
1644
+ if (cache.version !== LOCKFILE_VERSION) {
1645
+ serverLogger.warn(
1646
+ `[lockfile] Version mismatch, expected ${LOCKFILE_VERSION}, got ${cache.version}`
1647
+ );
1648
+ cache = createEmptyLockfile();
1649
+ }
1650
+ return cache;
1651
+ }
1652
+ } catch (e) {
1653
+ serverLogger.debug(`[lockfile] Could not read lockfile: ${e}`);
1654
+ }
1655
+ return null;
1656
+ };
1657
+ const write = async (data) => {
1658
+ cache = data;
1659
+ const sorted = {
1660
+ version: data.version,
1661
+ imports: Object.fromEntries(
1662
+ Object.entries(data.imports).sort(([a], [b]) => a.localeCompare(b))
1663
+ )
1664
+ };
1665
+ await fs.writeFile(lockfilePath, JSON.stringify(sorted, null, 2) + "\n");
1666
+ dirty = false;
1667
+ serverLogger.debug(`[lockfile] Written ${Object.keys(data.imports).length} entries`);
1668
+ };
1669
+ const get = async (url) => {
1670
+ const data = await read();
1671
+ return data?.imports[url] ?? null;
1672
+ };
1673
+ const set = async (url, entry) => {
1674
+ let data = await read();
1675
+ if (!data) {
1676
+ data = createEmptyLockfile();
1677
+ }
1678
+ data.imports[url] = entry;
1679
+ cache = data;
1680
+ dirty = true;
1681
+ };
1682
+ const has = async (url) => {
1683
+ const data = await read();
1684
+ return url in (data?.imports ?? {});
1685
+ };
1686
+ const clear = async () => {
1687
+ cache = createEmptyLockfile();
1688
+ if (fs.remove && await fs.exists(lockfilePath)) {
1689
+ await fs.remove(lockfilePath);
1690
+ }
1691
+ };
1692
+ const flush = async () => {
1693
+ if (dirty && cache) {
1694
+ await write(cache);
1695
+ }
1696
+ };
1697
+ return {
1698
+ read,
1699
+ write,
1700
+ get,
1701
+ set,
1702
+ has,
1703
+ clear,
1704
+ flush
1705
+ };
1706
+ }
1707
+ async function fetchWithLock(options) {
1708
+ const { lockfile, url, fetchFn = fetch, strict = false } = options;
1709
+ const entry = await lockfile.get(url);
1710
+ if (entry) {
1711
+ serverLogger.debug(`[lockfile] Cache hit for ${url}`);
1712
+ const res2 = await fetchFn(entry.resolved, {
1713
+ headers: { "user-agent": "Mozilla/5.0 Veryfront/1.0" }
1714
+ });
1715
+ if (!res2.ok) {
1716
+ if (strict) {
1717
+ throw new Error(
1718
+ `Lockfile entry stale: ${url} resolved to ${entry.resolved} returned ${res2.status}`
1719
+ );
1720
+ }
1721
+ serverLogger.warn(`[lockfile] Cached URL ${entry.resolved} returned ${res2.status}, refetching`);
1722
+ } else {
1723
+ const content2 = await res2.text();
1724
+ const currentIntegrity = await computeIntegrity(content2);
1725
+ if (currentIntegrity !== entry.integrity) {
1726
+ if (strict) {
1727
+ throw new Error(
1728
+ `Integrity mismatch for ${url}: expected ${entry.integrity}, got ${currentIntegrity}`
1729
+ );
1730
+ }
1731
+ serverLogger.warn(`[lockfile] Integrity mismatch for ${url}, updating lockfile`);
1732
+ } else {
1733
+ return {
1734
+ content: content2,
1735
+ resolvedUrl: entry.resolved,
1736
+ fromCache: true,
1737
+ integrity: entry.integrity
1738
+ };
1739
+ }
1740
+ }
1741
+ }
1742
+ serverLogger.debug(`[lockfile] Fetching fresh: ${url}`);
1743
+ const res = await fetchFn(url, {
1744
+ headers: { "user-agent": "Mozilla/5.0 Veryfront/1.0" },
1745
+ redirect: "follow"
1746
+ });
1747
+ if (!res.ok) {
1748
+ throw new Error(`Failed to fetch ${url}: ${res.status}`);
1749
+ }
1750
+ const content = await res.text();
1751
+ const resolvedUrl = res.url || url;
1752
+ const integrity = await computeIntegrity(content);
1753
+ await lockfile.set(url, {
1754
+ resolved: resolvedUrl,
1755
+ integrity,
1756
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
1757
+ });
1758
+ await lockfile.flush();
1759
+ return {
1760
+ content,
1761
+ resolvedUrl,
1762
+ fromCache: false,
1763
+ integrity
1764
+ };
1765
+ }
1766
+ function extractImports(content) {
1767
+ const imports = [];
1768
+ const seen = /* @__PURE__ */ new Set();
1769
+ for (const match of content.matchAll(IMPORT_REGEX)) {
1770
+ const specifier = match[1];
1771
+ if (specifier && !seen.has(specifier)) {
1772
+ seen.add(specifier);
1773
+ imports.push({ specifier, type: "static" });
1774
+ }
1775
+ }
1776
+ for (const match of content.matchAll(EXPORT_FROM_REGEX)) {
1777
+ const specifier = match[1];
1778
+ if (specifier && !seen.has(specifier)) {
1779
+ seen.add(specifier);
1780
+ imports.push({ specifier, type: "static" });
1781
+ }
1782
+ }
1783
+ for (const match of content.matchAll(DYNAMIC_IMPORT_REGEX)) {
1784
+ const specifier = match[1];
1785
+ if (specifier && !seen.has(specifier)) {
1786
+ seen.add(specifier);
1787
+ imports.push({ specifier, type: "dynamic" });
1788
+ }
1789
+ }
1790
+ return imports;
1791
+ }
1792
+ function resolveImportUrl(specifier, baseUrl) {
1793
+ if (specifier.startsWith("http://") || specifier.startsWith("https://")) {
1794
+ return specifier;
1795
+ }
1796
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
1797
+ try {
1798
+ return new URL(specifier, baseUrl).toString();
1799
+ } catch {
1800
+ return null;
1801
+ }
1802
+ }
1803
+ return null;
1804
+ }
1805
+ var LOCKFILE_NAME, LOCKFILE_VERSION, IMPORT_REGEX, DYNAMIC_IMPORT_REGEX, EXPORT_FROM_REGEX;
1806
+ var init_import_lockfile = __esm({
1807
+ "src/core/utils/import-lockfile.ts"() {
1808
+ init_deno_env();
1809
+ init_hash_utils();
1810
+ init_logger2();
1811
+ LOCKFILE_NAME = "veryfront.lock";
1812
+ LOCKFILE_VERSION = 1;
1813
+ IMPORT_REGEX = /import\s+(?:(?:[\w*\s{},]*)\s+from\s+)?['"]([^'"]+)['"]/g;
1814
+ DYNAMIC_IMPORT_REGEX = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
1815
+ EXPORT_FROM_REGEX = /export\s+(?:[\w*\s{},]*)\s+from\s+['"]([^'"]+)['"]/g;
1816
+ }
1817
+ });
1818
+
1819
+ // src/core/utils/perf-timer.ts
1820
+ function startRequest(requestId) {
1821
+ if (!enabled)
1822
+ return;
1823
+ currentRequestId = requestId;
1824
+ timings.set(requestId, []);
1825
+ }
1826
+ function startTimer(label, parent) {
1827
+ if (!enabled || !currentRequestId)
1828
+ return () => {
1829
+ };
1830
+ const entry = {
1831
+ label,
1832
+ startMs: performance.now(),
1833
+ parent
1834
+ };
1835
+ const entries = timings.get(currentRequestId);
1836
+ if (entries) {
1837
+ entries.push(entry);
1838
+ }
1839
+ return () => {
1840
+ entry.endMs = performance.now();
1841
+ entry.durationMs = entry.endMs - entry.startMs;
1842
+ };
1843
+ }
1844
+ async function timeAsync(label, fn, parent) {
1845
+ if (!enabled)
1846
+ return fn();
1847
+ const stop = startTimer(label, parent);
1848
+ try {
1849
+ return await fn();
1850
+ } finally {
1851
+ stop();
1852
+ }
1853
+ }
1854
+ function endRequest(requestId) {
1855
+ if (!enabled)
1856
+ return;
1857
+ const entries = timings.get(requestId);
1858
+ if (!entries || entries.length === 0) {
1859
+ currentRequestId = null;
1860
+ return;
1861
+ }
1862
+ const sorted = entries.filter((e) => e.durationMs !== void 0).sort((a, b) => (b.durationMs || 0) - (a.durationMs || 0));
1863
+ const total = entries.find((e) => e.label === "total")?.durationMs || sorted.reduce((sum, e) => sum + (e.durationMs || 0), 0);
1864
+ console.log(`
1865
+ [PERF] Request ${requestId} - Total: ${total.toFixed(1)}ms`);
1866
+ console.log("\u2500".repeat(60));
1867
+ const roots = sorted.filter((e) => !e.parent);
1868
+ const children = /* @__PURE__ */ new Map();
1869
+ for (const entry of sorted) {
1870
+ if (entry.parent) {
1871
+ const list = children.get(entry.parent) || [];
1872
+ list.push(entry);
1873
+ children.set(entry.parent, list);
1874
+ }
1875
+ }
1876
+ for (const entry of roots) {
1877
+ const pct = ((entry.durationMs || 0) / total * 100).toFixed(1);
1878
+ console.log(` ${entry.label}: ${entry.durationMs?.toFixed(1)}ms (${pct}%)`);
1879
+ const childList = children.get(entry.label);
1880
+ if (childList) {
1881
+ for (const child of childList.slice(0, 5)) {
1882
+ const childPct = ((child.durationMs || 0) / total * 100).toFixed(1);
1883
+ console.log(` \u2514\u2500 ${child.label}: ${child.durationMs?.toFixed(1)}ms (${childPct}%)`);
1884
+ }
1885
+ if (childList.length > 5) {
1886
+ console.log(` \u2514\u2500 ... and ${childList.length - 5} more`);
1887
+ }
1888
+ }
1889
+ }
1890
+ console.log("\u2500".repeat(60));
1891
+ timings.delete(requestId);
1892
+ currentRequestId = null;
1893
+ }
1894
+ function isEnabled() {
1895
+ return enabled;
1896
+ }
1897
+ var enabled, timings, currentRequestId;
1898
+ var init_perf_timer = __esm({
1899
+ "src/core/utils/perf-timer.ts"() {
1900
+ init_deno_env();
1901
+ enabled = typeof process !== "undefined" ? process.env?.VERYFRONT_PERF === "1" : typeof Deno !== "undefined" ? Deno.env.get("VERYFRONT_PERF") === "1" : false;
1902
+ timings = /* @__PURE__ */ new Map();
1903
+ currentRequestId = null;
1904
+ }
1905
+ });
1906
+
1907
+ // src/core/utils/cookie-utils.ts
1908
+ function parseCookies(cookieHeader) {
1909
+ const cookies = {};
1910
+ if (!cookieHeader)
1911
+ return cookies;
1912
+ cookieHeader.split(";").forEach((cookie) => {
1913
+ const trimmed = cookie.trim();
1914
+ if (!trimmed)
1915
+ return;
1916
+ const separatorIndex = trimmed.indexOf("=");
1917
+ if (separatorIndex <= 0)
1918
+ return;
1919
+ const name = trimmed.slice(0, separatorIndex).trim();
1920
+ const value = trimmed.slice(separatorIndex + 1);
1921
+ if (!name)
1922
+ return;
1923
+ cookies[name] = decodeURIComponent(value);
1924
+ });
1925
+ return cookies;
1926
+ }
1927
+ function parseCookiesFromHeaders(headers) {
1928
+ return parseCookies(headers.get("cookie") || "");
1929
+ }
1930
+ var init_cookie_utils = __esm({
1931
+ "src/core/utils/cookie-utils.ts"() {
1932
+ init_deno_env();
1933
+ }
1934
+ });
1935
+
1936
+ // src/core/utils/base64url.ts
1937
+ function base64urlEncode(input) {
1938
+ const b64 = btoa(input);
1939
+ return b64.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
1940
+ }
1941
+ function base64urlEncodeBytes(bytes) {
1942
+ const b64 = btoa(String.fromCharCode(...bytes));
1943
+ return b64.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
1944
+ }
1945
+ var init_base64url = __esm({
1946
+ "src/core/utils/base64url.ts"() {
1947
+ init_deno_env();
1948
+ }
1949
+ });
1950
+
1455
1951
  // src/core/utils/index.ts
1456
1952
  var utils_exports = {};
1457
1953
  __export(utils_exports, {
@@ -1599,6 +2095,7 @@ __export(utils_exports, {
1599
2095
  SECONDS_PER_MINUTE: () => SECONDS_PER_MINUTE,
1600
2096
  SERVER_ACTION_DEFAULT_TTL_SEC: () => SERVER_ACTION_DEFAULT_TTL_SEC,
1601
2097
  SERVER_FUNCTION_DEFAULT_TIMEOUT_MS: () => SERVER_FUNCTION_DEFAULT_TIMEOUT_MS,
2098
+ TAILWIND_VERSION: () => TAILWIND_VERSION,
1602
2099
  TSX_LAYOUT_MAX_ENTRIES: () => TSX_LAYOUT_MAX_ENTRIES,
1603
2100
  TSX_LAYOUT_TTL_MS: () => TSX_LAYOUT_TTL_MS,
1604
2101
  UNOCSS_VERSION: () => UNOCSS_VERSION,
@@ -1609,13 +2106,22 @@ __export(utils_exports, {
1609
2106
  Z_INDEX_ERROR_OVERLAY: () => Z_INDEX_ERROR_OVERLAY,
1610
2107
  __loggerResetForTests: () => __loggerResetForTests,
1611
2108
  agentLogger: () => agentLogger,
2109
+ base64urlEncode: () => base64urlEncode,
2110
+ base64urlEncodeBytes: () => base64urlEncodeBytes,
1612
2111
  bundlerLogger: () => bundlerLogger,
1613
2112
  cliLogger: () => cliLogger,
1614
2113
  computeCodeHash: () => computeCodeHash,
1615
2114
  computeContentHash: () => computeContentHash,
1616
2115
  computeHash: () => computeHash,
2116
+ computeIntegrity: () => computeIntegrity,
2117
+ createEmptyLockfile: () => createEmptyLockfile,
2118
+ createLockfileManager: () => createLockfileManager,
2119
+ createRequestLogger: () => createRequestLogger,
2120
+ endRequest: () => endRequest,
1617
2121
  estimateSize: () => estimateSize,
1618
2122
  estimateSizeWithCircularHandling: () => estimateSizeWithCircularHandling,
2123
+ extractImports: () => extractImports,
2124
+ fetchWithLock: () => fetchWithLock,
1619
2125
  formatBytes: () => formatBytes,
1620
2126
  formatDuration: () => formatDuration,
1621
2127
  formatNumber: () => formatNumber,
@@ -1646,6 +2152,7 @@ __export(utils_exports, {
1646
2152
  isDebugEnabled: () => isDebugEnabled,
1647
2153
  isDeepInspectEnabled: () => isDeepInspectEnabled,
1648
2154
  isDevelopmentEnvironment: () => isDevelopmentEnvironment,
2155
+ isEnabled: () => isEnabled,
1649
2156
  isInternalEndpoint: () => isInternalEndpoint,
1650
2157
  isProductionEnvironment: () => isProductionEnvironment,
1651
2158
  isRSCEnabled: () => isRSCEnabled,
@@ -1662,13 +2169,21 @@ __export(utils_exports, {
1662
2169
  normalizeChunkPath: () => normalizeChunkPath,
1663
2170
  normalizePath: () => normalizePath,
1664
2171
  numericHash: () => simpleHash,
2172
+ parseCookies: () => parseCookies,
2173
+ parseCookiesFromHeaders: () => parseCookiesFromHeaders,
2174
+ proxyLogger: () => proxyLogger,
1665
2175
  rendererLogger: () => rendererLogger,
2176
+ resolveImportUrl: () => resolveImportUrl,
1666
2177
  serverLogger: () => serverLogger,
1667
2178
  setBundleManifestStore: () => setBundleManifestStore,
1668
2179
  shortHash: () => shortHash,
1669
2180
  simpleHash: () => simpleHash,
2181
+ startRequest: () => startRequest,
2182
+ startTimer: () => startTimer,
2183
+ timeAsync: () => timeAsync,
1670
2184
  toBase64Url: () => toBase64Url,
1671
2185
  truncateString: () => truncateString,
2186
+ verifyIntegrity: () => verifyIntegrity,
1672
2187
  warmupBundleManifest: () => warmupBundleManifest
1673
2188
  });
1674
2189
  var init_utils = __esm({
@@ -1687,6 +2202,10 @@ var init_utils = __esm({
1687
2202
  init_bundle_manifest_init();
1688
2203
  init_feature_flags();
1689
2204
  init_platform();
2205
+ init_import_lockfile();
2206
+ init_perf_timer();
2207
+ init_cookie_utils();
2208
+ init_base64url();
1690
2209
  }
1691
2210
  });
1692
2211
 
@@ -1712,6 +2231,56 @@ var init_veryfront_error = __esm({
1712
2231
 
1713
2232
  // src/core/config/schema.ts
1714
2233
  import { z } from "zod";
2234
+ function validateVeryfrontConfig(input) {
2235
+ const parsed = veryfrontConfigSchema.safeParse(input);
2236
+ if (!parsed.success) {
2237
+ const first = parsed.error.issues[0];
2238
+ const path = first?.path?.length ? first.path.join(".") : "<root>";
2239
+ const expected = first?.message || String(first);
2240
+ let hint = "";
2241
+ if (String(path).includes("security.cors")) {
2242
+ hint = " Expected boolean or { origin?: string }.";
2243
+ }
2244
+ const context = {
2245
+ field: path,
2246
+ expected: expected + hint,
2247
+ value: input
2248
+ };
2249
+ throw toError(
2250
+ createError({
2251
+ type: "config",
2252
+ message: `Invalid veryfront.config at ${path}: ${expected}.${hint}`,
2253
+ context
2254
+ })
2255
+ );
2256
+ }
2257
+ return parsed.data;
2258
+ }
2259
+ function findUnknownTopLevelKeys(input) {
2260
+ const known = /* @__PURE__ */ new Set([
2261
+ "title",
2262
+ "description",
2263
+ "experimental",
2264
+ "router",
2265
+ "defaultLayout",
2266
+ "layout",
2267
+ "provider",
2268
+ "app",
2269
+ "theme",
2270
+ "build",
2271
+ "cache",
2272
+ "dev",
2273
+ "resolve",
2274
+ "security",
2275
+ "middleware",
2276
+ "theming",
2277
+ "assetPipeline",
2278
+ "observability",
2279
+ "fs",
2280
+ "client"
2281
+ ]);
2282
+ return Object.keys(input).filter((k) => !known.has(k));
2283
+ }
1715
2284
  var corsSchema, veryfrontConfigSchema;
1716
2285
  var init_schema = __esm({
1717
2286
  "src/core/config/schema.ts"() {
@@ -1727,6 +2296,9 @@ var init_schema = __esm({
1727
2296
  }).partial().optional(),
1728
2297
  router: z.enum(["app", "pages"]).optional(),
1729
2298
  defaultLayout: z.string().optional(),
2299
+ layout: z.string().optional(),
2300
+ provider: z.string().optional(),
2301
+ app: z.string().optional(),
1730
2302
  theme: z.object({ colors: z.record(z.string()).optional() }).partial().optional(),
1731
2303
  build: z.object({
1732
2304
  outDir: z.string().optional(),
@@ -1822,6 +2394,8 @@ var init_schema = __esm({
1822
2394
  apiBaseUrl: z.string().url(),
1823
2395
  apiToken: z.string(),
1824
2396
  projectSlug: z.string(),
2397
+ proxyMode: z.boolean().optional(),
2398
+ productionMode: z.boolean().optional(),
1825
2399
  cache: z.object({
1826
2400
  enabled: z.boolean().optional(),
1827
2401
  ttl: z.number().int().positive().optional(),
@@ -1854,71 +2428,434 @@ var init_schema = __esm({
1854
2428
  }
1855
2429
  });
1856
2430
 
1857
- // src/core/config/loader.ts
1858
- import { join } from "node:path";
1859
- function getDefaultImportMapForConfig() {
1860
- return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };
2431
+ // src/platform/compat/fs.ts
2432
+ function createFileSystem() {
2433
+ if (isDeno) {
2434
+ return new DenoFileSystem();
2435
+ } else {
2436
+ return new NodeFileSystem();
2437
+ }
1861
2438
  }
1862
- var DEFAULT_CONFIG;
1863
- var init_loader = __esm({
1864
- "src/core/config/loader.ts"() {
2439
+ var NodeFileSystem, DenoFileSystem;
2440
+ var init_fs = __esm({
2441
+ "src/platform/compat/fs.ts"() {
1865
2442
  init_deno_env();
1866
- init_schema();
1867
- init_logger();
1868
- init_cdn();
1869
- init_server();
1870
- init_defaults();
1871
- DEFAULT_CONFIG = {
1872
- title: "Veryfront App",
1873
- description: "Built with Veryfront",
1874
- experimental: {
1875
- esmLayouts: true
1876
- },
1877
- router: void 0,
1878
- defaultLayout: void 0,
1879
- theme: {
1880
- colors: {
1881
- primary: "#3B82F6"
1882
- }
1883
- },
1884
- build: {
1885
- outDir: "dist",
1886
- trailingSlash: false,
1887
- esbuild: {
1888
- wasmURL: "https://deno.land/x/esbuild@v0.20.1/esbuild.wasm",
1889
- worker: false
1890
- }
1891
- },
1892
- cache: {
1893
- dir: DEFAULT_CACHE_DIR,
1894
- render: {
1895
- type: "memory",
1896
- ttl: void 0,
1897
- maxEntries: 500,
1898
- kvPath: void 0,
1899
- redisUrl: void 0,
1900
- redisKeyPrefix: void 0
2443
+ init_veryfront_error();
2444
+ init_runtime();
2445
+ NodeFileSystem = class {
2446
+ fs = null;
2447
+ os = null;
2448
+ path = null;
2449
+ initialized = false;
2450
+ async ensureInitialized() {
2451
+ if (this.initialized)
2452
+ return;
2453
+ if (!isNode) {
2454
+ throw toError(createError({
2455
+ type: "not_supported",
2456
+ message: "Node.js fs modules not available",
2457
+ feature: "Node.js"
2458
+ }));
1901
2459
  }
1902
- },
1903
- dev: {
1904
- port: DEFAULT_PORT,
1905
- host: "localhost",
1906
- open: false
1907
- },
1908
- resolve: {
1909
- importMap: getDefaultImportMapForConfig()
1910
- },
1911
- client: {
1912
- moduleResolution: "cdn",
1913
- cdn: {
1914
- provider: "esm.sh",
1915
- versions: "auto"
2460
+ const [fsModule, osModule, pathModule] = await Promise.all([
2461
+ import("node:fs/promises"),
2462
+ import("node:os"),
2463
+ import("node:path")
2464
+ ]);
2465
+ this.fs = fsModule;
2466
+ this.os = osModule;
2467
+ this.path = pathModule;
2468
+ this.initialized = true;
2469
+ }
2470
+ async readTextFile(path) {
2471
+ await this.ensureInitialized();
2472
+ return await this.fs.readFile(path, { encoding: "utf8" });
2473
+ }
2474
+ async readFile(path) {
2475
+ await this.ensureInitialized();
2476
+ return await this.fs.readFile(path);
2477
+ }
2478
+ async writeTextFile(path, data) {
2479
+ await this.ensureInitialized();
2480
+ await this.fs.writeFile(path, data, { encoding: "utf8" });
2481
+ }
2482
+ async writeFile(path, data) {
2483
+ await this.ensureInitialized();
2484
+ await this.fs.writeFile(path, data);
2485
+ }
2486
+ async exists(path) {
2487
+ await this.ensureInitialized();
2488
+ try {
2489
+ await this.fs.access(path);
2490
+ return true;
2491
+ } catch (error) {
2492
+ if (error.code === "ENOENT") {
2493
+ return false;
2494
+ }
2495
+ throw error;
1916
2496
  }
1917
2497
  }
1918
- };
1919
- }
1920
- });
1921
-
2498
+ async stat(path) {
2499
+ await this.ensureInitialized();
2500
+ const stat = await this.fs.stat(path);
2501
+ return {
2502
+ isFile: stat.isFile(),
2503
+ isDirectory: stat.isDirectory(),
2504
+ isSymlink: stat.isSymbolicLink(),
2505
+ size: stat.size,
2506
+ mtime: stat.mtime
2507
+ };
2508
+ }
2509
+ async mkdir(path, options) {
2510
+ await this.ensureInitialized();
2511
+ await this.fs.mkdir(path, { recursive: options?.recursive ?? false });
2512
+ }
2513
+ async *readDir(path) {
2514
+ await this.ensureInitialized();
2515
+ const entries = await this.fs.readdir(path, { withFileTypes: true });
2516
+ for (const entry of entries) {
2517
+ yield {
2518
+ name: entry.name,
2519
+ isFile: entry.isFile(),
2520
+ isDirectory: entry.isDirectory()
2521
+ };
2522
+ }
2523
+ }
2524
+ async remove(path, options) {
2525
+ await this.ensureInitialized();
2526
+ await this.fs.rm(path, {
2527
+ recursive: options?.recursive ?? false,
2528
+ force: options?.recursive ?? false
2529
+ });
2530
+ }
2531
+ async makeTempDir(options) {
2532
+ await this.ensureInitialized();
2533
+ const tempDir = this.path.join(
2534
+ this.os.tmpdir(),
2535
+ `${options?.prefix ?? "tmp-"}${Math.random().toString(36).substring(2, 8)}`
2536
+ );
2537
+ await this.fs.mkdir(tempDir, { recursive: true });
2538
+ return tempDir;
2539
+ }
2540
+ };
2541
+ DenoFileSystem = class {
2542
+ async readTextFile(path) {
2543
+ return await Deno.readTextFile(path);
2544
+ }
2545
+ async readFile(path) {
2546
+ return await Deno.readFile(path);
2547
+ }
2548
+ async writeTextFile(path, data) {
2549
+ await Deno.writeTextFile(path, data);
2550
+ }
2551
+ async writeFile(path, data) {
2552
+ await Deno.writeFile(path, data);
2553
+ }
2554
+ async exists(path) {
2555
+ try {
2556
+ await Deno.stat(path);
2557
+ return true;
2558
+ } catch (error) {
2559
+ if (error instanceof Deno.errors.NotFound) {
2560
+ return false;
2561
+ }
2562
+ throw error;
2563
+ }
2564
+ }
2565
+ async stat(path) {
2566
+ const stat = await Deno.stat(path);
2567
+ return {
2568
+ isFile: stat.isFile,
2569
+ isDirectory: stat.isDirectory,
2570
+ isSymlink: stat.isSymlink,
2571
+ size: stat.size,
2572
+ mtime: stat.mtime
2573
+ };
2574
+ }
2575
+ async mkdir(path, options) {
2576
+ await Deno.mkdir(path, { recursive: options?.recursive ?? false });
2577
+ }
2578
+ async *readDir(path) {
2579
+ for await (const entry of Deno.readDir(path)) {
2580
+ yield {
2581
+ name: entry.name,
2582
+ isFile: entry.isFile,
2583
+ isDirectory: entry.isDirectory
2584
+ };
2585
+ }
2586
+ }
2587
+ async remove(path, options) {
2588
+ await Deno.remove(path, { recursive: options?.recursive ?? false });
2589
+ }
2590
+ async makeTempDir(options) {
2591
+ return await Deno.makeTempDir({ prefix: options?.prefix });
2592
+ }
2593
+ };
2594
+ }
2595
+ });
2596
+
2597
+ // src/core/config/loader.ts
2598
+ import { dirname, join } from "node:path";
2599
+ function getDefaultImportMapForConfig() {
2600
+ return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };
2601
+ }
2602
+ function validateCorsConfig(userConfig) {
2603
+ if (!userConfig || typeof userConfig !== "object") {
2604
+ return;
2605
+ }
2606
+ const config = userConfig;
2607
+ const security = config.security;
2608
+ const cors = security?.cors;
2609
+ if (!cors || typeof cors !== "object" || Array.isArray(cors)) {
2610
+ return;
2611
+ }
2612
+ const corsObj = cors;
2613
+ const origin = corsObj.origin;
2614
+ if (origin !== void 0 && typeof origin !== "string") {
2615
+ throw new ConfigValidationError(
2616
+ "security.cors.origin must be a string. Expected boolean or { origin?: string }"
2617
+ );
2618
+ }
2619
+ }
2620
+ function validateConfigShape(userConfig) {
2621
+ validateVeryfrontConfig(userConfig);
2622
+ const unknown = typeof userConfig === "object" && userConfig ? findUnknownTopLevelKeys(userConfig) : [];
2623
+ if (unknown.length > 0) {
2624
+ serverLogger.warn(`Unknown config keys: ${unknown.join(", ")}. These will be ignored.`);
2625
+ }
2626
+ }
2627
+ function mergeConfigs(userConfig) {
2628
+ const merged = {
2629
+ ...DEFAULT_CONFIG,
2630
+ ...userConfig,
2631
+ dev: {
2632
+ ...DEFAULT_CONFIG.dev,
2633
+ ...userConfig.dev
2634
+ },
2635
+ theme: {
2636
+ ...DEFAULT_CONFIG.theme,
2637
+ ...userConfig.theme
2638
+ },
2639
+ build: {
2640
+ ...DEFAULT_CONFIG.build,
2641
+ ...userConfig.build
2642
+ },
2643
+ cache: {
2644
+ ...DEFAULT_CONFIG.cache,
2645
+ ...userConfig.cache
2646
+ },
2647
+ resolve: {
2648
+ ...DEFAULT_CONFIG.resolve,
2649
+ ...userConfig.resolve
2650
+ },
2651
+ client: {
2652
+ ...DEFAULT_CONFIG.client,
2653
+ ...userConfig.client,
2654
+ cdn: {
2655
+ ...DEFAULT_CONFIG.client?.cdn,
2656
+ ...userConfig.client?.cdn
2657
+ }
2658
+ }
2659
+ };
2660
+ if (merged.resolve) {
2661
+ const defaultMap = DEFAULT_CONFIG.resolve?.importMap;
2662
+ const userMap = userConfig.resolve?.importMap;
2663
+ if (defaultMap || userMap) {
2664
+ merged.resolve.importMap = {
2665
+ imports: {
2666
+ ...defaultMap?.imports ?? {},
2667
+ ...userMap?.imports ?? {}
2668
+ },
2669
+ scopes: {
2670
+ ...defaultMap?.scopes ?? {},
2671
+ ...userMap?.scopes ?? {}
2672
+ }
2673
+ };
2674
+ }
2675
+ }
2676
+ return merged;
2677
+ }
2678
+ function isVirtualFilesystem(adapter) {
2679
+ const wrappedAdapter = adapter?.fs?.fsAdapter;
2680
+ const adapterName = wrappedAdapter?.constructor?.name;
2681
+ return adapterName === "VeryfrontFSAdapter" || adapterName === "MultiProjectFSAdapter";
2682
+ }
2683
+ async function loadConfigFromVirtualFS(configPath, projectDir, adapter) {
2684
+ const fs = createFileSystem();
2685
+ const content = await adapter.fs.readFile(configPath);
2686
+ const source = typeof content === "string" ? content : new TextDecoder().decode(content);
2687
+ serverLogger.debug(`[CONFIG] Loading config from virtual FS: ${configPath}`);
2688
+ const isTsx = configPath.endsWith(".tsx");
2689
+ const loader = isTsx ? "tsx" : configPath.endsWith(".ts") ? "ts" : "js";
2690
+ const { build } = await import("esbuild");
2691
+ const result = await build({
2692
+ bundle: false,
2693
+ // Config files shouldn't need bundling
2694
+ write: false,
2695
+ format: "esm",
2696
+ platform: "neutral",
2697
+ target: "es2022",
2698
+ stdin: {
2699
+ contents: source,
2700
+ loader,
2701
+ resolveDir: dirname(configPath),
2702
+ sourcefile: configPath
2703
+ }
2704
+ });
2705
+ if (result.errors && result.errors.length > 0) {
2706
+ const first = result.errors[0]?.text || "unknown error";
2707
+ throw new ConfigValidationError(`Failed to transpile config: ${first}`);
2708
+ }
2709
+ const js = result.outputFiles?.[0]?.text ?? "export default {}";
2710
+ const tempDir = await fs.makeTempDir({ prefix: "vf-config-" });
2711
+ const tempFile = join(tempDir, "config.mjs");
2712
+ try {
2713
+ await fs.writeTextFile(tempFile, js);
2714
+ const configModule = await import(`file://${tempFile}?v=${Date.now()}`);
2715
+ const userConfig = configModule.default || configModule;
2716
+ if (userConfig === null || typeof userConfig !== "object" || Array.isArray(userConfig)) {
2717
+ throw new ConfigValidationError(
2718
+ `Expected object, received ${userConfig === null ? "null" : typeof userConfig}`
2719
+ );
2720
+ }
2721
+ validateCorsConfig(userConfig);
2722
+ validateConfigShape(userConfig);
2723
+ const merged = mergeConfigs(userConfig);
2724
+ configCacheByProject.set(projectDir, { revision: cacheRevision, config: merged });
2725
+ return merged;
2726
+ } finally {
2727
+ await fs.remove(tempDir, { recursive: true });
2728
+ }
2729
+ }
2730
+ async function loadAndMergeConfig(configPath, projectDir, adapter) {
2731
+ if (isVirtualFilesystem(adapter)) {
2732
+ return loadConfigFromVirtualFS(configPath, projectDir, adapter);
2733
+ }
2734
+ try {
2735
+ const configUrl = `file://${configPath}?t=${Date.now()}-${crypto.randomUUID()}`;
2736
+ const configModule = await import(configUrl);
2737
+ const userConfig = configModule.default || configModule;
2738
+ if (userConfig === null || typeof userConfig !== "object" || Array.isArray(userConfig)) {
2739
+ throw new ConfigValidationError(
2740
+ `Expected object, received ${userConfig === null ? "null" : typeof userConfig}`
2741
+ );
2742
+ }
2743
+ validateCorsConfig(userConfig);
2744
+ validateConfigShape(userConfig);
2745
+ const merged = mergeConfigs(userConfig);
2746
+ configCacheByProject.set(projectDir, { revision: cacheRevision, config: merged });
2747
+ return merged;
2748
+ } catch (error) {
2749
+ if (error instanceof ConfigValidationError) {
2750
+ throw error;
2751
+ }
2752
+ if (error instanceof Error && error.message.startsWith("Invalid veryfront.config")) {
2753
+ throw error;
2754
+ }
2755
+ throw error;
2756
+ }
2757
+ }
2758
+ async function getConfig(projectDir, adapter) {
2759
+ const cached = configCacheByProject.get(projectDir);
2760
+ if (cached && cached.revision === cacheRevision)
2761
+ return cached.config;
2762
+ const configFiles = ["veryfront.config.js", "veryfront.config.ts", "veryfront.config.mjs"];
2763
+ for (const configFile of configFiles) {
2764
+ const configPath = join(projectDir, configFile);
2765
+ const exists = await adapter.fs.exists(configPath);
2766
+ if (!exists)
2767
+ continue;
2768
+ try {
2769
+ const merged = await loadAndMergeConfig(configPath, projectDir, adapter);
2770
+ if (merged)
2771
+ return merged;
2772
+ } catch (error) {
2773
+ if (error instanceof ConfigValidationError) {
2774
+ throw error;
2775
+ }
2776
+ if (error instanceof Error && error.message.startsWith("Invalid veryfront.config")) {
2777
+ throw error;
2778
+ }
2779
+ const errorMessage = error instanceof Error ? error.message : String(error);
2780
+ serverLogger.debug(`[CONFIG] Failed to load ${configFile}, trying next config file:`, {
2781
+ error: errorMessage
2782
+ });
2783
+ continue;
2784
+ }
2785
+ }
2786
+ const defaultConfig2 = DEFAULT_CONFIG;
2787
+ configCacheByProject.set(projectDir, { revision: cacheRevision, config: defaultConfig2 });
2788
+ return defaultConfig2;
2789
+ }
2790
+ var DEFAULT_CONFIG, configCacheByProject, cacheRevision, ConfigValidationError;
2791
+ var init_loader = __esm({
2792
+ "src/core/config/loader.ts"() {
2793
+ init_deno_env();
2794
+ init_schema();
2795
+ init_logger();
2796
+ init_cdn();
2797
+ init_server();
2798
+ init_defaults();
2799
+ init_fs();
2800
+ DEFAULT_CONFIG = {
2801
+ title: "Veryfront App",
2802
+ description: "Built with Veryfront",
2803
+ experimental: {
2804
+ esmLayouts: true
2805
+ },
2806
+ router: void 0,
2807
+ defaultLayout: void 0,
2808
+ theme: {
2809
+ colors: {
2810
+ primary: "#3B82F6"
2811
+ }
2812
+ },
2813
+ build: {
2814
+ outDir: "dist",
2815
+ trailingSlash: false,
2816
+ esbuild: {
2817
+ wasmURL: "https://deno.land/x/esbuild@v0.20.1/esbuild.wasm",
2818
+ worker: false
2819
+ }
2820
+ },
2821
+ cache: {
2822
+ dir: DEFAULT_CACHE_DIR,
2823
+ render: {
2824
+ type: "memory",
2825
+ ttl: void 0,
2826
+ maxEntries: 500,
2827
+ kvPath: void 0,
2828
+ redisUrl: void 0,
2829
+ redisKeyPrefix: void 0
2830
+ }
2831
+ },
2832
+ dev: {
2833
+ port: DEFAULT_PORT,
2834
+ host: "localhost",
2835
+ open: false
2836
+ },
2837
+ resolve: {
2838
+ importMap: getDefaultImportMapForConfig()
2839
+ },
2840
+ client: {
2841
+ moduleResolution: "cdn",
2842
+ cdn: {
2843
+ provider: "esm.sh",
2844
+ versions: "auto"
2845
+ }
2846
+ }
2847
+ };
2848
+ configCacheByProject = /* @__PURE__ */ new Map();
2849
+ cacheRevision = 0;
2850
+ ConfigValidationError = class extends Error {
2851
+ constructor(message) {
2852
+ super(message);
2853
+ this.name = "ConfigValidationError";
2854
+ }
2855
+ };
2856
+ }
2857
+ });
2858
+
1922
2859
  // src/core/config/define-config.ts
1923
2860
  var init_define_config = __esm({
1924
2861
  "src/core/config/define-config.ts"() {
@@ -2204,7 +3141,7 @@ var init_deno2 = __esm({
2204
3141
  });
2205
3142
 
2206
3143
  // src/platform/adapters/shared-watcher.ts
2207
- import { join as join3 } from "node:path";
3144
+ import { join as join5 } from "node:path";
2208
3145
  async function setupNodeFsWatcher(path, options) {
2209
3146
  try {
2210
3147
  const fs = await import("node:fs");
@@ -2216,7 +3153,7 @@ async function setupNodeFsWatcher(path, options) {
2216
3153
  if (options.closed() || options.signal?.aborted)
2217
3154
  return;
2218
3155
  const kind = eventType === "change" ? "modify" : "any";
2219
- const fullPath = filename ? join3(path, filename) : path;
3156
+ const fullPath = filename ? join5(path, filename) : path;
2220
3157
  enqueueWatchEvent(
2221
3158
  { kind, paths: [fullPath] },
2222
3159
  options.eventQueue,
@@ -2344,9 +3281,9 @@ var init_filesystem_adapter = __esm({
2344
3281
  }
2345
3282
  async makeTempDir(prefix) {
2346
3283
  const { mkdtemp } = await import("node:fs/promises");
2347
- const { join: join5 } = await import("node:path");
3284
+ const { join: join7 } = await import("node:path");
2348
3285
  const { tmpdir } = await import("node:os");
2349
- return await mkdtemp(join5(tmpdir(), prefix));
3286
+ return await mkdtemp(join7(tmpdir(), prefix));
2350
3287
  }
2351
3288
  watch(paths, options) {
2352
3289
  const pathArray = Array.isArray(paths) ? paths : [paths];
@@ -2848,6 +3785,14 @@ var init_error_handlers = __esm({
2848
3785
  }
2849
3786
  });
2850
3787
 
3788
+ // src/core/errors/error-context.ts
3789
+ var init_error_context = __esm({
3790
+ "src/core/errors/error-context.ts"() {
3791
+ init_deno_env();
3792
+ init_logger();
3793
+ }
3794
+ });
3795
+
2851
3796
  // src/core/errors/error-codes.ts
2852
3797
  function getErrorDocsUrl(code) {
2853
3798
  return `https://veryfront.com/docs/errors/${code}`;
@@ -3990,6 +4935,7 @@ var init_errors = __esm({
3990
4935
  init_runtime_errors();
3991
4936
  init_system_errors();
3992
4937
  init_error_handlers();
4938
+ init_error_context();
3993
4939
  init_catalog();
3994
4940
  init_user_friendly();
3995
4941
  }
@@ -4059,9 +5005,9 @@ var init_filesystem_adapter2 = __esm({
4059
5005
  }
4060
5006
  async makeTempDir(prefix) {
4061
5007
  const { mkdtemp } = await import("node:fs/promises");
4062
- const { join: join5 } = await import("node:path");
5008
+ const { join: join7 } = await import("node:path");
4063
5009
  const { tmpdir } = await import("node:os");
4064
- return await mkdtemp(join5(tmpdir(), prefix));
5010
+ return await mkdtemp(join7(tmpdir(), prefix));
4065
5011
  }
4066
5012
  watch(paths, options) {
4067
5013
  const pathArray = Array.isArray(paths) ? paths : [paths];
@@ -5134,6 +6080,9 @@ var LRUCache = class {
5134
6080
  this.adapter.cleanupExpired();
5135
6081
  }, this.cleanupIntervalMs);
5136
6082
  this.cleanupTimer = timer;
6083
+ if (typeof Deno !== "undefined" && "unrefTimer" in Deno) {
6084
+ Deno.unrefTimer(timer);
6085
+ }
5137
6086
  }
5138
6087
  toStringKey(key) {
5139
6088
  if (typeof key === "string") {
@@ -5211,20 +6160,110 @@ init_deno_env();
5211
6160
  init_deno_env();
5212
6161
  init_utils();
5213
6162
  init_config();
5214
- import { dirname, join as join2 } from "node:path";
6163
+ import { dirname as dirname2, join as join2 } from "node:path";
5215
6164
 
5216
6165
  // src/module-system/import-map/default-import-map.ts
5217
6166
  init_deno_env();
5218
- init_utils();
6167
+
6168
+ // src/build/transforms/esm/package-registry.ts
6169
+ init_deno_env();
6170
+ var REACT_VERSION = "18.3.1";
6171
+ var CONTEXT_PACKAGES = {
6172
+ "@tanstack/react-query": { version: "5", external: ["react"] },
6173
+ "@tanstack/query-core": { version: "5", external: [] },
6174
+ "next-themes": { version: "0.4", external: ["react"] },
6175
+ "framer-motion": { version: "11", external: ["react"] },
6176
+ "react-hook-form": { version: "7", external: ["react", "react-dom"] }
6177
+ };
6178
+ var CONTEXT_PACKAGE_NAMES = Object.keys(CONTEXT_PACKAGES);
6179
+ function getEsmShUrl(pkg, version, external) {
6180
+ const base = `https://esm.sh/${pkg}@${version}`;
6181
+ const params = [`target=es2022`];
6182
+ if (external?.length) {
6183
+ params.push(`external=${external.join(",")}`);
6184
+ }
6185
+ return `${base}?${params.join("&")}`;
6186
+ }
6187
+ function getContextPackageUrlSSR(pkg) {
6188
+ const config = CONTEXT_PACKAGES[pkg];
6189
+ return getEsmShUrl(pkg, config.version, config.external);
6190
+ }
6191
+ function getContextPackageUrlBrowser(pkg) {
6192
+ const config = CONTEXT_PACKAGES[pkg];
6193
+ return getEsmShUrl(pkg, config.version, config.external);
6194
+ }
6195
+ function isContextPackage(pkg) {
6196
+ return pkg in CONTEXT_PACKAGES;
6197
+ }
6198
+ function getReactUrls() {
6199
+ return {
6200
+ react: `https://esm.sh/react@${REACT_VERSION}?target=es2022`,
6201
+ "react-dom": `https://esm.sh/react-dom@${REACT_VERSION}?target=es2022`,
6202
+ "react-dom/client": `https://esm.sh/react-dom@${REACT_VERSION}/client?target=es2022`,
6203
+ "react-dom/server": `https://esm.sh/react-dom@${REACT_VERSION}/server?target=es2022`,
6204
+ "react/jsx-runtime": `https://esm.sh/react@${REACT_VERSION}/jsx-runtime?target=es2022`,
6205
+ "react/jsx-dev-runtime": `https://esm.sh/react@${REACT_VERSION}/jsx-dev-runtime?target=es2022`
6206
+ };
6207
+ }
6208
+ function getReactImportMap2() {
6209
+ return {
6210
+ ...getReactUrls(),
6211
+ // Prefix match for any react/* subpath imports
6212
+ "react/": `https://esm.sh/react@${REACT_VERSION}/?target=es2022`
6213
+ };
6214
+ }
6215
+
6216
+ // src/module-system/import-map/default-import-map.ts
6217
+ function getVeryfrontSsrImportMap() {
6218
+ return {
6219
+ "veryfront/head": "veryfront/head",
6220
+ "veryfront/router": "veryfront/router",
6221
+ "veryfront/context": "veryfront/context",
6222
+ "veryfront/fonts": "veryfront/fonts"
6223
+ };
6224
+ }
6225
+ function getContextPackageImportMapSSR() {
6226
+ const map = {};
6227
+ for (const pkg of CONTEXT_PACKAGE_NAMES) {
6228
+ map[pkg] = getContextPackageUrlSSR(pkg);
6229
+ }
6230
+ return map;
6231
+ }
5219
6232
  function getDefaultImportMap() {
5220
- const reactVersion = REACT_DEFAULT_VERSION;
5221
- const importMap = getReactImportMap(reactVersion);
5222
- importMap["react/"] = `https://esm.sh/react@${reactVersion}/`;
5223
- return { imports: importMap };
6233
+ return {
6234
+ imports: {
6235
+ // Veryfront exports - local resolution
6236
+ ...getVeryfrontSsrImportMap(),
6237
+ // Context packages via esm.sh URLs (matches browser)
6238
+ ...getContextPackageImportMapSSR()
6239
+ }
6240
+ };
5224
6241
  }
5225
6242
 
5226
6243
  // src/module-system/import-map/resolver.ts
5227
6244
  init_deno_env();
6245
+ function extractEsmShPackage(url) {
6246
+ if (!url.startsWith("https://esm.sh/") && !url.startsWith("http://esm.sh/")) {
6247
+ return null;
6248
+ }
6249
+ try {
6250
+ const parsed = new URL(url);
6251
+ let pathname = parsed.pathname.slice(1);
6252
+ pathname = pathname.replace(/^v\d+\//, "");
6253
+ let packageName;
6254
+ if (pathname.startsWith("@")) {
6255
+ const parts = pathname.split("/");
6256
+ const scopedName = parts.slice(0, 2).join("/");
6257
+ packageName = scopedName.replace(/@[\d.]+.*$/, "");
6258
+ } else {
6259
+ const parts = pathname.split("@");
6260
+ packageName = (parts[0] ?? "").split("/")[0] ?? "";
6261
+ }
6262
+ return packageName || null;
6263
+ } catch {
6264
+ return null;
6265
+ }
6266
+ }
5228
6267
  function resolveImport(specifier, importMap, scope) {
5229
6268
  if (scope && importMap.scopes?.[scope]?.[specifier]) {
5230
6269
  return importMap.scopes[scope][specifier];
@@ -5232,6 +6271,35 @@ function resolveImport(specifier, importMap, scope) {
5232
6271
  if (importMap.imports?.[specifier]) {
5233
6272
  return importMap.imports[specifier];
5234
6273
  }
6274
+ if (specifier.startsWith("https://esm.sh/") || specifier.startsWith("http://esm.sh/")) {
6275
+ const esmShPackage = extractEsmShPackage(specifier);
6276
+ const scopedMapping = scope && esmShPackage && importMap.scopes?.[scope]?.[esmShPackage];
6277
+ const globalMapping = esmShPackage && importMap.imports?.[esmShPackage];
6278
+ const mapping = scopedMapping || globalMapping;
6279
+ if (mapping) {
6280
+ const url = new URL(specifier);
6281
+ const pathname = url.pathname.slice(1).replace(/^v\d+\//, "");
6282
+ let subpath = "";
6283
+ if (pathname.startsWith("@")) {
6284
+ const parts = pathname.split("/");
6285
+ if (parts.length > 2) {
6286
+ const packageParts = parts.slice(0, 2).join("/");
6287
+ const afterPackage = pathname.slice(packageParts.length);
6288
+ const versionMatch = afterPackage.match(/^@[^/]+(.*)$/);
6289
+ subpath = versionMatch?.[1] ?? "";
6290
+ }
6291
+ } else {
6292
+ if (pathname.includes("/")) {
6293
+ const packageWithVersion = pathname.split("/")[0];
6294
+ const restPath = pathname.slice(packageWithVersion.length);
6295
+ if (restPath.startsWith("/")) {
6296
+ subpath = restPath;
6297
+ }
6298
+ }
6299
+ }
6300
+ return subpath ? mapping + subpath : mapping;
6301
+ }
6302
+ }
5235
6303
  if (specifier.endsWith(".js") || specifier.endsWith(".mjs") || specifier.endsWith(".cjs")) {
5236
6304
  const base = specifier.replace(/\.(m|c)?js$/, "");
5237
6305
  if (importMap.imports?.[base]) {
@@ -5250,13 +6318,22 @@ function resolveImport(specifier, importMap, scope) {
5250
6318
 
5251
6319
  // src/module-system/import-map/transformer.ts
5252
6320
  init_deno_env();
6321
+ function shouldResolve(specifier, options) {
6322
+ if (specifier.startsWith("https://esm.sh/") || specifier.startsWith("http://esm.sh/")) {
6323
+ return true;
6324
+ }
6325
+ const isBare = !specifier.startsWith("http") && !specifier.startsWith("/") && !specifier.startsWith(".");
6326
+ if (isBare && !options?.resolveBare) {
6327
+ return false;
6328
+ }
6329
+ return true;
6330
+ }
5253
6331
  function transformImportsWithMap(code, importMap, scope, options) {
5254
6332
  let transformedCode = code;
5255
6333
  transformedCode = transformedCode.replace(
5256
6334
  /((?:import|export)\s+(?:[\w,{}\s*]+\s+from\s+)?|export\s+(?:\*|\{[^}]+\})\s+from\s+)["']([^"']+)["']/g,
5257
6335
  (_match, prefix, specifier) => {
5258
- const isBare = !specifier.startsWith("http") && !specifier.startsWith("/") && !specifier.startsWith(".");
5259
- if (isBare && !options?.resolveBare) {
6336
+ if (!shouldResolve(specifier, options)) {
5260
6337
  return `${prefix}"${specifier}"`;
5261
6338
  }
5262
6339
  const resolved = resolveImport(specifier, importMap, scope);
@@ -5266,8 +6343,7 @@ function transformImportsWithMap(code, importMap, scope, options) {
5266
6343
  transformedCode = transformedCode.replace(
5267
6344
  /from\s+["']([^"']+)["']/g,
5268
6345
  (match, specifier) => {
5269
- const isBare = !specifier.startsWith("http") && !specifier.startsWith("/") && !specifier.startsWith(".");
5270
- if (isBare && !options?.resolveBare) {
6346
+ if (!shouldResolve(specifier, options)) {
5271
6347
  return match;
5272
6348
  }
5273
6349
  const resolved = resolveImport(specifier, importMap, scope);
@@ -5290,28 +6366,2157 @@ init_deno_env();
5290
6366
  // src/build/transforms/mdx/esm-module-loader.ts
5291
6367
  init_runtime();
5292
6368
  init_process();
5293
- import { join as join4 } from "node:path";
5294
- var IS_TRUE_NODE = isNode && !isDeno;
5295
- var LOG_PREFIX_MDX_LOADER = "[mdx-loader]";
5296
- var LOG_PREFIX_MDX_RENDERER = "[mdx-renderer]";
5297
- var JSX_IMPORT_PATTERN = /import\s+([^'"]+)\s+from\s+['"]file:\/\/([^'"]+\.(jsx|tsx))['"];?/g;
5298
- var REACT_IMPORT_PATTERN = /import\s+.*React.*\s+from\s+['"]react['"]/;
5299
- var HTTP_IMPORT_PATTERN = /['"]https?:\/\/[^'"]+['"]/;
5300
- var ESBUILD_JSX_FACTORY = "React.createElement";
5301
- var ESBUILD_JSX_FRAGMENT = "React.Fragment";
5302
- var HTTP_MODULE_FETCH_TIMEOUT_MS2 = 3e4;
5303
- var _resolvedPaths = {};
5304
- async function resolveNodePackage(packageSpec) {
5305
- if (!IS_TRUE_NODE)
5306
- return null;
5307
- if (packageSpec in _resolvedPaths)
5308
- return _resolvedPaths[packageSpec];
5309
- try {
5310
- const { createRequire } = await import("node:module");
5311
- const require2 = createRequire(import.meta.url);
5312
- const resolved = require2.resolve(packageSpec);
5313
- _resolvedPaths[packageSpec] = resolved;
5314
- return resolved;
6369
+ init_fs();
6370
+ import { join as join6, posix } from "node:path";
6371
+
6372
+ // src/build/transforms/esm-transform.ts
6373
+ init_deno_env();
6374
+
6375
+ // src/build/transforms/esm/index.ts
6376
+ init_deno_env();
6377
+
6378
+ // src/build/transforms/pipeline/index.ts
6379
+ init_deno_env();
6380
+
6381
+ // src/build/transforms/esm/transform-cache.ts
6382
+ init_deno_env();
6383
+
6384
+ // src/core/memory/index.ts
6385
+ init_deno_env();
6386
+
6387
+ // src/core/memory/profiler.ts
6388
+ init_deno_env();
6389
+ init_utils();
6390
+ var cacheRegistry = /* @__PURE__ */ new Map();
6391
+ function registerCache(name, getStats) {
6392
+ cacheRegistry.set(name, getStats);
6393
+ rendererLogger.debug(`[MemoryProfiler] Registered cache: ${name}`);
6394
+ }
6395
+
6396
+ // src/build/transforms/esm/transform-cache.ts
6397
+ init_logger();
6398
+
6399
+ // src/core/utils/redis-client.ts
6400
+ init_deno_env();
6401
+ init_logger();
6402
+
6403
+ // src/build/transforms/esm/transform-cache.ts
6404
+ var DEFAULT_TTL_MS = 5 * 60 * 1e3;
6405
+ var DEFAULT_TTL_SECONDS = 300;
6406
+ var MAX_ENTRIES = 2e3;
6407
+ var CLEANUP_INTERVAL_MS = 6e4;
6408
+ var REDIS_KEY_PREFIX = "veryfront:transform:";
6409
+ var memoryCache = /* @__PURE__ */ new Map();
6410
+ var redisEnabled = false;
6411
+ var redisClient = null;
6412
+ registerCache("transform-cache", () => ({
6413
+ name: "transform-cache",
6414
+ entries: memoryCache.size,
6415
+ maxEntries: MAX_ENTRIES,
6416
+ redisEnabled
6417
+ }));
6418
+ var cleanupInterval;
6419
+ function shouldDisableInterval2() {
6420
+ if (globalThis.__vfDisableLruInterval === true) {
6421
+ return true;
6422
+ }
6423
+ try {
6424
+ if (typeof Deno !== "undefined" && Deno.env) {
6425
+ return Deno.env.get("VF_DISABLE_LRU_INTERVAL") === "1";
6426
+ }
6427
+ } catch {
6428
+ }
6429
+ return false;
6430
+ }
6431
+ function startPeriodicCleanup() {
6432
+ if (shouldDisableInterval2()) {
6433
+ return;
6434
+ }
6435
+ if (cleanupInterval)
6436
+ return;
6437
+ cleanupInterval = setInterval(() => {
6438
+ const now = Date.now();
6439
+ for (const [key, entry] of memoryCache) {
6440
+ if (entry.expiresAt <= now) {
6441
+ memoryCache.delete(key);
6442
+ }
6443
+ }
6444
+ }, CLEANUP_INTERVAL_MS);
6445
+ if (typeof Deno !== "undefined" && "unrefTimer" in Deno) {
6446
+ Deno.unrefTimer(cleanupInterval);
6447
+ }
6448
+ }
6449
+ startPeriodicCleanup();
6450
+ function generateCacheKey(projectId, filePath, contentHash, ssr = false) {
6451
+ const projectKey = projectId?.trim() || "default";
6452
+ const ssrKey = ssr ? "ssr" : "browser";
6453
+ return `${projectKey}:${filePath}:${contentHash}:${ssrKey}`;
6454
+ }
6455
+ function redisKey(key) {
6456
+ return `${REDIS_KEY_PREFIX}${key}`;
6457
+ }
6458
+ function getCachedTransform(key) {
6459
+ const entry = memoryCache.get(key);
6460
+ if (!entry) {
6461
+ return void 0;
6462
+ }
6463
+ if (entry.expiresAt <= Date.now()) {
6464
+ memoryCache.delete(key);
6465
+ return void 0;
6466
+ }
6467
+ return entry;
6468
+ }
6469
+ function setCachedTransform(key, code, hash, ttl = DEFAULT_TTL_MS) {
6470
+ const now = Date.now();
6471
+ memoryCache.set(key, {
6472
+ code,
6473
+ hash,
6474
+ timestamp: now,
6475
+ expiresAt: now + Math.max(1, ttl)
6476
+ });
6477
+ if (memoryCache.size > MAX_ENTRIES) {
6478
+ pruneMemoryCache();
6479
+ }
6480
+ if (redisEnabled && redisClient) {
6481
+ const entry = {
6482
+ code,
6483
+ hash,
6484
+ timestamp: now,
6485
+ expiresAt: now + Math.max(1, ttl)
6486
+ };
6487
+ const ttlSeconds = Math.ceil(ttl / 1e3);
6488
+ redisClient.set(redisKey(key), JSON.stringify(entry), {
6489
+ EX: ttlSeconds > 0 ? ttlSeconds : DEFAULT_TTL_SECONDS
6490
+ }).catch((error) => {
6491
+ logger.debug("[TransformCache] Redis set failed", { key, error });
6492
+ });
6493
+ }
6494
+ }
6495
+ function pruneMemoryCache() {
6496
+ const entries = Array.from(memoryCache.entries()).sort(
6497
+ ([, a], [, b]) => a.timestamp - b.timestamp
6498
+ );
6499
+ const excess = memoryCache.size - MAX_ENTRIES;
6500
+ for (let i = 0; i < excess; i++) {
6501
+ const [key] = entries[i];
6502
+ memoryCache.delete(key);
6503
+ }
6504
+ }
6505
+
6506
+ // src/build/transforms/pipeline/index.ts
6507
+ init_utils();
6508
+
6509
+ // src/build/transforms/pipeline/context.ts
6510
+ init_deno_env();
6511
+
6512
+ // src/build/transforms/esm/transform-utils.ts
6513
+ init_deno_env();
6514
+ init_hash_utils();
6515
+ function computeContentHash2(content) {
6516
+ return shortHash(content);
6517
+ }
6518
+ function getLoaderFromPath(filePath) {
6519
+ if (filePath.endsWith(".tsx"))
6520
+ return "tsx";
6521
+ if (filePath.endsWith(".ts"))
6522
+ return "ts";
6523
+ if (filePath.endsWith(".jsx"))
6524
+ return "jsx";
6525
+ if (filePath.endsWith(".js"))
6526
+ return "js";
6527
+ if (filePath.endsWith(".mdx"))
6528
+ return "jsx";
6529
+ if (filePath.endsWith(".css"))
6530
+ return "css";
6531
+ if (filePath.endsWith(".json"))
6532
+ return "json";
6533
+ return "tsx";
6534
+ }
6535
+
6536
+ // src/build/transforms/pipeline/context.ts
6537
+ async function createTransformContext(source, filePath, projectDir, options) {
6538
+ const contentHash = await computeContentHash2(source);
6539
+ const target = options.ssr ? "ssr" : "browser";
6540
+ return {
6541
+ code: source,
6542
+ originalSource: source,
6543
+ filePath,
6544
+ projectDir,
6545
+ projectId: options.projectId,
6546
+ target,
6547
+ dev: options.dev ?? true,
6548
+ contentHash,
6549
+ moduleServerUrl: options.moduleServerUrl,
6550
+ vendorBundleHash: options.vendorBundleHash,
6551
+ apiBaseUrl: options.apiBaseUrl,
6552
+ jsxImportSource: options.jsxImportSource ?? "react",
6553
+ timing: /* @__PURE__ */ new Map(),
6554
+ debug: false,
6555
+ metadata: /* @__PURE__ */ new Map()
6556
+ };
6557
+ }
6558
+ function recordStageTiming(ctx, stage, startTime) {
6559
+ ctx.timing.set(stage, performance.now() - startTime);
6560
+ }
6561
+ function getTotalTiming(ctx) {
6562
+ let total = 0;
6563
+ for (const ms of ctx.timing.values()) {
6564
+ total += ms;
6565
+ }
6566
+ return total;
6567
+ }
6568
+ function formatTimingLog(ctx) {
6569
+ const stageNames = [
6570
+ "parse",
6571
+ "compile",
6572
+ "aliases",
6573
+ "react",
6574
+ "context",
6575
+ "relative",
6576
+ "bare",
6577
+ "finalize"
6578
+ ];
6579
+ const result = {
6580
+ file: ctx.filePath.slice(-40),
6581
+ target: ctx.target
6582
+ };
6583
+ for (const [stage, ms] of ctx.timing) {
6584
+ const name = stageNames[stage] ?? `stage${stage}`;
6585
+ result[`${name}Ms`] = ms.toFixed(1);
6586
+ }
6587
+ result.totalMs = getTotalTiming(ctx).toFixed(1);
6588
+ return result;
6589
+ }
6590
+ function isSSR(ctx) {
6591
+ return ctx.target === "ssr";
6592
+ }
6593
+ function isBrowser(ctx) {
6594
+ return ctx.target === "browser";
6595
+ }
6596
+ function isMDX(ctx) {
6597
+ return ctx.filePath.endsWith(".mdx");
6598
+ }
6599
+
6600
+ // src/build/transforms/pipeline/stages/index.ts
6601
+ init_deno_env();
6602
+
6603
+ // src/build/transforms/pipeline/stages/parse.ts
6604
+ init_deno_env();
6605
+
6606
+ // src/build/transforms/mdx/compiler/mdx-compiler.ts
6607
+ init_deno_env();
6608
+ init_utils();
6609
+
6610
+ // src/build/transforms/plugins/plugin-loader.ts
6611
+ init_deno_env();
6612
+ init_config();
6613
+ init_utils();
6614
+
6615
+ // src/build/transforms/plugins/rehype-utils.ts
6616
+ init_deno_env();
6617
+ import { visit } from "unist-util-visit";
6618
+ function rehypePreserveNodeIds() {
6619
+ return (tree) => {
6620
+ visit(tree, "element", (node) => {
6621
+ if (!node.properties) {
6622
+ node.properties = {};
6623
+ }
6624
+ if (node.data && node.data.hProperties) {
6625
+ Object.entries(
6626
+ node.data.hProperties
6627
+ ).forEach(([key, value]) => {
6628
+ if (key.startsWith("data-node-")) {
6629
+ node.properties[key] = value;
6630
+ }
6631
+ });
6632
+ }
6633
+ });
6634
+ };
6635
+ }
6636
+ function rehypeAddClasses() {
6637
+ return (tree) => {
6638
+ visit(tree, "element", (node) => {
6639
+ if (!node.properties) {
6640
+ node.properties = {};
6641
+ }
6642
+ switch (node.tagName) {
6643
+ case "p":
6644
+ addClassName(node, "mb-4");
6645
+ break;
6646
+ case "h1":
6647
+ addClassName(node, "text-4xl font-bold mb-8 mt-12");
6648
+ break;
6649
+ case "h2":
6650
+ addClassName(node, "text-3xl font-bold mb-6 mt-10");
6651
+ break;
6652
+ case "h3":
6653
+ addClassName(node, "text-2xl font-bold mb-4 mt-8");
6654
+ break;
6655
+ case "a":
6656
+ addClassName(node, "text-blue-600 hover:text-blue-800 underline");
6657
+ break;
6658
+ case "code":
6659
+ if (Array.isArray(node.properties.className) && node.properties.className.some((cls) => String(cls).includes("language-"))) {
6660
+ addClassName(node, "block p-4 bg-gray-900 text-gray-100 rounded-lg overflow-x-auto");
6661
+ } else {
6662
+ addClassName(node, "px-1 py-0.5 bg-gray-100 text-gray-900 rounded text-sm");
6663
+ }
6664
+ break;
6665
+ case "blockquote":
6666
+ addClassName(node, "border-l-4 border-gray-300 pl-4 italic");
6667
+ break;
6668
+ case "ul":
6669
+ addClassName(node, "list-disc list-inside mb-4");
6670
+ break;
6671
+ case "ol":
6672
+ addClassName(node, "list-decimal list-inside mb-4");
6673
+ break;
6674
+ case "li":
6675
+ addClassName(node, "mb-2");
6676
+ break;
6677
+ }
6678
+ });
6679
+ };
6680
+ }
6681
+ function rehypeMdxComponents() {
6682
+ return (tree) => {
6683
+ visit(tree, "mdxJsxFlowElement", (node) => {
6684
+ if (!node.data) {
6685
+ node.data = {};
6686
+ }
6687
+ if (!node.data.hProperties) {
6688
+ node.data.hProperties = {};
6689
+ }
6690
+ node.data.hProperties["data-mdx-component"] = node.name;
6691
+ });
6692
+ };
6693
+ }
6694
+ function addClassName(node, className) {
6695
+ if (!node.properties) {
6696
+ node.properties = {};
6697
+ }
6698
+ if (!node.properties.className) {
6699
+ node.properties.className = [];
6700
+ } else if (typeof node.properties.className === "string") {
6701
+ node.properties.className = node.properties.className.split(" ");
6702
+ }
6703
+ node.properties.className.push(className);
6704
+ }
6705
+
6706
+ // src/build/transforms/plugins/remark-headings.ts
6707
+ init_deno_env();
6708
+ import GithubSlugger from "github-slugger";
6709
+ import { toString } from "mdast-util-to-string";
6710
+ import { visit as visit2 } from "unist-util-visit";
6711
+ function remarkMdxHeadings() {
6712
+ const slugger = new GithubSlugger();
6713
+ return (tree, file) => {
6714
+ const headings = [];
6715
+ slugger.reset();
6716
+ visit2(tree, "heading", (node) => {
6717
+ const text = toString(node);
6718
+ const id = slugger.slug(text);
6719
+ if (!node.data) {
6720
+ node.data = {};
6721
+ }
6722
+ if (!node.data.hProperties) {
6723
+ node.data.hProperties = {};
6724
+ }
6725
+ node.data.hProperties.id = id;
6726
+ headings.push({
6727
+ text,
6728
+ id,
6729
+ level: node.depth
6730
+ });
6731
+ });
6732
+ if (!file.data) {
6733
+ file.data = {};
6734
+ }
6735
+ file.data.headings = headings;
6736
+ const headingsExport = {
6737
+ type: "mdxjsEsm",
6738
+ value: "",
6739
+ data: {
6740
+ estree: {
6741
+ type: "Program",
6742
+ sourceType: "module",
6743
+ body: [
6744
+ {
6745
+ type: "ExportNamedDeclaration",
6746
+ specifiers: [],
6747
+ source: null,
6748
+ declaration: {
6749
+ type: "VariableDeclaration",
6750
+ kind: "const",
6751
+ declarations: [
6752
+ {
6753
+ type: "VariableDeclarator",
6754
+ id: { type: "Identifier", name: "headings" },
6755
+ init: {
6756
+ type: "ArrayExpression",
6757
+ elements: headings.map((h) => ({
6758
+ type: "ObjectExpression",
6759
+ properties: [
6760
+ {
6761
+ type: "Property",
6762
+ key: { type: "Identifier", name: "text" },
6763
+ value: { type: "Literal", value: h.text },
6764
+ kind: "init",
6765
+ method: false,
6766
+ shorthand: false,
6767
+ computed: false
6768
+ },
6769
+ {
6770
+ type: "Property",
6771
+ key: { type: "Identifier", name: "id" },
6772
+ value: { type: "Literal", value: h.id },
6773
+ kind: "init",
6774
+ method: false,
6775
+ shorthand: false,
6776
+ computed: false
6777
+ },
6778
+ {
6779
+ type: "Property",
6780
+ key: { type: "Identifier", name: "level" },
6781
+ value: { type: "Literal", value: h.level },
6782
+ kind: "init",
6783
+ method: false,
6784
+ shorthand: false,
6785
+ computed: false
6786
+ }
6787
+ ]
6788
+ }))
6789
+ }
6790
+ }
6791
+ ]
6792
+ }
6793
+ }
6794
+ ]
6795
+ }
6796
+ }
6797
+ };
6798
+ tree.children.unshift(headingsExport);
6799
+ };
6800
+ }
6801
+
6802
+ // src/build/transforms/plugins/plugin-loader.ts
6803
+ init_veryfront_error();
6804
+
6805
+ // src/build/transforms/plugins/remark-mdx-utils.ts
6806
+ init_deno_env();
6807
+ import { visit as visit3 } from "unist-util-visit";
6808
+ function remarkMdxRemoveParagraphs() {
6809
+ return (tree) => {
6810
+ visit3(
6811
+ tree,
6812
+ "paragraph",
6813
+ (node, index, parent) => {
6814
+ const children = Array.isArray(node?.children) ? node.children : [];
6815
+ if (children.length === 1 && (children[0]?.type === "mdxJsxTextElement" || children[0]?.type === "mdxJsxFlowElement")) {
6816
+ if (parent && Array.isArray(parent.children) && typeof index === "number") {
6817
+ parent.children.splice(index, 1, children[0]);
6818
+ }
6819
+ }
6820
+ }
6821
+ );
6822
+ };
6823
+ }
6824
+ function remarkCodeBlocks() {
6825
+ return (tree) => {
6826
+ visit3(tree, "code", (node) => {
6827
+ if (!node.data) {
6828
+ node.data = {};
6829
+ }
6830
+ if (!node.data.hProperties) {
6831
+ node.data.hProperties = {};
6832
+ }
6833
+ if (node.lang) {
6834
+ node.data.hProperties.className = [`language-${node.lang}`];
6835
+ }
6836
+ if (node.meta) {
6837
+ const highlightMatch = node.meta.match(/\{([\d,-]+)\}/);
6838
+ if (highlightMatch) {
6839
+ node.data.hProperties["data-line-numbers"] = highlightMatch[1];
6840
+ }
6841
+ }
6842
+ });
6843
+ };
6844
+ }
6845
+ function remarkMdxImports() {
6846
+ return (tree, file) => {
6847
+ const imports = [];
6848
+ visit3(tree, "mdxjsEsm", (node) => {
6849
+ if (node.value?.includes("import")) {
6850
+ const importMatches = node.value.matchAll(
6851
+ /import\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s+from\s+)?['"]([^'"]+)['"]/g
6852
+ );
6853
+ for (const match of importMatches) {
6854
+ const path = match[1];
6855
+ if (typeof path === "string")
6856
+ imports.push(path);
6857
+ }
6858
+ }
6859
+ });
6860
+ if (!file.data) {
6861
+ file.data = {};
6862
+ }
6863
+ file.data.imports = imports;
6864
+ };
6865
+ }
6866
+
6867
+ // src/build/transforms/plugins/rehype-mermaid.ts
6868
+ init_deno_env();
6869
+ import { visit as visit4 } from "unist-util-visit";
6870
+ function rehypeMermaid() {
6871
+ return (tree) => {
6872
+ visit4(tree, "element", (node, index, parent) => {
6873
+ const firstChild = node.children[0];
6874
+ if (node.tagName === "pre" && node.children.length === 1 && firstChild && firstChild.type === "element" && firstChild.tagName === "code") {
6875
+ const codeNode = node.children[0];
6876
+ const className = codeNode.properties?.className;
6877
+ const isMermaid = Array.isArray(className) ? className.some(
6878
+ (c) => String(c).includes("mermaid") || String(c).includes("language-mermaid")
6879
+ ) : String(className || "").includes("mermaid");
6880
+ if (isMermaid && parent && typeof index === "number") {
6881
+ const textContent = extractText(codeNode);
6882
+ const mermaidDiv = {
6883
+ type: "element",
6884
+ tagName: "div",
6885
+ properties: {
6886
+ className: ["mermaid"]
6887
+ },
6888
+ children: [{ type: "text", value: textContent }]
6889
+ };
6890
+ parent.children[index] = mermaidDiv;
6891
+ }
6892
+ }
6893
+ });
6894
+ };
6895
+ }
6896
+ function extractText(node) {
6897
+ let text = "";
6898
+ for (const child of node.children) {
6899
+ if (child.type === "text") {
6900
+ text += child.value;
6901
+ } else if (child.type === "element") {
6902
+ text += extractText(child);
6903
+ }
6904
+ }
6905
+ return text.trim();
6906
+ }
6907
+
6908
+ // src/build/transforms/plugins/plugin-loader.ts
6909
+ import remarkGfm from "remark-gfm";
6910
+ import remarkFrontmatter from "remark-frontmatter";
6911
+ import rehypeHighlight from "rehype-highlight";
6912
+ import rehypeSlug from "rehype-slug";
6913
+ async function loadUserPlugins(projectDir, adapter, pluginType) {
6914
+ try {
6915
+ const _config = await getConfig(projectDir, adapter);
6916
+ return [];
6917
+ } catch (error) {
6918
+ serverLogger.warn(
6919
+ `Failed to load ${pluginType} plugins from config`,
6920
+ { error: error instanceof Error ? error.message : String(error) }
6921
+ );
6922
+ return [];
6923
+ }
6924
+ }
6925
+ async function getRemarkPlugins(projectDir, adapter) {
6926
+ const defaultPlugins = [
6927
+ remarkGfm,
6928
+ remarkFrontmatter,
6929
+ // remarkAddNodeId as PluginEntry,
6930
+ remarkMdxHeadings,
6931
+ remarkMdxRemoveParagraphs,
6932
+ remarkCodeBlocks,
6933
+ remarkMdxImports
6934
+ ];
6935
+ if (adapter) {
6936
+ try {
6937
+ const userPlugins = await loadUserPlugins(projectDir, adapter, "remark");
6938
+ return [...defaultPlugins, ...userPlugins];
6939
+ } catch (error) {
6940
+ serverLogger.error(
6941
+ "Error loading user remark plugins",
6942
+ { error: error instanceof Error ? error.message : String(error) }
6943
+ );
6944
+ }
6945
+ }
6946
+ return defaultPlugins;
6947
+ }
6948
+ async function getRehypePlugins(projectDir, adapter) {
6949
+ const defaultPlugins = [
6950
+ rehypeMermaid,
6951
+ // Must run before rehypeHighlight
6952
+ rehypeHighlight,
6953
+ rehypeSlug,
6954
+ rehypePreserveNodeIds,
6955
+ rehypeAddClasses,
6956
+ rehypeMdxComponents
6957
+ ];
6958
+ if (adapter) {
6959
+ try {
6960
+ const userPlugins = await loadUserPlugins(projectDir, adapter, "rehype");
6961
+ return [...defaultPlugins, ...userPlugins];
6962
+ } catch (error) {
6963
+ serverLogger.error(
6964
+ "Error loading user rehype plugins",
6965
+ { error: error instanceof Error ? error.message : String(error) }
6966
+ );
6967
+ }
6968
+ }
6969
+ return defaultPlugins;
6970
+ }
6971
+
6972
+ // src/build/transforms/mdx/compiler/frontmatter-extractor.ts
6973
+ init_deno_env();
6974
+ init_utils();
6975
+ async function extractYamlFrontmatter(content) {
6976
+ if (!content.trim().startsWith("---")) {
6977
+ return { body: content, frontmatter: {} };
6978
+ }
6979
+ const { extract } = await import("gray-matter");
6980
+ const extracted = extract(content);
6981
+ return {
6982
+ body: extracted.body,
6983
+ frontmatter: extracted.attrs
6984
+ };
6985
+ }
6986
+ function extractExportConstants(body) {
6987
+ const exportRegex = /^export\s+const\s+(\w+)\s*=\s*(['"`][^'"`\n]*['"`]|\d+(?:\.\d+)?|true|false|null)\s*;?\s*$/gm;
6988
+ const exports = {};
6989
+ const linesToRemove = [];
6990
+ let match;
6991
+ while ((match = exportRegex.exec(body)) !== null) {
6992
+ const key = match[1];
6993
+ const rawValue = match[2];
6994
+ if (key && key.length > 0 && rawValue) {
6995
+ linesToRemove.push(match[0]);
6996
+ if (rawValue === "true") {
6997
+ exports[key] = true;
6998
+ } else if (rawValue === "false") {
6999
+ exports[key] = false;
7000
+ } else if (rawValue === "null") {
7001
+ exports[key] = null;
7002
+ } else if (/^\d+(?:\.\d+)?$/.test(rawValue)) {
7003
+ exports[key] = parseFloat(rawValue);
7004
+ } else {
7005
+ exports[key] = rawValue.replace(/^['"`]|['"`]$/g, "");
7006
+ }
7007
+ }
7008
+ }
7009
+ let cleanedBody = body;
7010
+ for (const line of linesToRemove) {
7011
+ cleanedBody = cleanedBody.replace(line, "");
7012
+ }
7013
+ return { body: cleanedBody, exports };
7014
+ }
7015
+ async function extractFrontmatter(content, providedFrontmatter) {
7016
+ let body = content;
7017
+ let frontmatter = {};
7018
+ if (content.trim().startsWith("---")) {
7019
+ const yamlResult = await extractYamlFrontmatter(content);
7020
+ body = yamlResult.body;
7021
+ frontmatter = yamlResult.frontmatter;
7022
+ }
7023
+ if (providedFrontmatter) {
7024
+ frontmatter = { ...frontmatter, ...providedFrontmatter };
7025
+ }
7026
+ const exportResult = extractExportConstants(body);
7027
+ body = exportResult.body;
7028
+ frontmatter = { ...frontmatter, ...exportResult.exports };
7029
+ rendererLogger.info("Extracted frontmatter:", frontmatter);
7030
+ return { body, frontmatter };
7031
+ }
7032
+
7033
+ // src/build/transforms/mdx/compiler/import-rewriter.ts
7034
+ init_deno_env();
7035
+ import { dirname as dirname3, join as join3, resolve as pathResolve } from "node:path";
7036
+ function toAbsPath(spec, basedir) {
7037
+ try {
7038
+ if (spec.startsWith("file://"))
7039
+ return new URL(spec).pathname;
7040
+ if (spec.startsWith("/"))
7041
+ return pathResolve(spec);
7042
+ if (spec.startsWith("http://") || spec.startsWith("https://"))
7043
+ return spec;
7044
+ if (!spec.startsWith(".") && !spec.startsWith("/")) {
7045
+ return spec;
7046
+ }
7047
+ return pathResolve(join3(basedir, spec));
7048
+ } catch {
7049
+ return spec;
7050
+ }
7051
+ }
7052
+ function toBrowserFs(abs, baseUrl) {
7053
+ if (abs.startsWith("http://") || abs.startsWith("https://"))
7054
+ return abs;
7055
+ const b64 = btoa(abs).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
7056
+ const path = `/_veryfront/fs/${b64}.js`;
7057
+ return baseUrl ? `${baseUrl}${path}` : path;
7058
+ }
7059
+ function mapSpec(spec, basedir, target, baseUrl, _projectDir) {
7060
+ if (spec.startsWith("@/")) {
7061
+ const relativePath = spec.slice(2);
7062
+ if (target === "browser") {
7063
+ const path = `/_vf_modules/${relativePath}.js`;
7064
+ return baseUrl ? `${baseUrl}${path}` : path;
7065
+ } else {
7066
+ return spec;
7067
+ }
7068
+ }
7069
+ const abs = toAbsPath(spec, basedir);
7070
+ if (typeof abs !== "string")
7071
+ return spec;
7072
+ if (abs === spec && !spec.startsWith(".") && !spec.startsWith("/") && !spec.startsWith("file://") && !spec.startsWith("http")) {
7073
+ return spec;
7074
+ }
7075
+ if (target === "browser")
7076
+ return toBrowserFs(abs, baseUrl);
7077
+ return abs.startsWith("http") ? abs : `file://${abs}`;
7078
+ }
7079
+ function rewriteLine(line, basedir, target, baseUrl, projectDir) {
7080
+ const mapper = (spec) => mapSpec(spec, basedir, target, baseUrl, projectDir);
7081
+ line = line.replace(
7082
+ /^(\s*import\s+[^'";]+?from\s+)(["'])([^"']+)(\2)/,
7083
+ (_m, p1, q, s, q2) => `${p1}${q}${mapper(s)}${q2}`
7084
+ );
7085
+ line = line.replace(
7086
+ /^(\s*import\s+)(["'])([^"']+)(\2)/,
7087
+ (_m, p1, q, s, q2) => `${p1}${q}${mapper(s)}${q2}`
7088
+ );
7089
+ line = line.replace(
7090
+ /^(\s*export\s+[^'";]+?from\s+)(["'])([^"']+)(\2)/,
7091
+ (_m, p1, q, s, q2) => `${p1}${q}${mapper(s)}${q2}`
7092
+ );
7093
+ return line;
7094
+ }
7095
+ function rewriteBodyImports(body, config) {
7096
+ const basedir = dirname3(config.filePath);
7097
+ return body.split(/\r?\n/).map((ln) => {
7098
+ const trimmed = ln.trimStart();
7099
+ if (trimmed.startsWith("import") || trimmed.startsWith("export")) {
7100
+ return rewriteLine(ln, basedir, config.target, config.baseUrl, config.projectDir);
7101
+ }
7102
+ return ln;
7103
+ }).join("\n");
7104
+ }
7105
+ function rewriteCompiledImports(compiledCode, config) {
7106
+ const basedir = dirname3(config.filePath);
7107
+ const mapper = (spec) => mapSpec(spec, basedir, config.target, config.baseUrl, config.projectDir);
7108
+ let code = compiledCode;
7109
+ code = code.replace(
7110
+ /(from\s+["'])(@\/[^"']+)(["'])/g,
7111
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
7112
+ );
7113
+ code = code.replace(
7114
+ /(import\(\s*["'])(@\/[^"']+)(["']\s*\))/g,
7115
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
7116
+ );
7117
+ code = code.replace(
7118
+ /(from\s+["'])(\.{1,2}\/[^"']+)(["'])/g,
7119
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
7120
+ );
7121
+ code = code.replace(
7122
+ /(from\s+["'])(file:\/\/[^"']+)(["'])/g,
7123
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
7124
+ );
7125
+ code = code.replace(
7126
+ /(import\(\s*["'])(\.{1,2}\/[^"']+)(["']\s*\))/g,
7127
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
7128
+ );
7129
+ code = code.replace(
7130
+ /(import\(\s*["'])(file:\/\/[^"']+)(["']\s*\))/g,
7131
+ (_m, p1, p2, p3) => `${p1}${mapper(p2)}${p3}`
7132
+ );
7133
+ code = code.replace(/file:\/\/[A-Za-z0-9_\-./%]+/g, (match) => mapper(match));
7134
+ return code;
7135
+ }
7136
+
7137
+ // src/build/transforms/mdx/compiler/mdx-compiler.ts
7138
+ init_veryfront_error();
7139
+ async function compileMDXRuntime(_mode, projectDir, content, frontmatter, filePath, target = "server", baseUrl) {
7140
+ try {
7141
+ const { compile } = await import("@mdx-js/mdx");
7142
+ const remarkPlugins = await getRemarkPlugins(projectDir);
7143
+ const rehypePlugins = await getRehypePlugins(projectDir);
7144
+ const extracted = await extractFrontmatter(content, frontmatter);
7145
+ let { body } = extracted;
7146
+ const { frontmatter: extractedFrontmatter } = extracted;
7147
+ if (filePath && (target === "browser" || target === "server")) {
7148
+ body = rewriteBodyImports(body, { filePath, target, baseUrl, projectDir });
7149
+ }
7150
+ const allRehypePlugins = [
7151
+ ...rehypePlugins
7152
+ // [rehypeNodePositions, { filePath }],
7153
+ ];
7154
+ const compiled = await compile(body, {
7155
+ outputFormat: "program",
7156
+ development: false,
7157
+ remarkPlugins,
7158
+ rehypePlugins: allRehypePlugins,
7159
+ providerImportSource: void 0,
7160
+ jsxImportSource: "react"
7161
+ });
7162
+ rendererLogger.info("MDX compiled output preview:", String(compiled).substring(0, 200));
7163
+ rendererLogger.info("Extracted frontmatter:", extractedFrontmatter);
7164
+ let compiledCode = String(compiled);
7165
+ if (filePath && (target === "browser" || target === "server")) {
7166
+ compiledCode = rewriteCompiledImports(compiledCode, {
7167
+ filePath,
7168
+ target,
7169
+ baseUrl,
7170
+ projectDir
7171
+ });
7172
+ }
7173
+ return {
7174
+ compiledCode,
7175
+ frontmatter: extractedFrontmatter,
7176
+ globals: {},
7177
+ headings: [],
7178
+ nodeMap: /* @__PURE__ */ new Map()
7179
+ };
7180
+ } catch (error) {
7181
+ rendererLogger.error("[MDX Compiler] Compilation failed:", {
7182
+ filePath,
7183
+ error: error instanceof Error ? error.message : String(error),
7184
+ stack: error instanceof Error ? error.stack : void 0
7185
+ });
7186
+ throw toError(createError({
7187
+ type: "build",
7188
+ message: `MDX compilation error: ${error instanceof Error ? error.message : String(error)} | file: ${filePath || "<memory>"}`
7189
+ }));
7190
+ }
7191
+ }
7192
+
7193
+ // src/build/transforms/pipeline/types.ts
7194
+ init_deno_env();
7195
+
7196
+ // src/build/transforms/pipeline/stages/parse.ts
7197
+ var parsePlugin = {
7198
+ name: "parse-mdx",
7199
+ stage: 0 /* PARSE */,
7200
+ condition: isMDX,
7201
+ async transform(ctx) {
7202
+ const mdxTarget = isSSR(ctx) ? "server" : "browser";
7203
+ const mdxBaseUrl = isSSR(ctx) ? void 0 : ctx.moduleServerUrl;
7204
+ const result = await compileMDXRuntime(
7205
+ ctx.dev ? "development" : "production",
7206
+ ctx.projectDir,
7207
+ ctx.code,
7208
+ void 0,
7209
+ ctx.filePath,
7210
+ mdxTarget,
7211
+ mdxBaseUrl
7212
+ );
7213
+ if (result.frontmatter) {
7214
+ ctx.metadata.set("frontmatter", result.frontmatter);
7215
+ }
7216
+ return result.compiledCode;
7217
+ }
7218
+ };
7219
+
7220
+ // src/build/transforms/pipeline/stages/compile.ts
7221
+ init_deno_env();
7222
+ import * as esbuild from "esbuild/mod.js";
7223
+ init_utils();
7224
+ var compilePlugin = {
7225
+ name: "esbuild-compile",
7226
+ stage: 1 /* COMPILE */,
7227
+ async transform(ctx) {
7228
+ const loader = getLoaderFromPath(ctx.filePath);
7229
+ try {
7230
+ const result = await esbuild.transform(ctx.code, {
7231
+ loader,
7232
+ format: "esm",
7233
+ target: "es2020",
7234
+ jsx: "automatic",
7235
+ jsxImportSource: ctx.jsxImportSource,
7236
+ minify: !ctx.dev,
7237
+ sourcemap: ctx.dev ? "inline" : false,
7238
+ treeShaking: !ctx.dev,
7239
+ // Disable in dev mode to preserve import errors
7240
+ keepNames: true
7241
+ });
7242
+ let code = result.code;
7243
+ if (ctx.filePath.endsWith(".mdx")) {
7244
+ if (/\bconst\s+MDXLayout\b/.test(code) && !/export\s+\{[^}]*MDXLayout/.test(code)) {
7245
+ code += "\nexport { MDXLayout };\n";
7246
+ }
7247
+ }
7248
+ return code;
7249
+ } catch (transformError) {
7250
+ const sourcePreview = ctx.code.split("\n").slice(0, 10).map((line, i) => `${String(i + 1).padStart(3, " ")}| ${line}`).join("\n");
7251
+ rendererLogger.error("[ESM-TRANSFORM] Transform failed", {
7252
+ filePath: ctx.filePath,
7253
+ loader,
7254
+ sourceLength: ctx.code.length,
7255
+ isMdx: ctx.filePath.endsWith(".mdx"),
7256
+ error: transformError instanceof Error ? transformError.message : String(transformError)
7257
+ });
7258
+ rendererLogger.error("[ESM-TRANSFORM] Source preview (first 10 lines):\n" + sourcePreview);
7259
+ const errorMsg = transformError instanceof Error ? transformError.message : String(transformError);
7260
+ throw new Error(`ESM transform failed for ${ctx.filePath} (loader: ${loader}): ${errorMsg}`);
7261
+ }
7262
+ }
7263
+ };
7264
+
7265
+ // src/build/transforms/pipeline/stages/resolve-aliases.ts
7266
+ init_deno_env();
7267
+
7268
+ // src/build/transforms/esm/path-resolver.ts
7269
+ init_deno_env();
7270
+
7271
+ // src/build/transforms/esm/lexer.ts
7272
+ init_deno_env();
7273
+
7274
+ // node_modules/.deno/es-module-lexer@1.5.0/node_modules/es-module-lexer/dist/lexer.js
7275
+ init_deno_env();
7276
+ var ImportType;
7277
+ !function(A2) {
7278
+ A2[A2.Static = 1] = "Static", A2[A2.Dynamic = 2] = "Dynamic", A2[A2.ImportMeta = 3] = "ImportMeta", A2[A2.StaticSourcePhase = 4] = "StaticSourcePhase", A2[A2.DynamicSourcePhase = 5] = "DynamicSourcePhase";
7279
+ }(ImportType || (ImportType = {}));
7280
+ var A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0];
7281
+ function parse(E2, g = "@") {
7282
+ if (!C)
7283
+ return init.then(() => parse(E2));
7284
+ const I = E2.length + 1, w = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength;
7285
+ w > 0 && C.memory.grow(Math.ceil(w / 65536));
7286
+ const D = C.sa(I - 1);
7287
+ if ((A ? B : Q)(E2, new Uint16Array(C.memory.buffer, D, I)), !C.parse())
7288
+ throw Object.assign(new Error(`Parse error ${g}:${E2.slice(0, C.e()).split("\n").length}:${C.e() - E2.lastIndexOf("\n", C.e() - 1)}`), { idx: C.e() });
7289
+ const o = [], K = [];
7290
+ for (; C.ri(); ) {
7291
+ const A2 = C.is(), Q2 = C.ie(), B2 = C.it(), g2 = C.ai(), I2 = C.id(), w2 = C.ss(), D2 = C.se();
7292
+ let K2;
7293
+ C.ip() && (K2 = k(E2.slice(-1 === I2 ? A2 - 1 : A2, -1 === I2 ? Q2 + 1 : Q2))), o.push({ n: K2, t: B2, s: A2, e: Q2, ss: w2, se: D2, d: I2, a: g2 });
7294
+ }
7295
+ for (; C.re(); ) {
7296
+ const A2 = C.es(), Q2 = C.ee(), B2 = C.els(), g2 = C.ele(), I2 = E2.slice(A2, Q2), w2 = I2[0], D2 = B2 < 0 ? void 0 : E2.slice(B2, g2), o2 = D2 ? D2[0] : "";
7297
+ K.push({ s: A2, e: Q2, ls: B2, le: g2, n: '"' === w2 || "'" === w2 ? k(I2) : I2, ln: '"' === o2 || "'" === o2 ? k(D2) : D2 });
7298
+ }
7299
+ function k(A2) {
7300
+ try {
7301
+ return (0, eval)(A2);
7302
+ } catch (A3) {
7303
+ }
7304
+ }
7305
+ return [o, K, !!C.f(), !!C.ms()];
7306
+ }
7307
+ function Q(A2, Q2) {
7308
+ const B2 = A2.length;
7309
+ let C2 = 0;
7310
+ for (; C2 < B2; ) {
7311
+ const B3 = A2.charCodeAt(C2);
7312
+ Q2[C2++] = (255 & B3) << 8 | B3 >>> 8;
7313
+ }
7314
+ }
7315
+ function B(A2, Q2) {
7316
+ const B2 = A2.length;
7317
+ let C2 = 0;
7318
+ for (; C2 < B2; )
7319
+ Q2[C2] = A2.charCodeAt(C2++);
7320
+ }
7321
+ var C;
7322
+ var init = WebAssembly.compile((E = "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", "undefined" != typeof Buffer ? Buffer.from(E, "base64") : Uint8Array.from(atob(E), (A2) => A2.charCodeAt(0)))).then(WebAssembly.instantiate).then(({ exports: A2 }) => {
7323
+ C = A2;
7324
+ });
7325
+ var E;
7326
+
7327
+ // src/build/transforms/esm/lexer.ts
7328
+ var initPromise = null;
7329
+ var HTTP_URL_PATTERN = /(['"`])(https?:\/\/[^'"`\n]+)\1/g;
7330
+ function maskHttpUrls(code) {
7331
+ const urlMap = /* @__PURE__ */ new Map();
7332
+ let counter = 0;
7333
+ const masked = code.replace(HTTP_URL_PATTERN, (_match, quote, url) => {
7334
+ const placeholder = `__VFURL_${counter++}__`;
7335
+ urlMap.set(placeholder, url);
7336
+ return `${quote}${placeholder}${quote}`;
7337
+ });
7338
+ return { masked, urlMap };
7339
+ }
7340
+ function unmaskHttpUrls(code, urlMap) {
7341
+ let result = code;
7342
+ for (const [placeholder, url] of urlMap) {
7343
+ result = result.replaceAll(placeholder, url);
7344
+ }
7345
+ return result;
7346
+ }
7347
+ async function initLexer() {
7348
+ if (!initPromise) {
7349
+ const anyInit = init;
7350
+ initPromise = typeof anyInit === "function" ? anyInit() : anyInit;
7351
+ }
7352
+ await initPromise;
7353
+ }
7354
+ async function parseImports(code) {
7355
+ await initLexer();
7356
+ const { masked, urlMap } = maskHttpUrls(code);
7357
+ const [imports] = parse(masked);
7358
+ if (urlMap.size === 0) {
7359
+ return imports;
7360
+ }
7361
+ return imports.map((imp) => {
7362
+ if (imp.n) {
7363
+ const restoredN = unmaskHttpUrls(imp.n, urlMap);
7364
+ if (restoredN !== imp.n) {
7365
+ return { ...imp, n: restoredN };
7366
+ }
7367
+ }
7368
+ return imp;
7369
+ });
7370
+ }
7371
+ async function replaceSpecifiers(code, replacer) {
7372
+ await initLexer();
7373
+ const { masked, urlMap } = maskHttpUrls(code);
7374
+ const [imports] = parse(masked);
7375
+ let result = masked;
7376
+ for (let i = imports.length - 1; i >= 0; i--) {
7377
+ const imp = imports[i];
7378
+ if (!imp)
7379
+ continue;
7380
+ if (imp.n === void 0)
7381
+ continue;
7382
+ const originalSpecifier = unmaskHttpUrls(imp.n, urlMap);
7383
+ const replacement = replacer(originalSpecifier, imp.d > -1);
7384
+ if (replacement && replacement !== originalSpecifier) {
7385
+ const before = result.substring(0, imp.s);
7386
+ const after = result.substring(imp.e);
7387
+ result = before + replacement + after;
7388
+ }
7389
+ }
7390
+ return unmaskHttpUrls(result, urlMap);
7391
+ }
7392
+ async function rewriteImports(code, rewriter) {
7393
+ await initLexer();
7394
+ const { masked, urlMap } = maskHttpUrls(code);
7395
+ const [imports] = parse(masked);
7396
+ let result = masked;
7397
+ for (let i = imports.length - 1; i >= 0; i--) {
7398
+ const imp = imports[i];
7399
+ if (!imp)
7400
+ continue;
7401
+ const unmaskedImp = imp.n ? { ...imp, n: unmaskHttpUrls(imp.n, urlMap) } : imp;
7402
+ const statement = unmaskHttpUrls(masked.substring(imp.ss, imp.se), urlMap);
7403
+ const replacement = rewriter(unmaskedImp, statement);
7404
+ if (replacement !== null) {
7405
+ const before = result.substring(0, imp.ss);
7406
+ const after = result.substring(imp.se);
7407
+ result = before + replacement + after;
7408
+ }
7409
+ }
7410
+ return unmaskHttpUrls(result, urlMap);
7411
+ }
7412
+
7413
+ // src/build/transforms/esm/path-resolver.ts
7414
+ init_utils();
7415
+ var CROSS_PROJECT_VERSIONED_PATTERN = /^([a-z0-9-]+)@([\d^~x][\d.x^~-]*)\/@\/(.+)$/;
7416
+ var CROSS_PROJECT_LATEST_PATTERN = /^([a-z0-9-]+)\/@\/(.+)$/;
7417
+ function parseCrossProjectImport(specifier) {
7418
+ const versionedMatch = specifier.match(CROSS_PROJECT_VERSIONED_PATTERN);
7419
+ if (versionedMatch) {
7420
+ return {
7421
+ projectSlug: versionedMatch[1],
7422
+ version: versionedMatch[2],
7423
+ path: versionedMatch[3]
7424
+ };
7425
+ }
7426
+ const latestMatch = specifier.match(CROSS_PROJECT_LATEST_PATTERN);
7427
+ if (latestMatch) {
7428
+ return {
7429
+ projectSlug: latestMatch[1],
7430
+ version: "latest",
7431
+ path: latestMatch[2]
7432
+ };
7433
+ }
7434
+ return null;
7435
+ }
7436
+ function resolveCrossProjectImports(code, options) {
7437
+ const { ssr = false } = options;
7438
+ if (ssr) {
7439
+ return Promise.resolve(code);
7440
+ }
7441
+ return Promise.resolve(
7442
+ replaceSpecifiers(code, (specifier) => {
7443
+ const parsed = parseCrossProjectImport(specifier);
7444
+ if (!parsed)
7445
+ return null;
7446
+ const { projectSlug, version, path } = parsed;
7447
+ let modulePath = path;
7448
+ if (!/\.(js|mjs|jsx|ts|tsx|mdx)$/.test(modulePath)) {
7449
+ modulePath = `${modulePath}.tsx`;
7450
+ }
7451
+ const projectRef = version === "latest" ? projectSlug : `${projectSlug}@${version}`;
7452
+ const moduleServerUrl = `/_vf_modules/_cross/${projectRef}/@/${modulePath}`;
7453
+ rendererLogger.debug("[CrossProjectImport] Rewriting", { from: specifier, to: moduleServerUrl });
7454
+ return moduleServerUrl;
7455
+ })
7456
+ );
7457
+ }
7458
+ function blockExternalUrlImports(code, _filePath) {
7459
+ return Promise.resolve({ code, blockedUrls: [] });
7460
+ }
7461
+ function resolveVeryfrontImports(code) {
7462
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
7463
+ if (specifier.startsWith("@veryfront/")) {
7464
+ return specifier.replace("@veryfront/", "veryfront/");
7465
+ }
7466
+ if (specifier === "@veryfront") {
7467
+ return "veryfront";
7468
+ }
7469
+ return null;
7470
+ }));
7471
+ }
7472
+ function resolvePathAliases(code, filePath, projectDir, ssr = false) {
7473
+ const _normalizedProjectDir = projectDir.replace(/\\/g, "/").replace(/\/$/, "");
7474
+ let relativeFilePath = filePath;
7475
+ if (filePath.startsWith(_normalizedProjectDir)) {
7476
+ relativeFilePath = filePath.substring(_normalizedProjectDir.length + 1);
7477
+ } else if (filePath.startsWith("/")) {
7478
+ const pathParts = filePath.split("/");
7479
+ const projectParts = _normalizedProjectDir.split("/");
7480
+ const lastProjectPart = projectParts[projectParts.length - 1];
7481
+ const projectIndex = pathParts.indexOf(lastProjectPart);
7482
+ if (projectIndex >= 0) {
7483
+ relativeFilePath = pathParts.slice(projectIndex + 1).join("/");
7484
+ }
7485
+ }
7486
+ const fileDir = relativeFilePath.substring(0, relativeFilePath.lastIndexOf("/"));
7487
+ const depth = fileDir.split("/").filter(Boolean).length;
7488
+ const relativeToRoot = depth === 0 ? "." : "../".repeat(depth).slice(0, -1);
7489
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
7490
+ if (specifier.startsWith("@/")) {
7491
+ const path = specifier.substring(2);
7492
+ const relativePath = depth === 0 ? `./${path}` : `${relativeToRoot}/${path}`;
7493
+ if (!/\.(tsx?|jsx?|mjs|cjs|mdx)$/.test(relativePath)) {
7494
+ return relativePath + ".js";
7495
+ }
7496
+ if (ssr) {
7497
+ return relativePath.replace(/\.(tsx?|jsx|mdx)$/, ".js");
7498
+ }
7499
+ return relativePath;
7500
+ }
7501
+ return null;
7502
+ }));
7503
+ }
7504
+ function resolveRelativeImports(code, filePath, projectDir, moduleServerUrl) {
7505
+ const _normalizedProjectDir = projectDir.replace(/\\/g, "/").replace(/\/$/, "");
7506
+ let relativeFilePath = filePath;
7507
+ if (filePath.startsWith(_normalizedProjectDir)) {
7508
+ relativeFilePath = filePath.substring(_normalizedProjectDir.length + 1);
7509
+ } else if (filePath.startsWith("/")) {
7510
+ const pathParts = filePath.split("/");
7511
+ const projectParts = _normalizedProjectDir.split("/");
7512
+ const lastProjectPart = projectParts[projectParts.length - 1];
7513
+ const projectIndex = pathParts.indexOf(lastProjectPart);
7514
+ if (projectIndex >= 0) {
7515
+ relativeFilePath = pathParts.slice(projectIndex + 1).join("/");
7516
+ }
7517
+ }
7518
+ const fileDir = relativeFilePath.substring(0, relativeFilePath.lastIndexOf("/"));
7519
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
7520
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
7521
+ let rewrittenSpecifier = specifier;
7522
+ if (/\.(tsx?|jsx)$/.test(specifier)) {
7523
+ rewrittenSpecifier = specifier.replace(/\.(tsx?|jsx)$/, ".js");
7524
+ }
7525
+ if (moduleServerUrl) {
7526
+ const resolvedPath = resolveRelativePath(fileDir, rewrittenSpecifier);
7527
+ return `${moduleServerUrl}/${resolvedPath}`;
7528
+ }
7529
+ return rewrittenSpecifier;
7530
+ }
7531
+ return null;
7532
+ }));
7533
+ }
7534
+ function resolveRelativePath(currentDir, importPath) {
7535
+ const currentParts = currentDir.split("/").filter(Boolean);
7536
+ const importParts = importPath.split("/").filter(Boolean);
7537
+ const resolvedParts = [...currentParts];
7538
+ for (const part of importParts) {
7539
+ if (part === "..") {
7540
+ resolvedParts.pop();
7541
+ } else if (part !== ".") {
7542
+ resolvedParts.push(part);
7543
+ }
7544
+ }
7545
+ return resolvedParts.join("/");
7546
+ }
7547
+ function resolveRelativeImportsForSSR(code) {
7548
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
7549
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
7550
+ if (/\.(js|mjs|cjs)$/.test(specifier)) {
7551
+ return null;
7552
+ }
7553
+ const withoutExt = specifier.replace(/\.(tsx?|jsx|mdx)$/, "");
7554
+ return withoutExt + ".js";
7555
+ }
7556
+ return null;
7557
+ }));
7558
+ }
7559
+
7560
+ // src/build/transforms/pipeline/stages/resolve-aliases.ts
7561
+ var resolveAliasesPlugin = {
7562
+ name: "resolve-aliases",
7563
+ stage: 2 /* RESOLVE_ALIASES */,
7564
+ async transform(ctx) {
7565
+ let code = ctx.code;
7566
+ code = await resolvePathAliases(code, ctx.filePath, ctx.projectDir, isSSR(ctx));
7567
+ const apiBaseUrl = ctx.apiBaseUrl || Deno.env.get("VERYFRONT_API_BASE_URL") || Deno.env.get("VERYFRONT_API_URL")?.replace("/graphql", "/api") || "http://api.lvh.me:4000/api";
7568
+ code = await resolveCrossProjectImports(code, {
7569
+ apiBaseUrl,
7570
+ ssr: isSSR(ctx)
7571
+ });
7572
+ return code;
7573
+ }
7574
+ };
7575
+
7576
+ // src/build/transforms/pipeline/stages/resolve-react.ts
7577
+ init_deno_env();
7578
+
7579
+ // src/build/transforms/esm/react-imports.ts
7580
+ init_deno_env();
7581
+ function getVeryfrontAIReactPath(subpath = "") {
7582
+ const currentDir = new URL(".", import.meta.url).pathname;
7583
+ const srcDir = currentDir.replace(/\/build\/transforms\/esm\/?$/, "");
7584
+ const modulePath = subpath || "index.ts";
7585
+ return `file://${srcDir}/ai/react/${modulePath}`;
7586
+ }
7587
+ function getVeryfrontExportPath(name) {
7588
+ const currentDir = new URL(".", import.meta.url).pathname;
7589
+ const srcDir = currentDir.replace(/\/build\/transforms\/esm\/?$/, "");
7590
+ return `file://${srcDir}/exports/${name}.ts`;
7591
+ }
7592
+ async function resolveReactImports(code, forSSR = false) {
7593
+ if (forSSR) {
7594
+ const ssrImports = {
7595
+ // AI modules - file:// URLs for local resolution
7596
+ "veryfront/ai/react": getVeryfrontAIReactPath(),
7597
+ "veryfront/ai/components": getVeryfrontAIReactPath("components/index.ts"),
7598
+ "veryfront/ai/primitives": getVeryfrontAIReactPath("primitives/index.ts"),
7599
+ // Framework exports - file:// URLs for local resolution
7600
+ "veryfront/head": getVeryfrontExportPath("head"),
7601
+ "veryfront/router": getVeryfrontExportPath("router"),
7602
+ "veryfront/context": getVeryfrontExportPath("context"),
7603
+ "veryfront/fonts": getVeryfrontExportPath("fonts")
7604
+ };
7605
+ return replaceSpecifiers(code, (specifier) => {
7606
+ return ssrImports[specifier] || null;
7607
+ });
7608
+ }
7609
+ const reactImports = getReactImportMap2();
7610
+ return replaceSpecifiers(code, (specifier) => {
7611
+ return reactImports[specifier] || null;
7612
+ });
7613
+ }
7614
+ var IMPORT_MAP_PACKAGES = [
7615
+ "@tanstack/react-query",
7616
+ "@tanstack/query-core",
7617
+ "next-themes",
7618
+ "framer-motion",
7619
+ "react-hook-form"
7620
+ ];
7621
+ function extractPackageFromEsmSh(url) {
7622
+ if (!url.startsWith("https://esm.sh/") && !url.startsWith("http://esm.sh/")) {
7623
+ return null;
7624
+ }
7625
+ let path = url.replace(/^https?:\/\/esm\.sh\//, "");
7626
+ path = path.replace(/^v\d+\//, "");
7627
+ if (path.startsWith("@")) {
7628
+ const match = path.match(/^(@[^/]+\/[^@/?]+)/);
7629
+ return match?.[1] ?? null;
7630
+ } else {
7631
+ const match = path.match(/^([^@/?]+)/);
7632
+ return match?.[1] ?? null;
7633
+ }
7634
+ }
7635
+ function addDepsToEsmShUrls(code, _forSSR = false) {
7636
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
7637
+ if (specifier.startsWith("https://esm.sh/") && !specifier.includes(`react@${REACT_VERSION}`)) {
7638
+ const packageName = extractPackageFromEsmSh(specifier);
7639
+ if (packageName && IMPORT_MAP_PACKAGES.includes(packageName)) {
7640
+ return packageName;
7641
+ }
7642
+ const hasQuery = specifier.includes("?");
7643
+ if (hasQuery) {
7644
+ return null;
7645
+ }
7646
+ return `${specifier}?external=react,react-dom&target=es2022`;
7647
+ }
7648
+ return null;
7649
+ }));
7650
+ }
7651
+
7652
+ // src/build/transforms/pipeline/stages/resolve-react.ts
7653
+ var resolveReactPlugin = {
7654
+ name: "resolve-react",
7655
+ stage: 3 /* RESOLVE_REACT */,
7656
+ async transform(ctx) {
7657
+ let code = ctx.code;
7658
+ code = await resolveReactImports(code, isSSR(ctx));
7659
+ code = await addDepsToEsmShUrls(code, isSSR(ctx));
7660
+ if (ctx.dev && isBrowser(ctx)) {
7661
+ code = code.replace(
7662
+ /(['"])https?:\/\/[a-zA-Z0-9-]+\.(?:com|org|net|io|dev|app|veryfront\.com)\1/g,
7663
+ "location.origin"
7664
+ );
7665
+ }
7666
+ return code;
7667
+ }
7668
+ };
7669
+
7670
+ // src/build/transforms/pipeline/stages/resolve-context.ts
7671
+ init_deno_env();
7672
+ function buildContextImportMap(ssr) {
7673
+ const map = {};
7674
+ for (const pkg of CONTEXT_PACKAGE_NAMES) {
7675
+ map[pkg] = ssr ? getContextPackageUrlSSR(pkg) : getContextPackageUrlBrowser(pkg);
7676
+ }
7677
+ return map;
7678
+ }
7679
+ var resolveContextPlugin = {
7680
+ name: "resolve-context",
7681
+ stage: 4 /* RESOLVE_CONTEXT */,
7682
+ async transform(ctx) {
7683
+ const importMap = buildContextImportMap(ctx.target === "ssr");
7684
+ return await replaceSpecifiers(ctx.code, (specifier) => {
7685
+ if (isContextPackage(specifier)) {
7686
+ return importMap[specifier] || null;
7687
+ }
7688
+ if (specifier.startsWith("https://esm.sh/")) {
7689
+ const packageName = extractPackageFromEsmSh2(specifier);
7690
+ if (packageName && isContextPackage(packageName)) {
7691
+ return importMap[packageName] || null;
7692
+ }
7693
+ }
7694
+ return null;
7695
+ });
7696
+ }
7697
+ };
7698
+ function extractPackageFromEsmSh2(url) {
7699
+ if (!url.startsWith("https://esm.sh/") && !url.startsWith("http://esm.sh/")) {
7700
+ return null;
7701
+ }
7702
+ let path = url.replace(/^https?:\/\/esm\.sh\//, "");
7703
+ path = path.replace(/^v\d+\//, "");
7704
+ if (path.startsWith("@")) {
7705
+ const match = path.match(/^(@[^/]+\/[^@/?]+)/);
7706
+ return match?.[1] ?? null;
7707
+ } else {
7708
+ const match = path.match(/^([^@/?]+)/);
7709
+ return match?.[1] ?? null;
7710
+ }
7711
+ }
7712
+
7713
+ // src/build/transforms/pipeline/stages/ssr-http-stub.ts
7714
+ init_deno_env();
7715
+ function isHttpImport(specifier) {
7716
+ if (!specifier)
7717
+ return false;
7718
+ return specifier.startsWith("http://") || specifier.startsWith("https://");
7719
+ }
7720
+ function isBrowserOnlyModule(specifier) {
7721
+ if (specifier.includes("video.js") || specifier.includes("video-js"))
7722
+ return true;
7723
+ if (specifier.includes("videojs"))
7724
+ return true;
7725
+ if (specifier.includes("gsap"))
7726
+ return true;
7727
+ if (specifier.includes("three"))
7728
+ return true;
7729
+ if (specifier.includes("mapbox"))
7730
+ return true;
7731
+ if (specifier.includes("leaflet"))
7732
+ return true;
7733
+ return false;
7734
+ }
7735
+ function generateStub(imp, statement) {
7736
+ if (!imp.n || !isHttpImport(imp.n))
7737
+ return null;
7738
+ if (!isBrowserOnlyModule(imp.n))
7739
+ return null;
7740
+ if (imp.d > -1)
7741
+ return null;
7742
+ const trimmed = statement.trim();
7743
+ if (/^import\s+['"`]/.test(trimmed)) {
7744
+ return `/* SSR stub: ${trimmed} */`;
7745
+ }
7746
+ const fromIndex = trimmed.lastIndexOf(" from ");
7747
+ if (fromIndex === -1)
7748
+ return null;
7749
+ const importClause = trimmed.slice(6, fromIndex).trim();
7750
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(importClause)) {
7751
+ return `const ${importClause} = null; /* SSR stub for ${imp.n} */`;
7752
+ }
7753
+ const namespaceMatch = importClause.match(/^\*\s+as\s+([a-zA-Z_$][a-zA-Z0-9_$]*)$/);
7754
+ if (namespaceMatch) {
7755
+ return `const ${namespaceMatch[1]} = {}; /* SSR stub for ${imp.n} */`;
7756
+ }
7757
+ const namedMatch = importClause.match(/^\{([^}]+)\}$/);
7758
+ if (namedMatch?.[1]) {
7759
+ const names = namedMatch[1].split(",").map((n) => {
7760
+ const parts = n.trim().split(/\s+as\s+/);
7761
+ return parts[parts.length - 1]?.trim() ?? "";
7762
+ });
7763
+ const stubs = names.map((n) => `${n} = null`).join(", ");
7764
+ return `const ${stubs}; /* SSR stub for ${imp.n} */`;
7765
+ }
7766
+ const mixedMatch = importClause.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*)\s*,\s*\{([^}]+)\}$/);
7767
+ if (mixedMatch?.[1] && mixedMatch[2]) {
7768
+ const defaultName = mixedMatch[1];
7769
+ const names = mixedMatch[2].split(",").map((n) => {
7770
+ const parts = n.trim().split(/\s+as\s+/);
7771
+ return parts[parts.length - 1]?.trim() ?? "";
7772
+ });
7773
+ const allNames = [defaultName, ...names].map((n) => `${n} = null`).join(", ");
7774
+ return `const ${allNames}; /* SSR stub for ${imp.n} */`;
7775
+ }
7776
+ return null;
7777
+ }
7778
+ var ssrHttpStubPlugin = {
7779
+ name: "ssr-http-stub",
7780
+ stage: 4 /* RESOLVE_CONTEXT */ + 1,
7781
+ // Run just after resolve-context, before resolve-relative
7782
+ // No condition needed - this plugin is only added to SSR_PIPELINE
7783
+ async transform(ctx) {
7784
+ const imports = await parseImports(ctx.code);
7785
+ const needsStubbing = imports.some(
7786
+ (imp) => imp.n && isHttpImport(imp.n) && isBrowserOnlyModule(imp.n) && imp.d === -1
7787
+ );
7788
+ if (!needsStubbing) {
7789
+ return ctx.code;
7790
+ }
7791
+ return await rewriteImports(ctx.code, (imp, statement) => generateStub(imp, statement));
7792
+ }
7793
+ };
7794
+
7795
+ // src/build/transforms/pipeline/stages/resolve-relative.ts
7796
+ init_deno_env();
7797
+ init_utils();
7798
+ var resolveRelativePlugin = {
7799
+ name: "resolve-relative",
7800
+ stage: 5 /* RESOLVE_RELATIVE */,
7801
+ async transform(ctx) {
7802
+ let code = ctx.code;
7803
+ if (isSSR(ctx)) {
7804
+ const urlBlockResult = await blockExternalUrlImports(code, ctx.filePath);
7805
+ code = urlBlockResult.code;
7806
+ if (urlBlockResult.blockedUrls.length > 0) {
7807
+ rendererLogger.warn("[PIPELINE:resolve-relative] Blocked external URL imports in SSR mode", {
7808
+ file: ctx.filePath.slice(-60),
7809
+ blockedUrls: urlBlockResult.blockedUrls
7810
+ });
7811
+ }
7812
+ code = await resolveRelativeImportsForSSR(code);
7813
+ code = await resolveVeryfrontImports(code);
7814
+ } else if (isBrowser(ctx)) {
7815
+ code = await resolveRelativeImports(
7816
+ code,
7817
+ ctx.filePath,
7818
+ ctx.projectDir,
7819
+ ctx.moduleServerUrl
7820
+ );
7821
+ }
7822
+ return code;
7823
+ }
7824
+ };
7825
+
7826
+ // src/build/transforms/pipeline/stages/resolve-bare.ts
7827
+ init_deno_env();
7828
+
7829
+ // src/build/transforms/esm/import-rewriter.ts
7830
+ init_deno_env();
7831
+ init_cdn();
7832
+ init_utils();
7833
+ var unversionedImportsWarned = /* @__PURE__ */ new Set();
7834
+ function hasVersionSpecifier(specifier) {
7835
+ return /@[\d^~x][\d.x^~-]*(?=\/|$)/.test(specifier);
7836
+ }
7837
+ function warnUnversionedImport(specifier) {
7838
+ if (unversionedImportsWarned.has(specifier)) {
7839
+ return;
7840
+ }
7841
+ unversionedImportsWarned.add(specifier);
7842
+ const suggestedVersion = "x.y.z";
7843
+ const packageName = specifier.split("/")[0];
7844
+ const isScoped = specifier.startsWith("@");
7845
+ const scopedPackage = isScoped ? specifier.split("/").slice(0, 2).join("/") : packageName;
7846
+ const subpath = isScoped ? specifier.split("/").slice(2).join("/") : specifier.split("/").slice(1).join("/");
7847
+ const versionedSpecifier = subpath ? `${scopedPackage}@${suggestedVersion}/${subpath}` : `${scopedPackage}@${suggestedVersion}`;
7848
+ rendererLogger.warn("[ESM] Unversioned import may cause reproducibility issues", {
7849
+ import: specifier,
7850
+ suggestion: `Pin version: import '${versionedSpecifier}'`,
7851
+ help: "Run 'npm info " + (isScoped ? scopedPackage : packageName) + " version' to find current version"
7852
+ });
7853
+ }
7854
+ function normalizeVersionedSpecifier(specifier) {
7855
+ return specifier.replace(/@[\d^~x][\d.x^~-]*(?=\/|$)/, "");
7856
+ }
7857
+ function rewriteBareImports(code, _moduleServerUrl) {
7858
+ const htmlImportMapPackages = [
7859
+ "@tanstack/react-query",
7860
+ "@tanstack/query-core",
7861
+ "next-themes",
7862
+ "framer-motion"
7863
+ ];
7864
+ const importMap = {
7865
+ "react": `https://esm.sh/react@${REACT_DEFAULT_VERSION}?target=es2022`,
7866
+ "react-dom": `https://esm.sh/react-dom@${REACT_DEFAULT_VERSION}?target=es2022`,
7867
+ "react-dom/client": `https://esm.sh/react-dom@${REACT_DEFAULT_VERSION}/client?target=es2022`,
7868
+ "react-dom/server": `https://esm.sh/react-dom@${REACT_DEFAULT_VERSION}/server?target=es2022`,
7869
+ "react/jsx-runtime": `https://esm.sh/react@${REACT_DEFAULT_VERSION}/jsx-runtime?target=es2022`,
7870
+ "react/jsx-dev-runtime": `https://esm.sh/react@${REACT_DEFAULT_VERSION}/jsx-dev-runtime?target=es2022`
7871
+ // NOTE: veryfront/ai/react is NOT rewritten here - it's handled by the HTML import map
7872
+ // which points to /_veryfront/lib/ai/react.js served from the local package
7873
+ };
7874
+ return Promise.resolve(replaceSpecifiers(code, (specifier) => {
7875
+ if (importMap[specifier]) {
7876
+ return importMap[specifier];
7877
+ }
7878
+ if (specifier.startsWith("http://") || specifier.startsWith("https://") || specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/") || specifier.startsWith("@/") || // Project alias
7879
+ specifier.startsWith("veryfront")) {
7880
+ return null;
7881
+ }
7882
+ const normalized = normalizeVersionedSpecifier(specifier);
7883
+ const matchesImportMapPackage = htmlImportMapPackages.some(
7884
+ (pkg) => normalized === pkg || normalized.startsWith(`${pkg}/`)
7885
+ );
7886
+ if (matchesImportMapPackage) {
7887
+ return null;
7888
+ }
7889
+ let finalSpecifier = normalized;
7890
+ if (normalized === "tailwindcss" || normalized.startsWith("tailwindcss/")) {
7891
+ finalSpecifier = normalized.replace(/^tailwindcss/, `tailwindcss@${TAILWIND_VERSION}`);
7892
+ } else if (!hasVersionSpecifier(specifier)) {
7893
+ warnUnversionedImport(specifier);
7894
+ }
7895
+ return `https://esm.sh/${finalSpecifier}?external=react,react-dom&target=es2022`;
7896
+ }));
7897
+ }
7898
+ async function rewriteVendorImports(code, moduleServerUrl, vendorBundleHash) {
7899
+ const vendorUrl = `${moduleServerUrl}/_vendor.js?v=${vendorBundleHash}`;
7900
+ const reactPackages = /* @__PURE__ */ new Set([
7901
+ "react",
7902
+ "react-dom",
7903
+ "react-dom/client",
7904
+ "react-dom/server",
7905
+ "react/jsx-runtime",
7906
+ "react/jsx-dev-runtime"
7907
+ ]);
7908
+ let result = await rewriteImports(code, (imp, statement) => {
7909
+ if (!imp.n || !reactPackages.has(imp.n))
7910
+ return null;
7911
+ const trimmed = statement.trimStart();
7912
+ if (!trimmed.startsWith("export"))
7913
+ return null;
7914
+ const specStart = imp.s - imp.ss;
7915
+ const specEnd = imp.e - imp.ss;
7916
+ const before = statement.slice(0, specStart);
7917
+ const after = statement.slice(specEnd);
7918
+ return `${before}${vendorUrl}${after}`;
7919
+ });
7920
+ const baseSource = result;
7921
+ const imports = await parseImports(baseSource);
7922
+ for (let i = imports.length - 1; i >= 0; i--) {
7923
+ const imp = imports[i];
7924
+ if (!imp)
7925
+ continue;
7926
+ if (!imp.n || !reactPackages.has(imp.n))
7927
+ continue;
7928
+ const exportName = sanitizeVendorExportName(imp.n);
7929
+ if (imp.d > -1) {
7930
+ const afterSpecifier = baseSource.substring(imp.e);
7931
+ const match = afterSpecifier.match(/^['"]\s*\)/);
7932
+ if (!match)
7933
+ continue;
7934
+ const endOfCall = imp.e + match[0].length;
7935
+ const before = result.substring(0, imp.d);
7936
+ const after = result.substring(endOfCall);
7937
+ const replacement = `import('${vendorUrl}').then(m => m.${exportName})`;
7938
+ result = before + replacement + after;
7939
+ } else {
7940
+ const beforeSpecifier = baseSource.substring(imp.ss, imp.s);
7941
+ const fromIndex = beforeSpecifier.lastIndexOf("from");
7942
+ if (fromIndex === -1) {
7943
+ const before2 = result.substring(0, imp.ss);
7944
+ const after2 = result.substring(imp.se);
7945
+ result = before2 + `import '${vendorUrl}'` + after2;
7946
+ continue;
7947
+ }
7948
+ const clause = beforeSpecifier.substring(6, fromIndex).trim();
7949
+ let replacement = "";
7950
+ if (clause.startsWith("*")) {
7951
+ replacement = `import ${clause} from '${vendorUrl}'`;
7952
+ } else if (clause.startsWith("{")) {
7953
+ replacement = `import { ${exportName} } from '${vendorUrl}'; const ${clause} = ${exportName}`;
7954
+ } else {
7955
+ replacement = `import { ${exportName} as ${clause} } from '${vendorUrl}'`;
7956
+ }
7957
+ const before = result.substring(0, imp.ss);
7958
+ const after = result.substring(imp.se);
7959
+ result = before + replacement + after;
7960
+ }
7961
+ }
7962
+ return result;
7963
+ }
7964
+ function sanitizeVendorExportName(pkg) {
7965
+ return pkg.replace(/^@/, "").replace(/[\/\-]/g, "_").replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/^_/, "");
7966
+ }
7967
+
7968
+ // src/build/transforms/pipeline/stages/resolve-bare.ts
7969
+ var resolveBarePlugin = {
7970
+ name: "resolve-bare",
7971
+ stage: 6 /* RESOLVE_BARE */,
7972
+ async transform(ctx) {
7973
+ let code = ctx.code;
7974
+ if (isSSR(ctx)) {
7975
+ code = transformImportsWithMap(
7976
+ code,
7977
+ getDefaultImportMap(),
7978
+ void 0,
7979
+ { resolveBare: true }
7980
+ );
7981
+ } else if (isBrowser(ctx)) {
7982
+ if (ctx.moduleServerUrl && ctx.vendorBundleHash) {
7983
+ code = await rewriteVendorImports(code, ctx.moduleServerUrl, ctx.vendorBundleHash);
7984
+ } else {
7985
+ code = await rewriteBareImports(code, ctx.moduleServerUrl);
7986
+ }
7987
+ }
7988
+ return code;
7989
+ }
7990
+ };
7991
+
7992
+ // src/build/transforms/pipeline/stages/finalize.ts
7993
+ init_deno_env();
7994
+
7995
+ // src/build/transforms/esm/http-bundler.ts
7996
+ init_deno_env();
7997
+ init_utils();
7998
+ var LOG_PREFIX = "[HTTP-HANDLER]";
7999
+ function hasHttpImports(code) {
8000
+ return /['"]https?:\/\/[^'"]+['"]/.test(code);
8001
+ }
8002
+ function getReactAliases() {
8003
+ const urls = getReactUrls();
8004
+ return {
8005
+ // Bare specifiers
8006
+ "react": urls.react,
8007
+ "react-dom": urls["react-dom"],
8008
+ "react/jsx-runtime": urls["react/jsx-runtime"],
8009
+ "react/jsx-dev-runtime": urls["react/jsx-dev-runtime"],
8010
+ "react-dom/server": urls["react-dom/server"],
8011
+ "react-dom/client": urls["react-dom/client"],
8012
+ // npm: specifiers (Deno import map resolution produces these)
8013
+ "npm:react": urls.react,
8014
+ [`npm:react@${REACT_VERSION}`]: urls.react,
8015
+ [`npm:react@${REACT_VERSION}/jsx-runtime`]: urls["react/jsx-runtime"],
8016
+ [`npm:react@${REACT_VERSION}/jsx-dev-runtime`]: urls["react/jsx-dev-runtime"],
8017
+ "npm:react-dom": urls["react-dom"],
8018
+ [`npm:react-dom@${REACT_VERSION}`]: urls["react-dom"],
8019
+ [`npm:react-dom@${REACT_VERSION}/server`]: urls["react-dom/server"],
8020
+ [`npm:react-dom@${REACT_VERSION}/client`]: urls["react-dom/client"]
8021
+ };
8022
+ }
8023
+ function stripDenoShim(code) {
8024
+ const isDeno3 = typeof Deno !== "undefined";
8025
+ if (!isDeno3)
8026
+ return code;
8027
+ return code.replace(
8028
+ /globalThis\.Deno\s*=\s*globalThis\.Deno\s*\|\|\s*\{[\s\S]*?env:\s*\{[\s\S]*?\}\s*\};?/g,
8029
+ "/* Deno shim stripped */"
8030
+ );
8031
+ }
8032
+ function createHTTPPlugin() {
8033
+ return { name: "vf-http-noop", setup: () => {
8034
+ } };
8035
+ }
8036
+ function bundleHttpImports(code, _tempDir, hash) {
8037
+ const has = hasHttpImports(code);
8038
+ rendererLogger.debug(`${LOG_PREFIX} Check: hasHttp=${has}, hash=${hash.slice(0, 8)}`);
8039
+ if (!has)
8040
+ return code;
8041
+ const isDeno3 = typeof Deno !== "undefined";
8042
+ if (isDeno3) {
8043
+ rendererLogger.debug(`${LOG_PREFIX} Deno detected - passing through HTTP imports`);
8044
+ return code;
8045
+ }
8046
+ rendererLogger.warn(`${LOG_PREFIX} Non-Deno runtime detected - HTTP imports may fail`);
8047
+ return code;
8048
+ }
8049
+
8050
+ // src/build/transforms/pipeline/stages/finalize.ts
8051
+ init_process();
8052
+ import { join as join4 } from "node:path";
8053
+ var finalizePlugin = {
8054
+ name: "finalize",
8055
+ stage: 7 /* FINALIZE */,
8056
+ transform(ctx) {
8057
+ let code = ctx.code;
8058
+ if (isSSR(ctx)) {
8059
+ const httpCacheDir = join4(cwd(), ".cache", "veryfront-http-bundle");
8060
+ code = bundleHttpImports(code, httpCacheDir, ctx.contentHash);
8061
+ }
8062
+ return code;
8063
+ }
8064
+ };
8065
+
8066
+ // src/build/transforms/pipeline/index.ts
8067
+ var SSR_PIPELINE = [
8068
+ parsePlugin,
8069
+ compilePlugin,
8070
+ resolveAliasesPlugin,
8071
+ resolveReactPlugin,
8072
+ resolveContextPlugin,
8073
+ ssrHttpStubPlugin,
8074
+ // Stub browser-only HTTP imports during SSR
8075
+ resolveRelativePlugin,
8076
+ resolveBarePlugin,
8077
+ finalizePlugin
8078
+ ];
8079
+ var BROWSER_PIPELINE = [
8080
+ parsePlugin,
8081
+ compilePlugin,
8082
+ resolveAliasesPlugin,
8083
+ resolveReactPlugin,
8084
+ resolveContextPlugin,
8085
+ resolveRelativePlugin,
8086
+ resolveBarePlugin,
8087
+ finalizePlugin
8088
+ ];
8089
+ async function runPipeline(source, filePath, projectDir, options, config) {
8090
+ const transformStart = performance.now();
8091
+ const ctx = await createTransformContext(source, filePath, projectDir, options);
8092
+ ctx.debug = config?.debug ?? false;
8093
+ const cacheKey = generateCacheKey(
8094
+ options.projectId,
8095
+ filePath,
8096
+ ctx.contentHash,
8097
+ options.ssr ?? false
8098
+ );
8099
+ const cached = getCachedTransform(cacheKey);
8100
+ if (cached) {
8101
+ return {
8102
+ code: cached.code,
8103
+ contentHash: ctx.contentHash,
8104
+ timing: /* @__PURE__ */ new Map(),
8105
+ totalMs: performance.now() - transformStart,
8106
+ cached: true
8107
+ };
8108
+ }
8109
+ const basePipeline = options.ssr ? SSR_PIPELINE : BROWSER_PIPELINE;
8110
+ const pipeline = config?.plugins ? [...basePipeline, ...config.plugins].sort((a, b) => a.stage - b.stage) : basePipeline;
8111
+ for (const plugin of pipeline) {
8112
+ if (plugin.condition && !plugin.condition(ctx)) {
8113
+ continue;
8114
+ }
8115
+ const stageStart = performance.now();
8116
+ try {
8117
+ ctx.code = await plugin.transform(ctx);
8118
+ } catch (error) {
8119
+ rendererLogger.error(`[PIPELINE:${plugin.name}] Stage failed`, {
8120
+ file: filePath.slice(-60),
8121
+ stage: plugin.name,
8122
+ error: error instanceof Error ? error.message : String(error)
8123
+ });
8124
+ throw error;
8125
+ }
8126
+ recordStageTiming(ctx, plugin.stage, stageStart);
8127
+ }
8128
+ setCachedTransform(cacheKey, ctx.code, ctx.contentHash);
8129
+ const totalMs = performance.now() - transformStart;
8130
+ if (ctx.debug) {
8131
+ rendererLogger.debug("[PIPELINE] Transform complete", formatTimingLog(ctx));
8132
+ }
8133
+ return {
8134
+ code: ctx.code,
8135
+ contentHash: ctx.contentHash,
8136
+ timing: ctx.timing,
8137
+ totalMs,
8138
+ cached: false
8139
+ };
8140
+ }
8141
+ async function transformToESM(source, filePath, projectDir, _adapter, options) {
8142
+ if (filePath.endsWith(".css") || filePath.endsWith(".json")) {
8143
+ return source;
8144
+ }
8145
+ const result = await runPipeline(source, filePath, projectDir, options);
8146
+ return result.code;
8147
+ }
8148
+
8149
+ // src/rendering/ssr-globals.ts
8150
+ init_deno_env();
8151
+ var ssrGlobalsInitialized = false;
8152
+ var createDocumentStub = () => ({
8153
+ // Fullscreen API (video.js, etc.)
8154
+ exitFullscreen: void 0,
8155
+ webkitExitFullscreen: void 0,
8156
+ mozCancelFullScreen: void 0,
8157
+ msExitFullscreen: void 0,
8158
+ fullscreenElement: null,
8159
+ webkitFullscreenElement: null,
8160
+ mozFullScreenElement: null,
8161
+ msFullscreenElement: null,
8162
+ // DOM methods (return null/empty to indicate not found)
8163
+ createElement: () => createElementStub(),
8164
+ createElementNS: () => createElementStub(),
8165
+ createTextNode: () => ({ textContent: "" }),
8166
+ querySelector: () => null,
8167
+ querySelectorAll: () => [],
8168
+ getElementById: () => null,
8169
+ getElementsByClassName: () => [],
8170
+ getElementsByTagName: () => [],
8171
+ getElementsByName: () => [],
8172
+ // Document properties
8173
+ documentElement: {
8174
+ style: {},
8175
+ classList: { add: () => {
8176
+ }, remove: () => {
8177
+ }, contains: () => false }
8178
+ },
8179
+ body: {
8180
+ style: {},
8181
+ classList: { add: () => {
8182
+ }, remove: () => {
8183
+ }, contains: () => false },
8184
+ appendChild: () => {
8185
+ }
8186
+ },
8187
+ head: { appendChild: () => {
8188
+ }, removeChild: () => {
8189
+ } },
8190
+ readyState: "complete",
8191
+ cookie: "",
8192
+ domain: "",
8193
+ referrer: "",
8194
+ title: "",
8195
+ URL: "",
8196
+ location: { href: "", pathname: "/", search: "", hash: "" },
8197
+ // Event handling (no-op)
8198
+ addEventListener: () => {
8199
+ },
8200
+ removeEventListener: () => {
8201
+ },
8202
+ dispatchEvent: () => true,
8203
+ // Style/CSS
8204
+ styleSheets: [],
8205
+ adoptedStyleSheets: []
8206
+ });
8207
+ var createElementStub = () => ({
8208
+ style: {},
8209
+ classList: { add: () => {
8210
+ }, remove: () => {
8211
+ }, contains: () => false, toggle: () => false },
8212
+ dataset: {},
8213
+ setAttribute: () => {
8214
+ },
8215
+ getAttribute: () => null,
8216
+ removeAttribute: () => {
8217
+ },
8218
+ hasAttribute: () => false,
8219
+ appendChild: () => {
8220
+ },
8221
+ removeChild: () => {
8222
+ },
8223
+ insertBefore: () => {
8224
+ },
8225
+ replaceChild: () => {
8226
+ },
8227
+ cloneNode: () => createElementStub(),
8228
+ addEventListener: () => {
8229
+ },
8230
+ removeEventListener: () => {
8231
+ },
8232
+ querySelector: () => null,
8233
+ querySelectorAll: () => [],
8234
+ getBoundingClientRect: () => ({ top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }),
8235
+ offsetWidth: 0,
8236
+ offsetHeight: 0,
8237
+ scrollWidth: 0,
8238
+ scrollHeight: 0,
8239
+ clientWidth: 0,
8240
+ clientHeight: 0,
8241
+ innerHTML: "",
8242
+ outerHTML: "",
8243
+ textContent: "",
8244
+ innerText: "",
8245
+ children: [],
8246
+ childNodes: [],
8247
+ parentNode: null,
8248
+ parentElement: null,
8249
+ nextSibling: null,
8250
+ previousSibling: null,
8251
+ firstChild: null,
8252
+ lastChild: null
8253
+ });
8254
+ var createWindowStub = () => ({
8255
+ // Common properties
8256
+ document: createDocumentStub(),
8257
+ navigator: {
8258
+ userAgent: "SSR",
8259
+ language: "en-US",
8260
+ languages: ["en-US"],
8261
+ platform: "SSR",
8262
+ vendor: "",
8263
+ onLine: true,
8264
+ cookieEnabled: false,
8265
+ mediaDevices: { getUserMedia: () => Promise.reject(new Error("SSR")) }
8266
+ },
8267
+ location: {
8268
+ href: "",
8269
+ pathname: "/",
8270
+ search: "",
8271
+ hash: "",
8272
+ origin: "",
8273
+ protocol: "https:",
8274
+ host: "",
8275
+ hostname: "",
8276
+ port: "",
8277
+ assign: () => {
8278
+ },
8279
+ replace: () => {
8280
+ },
8281
+ reload: () => {
8282
+ }
8283
+ },
8284
+ history: {
8285
+ length: 0,
8286
+ state: null,
8287
+ pushState: () => {
8288
+ },
8289
+ replaceState: () => {
8290
+ },
8291
+ go: () => {
8292
+ },
8293
+ back: () => {
8294
+ },
8295
+ forward: () => {
8296
+ }
8297
+ },
8298
+ // Dimensions (common for responsive checks)
8299
+ innerWidth: 1024,
8300
+ innerHeight: 768,
8301
+ outerWidth: 1024,
8302
+ outerHeight: 768,
8303
+ screenX: 0,
8304
+ screenY: 0,
8305
+ pageXOffset: 0,
8306
+ pageYOffset: 0,
8307
+ scrollX: 0,
8308
+ scrollY: 0,
8309
+ devicePixelRatio: 1,
8310
+ // Timers (use real implementations if available)
8311
+ setTimeout: globalThis.setTimeout,
8312
+ clearTimeout: globalThis.clearTimeout,
8313
+ setInterval: globalThis.setInterval,
8314
+ clearInterval: globalThis.clearInterval,
8315
+ requestAnimationFrame: (cb) => globalThis.setTimeout(cb, 16),
8316
+ cancelAnimationFrame: globalThis.clearTimeout,
8317
+ // Storage (no-op)
8318
+ localStorage: {
8319
+ getItem: () => null,
8320
+ setItem: () => {
8321
+ },
8322
+ removeItem: () => {
8323
+ },
8324
+ clear: () => {
8325
+ },
8326
+ length: 0,
8327
+ key: () => null
8328
+ },
8329
+ sessionStorage: {
8330
+ getItem: () => null,
8331
+ setItem: () => {
8332
+ },
8333
+ removeItem: () => {
8334
+ },
8335
+ clear: () => {
8336
+ },
8337
+ length: 0,
8338
+ key: () => null
8339
+ },
8340
+ // Events
8341
+ addEventListener: () => {
8342
+ },
8343
+ removeEventListener: () => {
8344
+ },
8345
+ dispatchEvent: () => true,
8346
+ // Media queries
8347
+ matchMedia: (query) => ({
8348
+ matches: false,
8349
+ media: query,
8350
+ onchange: null,
8351
+ addListener: () => {
8352
+ },
8353
+ removeListener: () => {
8354
+ },
8355
+ addEventListener: () => {
8356
+ },
8357
+ removeEventListener: () => {
8358
+ },
8359
+ dispatchEvent: () => true
8360
+ }),
8361
+ // Misc
8362
+ getComputedStyle: () => ({
8363
+ getPropertyValue: () => ""
8364
+ }),
8365
+ getSelection: () => null,
8366
+ print: () => {
8367
+ },
8368
+ alert: () => {
8369
+ },
8370
+ confirm: () => false,
8371
+ prompt: () => null,
8372
+ open: () => null,
8373
+ close: () => {
8374
+ },
8375
+ focus: () => {
8376
+ },
8377
+ blur: () => {
8378
+ },
8379
+ scroll: () => {
8380
+ },
8381
+ scrollTo: () => {
8382
+ },
8383
+ scrollBy: () => {
8384
+ },
8385
+ resizeTo: () => {
8386
+ },
8387
+ resizeBy: () => {
8388
+ },
8389
+ moveTo: () => {
8390
+ },
8391
+ moveBy: () => {
8392
+ },
8393
+ // Crypto (basic stub)
8394
+ crypto: globalThis.crypto,
8395
+ // Performance
8396
+ performance: globalThis.performance,
8397
+ // fetch is available in Deno
8398
+ fetch: globalThis.fetch,
8399
+ // URL/URLSearchParams are available in Deno
8400
+ URL: globalThis.URL,
8401
+ URLSearchParams: globalThis.URLSearchParams,
8402
+ // TextEncoder/Decoder are available in Deno
8403
+ TextEncoder: globalThis.TextEncoder,
8404
+ TextDecoder: globalThis.TextDecoder
8405
+ });
8406
+ function createElementClass(name) {
8407
+ const ElementClass = class {
8408
+ };
8409
+ Object.defineProperty(ElementClass, "name", { value: name });
8410
+ return ElementClass;
8411
+ }
8412
+ function setupSSRGlobals() {
8413
+ if (ssrGlobalsInitialized)
8414
+ return;
8415
+ if (typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined") {
8416
+ return;
8417
+ }
8418
+ const windowStub = createWindowStub();
8419
+ globalThis.window = windowStub;
8420
+ globalThis.document = windowStub.document;
8421
+ globalThis.navigator = windowStub.navigator;
8422
+ globalThis.location = windowStub.location;
8423
+ globalThis.history = windowStub.history;
8424
+ globalThis.localStorage = windowStub.localStorage;
8425
+ globalThis.sessionStorage = windowStub.sessionStorage;
8426
+ globalThis.matchMedia = windowStub.matchMedia;
8427
+ globalThis.getComputedStyle = windowStub.getComputedStyle;
8428
+ globalThis.requestAnimationFrame = windowStub.requestAnimationFrame;
8429
+ globalThis.cancelAnimationFrame = windowStub.cancelAnimationFrame;
8430
+ globalThis.self = windowStub;
8431
+ if (typeof globalThis.Element === "undefined") {
8432
+ globalThis.Element = createElementClass("Element");
8433
+ }
8434
+ if (typeof globalThis.HTMLElement === "undefined") {
8435
+ globalThis.HTMLElement = createElementClass("HTMLElement");
8436
+ }
8437
+ if (typeof globalThis.SVGElement === "undefined") {
8438
+ globalThis.SVGElement = createElementClass("SVGElement");
8439
+ }
8440
+ if (typeof globalThis.Node === "undefined") {
8441
+ globalThis.Node = createElementClass("Node");
8442
+ }
8443
+ if (typeof globalThis.Text === "undefined") {
8444
+ globalThis.Text = createElementClass("Text");
8445
+ }
8446
+ if (typeof globalThis.Comment === "undefined") {
8447
+ globalThis.Comment = createElementClass("Comment");
8448
+ }
8449
+ if (typeof globalThis.DocumentFragment === "undefined") {
8450
+ globalThis.DocumentFragment = createElementClass(
8451
+ "DocumentFragment"
8452
+ );
8453
+ }
8454
+ ssrGlobalsInitialized = true;
8455
+ }
8456
+ var originalFetch = globalThis.fetch;
8457
+
8458
+ // src/build/transforms/mdx/esm-module-loader.ts
8459
+ var IS_TRUE_NODE = isNode && !isDeno;
8460
+ var FRAMEWORK_ROOT = new URL("../../../..", import.meta.url).pathname;
8461
+ var LOG_PREFIX_MDX_LOADER = "[mdx-loader]";
8462
+ var LOG_PREFIX_MDX_RENDERER = "[mdx-renderer]";
8463
+ var JSX_IMPORT_PATTERN = /import\s+([^'"]+)\s+from\s+['"]file:\/\/([^'"]+\.(jsx|tsx))['"];?/g;
8464
+ var REACT_IMPORT_PATTERN = /import\s+.*React.*\s+from\s+['"]react['"]/;
8465
+ var ESBUILD_JSX_FACTORY = "React.createElement";
8466
+ var ESBUILD_JSX_FRAGMENT = "React.Fragment";
8467
+ var _resolvedPaths = {};
8468
+ var _localFs = null;
8469
+ function getLocalFs() {
8470
+ if (!_localFs) {
8471
+ _localFs = createFileSystem();
8472
+ }
8473
+ return _localFs;
8474
+ }
8475
+ var _modulePathCache = null;
8476
+ var _modulePathCacheLoaded = false;
8477
+ async function getModulePathCache(cacheDir) {
8478
+ if (_modulePathCache && _modulePathCacheLoaded) {
8479
+ return _modulePathCache;
8480
+ }
8481
+ _modulePathCache = /* @__PURE__ */ new Map();
8482
+ const indexPath = join6(cacheDir, "_index.json");
8483
+ try {
8484
+ const content = await getLocalFs().readTextFile(indexPath);
8485
+ const index = JSON.parse(content);
8486
+ for (const [path, cachePath] of Object.entries(index)) {
8487
+ _modulePathCache.set(path, cachePath);
8488
+ }
8489
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Loaded module index: ${_modulePathCache.size} entries`);
8490
+ } catch {
8491
+ }
8492
+ _modulePathCacheLoaded = true;
8493
+ return _modulePathCache;
8494
+ }
8495
+ async function saveModulePathCache(cacheDir) {
8496
+ if (!_modulePathCache)
8497
+ return;
8498
+ const indexPath = join6(cacheDir, "_index.json");
8499
+ const index = {};
8500
+ for (const [path, cachePath] of _modulePathCache.entries()) {
8501
+ index[path] = cachePath;
8502
+ }
8503
+ try {
8504
+ await getLocalFs().writeTextFile(indexPath, JSON.stringify(index));
8505
+ } catch (error) {
8506
+ rendererLogger.warn(`${LOG_PREFIX_MDX_LOADER} Failed to save module index`, error);
8507
+ }
8508
+ }
8509
+ async function resolveNodePackage(packageSpec) {
8510
+ if (!IS_TRUE_NODE)
8511
+ return null;
8512
+ if (packageSpec in _resolvedPaths)
8513
+ return _resolvedPaths[packageSpec];
8514
+ try {
8515
+ const { createRequire } = await import("node:module");
8516
+ const require2 = createRequire(import.meta.url);
8517
+ const resolved = require2.resolve(packageSpec);
8518
+ _resolvedPaths[packageSpec] = resolved;
8519
+ return resolved;
5315
8520
  } catch {
5316
8521
  _resolvedPaths[packageSpec] = null;
5317
8522
  return null;
@@ -5360,98 +8565,537 @@ function hashString(input) {
5360
8565
  }
5361
8566
  return (hash >>> 0).toString(16);
5362
8567
  }
5363
- function createHTTPPluginForMDX() {
5364
- return {
5365
- name: "vf-mdx-http-fetch",
5366
- setup(build) {
5367
- build.onResolve({ filter: /^(http|https):\/\// }, (args) => ({
5368
- path: args.path,
5369
- namespace: "http-url"
5370
- }));
5371
- build.onResolve({ filter: /.*/, namespace: "http-url" }, (args) => {
5372
- if (args.path.startsWith("http://") || args.path.startsWith("https://")) {
5373
- return { path: args.path, namespace: "http-url" };
5374
- }
5375
- try {
5376
- const resolved = new URL(args.path, args.importer).toString();
5377
- return { path: resolved, namespace: "http-url" };
5378
- } catch {
5379
- return void 0;
5380
- }
5381
- });
5382
- build.onLoad({ filter: /.*/, namespace: "http-url" }, async (args) => {
5383
- let requestUrl = args.path;
5384
- try {
5385
- const u = new URL(args.path);
5386
- if (u.hostname === "esm.sh") {
5387
- if (u.pathname.includes("/denonext/")) {
5388
- u.pathname = u.pathname.replace("/denonext/", "/");
5389
- }
5390
- u.searchParams.set("target", "es2020");
5391
- u.searchParams.set("bundle", "true");
5392
- requestUrl = u.toString();
5393
- }
5394
- } catch {
5395
- }
5396
- const controller = new AbortController();
5397
- const timeout = setTimeout(() => controller.abort(), HTTP_MODULE_FETCH_TIMEOUT_MS2);
5398
- try {
5399
- const res = await fetch(requestUrl, {
5400
- headers: { "user-agent": "Mozilla/5.0 Veryfront/1.0" },
5401
- signal: controller.signal
5402
- });
5403
- clearTimeout(timeout);
5404
- if (!res.ok) {
5405
- return {
5406
- errors: [{ text: `Failed to fetch ${args.path}: ${res.status}` }]
5407
- };
5408
- }
5409
- const text = await res.text();
5410
- return { contents: text, loader: "js" };
5411
- } catch (e) {
5412
- clearTimeout(timeout);
5413
- return {
5414
- errors: [{
5415
- text: `Failed to fetch ${args.path}: ${e instanceof Error ? e.message : String(e)}`
5416
- }]
5417
- };
5418
- }
5419
- });
5420
- }
5421
- };
5422
- }
5423
8568
  async function loadModuleESM(compiledProgramCode, context) {
8569
+ const loadStart = performance.now();
5424
8570
  try {
5425
- const { getAdapter: getAdapter2 } = await Promise.resolve().then(() => (init_detect(), detect_exports));
5426
- const adapter = await getAdapter2();
8571
+ const adapter = context.adapter ?? await (async () => {
8572
+ const { getAdapter: getAdapter2 } = await Promise.resolve().then(() => (init_detect(), detect_exports));
8573
+ return getAdapter2();
8574
+ })();
5427
8575
  if (!context.esmCacheDir) {
5428
- if (IS_TRUE_NODE) {
5429
- const projectCacheDir = join4(
5430
- cwd(),
5431
- "node_modules",
5432
- ".cache",
5433
- "veryfront-mdx"
5434
- );
5435
- await adapter.fs.mkdir(projectCacheDir, { recursive: true });
5436
- context.esmCacheDir = projectCacheDir;
5437
- } else {
5438
- context.esmCacheDir = await adapter.fs.makeTempDir("veryfront-mdx-esm-");
8576
+ const persistentCacheDir = join6(cwd(), ".cache", "veryfront-mdx-esm");
8577
+ const localFs2 = getLocalFs();
8578
+ try {
8579
+ await localFs2.mkdir(persistentCacheDir, { recursive: true });
8580
+ context.esmCacheDir = persistentCacheDir;
8581
+ rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Using persistent cache dir: ${persistentCacheDir}`);
8582
+ } catch {
8583
+ if (IS_TRUE_NODE) {
8584
+ const projectCacheDir = join6(cwd(), "node_modules", ".cache", "veryfront-mdx");
8585
+ await localFs2.mkdir(projectCacheDir, { recursive: true });
8586
+ context.esmCacheDir = projectCacheDir;
8587
+ } else {
8588
+ context.esmCacheDir = await localFs2.makeTempDir({ prefix: "veryfront-mdx-esm-" });
8589
+ }
5439
8590
  }
5440
8591
  }
5441
- let rewritten;
8592
+ let rewritten = compiledProgramCode.replace(
8593
+ /from\s+["']@\/([^"']+)["']/g,
8594
+ (_match, path) => {
8595
+ const jsPath = path.endsWith(".js") ? path : `${path}.js`;
8596
+ return `from "/_vf_modules/${jsPath}"`;
8597
+ }
8598
+ );
5442
8599
  if (IS_TRUE_NODE) {
5443
- rewritten = await transformReactImportsToAbsolute(compiledProgramCode);
8600
+ rewritten = await transformReactImportsToAbsolute(rewritten);
5444
8601
  } else {
5445
8602
  rewritten = transformImportsWithMap(
5446
- compiledProgramCode,
8603
+ rewritten,
5447
8604
  getDefaultImportMap(),
5448
8605
  void 0,
5449
8606
  { resolveBare: true }
5450
8607
  );
5451
8608
  }
8609
+ const vfModulePattern = /from\s+["'](\/?)(_vf_modules\/[^"']+)["']/g;
8610
+ const vfModuleImports = [];
8611
+ let vfMatch;
8612
+ while ((vfMatch = vfModulePattern.exec(rewritten)) !== null) {
8613
+ const [original, , path] = vfMatch;
8614
+ if (path) {
8615
+ vfModuleImports.push({ original, path });
8616
+ }
8617
+ }
8618
+ const projectDir = cwd();
8619
+ const projectId = "default";
8620
+ const inFlight = /* @__PURE__ */ new Map();
8621
+ async function fetchAndCacheModule(modulePath, parentModulePath) {
8622
+ let normalizedPath = modulePath.replace(/^\//, "");
8623
+ if (parentModulePath && (modulePath.startsWith("./") || modulePath.startsWith("../"))) {
8624
+ const parentDir = parentModulePath.replace(/\/[^/]+$/, "");
8625
+ const joinedPath = posix.join(parentDir, modulePath);
8626
+ normalizedPath = posix.normalize(joinedPath);
8627
+ if (!normalizedPath.startsWith("_vf_modules/")) {
8628
+ normalizedPath = `_vf_modules/${normalizedPath}`;
8629
+ }
8630
+ }
8631
+ const existingFetch = inFlight.get(normalizedPath);
8632
+ if (existingFetch) {
8633
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Waiting for in-flight fetch: ${normalizedPath}`);
8634
+ return existingFetch;
8635
+ }
8636
+ let resolveDeferred;
8637
+ const fetchPromise = new Promise((resolve) => {
8638
+ resolveDeferred = resolve;
8639
+ });
8640
+ inFlight.set(normalizedPath, fetchPromise);
8641
+ const result2 = await (async () => {
8642
+ const pathCache = await getModulePathCache(context.esmCacheDir);
8643
+ const cachedPath = pathCache.get(normalizedPath);
8644
+ if (cachedPath) {
8645
+ try {
8646
+ const localFs2 = getLocalFs();
8647
+ const stat = await localFs2.stat(cachedPath);
8648
+ if (stat?.isFile) {
8649
+ return cachedPath;
8650
+ }
8651
+ } catch {
8652
+ pathCache.delete(normalizedPath);
8653
+ }
8654
+ }
8655
+ try {
8656
+ const filePathWithoutJs = normalizedPath.replace(/^_vf_modules\//, "").replace(/\.js$/, "");
8657
+ const extensions = [".tsx", ".ts", ".jsx", ".js", ".mdx"];
8658
+ const prefixes = ["", "src/"];
8659
+ const prefixesToStrip = ["components/", "pages/", "lib/", "app/"];
8660
+ let sourceCode = null;
8661
+ let actualFilePath = null;
8662
+ const hasKnownExt = extensions.some((ext) => filePathWithoutJs.endsWith(ext));
8663
+ if (hasKnownExt) {
8664
+ for (const prefix of prefixes) {
8665
+ const tryPath = prefix + filePathWithoutJs;
8666
+ try {
8667
+ const content = await adapter.fs.readFile(tryPath);
8668
+ sourceCode = typeof content === "string" ? content : new TextDecoder().decode(content);
8669
+ actualFilePath = tryPath;
8670
+ break;
8671
+ } catch {
8672
+ }
8673
+ }
8674
+ }
8675
+ if (!sourceCode) {
8676
+ const filePathWithoutExt = hasKnownExt ? filePathWithoutJs.replace(/\.(tsx|ts|jsx|js|mdx)$/, "") : filePathWithoutJs;
8677
+ const triedPaths = [];
8678
+ outer:
8679
+ for (const prefix of prefixes) {
8680
+ for (const ext of extensions) {
8681
+ const tryPath = prefix + filePathWithoutExt + ext;
8682
+ triedPaths.push(tryPath);
8683
+ try {
8684
+ const content = await adapter.fs.readFile(tryPath);
8685
+ sourceCode = typeof content === "string" ? content : new TextDecoder().decode(content);
8686
+ actualFilePath = tryPath;
8687
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Found file with extension`, {
8688
+ normalizedPath,
8689
+ tryPath
8690
+ });
8691
+ break outer;
8692
+ } catch {
8693
+ }
8694
+ }
8695
+ }
8696
+ if (!sourceCode) {
8697
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Extension resolution failed`, {
8698
+ normalizedPath,
8699
+ filePathWithoutExt,
8700
+ triedPaths
8701
+ });
8702
+ }
8703
+ }
8704
+ if (!sourceCode) {
8705
+ const filePathWithoutExt = hasKnownExt ? filePathWithoutJs.replace(/\.(tsx|ts|jsx|js|mdx)$/, "") : filePathWithoutJs;
8706
+ stripLoop:
8707
+ for (const stripPrefix of prefixesToStrip) {
8708
+ if (filePathWithoutExt.startsWith(stripPrefix)) {
8709
+ const strippedPath = filePathWithoutExt.slice(stripPrefix.length);
8710
+ for (const ext of extensions) {
8711
+ const tryPath = strippedPath + ext;
8712
+ try {
8713
+ const content = await adapter.fs.readFile(tryPath);
8714
+ sourceCode = typeof content === "string" ? content : new TextDecoder().decode(content);
8715
+ actualFilePath = tryPath;
8716
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Found file after stripping prefix`, {
8717
+ originalPath: filePathWithoutJs,
8718
+ strippedPath: tryPath
8719
+ });
8720
+ break stripLoop;
8721
+ } catch {
8722
+ }
8723
+ }
8724
+ }
8725
+ }
8726
+ }
8727
+ if (!sourceCode) {
8728
+ const basePath = hasKnownExt ? filePathWithoutJs.replace(/\.(tsx|ts|jsx|js|mdx)$/, "") : filePathWithoutJs;
8729
+ outer:
8730
+ for (const prefix of prefixes) {
8731
+ for (const ext of extensions) {
8732
+ const tryPath = `${prefix}${basePath}/index${ext}`;
8733
+ try {
8734
+ const content = await adapter.fs.readFile(tryPath);
8735
+ sourceCode = typeof content === "string" ? content : new TextDecoder().decode(content);
8736
+ actualFilePath = tryPath;
8737
+ break outer;
8738
+ } catch {
8739
+ }
8740
+ }
8741
+ }
8742
+ }
8743
+ if (!sourceCode && filePathWithoutJs.startsWith("lib/")) {
8744
+ const localFs3 = getLocalFs();
8745
+ for (const ext of extensions) {
8746
+ const frameworkPath = join6(FRAMEWORK_ROOT, filePathWithoutJs + ext);
8747
+ try {
8748
+ const stat = await localFs3.stat(frameworkPath);
8749
+ if (stat?.isFile) {
8750
+ const content = await localFs3.readTextFile(frameworkPath);
8751
+ sourceCode = content;
8752
+ actualFilePath = frameworkPath;
8753
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Found framework lib file (fallback)`, {
8754
+ basePath: filePathWithoutJs,
8755
+ resolvedPath: frameworkPath
8756
+ });
8757
+ break;
8758
+ }
8759
+ } catch {
8760
+ }
8761
+ }
8762
+ }
8763
+ if (!sourceCode || !actualFilePath) {
8764
+ const isProxyMode = adapter.env.get("PROXY_MODE") === "1";
8765
+ if (isProxyMode) {
8766
+ rendererLogger.warn(
8767
+ `${LOG_PREFIX_MDX_LOADER} Direct read failed in proxy mode (module must be pre-loaded): ${filePathWithoutJs}`
8768
+ );
8769
+ return null;
8770
+ }
8771
+ rendererLogger.debug(
8772
+ `${LOG_PREFIX_MDX_LOADER} Direct read failed, falling back to HTTP: ${filePathWithoutJs}`
8773
+ );
8774
+ const port = adapter.env.get("VERYFRONT_DEV_PORT") || adapter.env.get("PORT") || "3001";
8775
+ const moduleUrl = `http://localhost:${port}/${normalizedPath}?ssr=true`;
8776
+ const response = await fetch(moduleUrl);
8777
+ if (!response.ok) {
8778
+ rendererLogger.warn(
8779
+ `${LOG_PREFIX_MDX_LOADER} HTTP fetch also failed: ${moduleUrl} (${response.status})`
8780
+ );
8781
+ return null;
8782
+ }
8783
+ let moduleCode2 = await response.text();
8784
+ const vfModuleImportPattern2 = /from\s+["'](\/?_vf_modules\/[^"'?]+)(?:\?[^"']*)?["']/g;
8785
+ const nestedImports2 = [];
8786
+ let match2;
8787
+ while ((match2 = vfModuleImportPattern2.exec(moduleCode2)) !== null) {
8788
+ if (match2[1]) {
8789
+ nestedImports2.push({ original: match2[0], path: match2[1].replace(/^\//, "") });
8790
+ }
8791
+ }
8792
+ const relativeImportPattern2 = /from\s+["'](\.\.?\/[^"'?]+)(?:\?[^"']*)?["']/g;
8793
+ const relativeImports2 = [];
8794
+ let relMatch2;
8795
+ while ((relMatch2 = relativeImportPattern2.exec(moduleCode2)) !== null) {
8796
+ if (relMatch2[1]) {
8797
+ relativeImports2.push({ original: relMatch2[0], path: relMatch2[1] });
8798
+ }
8799
+ }
8800
+ const nestedResults2 = await Promise.all(
8801
+ nestedImports2.map(async ({ original, path: nestedPath }) => {
8802
+ const nestedFilePath = await fetchAndCacheModule(nestedPath, normalizedPath);
8803
+ return { original, nestedFilePath };
8804
+ })
8805
+ );
8806
+ for (const { original, nestedFilePath } of nestedResults2) {
8807
+ if (nestedFilePath) {
8808
+ moduleCode2 = moduleCode2.replace(original, `from "file://${nestedFilePath}"`);
8809
+ }
8810
+ }
8811
+ const relativeResults2 = await Promise.all(
8812
+ relativeImports2.map(async ({ original, path: relativePath }) => {
8813
+ const nestedFilePath = await fetchAndCacheModule(relativePath, normalizedPath);
8814
+ return { original, nestedFilePath };
8815
+ })
8816
+ );
8817
+ for (const { original, nestedFilePath } of relativeResults2) {
8818
+ if (nestedFilePath) {
8819
+ moduleCode2 = moduleCode2.replace(original, `from "file://${nestedFilePath}"`);
8820
+ }
8821
+ }
8822
+ const unresolvedPattern3 = /from\s+["'](\/?_vf_modules\/[^"']+)["']/g;
8823
+ const unresolvedMatches3 = [...moduleCode2.matchAll(unresolvedPattern3)];
8824
+ if (unresolvedMatches3.length > 0) {
8825
+ const unresolvedPaths = unresolvedMatches3.map((m) => m[1]).slice(0, 3);
8826
+ rendererLogger.warn(
8827
+ `${LOG_PREFIX_MDX_LOADER} Module has ${unresolvedMatches3.length} unresolved imports, skipping cache`,
8828
+ { path: normalizedPath, unresolved: unresolvedPaths }
8829
+ );
8830
+ return null;
8831
+ }
8832
+ const contentHash2 = hashString(normalizedPath + moduleCode2);
8833
+ const cachePath2 = join6(context.esmCacheDir, `vfmod-${contentHash2}.mjs`);
8834
+ const localFs3 = getLocalFs();
8835
+ try {
8836
+ const stat = await localFs3.stat(cachePath2);
8837
+ if (stat?.isFile) {
8838
+ pathCache.set(normalizedPath, cachePath2);
8839
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Content cache hit: ${normalizedPath}`);
8840
+ return cachePath2;
8841
+ }
8842
+ } catch {
8843
+ }
8844
+ await localFs3.mkdir(context.esmCacheDir, { recursive: true });
8845
+ await localFs3.writeTextFile(cachePath2, moduleCode2);
8846
+ pathCache.set(normalizedPath, cachePath2);
8847
+ await saveModulePathCache(context.esmCacheDir);
8848
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Cached: ${normalizedPath} -> ${cachePath2}`);
8849
+ return cachePath2;
8850
+ }
8851
+ let moduleCode;
8852
+ try {
8853
+ moduleCode = await transformToESM(
8854
+ sourceCode,
8855
+ actualFilePath,
8856
+ projectDir,
8857
+ adapter,
8858
+ { projectId, dev: true, ssr: true }
8859
+ );
8860
+ } catch (transformError) {
8861
+ rendererLogger.error(`${LOG_PREFIX_MDX_LOADER} Transform failed for module`, {
8862
+ normalizedPath,
8863
+ actualFilePath,
8864
+ sourceLength: sourceCode.length,
8865
+ sourcePreview: sourceCode.slice(0, 200),
8866
+ error: transformError instanceof Error ? transformError.message : String(transformError)
8867
+ });
8868
+ throw transformError;
8869
+ }
8870
+ const vfModuleImportPattern = /from\s+["'](\/?_vf_modules\/[^"'?]+)(?:\?[^"']*)?["']/g;
8871
+ const nestedImports = [];
8872
+ let match;
8873
+ while ((match = vfModuleImportPattern.exec(moduleCode)) !== null) {
8874
+ if (match[1]) {
8875
+ nestedImports.push({ original: match[0], path: match[1].replace(/^\//, "") });
8876
+ }
8877
+ }
8878
+ const relativeImportPattern = /from\s+["'](\.\.?\/[^"'?]+)(?:\?[^"']*)?["']/g;
8879
+ const relativeImports = [];
8880
+ let relMatch;
8881
+ while ((relMatch = relativeImportPattern.exec(moduleCode)) !== null) {
8882
+ if (relMatch[1]) {
8883
+ relativeImports.push({ original: relMatch[0], path: relMatch[1] });
8884
+ }
8885
+ }
8886
+ const nestedResults = await Promise.all(
8887
+ nestedImports.map(async ({ original, path: nestedPath }) => {
8888
+ const nestedFilePath = await fetchAndCacheModule(nestedPath, normalizedPath);
8889
+ return { original, nestedFilePath, nestedPath };
8890
+ })
8891
+ );
8892
+ for (const { original, nestedFilePath, nestedPath } of nestedResults) {
8893
+ if (nestedFilePath) {
8894
+ moduleCode = moduleCode.replace(original, `from "file://${nestedFilePath}"`);
8895
+ } else {
8896
+ const importNamePattern = new RegExp(
8897
+ `import\\s+(?:({[^}]+})|([\\w$]+))\\s*${original.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`
8898
+ );
8899
+ const importMatch = moduleCode.match(importNamePattern);
8900
+ let namedExports = "";
8901
+ if (importMatch) {
8902
+ if (importMatch[1]) {
8903
+ const names = importMatch[1].replace(/[{}]/g, "").split(",").map((n) => n.trim().split(/\s+as\s+/)[0]?.trim()).filter((n) => !!n);
8904
+ namedExports = names.map(
8905
+ (n) => `export const ${n} = () => { console.warn('[Veryfront] Missing export "${n}" from "${nestedPath}"'); return null; };`
8906
+ ).join("\n");
8907
+ }
8908
+ }
8909
+ const stubCode = `
8910
+ // Stub module for missing file: ${nestedPath}
8911
+ // This file was not found in the project's published release.
8912
+ const handler = {
8913
+ get(_, prop) {
8914
+ if (prop === 'default' || prop === '__esModule' || typeof prop === 'symbol') {
8915
+ return new Proxy({}, handler);
8916
+ }
8917
+ console.warn('[Veryfront] Missing module: ${nestedPath}. Component "' + prop + '" was not found.');
8918
+ return () => null;
8919
+ },
8920
+ apply() { return null; }
8921
+ };
8922
+ export default new Proxy(function(){}, handler);
8923
+ ${namedExports}
8924
+ `;
8925
+ const stubHash = hashString(`stub:${nestedPath}:${namedExports}`);
8926
+ const stubPath = join6(context.esmCacheDir, `stub-${stubHash}.mjs`);
8927
+ try {
8928
+ await getLocalFs().writeTextFile(stubPath, stubCode);
8929
+ moduleCode = moduleCode.replace(original, `from "file://${stubPath}"`);
8930
+ rendererLogger.warn(
8931
+ `${LOG_PREFIX_MDX_LOADER} Created stub for missing module: ${nestedPath}`
8932
+ );
8933
+ } catch (e) {
8934
+ rendererLogger.error(
8935
+ `${LOG_PREFIX_MDX_LOADER} Failed to create stub for: ${nestedPath}`,
8936
+ e
8937
+ );
8938
+ }
8939
+ }
8940
+ }
8941
+ const relativeResults = await Promise.all(
8942
+ relativeImports.map(async ({ original, path: relativePath }) => {
8943
+ const nestedFilePath = await fetchAndCacheModule(relativePath, normalizedPath);
8944
+ return { original, nestedFilePath, relativePath };
8945
+ })
8946
+ );
8947
+ for (const { original, nestedFilePath, relativePath } of relativeResults) {
8948
+ if (nestedFilePath) {
8949
+ moduleCode = moduleCode.replace(original, `from "file://${nestedFilePath}"`);
8950
+ } else {
8951
+ const importNamePattern = new RegExp(
8952
+ `import\\s+(?:({[^}]+})|([\\w$]+))\\s*${original.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`
8953
+ );
8954
+ const importMatch = moduleCode.match(importNamePattern);
8955
+ let namedExports = "";
8956
+ if (importMatch) {
8957
+ if (importMatch[1]) {
8958
+ const names = importMatch[1].replace(/[{}]/g, "").split(",").map((n) => n.trim().split(/\s+as\s+/)[0]?.trim()).filter((n) => !!n);
8959
+ namedExports = names.map(
8960
+ (n) => `export const ${n} = () => { console.warn('[Veryfront] Missing export "${n}" from "${relativePath}"'); return null; };`
8961
+ ).join("\n");
8962
+ }
8963
+ }
8964
+ const stubCode = `
8965
+ // Stub module for missing file: ${relativePath}
8966
+ // This file was not found in the project's published release.
8967
+ const handler = {
8968
+ get(_, prop) {
8969
+ if (prop === 'default' || prop === '__esModule' || typeof prop === 'symbol') {
8970
+ return new Proxy({}, handler);
8971
+ }
8972
+ console.warn('[Veryfront] Missing module: ${relativePath}. Component "' + prop + '" was not found.');
8973
+ return () => null;
8974
+ },
8975
+ apply() { return null; }
8976
+ };
8977
+ export default new Proxy(function(){}, handler);
8978
+ ${namedExports}
8979
+ `;
8980
+ const stubHash = hashString(`stub:${relativePath}:${namedExports}`);
8981
+ const stubPath = join6(context.esmCacheDir, `stub-${stubHash}.mjs`);
8982
+ try {
8983
+ await getLocalFs().writeTextFile(stubPath, stubCode);
8984
+ moduleCode = moduleCode.replace(original, `from "file://${stubPath}"`);
8985
+ rendererLogger.warn(
8986
+ `${LOG_PREFIX_MDX_LOADER} Created stub for missing module: ${relativePath}`
8987
+ );
8988
+ } catch (e) {
8989
+ rendererLogger.error(
8990
+ `${LOG_PREFIX_MDX_LOADER} Failed to create stub for: ${relativePath}`,
8991
+ e
8992
+ );
8993
+ }
8994
+ }
8995
+ }
8996
+ const unresolvedPattern2 = /from\s+["'](\/?_vf_modules\/[^"']+)["']/g;
8997
+ const unresolvedMatches2 = [...moduleCode.matchAll(unresolvedPattern2)];
8998
+ if (unresolvedMatches2.length > 0) {
8999
+ const unresolvedPaths = unresolvedMatches2.map((m) => m[1]).slice(0, 3);
9000
+ rendererLogger.warn(
9001
+ `${LOG_PREFIX_MDX_LOADER} Module has ${unresolvedMatches2.length} unresolved imports, skipping cache`,
9002
+ { path: normalizedPath, unresolved: unresolvedPaths }
9003
+ );
9004
+ return null;
9005
+ }
9006
+ const contentHash = hashString(normalizedPath + moduleCode);
9007
+ const cachePath = join6(context.esmCacheDir, `vfmod-${contentHash}.mjs`);
9008
+ const localFs2 = getLocalFs();
9009
+ try {
9010
+ const stat = await localFs2.stat(cachePath);
9011
+ if (stat?.isFile) {
9012
+ pathCache.set(normalizedPath, cachePath);
9013
+ rendererLogger.debug(`${LOG_PREFIX_MDX_LOADER} Content cache hit: ${normalizedPath}`);
9014
+ return cachePath;
9015
+ }
9016
+ } catch {
9017
+ }
9018
+ await localFs2.mkdir(context.esmCacheDir, { recursive: true });
9019
+ await localFs2.writeTextFile(cachePath, moduleCode);
9020
+ pathCache.set(normalizedPath, cachePath);
9021
+ await saveModulePathCache(context.esmCacheDir);
9022
+ rendererLogger.debug(
9023
+ `${LOG_PREFIX_MDX_LOADER} Cached vf_module: ${normalizedPath} -> ${cachePath}`
9024
+ );
9025
+ return cachePath;
9026
+ } catch (error) {
9027
+ rendererLogger.warn(`${LOG_PREFIX_MDX_LOADER} Failed to process ${normalizedPath}`, error);
9028
+ return null;
9029
+ }
9030
+ })();
9031
+ resolveDeferred(result2);
9032
+ inFlight.delete(normalizedPath);
9033
+ return result2;
9034
+ }
9035
+ const fetchStart = performance.now();
9036
+ const vfModuleResults = await Promise.all(
9037
+ vfModuleImports.map(async ({ original, path }) => {
9038
+ const filePath2 = await fetchAndCacheModule(path);
9039
+ return { original, filePath: filePath2, path };
9040
+ })
9041
+ );
9042
+ const fetchEnd = performance.now();
9043
+ rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Module fetch phase completed`, {
9044
+ moduleCount: vfModuleImports.length,
9045
+ durationMs: (fetchEnd - fetchStart).toFixed(1)
9046
+ });
9047
+ for (const { original, filePath: filePath2, path } of vfModuleResults) {
9048
+ if (filePath2) {
9049
+ rewritten = rewritten.replace(original, `from "file://${filePath2}"`);
9050
+ } else {
9051
+ const importNamePattern = new RegExp(
9052
+ `import\\s+(?:({[^}]+})|([\\w$]+))\\s*${original.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`
9053
+ );
9054
+ const importMatch = rewritten.match(importNamePattern);
9055
+ let namedExports = "";
9056
+ if (importMatch) {
9057
+ if (importMatch[1]) {
9058
+ const names = importMatch[1].replace(/[{}]/g, "").split(",").map((n) => n.trim().split(/\s+as\s+/)[0]?.trim()).filter((n) => !!n);
9059
+ namedExports = names.map(
9060
+ (n) => `export const ${n} = () => { console.warn('[Veryfront] Missing export "${n}" from "${path}"'); return null; };`
9061
+ ).join("\n");
9062
+ }
9063
+ }
9064
+ const stubCode = `
9065
+ // Stub module for missing file: ${path}
9066
+ // This file was not found in the project's published release.
9067
+ const handler = {
9068
+ get(_, prop) {
9069
+ if (prop === 'default' || prop === '__esModule' || typeof prop === 'symbol') {
9070
+ return new Proxy({}, handler);
9071
+ }
9072
+ console.warn('[Veryfront] Missing module: ${path}. Component "' + prop + '" was not found.');
9073
+ return () => null;
9074
+ },
9075
+ apply() { return null; }
9076
+ };
9077
+ export default new Proxy(function(){}, handler);
9078
+ ${namedExports}
9079
+ `;
9080
+ const stubHash = hashString(`stub:${path}:${namedExports}`);
9081
+ const stubPath = join6(context.esmCacheDir, `stub-${stubHash}.mjs`);
9082
+ try {
9083
+ await getLocalFs().writeTextFile(stubPath, stubCode);
9084
+ rewritten = rewritten.replace(original, `from "file://${stubPath}"`);
9085
+ rendererLogger.warn(
9086
+ `${LOG_PREFIX_MDX_LOADER} Created stub for missing top-level module: ${path}`
9087
+ );
9088
+ } catch (e) {
9089
+ rendererLogger.error(
9090
+ `${LOG_PREFIX_MDX_LOADER} Failed to create stub for: ${path}`,
9091
+ e
9092
+ );
9093
+ }
9094
+ }
9095
+ }
5452
9096
  let jsxMatch;
5453
9097
  const jsxTransforms = [];
5454
- const { transform } = await import("esbuild/mod.js");
9098
+ const { transform: transform2 } = await import("esbuild/mod.js");
5455
9099
  while ((jsxMatch = JSX_IMPORT_PATTERN.exec(rewritten)) !== null) {
5456
9100
  const [fullMatch, importClause, filePath2, ext] = jsxMatch;
5457
9101
  if (!filePath2) {
@@ -5462,7 +9106,7 @@ async function loadModuleESM(compiledProgramCode, context) {
5462
9106
  }
5463
9107
  try {
5464
9108
  const jsxCode = await adapter.fs.readFile(filePath2);
5465
- const result2 = await transform(jsxCode, {
9109
+ const result2 = await transform2(jsxCode, {
5466
9110
  loader: ext === "tsx" ? "tsx" : "jsx",
5467
9111
  jsx: "transform",
5468
9112
  jsxFactory: ESBUILD_JSX_FACTORY,
@@ -5475,8 +9119,8 @@ async function loadModuleESM(compiledProgramCode, context) {
5475
9119
  ${transformed}`;
5476
9120
  }
5477
9121
  const transformedFileName = `jsx-${hashString(filePath2)}.mjs`;
5478
- const transformedPath = join4(context.esmCacheDir, transformedFileName);
5479
- await adapter.fs.writeFile(transformedPath, transformed);
9122
+ const transformedPath = join6(context.esmCacheDir, transformedFileName);
9123
+ await getLocalFs().writeTextFile(transformedPath, transformed);
5480
9124
  jsxTransforms.push({
5481
9125
  original: fullMatch,
5482
9126
  transformed: `import ${importClause} from "file://${transformedPath}";`
@@ -5494,12 +9138,18 @@ ${transformed}`;
5494
9138
  if (/\bconst\s+MDXLayout\b/.test(rewritten) && !/export\s+\{[^}]*MDXLayout/.test(rewritten)) {
5495
9139
  rewritten += "\nexport { MDXLayout as __vfLayout };\n";
5496
9140
  }
5497
- if (IS_TRUE_NODE && HTTP_IMPORT_PATTERN.test(rewritten)) {
5498
- rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Bundling HTTP imports via esbuild for Node.js`);
9141
+ const codeHasHttpImports = hasHttpImports(rewritten);
9142
+ rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} HTTP imports check`, {
9143
+ hasHttpImports: codeHasHttpImports,
9144
+ codePreview: rewritten.substring(0, 500)
9145
+ });
9146
+ if (codeHasHttpImports) {
9147
+ rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Bundling HTTP imports via esbuild`);
5499
9148
  const { build } = await import("esbuild/mod.js");
5500
- const tempSourcePath = join4(context.esmCacheDir, `temp-${hashString(rewritten)}.mjs`);
5501
- await adapter.fs.writeFile(tempSourcePath, rewritten);
9149
+ const tempSourcePath = join6(context.esmCacheDir, `temp-${hashString(rewritten)}.mjs`);
9150
+ await getLocalFs().writeTextFile(tempSourcePath, rewritten);
5502
9151
  try {
9152
+ const reactAliases = getReactAliases();
5503
9153
  const result2 = await build({
5504
9154
  entryPoints: [tempSourcePath],
5505
9155
  bundle: true,
@@ -5507,9 +9157,15 @@ ${transformed}`;
5507
9157
  platform: "neutral",
5508
9158
  target: "es2020",
5509
9159
  write: false,
5510
- plugins: [createHTTPPluginForMDX()],
5511
- // Mark npm packages as external so they're not bundled
5512
- external: ["react", "react-dom", "react/jsx-runtime", "react/jsx-dev-runtime"]
9160
+ plugins: [createHTTPPlugin()],
9161
+ // Use aliases to normalize all React imports to esm.sh URLs
9162
+ alias: reactAliases,
9163
+ // Mark external: React URLs, file:// URLs (local modules), veryfront/* (framework)
9164
+ external: [
9165
+ ...Object.values(reactAliases),
9166
+ "file://*",
9167
+ "veryfront/*"
9168
+ ]
5513
9169
  });
5514
9170
  const bundledCode = result2.outputFiles?.[0]?.text;
5515
9171
  if (bundledCode) {
@@ -5517,8 +9173,8 @@ ${transformed}`;
5517
9173
  rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} Successfully bundled HTTP imports`);
5518
9174
  }
5519
9175
  } catch (bundleError) {
5520
- rendererLogger.warn(
5521
- `${LOG_PREFIX_MDX_LOADER} Failed to bundle HTTP imports, falling back to original code`,
9176
+ rendererLogger.error(
9177
+ `${LOG_PREFIX_MDX_LOADER} Failed to bundle HTTP imports`,
5522
9178
  bundleError
5523
9179
  );
5524
9180
  } finally {
@@ -5533,35 +9189,46 @@ ${transformed}`;
5533
9189
  }
5534
9190
  }
5535
9191
  }
9192
+ rewritten = stripDenoShim(rewritten);
5536
9193
  const codeHash = hashString(rewritten);
5537
9194
  const namespace = getCacheNamespace() || "default";
5538
9195
  const compositeKey = `${namespace}:${codeHash}`;
5539
9196
  const cached = context.moduleCache.get(compositeKey);
5540
9197
  if (cached)
5541
9198
  return cached;
5542
- const nsDir = join4(context.esmCacheDir, namespace);
9199
+ const unresolvedPattern = /from\s+["'](\/?_vf_modules\/[^"']+)["']/g;
9200
+ const unresolvedMatches = [...rewritten.matchAll(unresolvedPattern)];
9201
+ if (unresolvedMatches.length > 0) {
9202
+ const unresolvedPaths = unresolvedMatches.map((m) => m[1]).slice(0, 5);
9203
+ const errorMsg = `MDX has ${unresolvedMatches.length} unresolved module imports: ${unresolvedPaths.join(", ")}`;
9204
+ rendererLogger.error(`${LOG_PREFIX_MDX_RENDERER} ${errorMsg}`);
9205
+ throw new Error(errorMsg);
9206
+ }
9207
+ const nsDir = join6(context.esmCacheDir, namespace);
9208
+ const localFs = getLocalFs();
5543
9209
  try {
5544
- await adapter.fs.mkdir(nsDir, { recursive: true });
9210
+ await localFs.mkdir(nsDir, { recursive: true });
5545
9211
  } catch (e) {
5546
9212
  rendererLogger.debug(
5547
9213
  `${LOG_PREFIX_MDX_RENDERER} mkdir nsDir failed`,
5548
9214
  e instanceof Error ? e : String(e)
5549
9215
  );
5550
9216
  }
5551
- const filePath = join4(nsDir, `${codeHash}.mjs`);
9217
+ const filePath = join6(nsDir, `${codeHash}.mjs`);
5552
9218
  try {
5553
- const stat = await adapter.fs.stat(filePath);
9219
+ const stat = await localFs.stat(filePath);
5554
9220
  if (!stat?.isFile) {
5555
- await adapter.fs.writeFile(filePath, rewritten);
9221
+ await localFs.writeTextFile(filePath, rewritten);
5556
9222
  }
5557
9223
  } catch (error) {
5558
9224
  rendererLogger.debug(`${LOG_PREFIX_MDX_RENDERER} Writing temporary MDX module file:`, error);
5559
- await adapter.fs.writeFile(filePath, rewritten);
9225
+ await localFs.writeTextFile(filePath, rewritten);
5560
9226
  }
5561
9227
  rendererLogger.info(`${LOG_PREFIX_MDX_RENDERER} Loading MDX module`, {
5562
9228
  filePath,
5563
9229
  codePreview: rewritten.substring(0, 300)
5564
9230
  });
9231
+ setupSSRGlobals();
5565
9232
  const mod = await import(`file://${filePath}?v=${codeHash}`);
5566
9233
  const result = {
5567
9234
  ...mod,
@@ -5576,6 +9243,10 @@ ${transformed}`;
5576
9243
  MainLayout: mod?.MainLayout
5577
9244
  };
5578
9245
  context.moduleCache.set(compositeKey, result);
9246
+ const loadEnd = performance.now();
9247
+ rendererLogger.info(`${LOG_PREFIX_MDX_LOADER} loadModuleESM completed`, {
9248
+ durationMs: (loadEnd - loadStart).toFixed(1)
9249
+ });
5579
9250
  return result;
5580
9251
  } catch (error) {
5581
9252
  rendererLogger.error(`${LOG_PREFIX_MDX_RENDERER} MDX ESM load failed:`, error);
@@ -5634,7 +9305,7 @@ function parseJsonish(value) {
5634
9305
  }
5635
9306
 
5636
9307
  // src/build/transforms/mdx/module-loader/metadata-extractor.ts
5637
- function extractFrontmatter(moduleCode) {
9308
+ function extractFrontmatter2(moduleCode) {
5638
9309
  try {
5639
9310
  const fmIndex = moduleCode.search(/(?:export\s+)?const\s+frontmatter\s*=\s*/);
5640
9311
  if (fmIndex < 0)
@@ -5733,7 +9404,7 @@ function parseMDXCode(compiledCode) {
5733
9404
  rendererLogger.debug("Code snippet:", cleanedCode.substring(0, 200));
5734
9405
  }
5735
9406
  const exports = {};
5736
- const frontmatter = extractFrontmatter(cleanedCode);
9407
+ const frontmatter = extractFrontmatter2(cleanedCode);
5737
9408
  if (frontmatter) {
5738
9409
  exports.frontmatter = frontmatter;
5739
9410
  }
@@ -5772,10 +9443,11 @@ var MDXRenderer = class {
5772
9443
  this.esmCacheDir = void 0;
5773
9444
  }
5774
9445
  }
5775
- async loadModuleESM(compiledProgramCode) {
9446
+ async loadModuleESM(compiledProgramCode, adapter) {
5776
9447
  const context = {
5777
9448
  esmCacheDir: this.esmCacheDir,
5778
- moduleCache: this.moduleCache
9449
+ moduleCache: this.moduleCache,
9450
+ adapter
5779
9451
  };
5780
9452
  const result = await loadModuleESM(compiledProgramCode, context);
5781
9453
  this.esmCacheDir = context.esmCacheDir;
@@ -5952,15 +9624,61 @@ function AppWrapper({
5952
9624
 
5953
9625
  // src/react/components/Head.tsx
5954
9626
  init_deno_env();
5955
- import React2 from "react";
9627
+ import React2, { useEffect, useRef as useRef3 } from "react";
9628
+ var isServer = typeof window === "undefined";
5956
9629
  function Head({ children }) {
9630
+ const mountedRef = useRef3(false);
9631
+ useEffect(() => {
9632
+ mountedRef.current = true;
9633
+ if (!children)
9634
+ return;
9635
+ const childArray = React2.Children.toArray(children);
9636
+ const addedElements = [];
9637
+ childArray.forEach((child) => {
9638
+ if (!React2.isValidElement(child))
9639
+ return;
9640
+ const { type, props } = child;
9641
+ if (typeof type !== "string")
9642
+ return;
9643
+ if (type === "body")
9644
+ return;
9645
+ if (type === "title") {
9646
+ document.title = props.children || "";
9647
+ return;
9648
+ }
9649
+ const element = document.createElement(type);
9650
+ Object.entries(props).forEach(([key, value]) => {
9651
+ if (key === "children")
9652
+ return;
9653
+ if (key === "className") {
9654
+ element.setAttribute("class", String(value));
9655
+ } else if (key === "htmlFor") {
9656
+ element.setAttribute("for", String(value));
9657
+ } else if (typeof value === "boolean") {
9658
+ if (value)
9659
+ element.setAttribute(key, "");
9660
+ } else if (value != null) {
9661
+ element.setAttribute(key, String(value));
9662
+ }
9663
+ });
9664
+ if (props.children && typeof props.children === "string") {
9665
+ element.textContent = props.children;
9666
+ }
9667
+ element.setAttribute("data-veryfront-managed", "1");
9668
+ document.head.appendChild(element);
9669
+ addedElements.push(element);
9670
+ });
9671
+ return () => {
9672
+ addedElements.forEach((el) => el.remove());
9673
+ };
9674
+ }, [children]);
5957
9675
  return React2.createElement(
5958
9676
  "div",
5959
9677
  {
5960
9678
  "data-veryfront-head": "1",
5961
9679
  style: { display: "none" }
5962
9680
  },
5963
- children
9681
+ isServer ? children : null
5964
9682
  );
5965
9683
  }
5966
9684