@vesk/vesk-cli 0.2.94 → 0.2.96

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.
Files changed (2) hide show
  1. package/dist/cli.js +851 -289
  2. package/package.json +5 -5
package/dist/cli.js CHANGED
@@ -608,6 +608,14 @@ var init_errors = __esm({
608
608
  });
609
609
 
610
610
  // ../compiler/src/ir.ts
611
+ function regionMarkerId(node) {
612
+ const ast = node.condition.ast;
613
+ if (ast && typeof ast.start === "number") return `s${ast.start}`;
614
+ const raw2 = node.condition.raw;
615
+ let hash = 5381;
616
+ for (let i = 0; i < raw2.length; i++) hash = (hash << 5) + hash + raw2.charCodeAt(i) | 0;
617
+ return `h${(hash >>> 0).toString(36)}`;
618
+ }
611
619
  var Expression, IRRoot, ComponentIR, StaticNode, TextNode, DynamicBinding, OpaqueDynamicRegion, MapRegion, ComponentRef, ComponentCall, SlotNode, PropSlot, PropSlotRender, WhileLoop, SwitchCase, SwitchBlock, TryCatch, TrackDecl, RuntimeStatement, BreakSignal, ForLoop, ServerBlock, ClientBlock, HeadBlock;
612
620
  var init_ir = __esm({
613
621
  "../compiler/src/ir.ts"() {
@@ -2143,7 +2151,7 @@ function buildRequestInit(options) {
2143
2151
  function resolveFetchUrl(url) {
2144
2152
  if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith("//")) return url;
2145
2153
  const ctx2 = g().__vesk_request;
2146
- const resolver = ctx2 && typeof ctx2.resolveUrl === "function" ? ctx2.resolveUrl : null;
2154
+ const resolver = ctx2 && typeof ctx2.resolveUrl === "function" ? ctx2.resolveUrl.bind(ctx2) : null;
2147
2155
  if (resolver) return resolver(url);
2148
2156
  const reqUrl = ctx2?.url;
2149
2157
  let base = typeof reqUrl === "string" && /^https?:\/\//i.test(reqUrl) ? reqUrl : globalThis.__vesk_ssr_base_url || "";
@@ -2434,7 +2442,17 @@ function mutate(key, data2) {
2434
2442
  }
2435
2443
  function createResourceAccessor(handle2) {
2436
2444
  const state = handle2.state;
2437
- const accessor = {};
2445
+ const read = async () => {
2446
+ for (; ; ) {
2447
+ const s = get(state);
2448
+ if (!s.loading) {
2449
+ if (s.error) throw s.error;
2450
+ return s.data;
2451
+ }
2452
+ await handle2.settled;
2453
+ }
2454
+ };
2455
+ const accessor = new ResourcePromise(read);
2438
2456
  Object.defineProperty(accessor, "loading", {
2439
2457
  get() {
2440
2458
  return get(state).loading;
@@ -2451,19 +2469,6 @@ function createResourceAccessor(handle2) {
2451
2469
  }
2452
2470
  });
2453
2471
  accessor._state = state;
2454
- const toData = async () => {
2455
- for (; ; ) {
2456
- const s = get(state);
2457
- if (!s.loading) {
2458
- if (s.error) throw s.error;
2459
- return s.data;
2460
- }
2461
- await handle2.settled;
2462
- }
2463
- };
2464
- accessor.then = (onFulfilled, onRejected) => toData().then(onFulfilled, onRejected);
2465
- accessor.catch = (onRejected) => toData().catch(onRejected);
2466
- accessor.finally = (onFinally) => toData().finally(onFinally);
2467
2472
  accessor.refresh = () => revalidate(handle2);
2468
2473
  accessor.abort = () => {
2469
2474
  if (!isServer()) handle2.controller?.abort();
@@ -2546,7 +2551,7 @@ async function resolveSsrResources() {
2546
2551
  delete g().__vsk_ssr_failures;
2547
2552
  return data2;
2548
2553
  }
2549
- var HttpError, TimeoutError, g, isServer, ssrSink, DEFAULT_FAILURE_TTL;
2554
+ var HttpError, TimeoutError, g, isServer, ssrSink, DEFAULT_FAILURE_TTL, ResourcePromise;
2550
2555
  var init_resource = __esm({
2551
2556
  "../runtime/src/resource.ts"() {
2552
2557
  "use strict";
@@ -2572,6 +2577,23 @@ var init_resource = __esm({
2572
2577
  isServer = () => !!g().__vsk_ssr;
2573
2578
  ssrSink = null;
2574
2579
  DEFAULT_FAILURE_TTL = 1e4;
2580
+ ResourcePromise = class extends Promise {
2581
+ read;
2582
+ constructor(read) {
2583
+ super(() => {
2584
+ });
2585
+ this.read = read;
2586
+ }
2587
+ then(onfulfilled, onrejected) {
2588
+ return this.read().then(onfulfilled, onrejected);
2589
+ }
2590
+ catch(onrejected) {
2591
+ return this.read().catch(onrejected);
2592
+ }
2593
+ finally(onfinally) {
2594
+ return this.read().finally(onfinally);
2595
+ }
2596
+ };
2575
2597
  useFetch.text = (url, options) => useFetch(async () => {
2576
2598
  const res = await doFetch(resolveFetchUrl(url), buildRequestInit(options ?? {}));
2577
2599
  if (!res.ok) throw new HttpError(res.status, res.statusText);
@@ -2963,6 +2985,47 @@ function adoptElementRaw(root3, marker, tag) {
2963
2985
  recordAdopted(root3, el, tag || el.tagName.toLowerCase());
2964
2986
  return el;
2965
2987
  }
2988
+ function classTokens(value) {
2989
+ const out = [];
2990
+ let token = "";
2991
+ for (let i = 0; i < value.length; i++) {
2992
+ const ch = value[i];
2993
+ if (ch === " " || ch === "\n" || ch === " " || ch === "\r" || ch === "\f") {
2994
+ if (token) {
2995
+ out.push(token);
2996
+ token = "";
2997
+ }
2998
+ } else {
2999
+ token += ch;
3000
+ }
3001
+ }
3002
+ if (token) out.push(token);
3003
+ return out;
3004
+ }
3005
+ function descriptorMatches(el, descriptor) {
3006
+ if (!descriptor || !descriptor.class) return true;
3007
+ const wanted = classTokens(descriptor.class);
3008
+ if (wanted.length === 0) return true;
3009
+ const actual = el.classList;
3010
+ if (actual) {
3011
+ for (const token of wanted) {
3012
+ if (!actual.contains(token)) return false;
3013
+ }
3014
+ return true;
3015
+ }
3016
+ const raw2 = el.getAttribute("class") ?? el.className ?? "";
3017
+ const present2 = classTokens(String(raw2));
3018
+ for (const token of wanted) {
3019
+ if (!present2.includes(token)) return false;
3020
+ }
3021
+ return true;
3022
+ }
3023
+ function structuralBranchMatches(el, branch2) {
3024
+ const actualTag = el.tagName.toLowerCase();
3025
+ if (branch2.tag && actualTag !== branch2.tag) return false;
3026
+ if (branch2.descriptor) return descriptorMatches(el, branch2.descriptor);
3027
+ return !!branch2.tag;
3028
+ }
2966
3029
  function createHydrateWalker(container, markerList) {
2967
3030
  const markers = markerList || (container ? collectVskMarkers(container) : []);
2968
3031
  if (!markerList && container && markers.length === 0 && container.children.length > 0) {
@@ -3575,7 +3638,7 @@ ${String(this.root.outerHTML).slice(0, 800)}` : ""),
3575
3638
  this.inheritOffset = 0;
3576
3639
  return n;
3577
3640
  }
3578
- claimAt(tag, skipK, raw2) {
3641
+ claimAt(tag, skipK, raw2, descriptor) {
3579
3642
  if (globalThis.__vesk_hydrate_debug) {
3580
3643
  console.error("[hyd-dbg] claimAt", tag, "skip=", skipK, "idx=", this.idx, "els=", this.els.length);
3581
3644
  }
@@ -3587,14 +3650,18 @@ ${String(this.root.outerHTML).slice(0, 800)}` : ""),
3587
3650
  if (target > this.els.length) target = this.idx;
3588
3651
  while (target < this.els.length) {
3589
3652
  const el = this.els[target];
3590
- if (tag && el.tagName.toLowerCase() !== tag) {
3653
+ const actualTag = el.tagName.toLowerCase();
3654
+ const tagMismatch = !!tag && actualTag !== tag;
3655
+ const descriptorMismatch = !tagMismatch && !descriptorMatches(el, descriptor);
3656
+ if (tagMismatch || descriptorMismatch) {
3591
3657
  this.idx = this.advancePastSkippable(target + 1);
3658
+ const expectedTag = tag || "div";
3592
3659
  const ghost = {
3593
3660
  state: "ghost",
3594
3661
  el,
3595
3662
  owner: this.root,
3596
- expectedTag: tag || "div",
3597
- actualTag: el.tagName.toLowerCase(),
3663
+ expectedTag,
3664
+ actualTag,
3598
3665
  detached: false
3599
3666
  };
3600
3667
  recordClaim(this.root, ghost);
@@ -3605,20 +3672,18 @@ ${String(this.root.outerHTML).slice(0, 800)}` : ""),
3605
3672
  } catch {
3606
3673
  }
3607
3674
  }
3608
- const fresh2 = document.createElement(tag || "div");
3675
+ const fresh2 = document.createElement(expectedTag);
3609
3676
  recordClaim(this.root, {
3610
3677
  state: "fresh",
3611
3678
  el: fresh2,
3612
3679
  owner: this.root,
3613
- expectedTag: tag || "div",
3680
+ expectedTag,
3614
3681
  actualTag: fresh2.tagName.toLowerCase(),
3615
3682
  detached: false
3616
3683
  });
3617
- reportMiss(
3618
- "tag-mismatch",
3619
- `descriptor wanted <${tag}> but the SSR slot holds <${el.tagName.toLowerCase()}>; consumed one slot, detached the local ghost, and rendered fresh.`,
3620
- false
3621
- );
3684
+ const actualClass = el.getAttribute("class") || "";
3685
+ const detail = descriptorMismatch ? `descriptor wanted <${expectedTag} class="${descriptor?.class || ""}"> but the SSR slot holds <${actualTag} class="${actualClass}">; consumed one slot, detached the local ghost, and rendered fresh.` : `descriptor wanted <${tag}> but the SSR slot holds <${actualTag}>; consumed one slot, detached the local ghost, and rendered fresh.`;
3686
+ reportMiss(descriptorMismatch ? "descriptor-mismatch" : "tag-mismatch", detail, false);
3622
3687
  return fresh2;
3623
3688
  }
3624
3689
  if (this.adopted.has(el)) {
@@ -3652,11 +3717,74 @@ ${String(this.root.outerHTML).slice(0, 800)}` : ""),
3652
3717
  );
3653
3718
  return fresh;
3654
3719
  }
3655
- nextElement(tag, skipK = 0) {
3656
- return this.claimAt(tag, skipK, false);
3720
+ nextElement(tag, skipK = 0, descriptor) {
3721
+ return this.claimAt(tag, skipK, false, descriptor);
3722
+ }
3723
+ claimOnly(tag, skipK = 0, descriptor) {
3724
+ return this.claimAt(tag, skipK, true, descriptor);
3657
3725
  }
3658
- claimOnly(tag, skipK = 0) {
3659
- return this.claimAt(tag, skipK, true);
3726
+ discardStructuralRegion(branches, selected, skipK = 0) {
3727
+ if (!branches || branches.length === 0) return false;
3728
+ let offset2 = skipK || 0;
3729
+ if (!offset2) offset2 = this.inheritOffset;
3730
+ let target = this.advancePastSkippable(this.idx + offset2);
3731
+ if (target > this.els.length) target = this.idx;
3732
+ target = this.advancePastSkippable(target);
3733
+ while (target < this.els.length) {
3734
+ const el = this.els[target];
3735
+ if (this.adopted.has(el)) {
3736
+ target = this.advancePastSkippable(target + 1);
3737
+ continue;
3738
+ }
3739
+ let matchCount = 0;
3740
+ let matchIdx = -1;
3741
+ for (let i = 0; i < branches.length; i++) {
3742
+ if (structuralBranchMatches(el, branches[i])) {
3743
+ matchCount++;
3744
+ matchIdx = i;
3745
+ }
3746
+ }
3747
+ if (matchCount !== 1 || matchIdx === selected) return false;
3748
+ const count = branches[matchIdx].count;
3749
+ if (!count || count < 1) return false;
3750
+ this.inheritOffset = 0;
3751
+ let p = target;
3752
+ let removed = 0;
3753
+ while (removed < count && p < this.els.length) {
3754
+ const candidate = this.els[p];
3755
+ if (this.adopted.has(candidate)) {
3756
+ p = this.advancePastSkippable(p + 1);
3757
+ continue;
3758
+ }
3759
+ const actualTag = candidate.tagName.toLowerCase();
3760
+ const ghost = {
3761
+ state: "ghost",
3762
+ el: candidate,
3763
+ owner: this.root,
3764
+ expectedTag: branches[matchIdx].tag || actualTag,
3765
+ actualTag,
3766
+ detached: false
3767
+ };
3768
+ recordClaim(this.root, ghost);
3769
+ if (this.root && candidate.parentNode === this.root) {
3770
+ try {
3771
+ candidate.remove();
3772
+ ghost.detached = true;
3773
+ } catch {
3774
+ }
3775
+ }
3776
+ p = this.advancePastSkippable(p + 1);
3777
+ removed++;
3778
+ }
3779
+ this.idx = p;
3780
+ reportMiss(
3781
+ "descriptor-mismatch",
3782
+ `structural region reconciliation removed SSR branch ${matchIdx}; the client selected branch ${selected}.`,
3783
+ false
3784
+ );
3785
+ return true;
3786
+ }
3787
+ return false;
3660
3788
  }
3661
3789
  subWalker(rootEl) {
3662
3790
  if (globalThis.__vesk_hydrate_debug) {
@@ -3836,6 +3964,7 @@ function flattenLayoutChain(tree, pathParts, result = []) {
3836
3964
  const remaining = pathParts.slice(consumeCount);
3837
3965
  const isLeaf2 = remaining.length === 0 || remaining.every((p) => p === "");
3838
3966
  if (node.standalone) result.length = 0;
3967
+ const marker = result.length;
3839
3968
  result.push(node);
3840
3969
  if (isLeaf2) {
3841
3970
  if (!node.page && (node.children || []).length > 0) {
@@ -3845,8 +3974,17 @@ function flattenLayoutChain(tree, pathParts, result = []) {
3845
3974
  }
3846
3975
  break;
3847
3976
  } else if ((node.children || []).length > 0) {
3977
+ const before = result.length;
3848
3978
  flattenLayoutChain(node.children || [], remaining, result);
3979
+ if (result.length > before) break;
3980
+ if (node.isDynamic) {
3981
+ result.length = marker;
3982
+ continue;
3983
+ }
3849
3984
  break;
3985
+ } else if (node.isDynamic) {
3986
+ result.length = marker;
3987
+ continue;
3850
3988
  }
3851
3989
  }
3852
3990
  }
@@ -4395,7 +4533,8 @@ function Link(props, registry, hydrate) {
4395
4533
  props.class ? `class="${String(props.class).replace(/"/g, "&quot;")}"` : "",
4396
4534
  props.style ? `style="${String(props.style).replace(/"/g, "&quot;")}"` : "",
4397
4535
  props.target ? `target="${String(props.target).replace(/"/g, "&quot;")}"` : "",
4398
- props.rel ? `rel="${String(props.rel).replace(/"/g, "&quot;")}"` : ""
4536
+ props.rel ? `rel="${String(props.rel).replace(/"/g, "&quot;")}"` : "",
4537
+ ...passThroughAttrs(props).map(([key, value]) => `${key}="${value.replace(/"/g, "&quot;")}"`)
4399
4538
  ].filter(Boolean).join(" ");
4400
4539
  let childStr = "";
4401
4540
  if (props.children != null) {
@@ -4426,6 +4565,17 @@ function Link(props, registry, hydrate) {
4426
4565
  });
4427
4566
  return a;
4428
4567
  }
4568
+ function passThroughAttrs(props) {
4569
+ const out = [];
4570
+ for (const [key, value] of Object.entries(props)) {
4571
+ if (value == null || value === false) continue;
4572
+ const lower2 = key.toLowerCase();
4573
+ const allowed = lower2.startsWith("data-") || lower2.startsWith("aria-") || lower2 === "role" || lower2 === "id" || lower2 === "title" || lower2 === "tabindex" || lower2 === "download" || lower2 === "hreflang" || lower2 === "referrerpolicy";
4574
+ if (!allowed) continue;
4575
+ out.push([key, value === true ? "" : String(value)]);
4576
+ }
4577
+ return out;
4578
+ }
4429
4579
  function applyLinkDom(a, props, href) {
4430
4580
  const displayHref = routerMode() && !href.startsWith("#") ? "#" + href : href;
4431
4581
  a.href = displayHref;
@@ -4433,6 +4583,7 @@ function applyLinkDom(a, props, href) {
4433
4583
  if (props.style) a.setAttribute("style", props.style);
4434
4584
  if (props.target) a.target = props.target;
4435
4585
  if (props.rel) a.rel = props.rel;
4586
+ for (const [key, value] of passThroughAttrs(props)) a.setAttribute(key, value);
4436
4587
  }
4437
4588
  function NavLink(props, registry, hydrate) {
4438
4589
  if (typeof document === "undefined") {
@@ -5510,6 +5661,19 @@ async function renderErrorPage(router, match, container, error, navToken) {
5510
5661
  container.innerHTML = dom;
5511
5662
  }
5512
5663
  }
5664
+ function trackHydration(promise) {
5665
+ const g5 = globalThis;
5666
+ g5.__vesk_hydrated = false;
5667
+ promise.then(
5668
+ () => {
5669
+ g5.__vesk_hydrated = true;
5670
+ },
5671
+ () => {
5672
+ g5.__vesk_hydrated = true;
5673
+ }
5674
+ );
5675
+ return promise;
5676
+ }
5513
5677
  async function hydrateInitial(router, match, container, strategy) {
5514
5678
  const hydrationNavToken = router._navToken || 0;
5515
5679
  const chain = match.matchChain;
@@ -5821,13 +5985,15 @@ function createRouter(routes, options = {}) {
5821
5985
  const match = matchRoute(this.routeTree, url.pathname);
5822
5986
  if (match) {
5823
5987
  match.pathname = url.pathname;
5824
- hydrateInitial(this, match, container, hydrateStrategy);
5988
+ trackHydration(hydrateInitial(this, match, container, hydrateStrategy));
5825
5989
  this._currentMatch = match;
5826
5990
  } else {
5827
5991
  this.navigate(path, { replace: true });
5992
+ globalThis.__vesk_hydrated = true;
5828
5993
  }
5829
5994
  } else {
5830
5995
  this.navigate(path, { replace: true });
5996
+ globalThis.__vesk_hydrated = true;
5831
5997
  }
5832
5998
  return this;
5833
5999
  },
@@ -5861,7 +6027,9 @@ function createRouter(routes, options = {}) {
5861
6027
  const updateUrl = () => {
5862
6028
  const fullPath = url.pathname + url.search;
5863
6029
  const target = mode ? fullPath.startsWith("/") ? "#" + fullPath : "#" + fullPath : fullPath;
5864
- if (!opts.replace) {
6030
+ const liveFull = window.location.pathname + window.location.search + window.location.hash;
6031
+ if (!opts.replace && target === liveFull) {
6032
+ } else if (!opts.replace) {
5865
6033
  window.history.pushState({ path: url.pathname }, "", target);
5866
6034
  } else {
5867
6035
  window.history.replaceState({ path: url.pathname }, "", target);
@@ -6056,6 +6224,41 @@ function createFileRouter(routeTree, options = {}) {
6056
6224
  const renderFn = options.render || renderMatch;
6057
6225
  const hydrateStrategy = options.hydrate || "full";
6058
6226
  const hashMode = options.hash === true;
6227
+ const serverMiddlewareCache = /* @__PURE__ */ new Map();
6228
+ let serverMiddlewareDisabled = false;
6229
+ const runServerMiddleware = async (ctx2, next) => {
6230
+ if (options.serverMiddleware !== true || typeof window === "undefined" || serverMiddlewareDisabled) return next();
6231
+ const path = String(ctx2.url || "/");
6232
+ const cached = serverMiddlewareCache.get(path);
6233
+ if (cached && Date.now() - cached.at < 2500) {
6234
+ if (cached.body && typeof cached.body.redirect === "string" && cached.body.redirect) {
6235
+ return { redirect: cached.body.redirect };
6236
+ }
6237
+ if (cached.body && typeof cached.body.rewrite === "string" && cached.body.rewrite) return next(cached.body.rewrite);
6238
+ return next();
6239
+ }
6240
+ const endpoint = globalThis.__veskServerMiddlewareEndpoint ?? "/_vesk/middleware";
6241
+ try {
6242
+ const res = await fetch(`${endpoint}?path=${encodeURIComponent(path)}`, {
6243
+ credentials: "include",
6244
+ headers: { Accept: "application/json" },
6245
+ cache: "no-store"
6246
+ });
6247
+ if (res.status === 404) {
6248
+ serverMiddlewareDisabled = true;
6249
+ return next();
6250
+ }
6251
+ const body = await res.json().catch(() => null);
6252
+ serverMiddlewareCache.set(path, { at: Date.now(), body });
6253
+ if (body && typeof body.redirect === "string" && body.redirect) {
6254
+ return { redirect: body.redirect };
6255
+ }
6256
+ if (body && typeof body.rewrite === "string" && body.rewrite) return next(body.rewrite);
6257
+ return next();
6258
+ } catch {
6259
+ return next();
6260
+ }
6261
+ };
6059
6262
  const router = {
6060
6263
  _hydrateStrategy: hydrateStrategy,
6061
6264
  routeTree,
@@ -6168,13 +6371,15 @@ function createFileRouter(routeTree, options = {}) {
6168
6371
  const match = matchRoute(routeTree, path);
6169
6372
  if (match) {
6170
6373
  match.pathname = path;
6171
- hydrateInitial(router, match, container, hydrateStrategy);
6374
+ trackHydration(hydrateInitial(router, match, container, hydrateStrategy));
6172
6375
  router._currentMatch = match;
6173
6376
  } else {
6174
6377
  router.navigate(path, { replace: true });
6378
+ globalThis.__vesk_hydrated = true;
6175
6379
  }
6176
6380
  } else {
6177
6381
  router.navigate(path, { replace: true });
6382
+ globalThis.__vesk_hydrated = true;
6178
6383
  }
6179
6384
  return router;
6180
6385
  },
@@ -6228,12 +6433,17 @@ function createFileRouter(routeTree, options = {}) {
6228
6433
  navDebug("navigate", url.pathname, "token=" + router._navToken, "pendingChunks", hasPendingChunks(match.matchChain));
6229
6434
  const navToken = router._navToken;
6230
6435
  loadingStart();
6231
- const middlewareFns = Array.isArray(middleware) ? middleware : middleware ? [middleware] : [];
6436
+ const middlewareFns = [
6437
+ ...options.serverMiddleware === true ? [runServerMiddleware] : [],
6438
+ ...Array.isArray(middleware) ? middleware : middleware ? [middleware] : []
6439
+ ];
6232
6440
  let firstRenderFailed = false;
6233
6441
  const updateUrl = () => {
6234
6442
  const fullUrl = url.pathname + url.search;
6235
6443
  const target = mode ? fullUrl.startsWith("/") ? "#" + fullUrl : "#" + fullUrl : fullUrl;
6236
- if (!opts.replace) {
6444
+ const liveFull = window.location.pathname + window.location.search + window.location.hash;
6445
+ if (!opts.replace && target === liveFull) {
6446
+ } else if (!opts.replace) {
6237
6447
  window.history.pushState({ path: fullUrl }, "", target);
6238
6448
  } else {
6239
6449
  window.history.replaceState({ path: fullUrl }, "", target);
@@ -32393,6 +32603,17 @@ function emitNode(ctx2, node, tracked2, effectsVar, parentVar, compPrefix = "__c
32393
32603
  }
32394
32604
  return null;
32395
32605
  }
32606
+ function staticClassDescriptor(node) {
32607
+ const hasDynamicClass = node.children.some(
32608
+ (child) => child instanceof DynamicBinding && child.kind === "attribute" && child.target === "class"
32609
+ );
32610
+ if (hasDynamicClass) return null;
32611
+ const attr = node.attributes.find((a) => a.name === "class");
32612
+ if (!attr) return null;
32613
+ const value = attr.value.trim();
32614
+ if (!value) return null;
32615
+ return JSON.stringify({ class: value });
32616
+ }
32396
32617
  function emitStatic(ctx2, node, tracked2, effectsVar, skipK = 0, regionBudget) {
32397
32618
  const el = ctx2.n();
32398
32619
  if (ctx2.hydrate) {
@@ -32403,7 +32624,11 @@ function emitStatic(ctx2, node, tracked2, effectsVar, skipK = 0, regionBudget) {
32403
32624
  ctx2.rootClaim = false;
32404
32625
  const skipExpr = regionBudget && ctx2.markerless ? markerlessSkipExpr(regionBudget, skipK) : skipK;
32405
32626
  const skipArg = ctx2.markerless ? `, ${skipExpr}` : "";
32406
- const claimedExpr = rootClaim ? `__root || document.createElement(${JSON.stringify(node.tag)})` : `${ctx2.walker}.nextElement(${JSON.stringify(node.tag)}${skipArg})`;
32627
+ const wantsDescriptor = ctx2.markerless && ctx2.descriptorClaim;
32628
+ ctx2.descriptorClaim = false;
32629
+ const descriptor = wantsDescriptor && !rootClaim ? staticClassDescriptor(node) : null;
32630
+ const descriptorArg = descriptor ? `, ${descriptor}` : "";
32631
+ const claimedExpr = rootClaim ? `__root || document.createElement(${JSON.stringify(node.tag)})` : `${ctx2.walker}.nextElement(${JSON.stringify(node.tag)}${skipArg}${descriptorArg})`;
32407
32632
  ctx2.push(`const ${el} = ${claimedExpr};`);
32408
32633
  if (regionBudget && ctx2.markerless) ctx2.push(`${regionBudget} = 0;`);
32409
32634
  } else {
@@ -32787,6 +33012,7 @@ function emitComponentCall(ctx2, node, tracked2, effectsVar, parentVar, compPref
32787
33012
  }
32788
33013
  const callArgs = () => plainTarget ? `reactiveProps({ ${propsEntries.join(", ")} })` : `{ ${propsEntries.join(", ")} }`;
32789
33014
  if (ctx2.hydrate) {
33015
+ ctx2.descriptorClaim = false;
32790
33016
  const access = calleeExpr ?? (ctx2.importedNames.has(node.componentName) ? node.componentName : `${ctx2.hydrateRegistry}[${JSON.stringify(node.componentName)}]`);
32791
33017
  if (!calleeExpr && !ctx2.importedNames.has(node.componentName)) {
32792
33018
  ctx2.push(`if (${access} == null) throw new Error(${JSON.stringify(`Component "${node.componentName}" was not found while rendering. Declare it with the \`component\` keyword, import it, or register it in the component registry.`)});`);
@@ -33009,13 +33235,14 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33009
33235
  const hyd = ctx2.hydrate;
33010
33236
  const parent = parentVar || "$root";
33011
33237
  const budget = hyd ? regionBudgetVar(ctx2, skipK, regionBudget) : null;
33238
+ const rid = regionMarkerId(node);
33012
33239
  const isOpaque = (n) => !!n && typeof n.condition !== "undefined";
33013
33240
  if (hyd && node.alternateNodes.length === 1 && isOpaque(node.alternateNodes[0])) {
33014
33241
  const chain = [];
33015
33242
  let cur = node;
33016
33243
  let finalElse = null;
33017
33244
  while (cur) {
33018
- chain.push({ cond: transformTracked(cur.condition, tracked2), nodes: cur.consequentNodes });
33245
+ chain.push({ cond: transformTracked(cur.condition, tracked2), nodes: cur.consequentNodes, id: regionMarkerId(cur) });
33019
33246
  if (cur.alternateNodes.length === 1 && isOpaque(cur.alternateNodes[0])) {
33020
33247
  cur = cur.alternateNodes[0];
33021
33248
  } else {
@@ -33039,6 +33266,8 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33039
33266
  ctx2.push(`const ${rn} = ${fnOpen2}`);
33040
33267
  const cl = ctx2.n();
33041
33268
  ctx2.push(indent2(`const ${cl} = [];`));
33269
+ const savedDescriptor = ctx2.descriptorClaim;
33270
+ if (hyd && ctx2.markerless) ctx2.descriptorClaim = true;
33042
33271
  for (const n of chain[i].nodes) {
33043
33272
  const savedClaim = ctx2.claimStatic;
33044
33273
  if (hyd) ctx2.claimStatic = true;
@@ -33046,6 +33275,7 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33046
33275
  ctx2.claimStatic = savedClaim;
33047
33276
  if (v) ctx2.push(indent2(`${cl}.push(${v});`));
33048
33277
  }
33278
+ ctx2.descriptorClaim = savedDescriptor;
33049
33279
  ctx2.push(indent2(`__place(${anchor2}, ${endAnchor2}, ${cl}, ${parent});`));
33050
33280
  ctx2.push(`};`);
33051
33281
  }
@@ -33055,6 +33285,8 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33055
33285
  ctx2.push(`const ${finalRender} = ${fnOpen2}`);
33056
33286
  const cl2 = ctx2.n();
33057
33287
  ctx2.push(indent2(`const ${cl2} = [];`));
33288
+ const savedDescriptor = ctx2.descriptorClaim;
33289
+ if (hyd && ctx2.markerless) ctx2.descriptorClaim = true;
33058
33290
  for (const n of finalElse) {
33059
33291
  const savedClaim = ctx2.claimStatic;
33060
33292
  if (hyd) ctx2.claimStatic = true;
@@ -33062,23 +33294,34 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33062
33294
  ctx2.claimStatic = savedClaim;
33063
33295
  if (v) ctx2.push(indent2(`${cl2}.push(${v});`));
33064
33296
  }
33297
+ ctx2.descriptorClaim = savedDescriptor;
33065
33298
  ctx2.push(indent2(`__place(${anchor2}, ${endAnchor2}, ${cl2}, ${parent});`));
33066
33299
  ctx2.push(`};`);
33067
33300
  }
33068
- let init = `if (${chain[0].cond}) { ${asyncKw2}${renderNames[0]}(); }`;
33069
- for (let i = 1; i < chain.length; i++) init += ` else if (${chain[i].cond}) { ${asyncKw2}${renderNames[i]}(); }`;
33070
- if (finalRender) init += ` else { ${asyncKw2}${finalRender}(); }`;
33071
- ctx2.push(init);
33072
33301
  let branchInitFallback = finalRender ? `${chain.length}` : "-1";
33073
33302
  for (let i = chain.length - 1; i >= 0; i--) {
33074
33303
  branchInitFallback = `(${chain[i].cond} ? ${i} : ${branchInitFallback})`;
33075
33304
  }
33076
33305
  const branchInit = `(${branchInitFallback})`;
33306
+ const branchSnapshot = ctx2.n();
33307
+ ctx2.push(`const ${branchSnapshot} = ${branchInit};`);
33308
+ if (!ctx2.markerless) {
33309
+ for (let i = 0; i < chain.length; i++) {
33310
+ ctx2.push(`if (__hydrate) __reconcileRegion(${parent}, '${chain[i].id}', ${branchSnapshot} === ${i} ? 0 : 1, ${ctx2.walker});`);
33311
+ }
33312
+ } else {
33313
+ const chainBranches = chain.map((c) => c.nodes);
33314
+ if (finalElse) chainBranches.push(finalElse);
33315
+ emitStructuralRegionDiscard(ctx2, chainBranches, branchSnapshot, budget);
33316
+ }
33317
+ let init = `if (${branchSnapshot} === 0) { ${asyncKw2}${renderNames[0]}(); }`;
33318
+ for (let i = 1; i < chain.length; i++) init += ` else if (${branchSnapshot} === ${i}) { ${asyncKw2}${renderNames[i]}(); }`;
33319
+ if (finalRender) init += ` else { ${asyncKw2}${finalRender}(); }`;
33320
+ ctx2.push(init);
33077
33321
  let effInner = `if (__new === 0) { ${asyncKw2}${renderNames[0]}(); }`;
33078
33322
  for (let i = 1; i < chain.length; i++) effInner += ` else if (__new === ${i}) { ${asyncKw2}${renderNames[i]}(); }`;
33079
33323
  if (finalRender) effInner += ` else { ${asyncKw2}${finalRender}(); }`;
33080
33324
  const effBody = `effect(${ctx2.isAsyncScope ? "async () => {" : "() => {"}
33081
- if (__first) { __first = false; __iv = ${branchInit}; return; }
33082
33325
  const __new = ${branchInit};
33083
33326
  if (__new !== __iv) {
33084
33327
  for (const e of ${effectsVar2}) destroy_block(e);
@@ -33090,14 +33333,12 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33090
33333
  }, true);`;
33091
33334
  if (effTarget) {
33092
33335
  ctx2.push(`${effTarget}.push((() => {
33093
- let __iv = ${branchInit};
33094
- let __first = true;
33336
+ let __iv = ${branchSnapshot};
33095
33337
  return ${effBody}
33096
33338
  })());`);
33097
33339
  } else {
33098
33340
  ctx2.effects.push(`{
33099
- let __iv = ${branchInit};
33100
- let __first = true;
33341
+ let __iv = ${branchSnapshot};
33101
33342
  ${effBody}
33102
33343
  }`);
33103
33344
  }
@@ -33121,6 +33362,8 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33121
33362
  const conFrag = ctx2.n();
33122
33363
  if (!hyd) ctx2.push(indent2(`const ${conFrag} = document.createDocumentFragment();`));
33123
33364
  if (hyd) ctx2.push(indent2(`const __cl = [];`));
33365
+ const savedConDescriptor = ctx2.descriptorClaim;
33366
+ if (hyd && ctx2.markerless) ctx2.descriptorClaim = true;
33124
33367
  for (const n of node.consequentNodes) {
33125
33368
  const savedClaim = ctx2.claimStatic;
33126
33369
  if (hyd) ctx2.claimStatic = true;
@@ -33131,6 +33374,7 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33131
33374
  else ctx2.push(indent2(`${conFrag}.appendChild(${v});`));
33132
33375
  }
33133
33376
  }
33377
+ ctx2.descriptorClaim = savedConDescriptor;
33134
33378
  if (hyd) ctx2.push(indent2(`__place(${anchor}, ${endAnchor}, __cl, ${parent});`));
33135
33379
  else ctx2.push(indent2(`__p.insertBefore(${conFrag}, ${endAnchor});`));
33136
33380
  ctx2.push(`};`);
@@ -33142,6 +33386,8 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33142
33386
  const altFrag = ctx2.n();
33143
33387
  if (!hyd) ctx2.push(indent2(`const ${altFrag} = document.createDocumentFragment();`));
33144
33388
  if (hyd) ctx2.push(indent2(`const __cl = [];`));
33389
+ const savedAltDescriptor = ctx2.descriptorClaim;
33390
+ if (hyd && ctx2.markerless) ctx2.descriptorClaim = true;
33145
33391
  for (const n of node.alternateNodes) {
33146
33392
  const savedAltClaim = ctx2.claimStatic;
33147
33393
  if (hyd) ctx2.claimStatic = true;
@@ -33152,15 +33398,19 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33152
33398
  else ctx2.push(indent2(`${altFrag}.appendChild(${v});`));
33153
33399
  }
33154
33400
  }
33401
+ ctx2.descriptorClaim = savedAltDescriptor;
33155
33402
  if (hyd) ctx2.push(indent2(`__place(${anchor}, ${endAnchor}, __cl, ${parent});`));
33156
33403
  else ctx2.push(indent2(`__p.insertBefore(${altFrag}, ${endAnchor});`));
33157
33404
  ctx2.push(`};`);
33158
33405
  }
33159
33406
  if (!hyd) ctx2.push(`${parent}.appendChild(${endAnchor});`);
33160
- ctx2.push(`if (${condExpr}) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : ""));
33407
+ const condSnapshot = ctx2.n();
33408
+ ctx2.push(`const ${condSnapshot} = ${condExpr};`);
33409
+ if (hyd && !ctx2.markerless) ctx2.push(`if (__hydrate) __reconcileRegion(${parent}, '${rid}', ${condSnapshot} ? 0 : 1, ${ctx2.walker});`);
33410
+ if (hyd && ctx2.markerless) emitStructuralRegionDiscard(ctx2, [node.consequentNodes, node.alternateNodes], hasElse ? `(${condSnapshot} ? 0 : 1)` : `(${condSnapshot} ? 0 : -1)`, budget);
33411
+ ctx2.push(`if (${condSnapshot}) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : ""));
33161
33412
  const renderBranch = `if (__nv) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : "");
33162
33413
  const effectBody = `effect(${ctx2.isAsyncScope ? "async () => {" : "() => {"}
33163
- if (__first) { __first = false; __iv = ${condExpr}; return; }
33164
33414
  const __nv = ${condExpr};
33165
33415
  if (__nv !== __iv) {
33166
33416
  for (const e of ${effectsVar}) destroy_block(e);
@@ -33173,14 +33423,12 @@ function emitOpaque(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regio
33173
33423
  if (!isReactiveExpression(node.condition, tracked2)) return null;
33174
33424
  if (effTarget) {
33175
33425
  ctx2.push(`${effTarget}.push((() => {
33176
- let __iv = ${condExpr};
33177
- let __first = true;
33426
+ let __iv = ${condSnapshot};
33178
33427
  return ${effectBody}
33179
33428
  })());`);
33180
33429
  } else {
33181
33430
  ctx2.effects.push(`{
33182
- let __iv = ${condExpr};
33183
- let __first = true;
33431
+ let __iv = ${condSnapshot};
33184
33432
  ${effectBody}
33185
33433
  }`);
33186
33434
  }
@@ -33561,25 +33809,23 @@ function emitMap(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionBu
33561
33809
  let emptyRenderName = null;
33562
33810
  if (node.alternateNodes.length > 0) {
33563
33811
  emptyRenderName = ctx2.n();
33564
- const emptySig = !hyd ? ctx2.isAsyncScope ? "async () => {" : "() => {" : ctx2.isAsyncScope ? "async (__cl) => {" : "(__cl) => {";
33812
+ const emptyClaims = ctx2.hydrate;
33813
+ const emptySig = !emptyClaims ? ctx2.isAsyncScope ? "async () => {" : "() => {" : ctx2.isAsyncScope ? "async (__cl) => {" : "(__cl) => {";
33565
33814
  ctx2.push(`const ${emptyRenderName} = ${emptySig}`);
33566
33815
  ctx2.push(indent2(`const __p = ${anchor}.parentNode;`));
33567
33816
  const frag = ctx2.n();
33568
- if (!hyd) ctx2.push(indent2(`const ${frag} = document.createDocumentFragment();`));
33817
+ if (!emptyClaims) ctx2.push(indent2(`const ${frag} = document.createDocumentFragment();`));
33569
33818
  const savedClaim = ctx2.claimStatic;
33570
- const savedHydrate = ctx2.hydrate;
33571
- if (hydKeyed) ctx2.hydrate = false;
33572
33819
  for (const n of node.alternateNodes) {
33573
33820
  ctx2.claimStatic = true;
33574
- const v = emitNode(ctx2, n, tracked2, effectsVar, hyd ? void 0 : frag, "__components", 0, budget || void 0);
33821
+ const v = emitNode(ctx2, n, tracked2, effectsVar, emptyClaims ? void 0 : frag, "__components", 0, budget || void 0);
33575
33822
  if (v) {
33576
- if (hyd) ctx2.push(indent2(`if (__cl) __cl.push(${v}); else __p.insertBefore(${v}, ${endAnchor});`));
33823
+ if (emptyClaims) ctx2.push(indent2(`if (__cl) __cl.push(${v}); else __p.insertBefore(${v}, ${endAnchor});`));
33577
33824
  else ctx2.push(indent2(`${frag}.appendChild(${v});`));
33578
33825
  }
33579
33826
  }
33580
33827
  ctx2.claimStatic = savedClaim;
33581
- ctx2.hydrate = savedHydrate;
33582
- if (!hyd) ctx2.push(indent2(`if (${frag}.childNodes.length > 0) __p.insertBefore(${frag}, ${endAnchor});`));
33828
+ if (!emptyClaims) ctx2.push(indent2(`if (${frag}.childNodes.length > 0) __p.insertBefore(${frag}, ${endAnchor});`));
33583
33829
  ctx2.push(`};`);
33584
33830
  }
33585
33831
  if (!hyd && !hydKeyed) ctx2.push(`${parent}.appendChild(${endAnchor});`);
@@ -33599,8 +33845,11 @@ function emitMap(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionBu
33599
33845
  }
33600
33846
  if (emptyRenderName) {
33601
33847
  const isEmptyVar = ctx2.n();
33848
+ const collectVar = hydKeyed ? ctx2.n() : null;
33602
33849
  ctx2.push(`let ${isEmptyVar} = !${hasItems}();`);
33603
- ctx2.push(`if (!${isEmptyVar}) { ${initList}(); } else { ${aw}${emptyRenderName}(); }`);
33850
+ if (collectVar) ctx2.push(`const ${collectVar} = [];`);
33851
+ ctx2.push(`if (!${isEmptyVar}) { ${initList}(); } else { ${aw}${emptyRenderName}(${collectVar || ""}); }`);
33852
+ if (collectVar) ctx2.push(`__place(${anchor}, ${endAnchor}, ${collectVar}, ${parent});`);
33604
33853
  if (!reactiveSource) return null;
33605
33854
  pushEffect(`let __first = true;`, `effect(${effOpen}
33606
33855
  const __new = ${hasItems}();
@@ -33671,7 +33920,7 @@ ${renderAllItems(" ", null)}
33671
33920
  __cleanup(${anchor}, ${endAnchor});
33672
33921
  if (__new) {
33673
33922
  ${renderAllItems(" ", null)}
33674
- } else { ${aw}${emptyRenderName}(${collectVar ? collectVar : ""}); }
33923
+ } else { ${aw}${emptyRenderName}(); }
33675
33924
  }, true)`);
33676
33925
  } else {
33677
33926
  const collectVar = hyd ? ctx2.n() : null;
@@ -33762,6 +34011,7 @@ function generateComponent(comp, importedNames = /* @__PURE__ */ new Set(), hydr
33762
34011
  }
33763
34012
  }
33764
34013
  }
34014
+ if (ctx2.hydrate && ctx2.markerless) ctx2.descriptorClaim = true;
33765
34015
  for (const node of comp.body) {
33766
34016
  if (node instanceof TrackDecl) {
33767
34017
  if (deferredTrackDecls.has(node)) emitNode(ctx2, node, tracked2, null);
@@ -33842,6 +34092,33 @@ function buildComponentMap(irRoot, hydrate = false, alloc, markerless = true) {
33842
34092
  const code = generateComponent(comp, directNames, hydrate, asyncComps, linkNames, selfClaimNames, alloc, markerless);
33843
34093
  mapLines.push(`${registry}[${JSON.stringify(comp.name)}] = ${code};`);
33844
34094
  }
34095
+ if (hydrate && !markerless) {
34096
+ mapLines.push(`function __reconcileRegion(parent, id, branch, walker) {`);
34097
+ mapLines.push(` if (!parent) return;`);
34098
+ mapLines.push(` let start = null;`);
34099
+ mapLines.push(` let end = null;`);
34100
+ mapLines.push(` for (let n = parent.firstChild; n; n = n.nextSibling) {`);
34101
+ mapLines.push(` if (n.nodeType !== 8) continue;`);
34102
+ mapLines.push(` const text = n.textContent || '';`);
34103
+ mapLines.push(` if (text === 'vesk-r:' + id + ':0' || text === 'vesk-r:' + id + ':1') start = n;`);
34104
+ mapLines.push(` else if (text === 'vesk-r-end:' + id) end = n;`);
34105
+ mapLines.push(` if (start && end) break;`);
34106
+ mapLines.push(` }`);
34107
+ mapLines.push(` if (!start || !end) return;`);
34108
+ mapLines.push(` const ssrBranch = (start.textContent || '').slice(-2) === ':1' ? 1 : 0;`);
34109
+ mapLines.push(` if (ssrBranch !== branch) {`);
34110
+ mapLines.push(` let n = start.nextSibling;`);
34111
+ mapLines.push(` while (n && n !== end) {`);
34112
+ mapLines.push(` const next = n.nextSibling;`);
34113
+ mapLines.push(` n.remove();`);
34114
+ mapLines.push(` n = next;`);
34115
+ mapLines.push(` }`);
34116
+ mapLines.push(` if (walker && walker.retireDetached) walker.retireDetached();`);
34117
+ mapLines.push(` }`);
34118
+ mapLines.push(` start.remove();`);
34119
+ mapLines.push(` end.remove();`);
34120
+ mapLines.push(`}`);
34121
+ }
33845
34122
  mapLines.push(`function __cleanup(start, end) {`);
33846
34123
  mapLines.push(` let n = start.nextSibling;`);
33847
34124
  mapLines.push(` while (n && n !== end) {`);
@@ -33900,6 +34177,43 @@ function ssrResidueEstimate(node) {
33900
34177
  }
33901
34178
  return 0;
33902
34179
  }
34180
+ function firstBranchRoot(nodes) {
34181
+ for (const n of nodes) {
34182
+ if (n instanceof StaticNode) return { tag: n.tag, descriptor: staticClassDescriptor(n) };
34183
+ if (n instanceof ComponentCall || n instanceof ComponentRef) return null;
34184
+ if (n instanceof OpaqueDynamicRegion) return null;
34185
+ if (n instanceof MapRegion || n instanceof ForLoop || n instanceof WhileLoop) {
34186
+ const child = firstBranchRoot(n.bodyTemplate);
34187
+ if (child) return child;
34188
+ }
34189
+ if (n instanceof SwitchBlock) {
34190
+ for (const c of n.cases) {
34191
+ const child = firstBranchRoot(c.body);
34192
+ if (child) return child;
34193
+ }
34194
+ }
34195
+ if (n instanceof TryCatch) {
34196
+ const child = firstBranchRoot(n.bodyTemplate) || firstBranchRoot(n.catchBody);
34197
+ if (child) return child;
34198
+ }
34199
+ }
34200
+ return null;
34201
+ }
34202
+ function structuralRegionMetadata(branches) {
34203
+ const parts = branches.map((nodes) => {
34204
+ const first = firstBranchRoot(nodes);
34205
+ const tag = first ? JSON.stringify(first.tag) : "undefined";
34206
+ const descriptor = first && first.descriptor ? first.descriptor : "null";
34207
+ return `{ tag: ${tag}, descriptor: ${descriptor}, count: ${ssrResidueEstimate(nodes)} }`;
34208
+ });
34209
+ return `[${parts.join(", ")}]`;
34210
+ }
34211
+ function emitStructuralRegionDiscard(ctx2, branches, selectedExpr, budget) {
34212
+ if (!ctx2.hydrate || !ctx2.markerless) return;
34213
+ const offset2 = budget ? `, ${budget}` : "";
34214
+ const consume = budget ? ` ${budget} = 0;` : "";
34215
+ ctx2.push(`if (${ctx2.walker} && typeof ${ctx2.walker}.discardStructuralRegion === 'function' && ${ctx2.walker}.discardStructuralRegion(${structuralRegionMetadata(branches)}, ${selectedExpr}${offset2})) {${consume}}`);
34216
+ }
33903
34217
  function isStaticIR(body) {
33904
34218
  for (const node of body) {
33905
34219
  if (node instanceof StaticNode) {
@@ -34230,6 +34544,10 @@ var init_client_codegen = __esm({
34230
34544
  markerless = true;
34231
34545
  inTryBody = false;
34232
34546
  claimStatic = false;
34547
+ // Markerless only: the next real claim carries a compiler-generated static
34548
+ // class descriptor so a same-tag but structurally different SSR slot is
34549
+ // substituted instead of adopted (e.g. an empty-state <div> vs a list <div>).
34550
+ descriptorClaim = false;
34233
34551
  // While set, the next StaticNode claimed in hydrate mode uses `__root` (the
34234
34552
  // item element already claimed by key) instead of walking for a new element.
34235
34553
  rootClaim = false;
@@ -35081,15 +35399,19 @@ function dynamicBindingToJS(node, tracked2) {
35081
35399
  function opaqueRegionToJS(node, isAsync = false, tracked2) {
35082
35400
  const lines = [];
35083
35401
  const cond = exprJSX(node.condition, tracked2);
35402
+ const rid = regionMarkerId(node);
35403
+ const mark = __vskHydrate && !__vskMarkerless;
35084
35404
  lines.push(`if (${cond}) {`);
35405
+ if (mark) lines.push(indent(`__out.push('<!--vesk-r:${rid}:0-->');`));
35085
35406
  setVskForceClaim(true);
35086
35407
  for (const n of node.consequentNodes) {
35087
35408
  const code = irNodeToJS(n, null, isAsync, tracked2);
35088
35409
  if (code) lines.push(indent(code));
35089
35410
  }
35090
35411
  setVskForceClaim(false);
35412
+ lines.push(`} else {`);
35413
+ if (mark) lines.push(indent(`__out.push('<!--vesk-r:${rid}:1-->');`));
35091
35414
  if (node.alternateNodes.length > 0) {
35092
- lines.push(`} else {`);
35093
35415
  setVskForceClaim(true);
35094
35416
  for (const n of node.alternateNodes) {
35095
35417
  const code = irNodeToJS(n, null, isAsync, tracked2);
@@ -35098,6 +35420,7 @@ function opaqueRegionToJS(node, isAsync = false, tracked2) {
35098
35420
  setVskForceClaim(false);
35099
35421
  }
35100
35422
  lines.push(`}`);
35423
+ if (mark) lines.push(`__out.push('<!--vesk-r-end:${rid}-->');`);
35101
35424
  return lines.join("\n");
35102
35425
  }
35103
35426
  function mapRegionToJS(node, isAsync = false, tracked2) {
@@ -49833,20 +50156,16 @@ interface VeskLocals<T extends object> {
49833
50156
  all(): T;
49834
50157
  }
49835
50158
  declare function createLocals<T extends object = Record<string, unknown>>(): VeskLocals<T>;
49836
- // useFetch returns a THENABLE resource, not the data itself. In async
49837
- // components you must \`await\` it before reading/iterating the payload;
49838
- // passing \`into: <tracked cell>\` writes the payload into the cell and makes
49839
- // awaiting unnecessary (the return value can be ignored).
49840
- interface VeskResource<T> {
50159
+ // useFetch returns a real Promise carrying resource state. In async components
50160
+ // you must \`await\` it before reading/iterating the payload; passing
50161
+ // \`into: <tracked cell>\` writes the payload into the cell and makes awaiting
50162
+ // unnecessary (the return value can be ignored).
50163
+ interface VeskResource<T> extends Promise<T> {
49841
50164
  loading: boolean;
49842
50165
  error: unknown;
49843
50166
  data: T | undefined;
49844
50167
  refresh(): void;
49845
50168
  abort(): void;
49846
- then<TResult1 = T, TResult2 = never>(
49847
- onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
49848
- onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,
49849
- ): PromiseLike<TResult1 | TResult2>;
49850
50169
  }
49851
50170
  interface VeskUseFetchOptions<T> {
49852
50171
  /** Cache/SSR key \u2014 defaults to the URL string. */
@@ -51613,7 +51932,10 @@ function __getNotFoundCompiled() { if (!_notFoundCompiled) _notFoundCompiled = $
51613
51932
  " }"
51614
51933
  ];
51615
51934
  const dataNavWrap = (body) => [
51616
- " return withSsrStore(async () => {",
51935
+ // Awaited for the same reason as the main render below: the caller restores
51936
+ // `__vesk_request` in a finally, and that must happen only after the async
51937
+ // data render (which reads params through useParams) has fully resolved.
51938
+ " return await withSsrStore(async () => {",
51617
51939
  ...body.map((l) => l ? " " + l : l),
51618
51940
  " });"
51619
51941
  ];
@@ -51641,7 +51963,13 @@ function __getNotFoundCompiled() { if (!_notFoundCompiled) _notFoundCompiled = $
51641
51963
  ...dataNavCleanup
51642
51964
  ]),
51643
51965
  " }",
51644
- " return __renderHtml(params, url.href);"
51966
+ // Awaited so the surrounding try/finally keeps `__vesk_request` installed
51967
+ // for the whole async render. Without the await the finally restores the
51968
+ // previous context synchronously, while the async page body is still
51969
+ // suspended on its SSR fetches; every render pass after the first `await`
51970
+ // then reads an empty params object and `useParams()`-derived keys/URLs
51971
+ // collapse (e.g. a verify page rendering its not-found branch).
51972
+ " return await __renderHtml(params, url.href);"
51645
51973
  ].join("\n");
51646
51974
  } else {
51647
51975
  dataCode = [
@@ -51662,7 +51990,13 @@ function __getNotFoundCompiled() { if (!_notFoundCompiled) _notFoundCompiled = $
51662
51990
  ...dataNavCleanup
51663
51991
  ]),
51664
51992
  " }",
51665
- " return __renderHtml(params, url.href);"
51993
+ // Awaited so the surrounding try/finally keeps `__vesk_request` installed
51994
+ // for the whole async render. Without the await the finally restores the
51995
+ // previous context synchronously, while the async page body is still
51996
+ // suspended on its SSR fetches; every render pass after the first `await`
51997
+ // then reads an empty params object and `useParams()`-derived keys/URLs
51998
+ // collapse (e.g. a verify page rendering its not-found branch).
51999
+ " return await __renderHtml(params, url.href);"
51666
52000
  ].join("\n");
51667
52001
  }
51668
52002
  const hasMiddleware = !!middlewareCode;
@@ -52157,8 +52491,18 @@ function extractMiddlewareParts(src2) {
52157
52491
  decls.push(src2.slice(stmt.declaration.start, stmt.declaration.end).trim());
52158
52492
  }
52159
52493
  }
52494
+ const imports = [];
52495
+ for (const stmt of ast.body) {
52496
+ if (stmt.type !== "ImportDeclaration") continue;
52497
+ if (stmt.importKind === "type") continue;
52498
+ const source = stmt.source?.value;
52499
+ if (typeof source !== "string") continue;
52500
+ if (source.startsWith(".") || source.startsWith("/")) continue;
52501
+ const line = src2.slice(stmt.start, stmt.end).trim();
52502
+ if (line && !imports.includes(line)) imports.push(line);
52503
+ }
52160
52504
  const bodyWithDecls = decls.length > 0 ? decls.join("\n") + "\n" + body.trim() : body.trim();
52161
- return { params, body: bodyWithDecls };
52505
+ return { params, body: bodyWithDecls, imports };
52162
52506
  } catch {
52163
52507
  return fallbackExtractMiddleware(src2);
52164
52508
  }
@@ -52199,7 +52543,7 @@ function fallbackExtractMiddleware(src2) {
52199
52543
  m++;
52200
52544
  }
52201
52545
  const body = src2.slice(b + 1, m - 1);
52202
- return { params, body: body.trim() };
52546
+ return { params, body: body.trim(), imports: [] };
52203
52547
  }
52204
52548
  return null;
52205
52549
  }
@@ -52221,16 +52565,18 @@ ${parts.body}
52221
52565
  function extractMiddlewareBody(src2) {
52222
52566
  const parts = extractMiddlewareParts(src2);
52223
52567
  if (!parts) return null;
52224
- return { params: parts.params, body: parts.body };
52568
+ return { params: parts.params, body: parts.body, imports: parts.imports };
52225
52569
  }
52226
52570
  function compileMiddleware(mwChain, _appDir) {
52227
52571
  if (mwChain.length === 0) return null;
52228
52572
  const parts = [];
52573
+ const imports = [];
52229
52574
  for (let i = 0; i < mwChain.length; i++) {
52230
52575
  const { sourcePath: sourcePath2 } = mwChain[i];
52231
52576
  const src2 = readFileSync10(sourcePath2, "utf-8");
52232
52577
  const extracted = extractMiddlewareBody(src2);
52233
52578
  if (!extracted) continue;
52579
+ for (const line of extracted.imports) if (!imports.includes(line)) imports.push(line);
52234
52580
  parts.push(`async function mw_${i}(${extracted.params}) {
52235
52581
  ${extracted.body}
52236
52582
  }`);
@@ -52239,6 +52585,8 @@ ${extracted.body}
52239
52585
  const code = [
52240
52586
  "// Auto-generated middleware chain \u2014 do not edit",
52241
52587
  "",
52588
+ ...imports,
52589
+ ...imports.length ? [""] : [],
52242
52590
  parts.join("\n\n"),
52243
52591
  "",
52244
52592
  `const chain = [${parts.map((_, i) => `mw_${i}`).join(", ")}];`,
@@ -52308,9 +52656,11 @@ ${extracted.body}
52308
52656
  function compileMiddlewareCode(mwSourceTexts) {
52309
52657
  if (!mwSourceTexts || mwSourceTexts.length === 0) return null;
52310
52658
  const parts = [];
52659
+ const imports = [];
52311
52660
  for (let i = 0; i < mwSourceTexts.length; i++) {
52312
52661
  const extracted = extractMiddlewareBody(mwSourceTexts[i]);
52313
52662
  if (!extracted) continue;
52663
+ for (const line of extracted.imports) if (!imports.includes(line)) imports.push(line);
52314
52664
  parts.push(`async function mw_${i}(${extracted.params}) {
52315
52665
  ${extracted.body}
52316
52666
  }`);
@@ -52319,6 +52669,8 @@ ${extracted.body}
52319
52669
  const code = [
52320
52670
  "// \u2500\u2500 Middleware chain (inline) \u2500\u2500",
52321
52671
  "",
52672
+ ...imports,
52673
+ ...imports.length ? [""] : [],
52322
52674
  parts.join("\n\n"),
52323
52675
  "",
52324
52676
  `const __mwChain = [${parts.map((_, i) => `mw_${i}`).join(", ")}];`,
@@ -52695,12 +53047,21 @@ function fileUnchanged(filePath, cached) {
52695
53047
  return false;
52696
53048
  }
52697
53049
  }
52698
- function buildRouterOpts(options) {
53050
+ function hasServerMiddleware(nodes) {
53051
+ for (const node of nodes) {
53052
+ if (node.hasMiddleware) return true;
53053
+ if (node.children?.length && hasServerMiddleware(node.children)) return true;
53054
+ }
53055
+ return false;
53056
+ }
53057
+ function buildRouterOpts(options, serverMiddleware) {
52699
53058
  const ttl = options?.routeDataCache;
53059
+ const opts = [];
53060
+ if (serverMiddleware) opts.push("serverMiddleware: true");
52700
53061
  if (typeof ttl === "number" && ttl > 0) {
52701
- return `, { routeDataCache: ${ttl} }`;
53062
+ opts.push(`routeDataCache: ${ttl}`);
52702
53063
  }
52703
- return "";
53064
+ return opts.length ? `, { ${opts.join(", ")} }` : "";
52704
53065
  }
52705
53066
  function findRuntimeSrc2(appDir) {
52706
53067
  const monorepoRoot = resolve10(__dirname3, "..", "..", "..");
@@ -52748,7 +53109,7 @@ function isAnyImport(node) {
52748
53109
  return node.type === "ImportDeclaration";
52749
53110
  }
52750
53111
  function isRuntimePreamble(node) {
52751
- if (node.type === "FunctionDeclaration" && (node.id?.name === "__cleanup" || node.id?.name === "__place")) {
53112
+ if (node.type === "FunctionDeclaration" && (node.id?.name === "__cleanup" || node.id?.name === "__place" || node.id?.name === "__reconcileRegion")) {
52752
53113
  return true;
52753
53114
  }
52754
53115
  if (node.type === "VariableDeclaration") {
@@ -53909,12 +54270,13 @@ async function buildMainBundle(routeTree, runtimeDir, codeSplit, mono, hmr, impo
53909
54270
  ` : runtimeCode + "\n";
53910
54271
  const cleanupFn = "function __cleanup(start, end) {\n let n = start.nextSibling;\n while (n && n !== end) {\n const next = n.nextSibling;\n n.remove();\n n = next;\n }\n}\n";
53911
54272
  const placeFn = "function __place(start, end, nodes, fallback) {\n if (start.parentNode !== null) {\n const p = start.parentNode;\n for (let i = 0; i < nodes.length; i++) p.insertBefore(nodes[i], end);\n return;\n }\n if (nodes.length > 0 && nodes[0].parentNode) {\n const p = nodes[0].parentNode;\n p.insertBefore(start, nodes[0]);\n p.insertBefore(end, nodes[nodes.length - 1].nextSibling);\n // Client-surplus nodes (SSR rendered fewer items than the client data)\n // are freshly claimed and still detached \u2014 move them into the region in\n // client order before `end`, instead of stranding them off-parent.\n for (let i = 0; i < nodes.length; i++) {\n if (nodes[i].parentNode === null) p.insertBefore(nodes[i], end);\n }\n return;\n }\n fallback.appendChild(start);\n fallback.appendChild(end);\n for (let i = 0; i < nodes.length; i++) fallback.insertBefore(nodes[i], end);\n}\n";
54273
+ const reconcileRegionFn = "function __reconcileRegion(parent, id, branch, walker) {\n if (!parent) return;\n let start = null;\n let end = null;\n for (let n = parent.firstChild; n; n = n.nextSibling) {\n if (n.nodeType !== 8) continue;\n const text = n.textContent || '';\n if (text === 'vesk-r:' + id + ':0' || text === 'vesk-r:' + id + ':1') start = n;\n else if (text === 'vesk-r-end:' + id) end = n;\n if (start && end) break;\n }\n if (!start || !end) return;\n const ssrBranch = (start.textContent || '').slice(-2) === ':1' ? 1 : 0;\n if (ssrBranch !== branch) {\n let n = start.nextSibling;\n while (n && n !== end) {\n const next = n.nextSibling;\n n.remove();\n n = next;\n }\n if (walker && walker.retireDetached) walker.retireDetached();\n }\n start.remove();\n end.remove();\n}\n";
53912
54274
  const updateComponentsFn = "function __updateComponents(nodes) {\n for (const n of nodes) {\n if (n._pageName && __components[n._pageName]) n.page = __components[n._pageName];\n if (n._layoutName && __components[n._layoutName]) n.layout = __components[n._layoutName];\n if (n._errorName && __components[n._errorName]) n.error = __components[n._errorName];\n if (n._notFoundName && __components[n._notFoundName]) n.notFound = __components[n._notFoundName];\n if (n._offlineName && __components[n._offlineName]) n.offline = __components[n._offlineName];\n if (n._networkName && __components[n._networkName]) n.network = __components[n._networkName];\n if (n.children) __updateComponents(n.children);\n }\n}\n";
53913
54275
  const routeTreeJson = JSON.stringify(routeTree);
53914
54276
  if (codeSplit) {
53915
54277
  const resolveNamesFn = "function __resolveNames(nodes) {\n for (const n of nodes) {\n if (n.chunk) n._chunk = n.chunk;\n if (n.chunkError) n._chunkError = n.chunkError;\n if (typeof n.page === 'string') n._pageName = n.page;\n if (typeof n.layout === 'string') n._layoutName = n.layout;\n if (typeof n.error === 'string') n._errorName = n.error;\n if (typeof n.notFound === 'string') n._notFoundName = n.notFound;\n if (typeof n.offline === 'string') n._offlineName = n.offline;\n if (typeof n.network === 'string') n._networkName = n.network;\n if (n.children) __resolveNames(n.children);\n }\n}\n";
53916
54278
  const pendCode = "const __pendChunks = [];\nconst __currentPath = typeof window !== 'undefined' ? window.location.pathname : '/';\nif (typeof matchRoute === 'function') {\n const __currentMatch = matchRoute(__routeTree, __currentPath);\n if (__currentMatch) {\n for (const n of __currentMatch.matchChain) {\n if (n._chunk && !__pendChunks.includes(n._chunk)) __pendChunks.push(n._chunk);\n }\n }\n}\n";
53917
- const routerOpts2 = buildRouterOpts({ routeDataCache });
54279
+ const routerOpts2 = buildRouterOpts({ routeDataCache }, hasServerMiddleware(routeTree));
53918
54280
  const startRouterCode = `const __startRouter = function() {
53919
54281
  __updateComponents(__routeTree);
53920
54282
  const __router = createFileRouter(__routeTree${routerOpts2});
@@ -53953,14 +54315,14 @@ if (__pendChunks.length > 0 && typeof ensureChunk === 'function') {
53953
54315
  ];
53954
54316
  const importedSet = new Set(allRuntimeImports);
53955
54317
  const runtimeGlobals2 = globalNames.filter((n) => importedSet.has(n)).map((n) => `globalThis.${n} = ${n};
53956
- `).join("") + "globalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\n\n";
54318
+ `).join("") + "globalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\nglobalThis.__reconcileRegion = __reconcileRegion;\n\n";
53957
54319
  const extraGlobals = [...runtimeImportNames || []].filter((n) => n && n !== "default").map((n) => `globalThis.${n} = ${n};
53958
54320
  `).join("");
53959
54321
  const code2 = preamble + "const __components = globalThis.__components || (globalThis.__components = {});\nconst __hydrators = globalThis.__hydrators || (globalThis.__hydrators = {});\nconst __runtime_comps = __components;\n\n" + runtimeGlobals2 + extraGlobals + // Shared app modules run HERE: after the runtime bindings are published,
53960
54322
  // before anything can request a route chunk. Earlier (at the top of the
53961
54323
  // bundle) `globalThis.track` was still undefined, so every module-scope
53962
54324
  // cell in a store was created against a missing runtime.
53963
- (sharedModuleBundle ? sharedModuleBundle + "\n" : "") + cleanupFn + placeFn + "globalThis.__components = __components;\n" + resolveNamesFn + updateComponentsFn + "const __routeTree = " + routeTreeJson + ";\n__resolveNames(__routeTree);\n" + pendCode + startRouterCode;
54325
+ (sharedModuleBundle ? sharedModuleBundle + "\n" : "") + cleanupFn + placeFn + reconcileRegionFn + "globalThis.__components = __components;\n" + resolveNamesFn + updateComponentsFn + "const __routeTree = " + routeTreeJson + ";\n__resolveNames(__routeTree);\n" + pendCode + startRouterCode;
53964
54326
  return hmr ? appendHmrGlobals(code2) : code2;
53965
54327
  }
53966
54328
  const componentLines = mono?.componentLines || [];
@@ -53969,8 +54331,8 @@ if (__pendChunks.length > 0 && typeof ensureChunk === 'function') {
53969
54331
  const hydratorAliasLines = mono?.hydratorAliasLines || [];
53970
54332
  const aliasCode = aliasLines.length > 0 ? aliasLines.join("\n") + "\n" : "";
53971
54333
  const hydratorAliasCode = hydratorAliasLines.length > 0 ? hydratorAliasLines.join("\n") + "\n" : "";
53972
- const routerOpts = buildRouterOpts({ routeDataCache });
53973
- const code = preamble + "const __components = {};\nconst __hydrators = {};\nconst __runtime_comps = __components;\n\n" + componentLines.join("\n\n") + "\n" + aliasCode + hydratorLines.join("\n\n") + "\n" + hydratorAliasCode + cleanupFn + placeFn + "globalThis.__components = __components;\nglobalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\n" + allRuntimeImports.map((n) => `globalThis.${n} = ${n};
54334
+ const routerOpts = buildRouterOpts({ routeDataCache }, hasServerMiddleware(routeTree));
54335
+ const code = preamble + "const __components = {};\nconst __hydrators = {};\nconst __runtime_comps = __components;\n\n" + componentLines.join("\n\n") + "\n" + aliasCode + hydratorLines.join("\n\n") + "\n" + hydratorAliasCode + cleanupFn + placeFn + reconcileRegionFn + "globalThis.__components = __components;\nglobalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\nglobalThis.__reconcileRegion = __reconcileRegion;\n" + allRuntimeImports.map((n) => `globalThis.${n} = ${n};
53974
54336
  `).join("") + "function __resolveNames(nodes) {\n for (const n of nodes) {\n if (typeof n.page === 'string') {\n n._pageName = n.page;\n n.page = __components[n.page];\n }\n if (typeof n.layout === 'string') {\n n._layoutName = n.layout;\n n.layout = __components[n.layout];\n }\n if (typeof n.error === 'string') n.error = __components[n.error];\n if (typeof n.notFound === 'string') n.notFound = __components[n.notFound];\n if (typeof n.offline === 'string') n.offline = __components[n.offline];\n if (typeof n.network === 'string') n.network = __components[n.network];\n if (n.children) __resolveNames(n.children);\n }\n}\n" + updateComponentsFn + "const __routeTree = " + routeTreeJson + `;
53975
54337
  __resolveNames(__routeTree);
53976
54338
  const __router = createFileRouter(__routeTree${routerOpts});
@@ -54942,6 +55304,41 @@ async function startProdServer(outDir, options) {
54942
55304
  }
54943
55305
  }
54944
55306
  }
55307
+ if (url.pathname === "/_vesk/middleware" && middlewareMod) {
55308
+ const targetPath = url.searchParams.get("path") || "/";
55309
+ const targetUrl = new URL(targetPath, url.origin);
55310
+ const middlewareRequest = new Request(targetUrl.href, {
55311
+ method: "GET",
55312
+ headers: req.headers
55313
+ });
55314
+ const mwEndpointCtx = {
55315
+ request: middlewareRequest,
55316
+ params: {},
55317
+ url: targetUrl,
55318
+ locals: Object.assign({}, globalThis.__vesk_server_ctx || {}),
55319
+ cookies: {},
55320
+ set(key, value) {
55321
+ this.locals[key] = value;
55322
+ },
55323
+ get(key) {
55324
+ return this.locals[key];
55325
+ }
55326
+ };
55327
+ const mwResult = await middlewareMod.execute(mwEndpointCtx);
55328
+ res.writeHead(200, {
55329
+ "Content-Type": "application/json; charset=utf-8",
55330
+ "Cache-Control": "no-store"
55331
+ });
55332
+ if (mwResult.response) {
55333
+ const location = mwResult.response.headers.get("location") || mwResult.response.headers.get("Location");
55334
+ if (location) {
55335
+ res.end(JSON.stringify({ redirect: location }));
55336
+ return;
55337
+ }
55338
+ }
55339
+ res.end(JSON.stringify(mwResult.rewriteUrl ? { rewrite: mwResult.rewriteUrl } : { allow: true }));
55340
+ return;
55341
+ }
54945
55342
  let mwCtx;
54946
55343
  const serverStore = globalThis.__vesk_server_ctx;
54947
55344
  if (middlewareMod) {
@@ -54991,186 +55388,191 @@ async function startProdServer(outDir, options) {
54991
55388
  url.pathname = mwResult.rewriteUrl;
54992
55389
  }
54993
55390
  }
55391
+ const __outerRequest = globalThis.__vesk_request;
54994
55392
  globalThis.__vesk_request = mwCtx;
54995
- if (url.pathname.startsWith("/_vesk/action/")) {
54996
- const actionId = url.pathname.replace("/_vesk/action/", "");
54997
- const actionEntry = buildConfig.actions && buildConfig.actions.find((a) => a.id === actionId);
54998
- if (!actionEntry) {
54999
- res.writeHead(404, { "Content-Type": "application/json" });
55000
- res.end(JSON.stringify({ ok: false, error: "Action not found" }));
55001
- return;
55002
- }
55003
- const mod = await loadFunction(actionEntry.function);
55004
- if (!mod || !mod.handleAction) {
55005
- res.writeHead(404, { "Content-Type": "application/json" });
55006
- res.end(JSON.stringify({ ok: false, error: "Action not found" }));
55393
+ try {
55394
+ if (url.pathname.startsWith("/_vesk/action/")) {
55395
+ const actionId = url.pathname.replace("/_vesk/action/", "");
55396
+ const actionEntry = buildConfig.actions && buildConfig.actions.find((a) => a.id === actionId);
55397
+ if (!actionEntry) {
55398
+ res.writeHead(404, { "Content-Type": "application/json" });
55399
+ res.end(JSON.stringify({ ok: false, error: "Action not found" }));
55400
+ return;
55401
+ }
55402
+ const mod = await loadFunction(actionEntry.function);
55403
+ if (!mod || !mod.handleAction) {
55404
+ res.writeHead(404, { "Content-Type": "application/json" });
55405
+ res.end(JSON.stringify({ ok: false, error: "Action not found" }));
55406
+ return;
55407
+ }
55408
+ try {
55409
+ const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
55410
+ const handleAction = mod.handleAction.bind(mod);
55411
+ const response = await withSecurityScope(() => handleAction(webRequest, actionId));
55412
+ await deliverResponse(res, response);
55413
+ } catch (e) {
55414
+ const status = errorStatus(e, 500);
55415
+ const message = status === 500 && process.env.NODE_ENV === "production" ? "Internal Server Error" : e instanceof Error ? e.message : String(e);
55416
+ res.writeHead(status, { "Content-Type": "application/json" });
55417
+ res.end(JSON.stringify({ ok: false, error: message }));
55418
+ }
55007
55419
  return;
55008
55420
  }
55009
- try {
55010
- const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
55011
- const handleAction = mod.handleAction.bind(mod);
55012
- const response = await withSecurityScope(() => handleAction(webRequest, actionId));
55013
- await deliverResponse(res, response);
55014
- } catch (e) {
55015
- const status = errorStatus(e, 500);
55016
- const message = status === 500 && process.env.NODE_ENV === "production" ? "Internal Server Error" : e instanceof Error ? e.message : String(e);
55017
- res.writeHead(status, { "Content-Type": "application/json" });
55018
- res.end(JSON.stringify({ ok: false, error: message }));
55019
- }
55020
- return;
55021
- }
55022
- if (url.pathname.startsWith("/api")) {
55023
- for (const route of buildConfig.routes) {
55024
- if (route.type === "api") {
55025
- const params = matchPath(route.path, url.pathname);
55026
- if (params) {
55027
- const mod = await loadFunction(route.function);
55028
- if (!mod) {
55029
- if (functionFailure(route.function)) {
55030
- res.writeHead(500, { "Content-Type": "application/json" });
55031
- res.end(JSON.stringify({ error: "Internal Server Error" }));
55421
+ if (url.pathname.startsWith("/api")) {
55422
+ for (const route of buildConfig.routes) {
55423
+ if (route.type === "api") {
55424
+ const params = matchPath(route.path, url.pathname);
55425
+ if (params) {
55426
+ const mod = await loadFunction(route.function);
55427
+ if (!mod) {
55428
+ if (functionFailure(route.function)) {
55429
+ res.writeHead(500, { "Content-Type": "application/json" });
55430
+ res.end(JSON.stringify({ error: "Internal Server Error" }));
55431
+ return;
55432
+ }
55433
+ continue;
55434
+ }
55435
+ try {
55436
+ const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
55437
+ const response = await withSecurityScope(() => mod.handle(webRequest));
55438
+ await deliverResponse(res, response);
55439
+ return;
55440
+ } catch (e) {
55441
+ const status = errorStatus(e, 500);
55442
+ res.writeHead(status, { "Content-Type": "application/json" });
55443
+ res.end(JSON.stringify({ error: status === 500 ? "Internal Server Error" : e instanceof Error ? e.message : String(e) }));
55032
55444
  return;
55033
55445
  }
55034
- continue;
55035
- }
55036
- try {
55037
- const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
55038
- const response = await withSecurityScope(() => mod.handle(webRequest));
55039
- await deliverResponse(res, response);
55040
- return;
55041
- } catch (e) {
55042
- const status = errorStatus(e, 500);
55043
- res.writeHead(status, { "Content-Type": "application/json" });
55044
- res.end(JSON.stringify({ error: status === 500 ? "Internal Server Error" : e instanceof Error ? e.message : String(e) }));
55045
- return;
55046
55446
  }
55047
55447
  }
55048
55448
  }
55049
55449
  }
55050
- }
55051
- const appDir = resolve14(projectDir, "app");
55052
- const pageCssUrls = resolveCssUrls({
55053
- enabled: hasBuiltGlobalCss(outDir)
55054
- });
55055
- const boundaryCache = /* @__PURE__ */ new Map();
55056
- async function renderBoundaryFile(file, pathname, props) {
55057
- const boundaryPath = resolveBoundaryFileForUrl(pathname, appDir, file);
55058
- if (!boundaryPath) return null;
55059
- const key = `${file}:${boundaryPath}`;
55060
- let html = boundaryCache.has(key) ? boundaryCache.get(key) : null;
55061
- if (html === null) {
55062
- try {
55063
- const runtimePath = resolve14(outDir, "server", "runtime.js");
55064
- const { renderFullPage: renderFullPage2, storeDataScriptGlobal } = await import(runtimePath);
55065
- const src2 = readFileSync18(boundaryPath, "utf-8");
55066
- const compName = resolveComponentName(src2) || (file === "error.vsk" ? "Error" : "NotFound");
55067
- html = await renderFullPage2(src2, compName, props, /* @__PURE__ */ new Map(), { hydrate: true, cssUrls: pageCssUrls, clientScriptUrl: buildConfig?.assets?.client?.url || "/_vesk/static/client.js", clientScriptIntegrity: buildConfig?.assets?.client?.integrity, security: securityConfig?.security || {}, externalDataScript: storeDataScriptGlobal, sourcePath: boundaryPath, headExtra: bakedHeadExtra });
55068
- } catch {
55069
- return null;
55450
+ const appDir = resolve14(projectDir, "app");
55451
+ const pageCssUrls = resolveCssUrls({
55452
+ enabled: hasBuiltGlobalCss(outDir)
55453
+ });
55454
+ const boundaryCache = /* @__PURE__ */ new Map();
55455
+ async function renderBoundaryFile(file, pathname, props) {
55456
+ const boundaryPath = resolveBoundaryFileForUrl(pathname, appDir, file);
55457
+ if (!boundaryPath) return null;
55458
+ const key = `${file}:${boundaryPath}`;
55459
+ let html = boundaryCache.has(key) ? boundaryCache.get(key) : null;
55460
+ if (html === null) {
55461
+ try {
55462
+ const runtimePath = resolve14(outDir, "server", "runtime.js");
55463
+ const { renderFullPage: renderFullPage2, storeDataScriptGlobal } = await import(runtimePath);
55464
+ const src2 = readFileSync18(boundaryPath, "utf-8");
55465
+ const compName = resolveComponentName(src2) || (file === "error.vsk" ? "Error" : "NotFound");
55466
+ html = await renderFullPage2(src2, compName, props, /* @__PURE__ */ new Map(), { hydrate: true, cssUrls: pageCssUrls, clientScriptUrl: buildConfig?.assets?.client?.url || "/_vesk/static/client.js", clientScriptIntegrity: buildConfig?.assets?.client?.integrity, security: securityConfig?.security || {}, externalDataScript: storeDataScriptGlobal, sourcePath: boundaryPath, headExtra: bakedHeadExtra });
55467
+ } catch {
55468
+ return null;
55469
+ }
55070
55470
  }
55471
+ return html;
55071
55472
  }
55072
- return html;
55073
- }
55074
- let notFoundHtml = null;
55075
- {
55076
- const rendered = await renderBoundaryFile("not-found.vsk", url.pathname, { params: {}, url: url.pathname });
55077
- notFoundHtml = rendered;
55078
- }
55079
- for (const route of buildConfig.routes) {
55080
- if (route.type === "ssr") {
55081
- const params = matchPath(route.path, url.pathname);
55082
- if (params) {
55083
- const mod = await loadFunction(route.function);
55084
- if (mod) {
55085
- const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
55086
- const origin = new URL(url.href).origin;
55087
- const origFetch = globalThis.fetch;
55088
- globalThis.fetch = async (input, init) => {
55089
- if (typeof input === "string" && input.startsWith("/")) {
55090
- input = origin + input;
55091
- }
55092
- return origFetch(input, init);
55093
- };
55094
- try {
55095
- let cachedResult = null;
55096
- if (route.revalidate && route.revalidate > 0) {
55097
- const { pageIsr: pageIsr2 } = await Promise.resolve().then(() => (init_index_server(), index_server_exports));
55098
- cachedResult = await pageIsr2(url.pathname, async () => {
55099
- const response2 = await withSecurityScope(() => mod.handle(webRequest));
55100
- return { html: await response2.text(), headers: Object.fromEntries(response2.headers) };
55101
- }, { revalidate: route.revalidate, tags: route.tags || [] });
55102
- }
55103
- if (cachedResult) {
55104
- res.writeHead(200, cachedResult.headers || { "Content-Type": "text/html" });
55105
- res.end(cachedResult.html);
55106
- return;
55107
- }
55108
- const response = await withSecurityScope(() => mod.handle(webRequest));
55109
- const headers2 = Object.fromEntries(response.headers);
55110
- if (!headers2["content-type"] && !headers2["Content-Type"]) headers2["Content-Type"] = "text/html";
55111
- if (response.body && typeof response.body.getReader === "function") {
55112
- res.writeHead(response.status, headers2);
55113
- const reader = response.body.getReader();
55114
- const pump = () => {
55115
- reader.read().then(({ done, value }) => {
55116
- if (done) {
55117
- res.end();
55118
- return;
55119
- }
55120
- res.write(value);
55121
- pump();
55122
- }).catch(() => res.end());
55123
- };
55124
- pump();
55125
- } else {
55126
- const body = await response.text();
55127
- res.writeHead(response.status, headers2);
55128
- res.end(body);
55129
- }
55130
- return;
55131
- } catch (e) {
55132
- const err = e instanceof Error ? e : new Error(String(e));
55133
- if (err.name === "Redirect") {
55134
- const redirect2 = err;
55135
- res.writeHead(Number(redirect2.status) || 302, { Location: typeof redirect2.url === "string" ? redirect2.url : "/" });
55136
- res.end();
55473
+ let notFoundHtml = null;
55474
+ {
55475
+ const rendered = await renderBoundaryFile("not-found.vsk", url.pathname, { params: {}, url: url.pathname });
55476
+ notFoundHtml = rendered;
55477
+ }
55478
+ for (const route of buildConfig.routes) {
55479
+ if (route.type === "ssr") {
55480
+ const params = matchPath(route.path, url.pathname);
55481
+ if (params) {
55482
+ const mod = await loadFunction(route.function);
55483
+ if (mod) {
55484
+ const webRequest = makeWebRequest(req, url.href, maxBodyBytes);
55485
+ const origin = new URL(url.href).origin;
55486
+ const origFetch = globalThis.fetch;
55487
+ globalThis.fetch = async (input, init) => {
55488
+ if (typeof input === "string" && input.startsWith("/")) {
55489
+ input = origin + input;
55490
+ }
55491
+ return origFetch(input, init);
55492
+ };
55493
+ try {
55494
+ let cachedResult = null;
55495
+ if (route.revalidate && route.revalidate > 0) {
55496
+ const { pageIsr: pageIsr2 } = await Promise.resolve().then(() => (init_index_server(), index_server_exports));
55497
+ cachedResult = await pageIsr2(url.pathname, async () => {
55498
+ const response2 = await withSecurityScope(() => mod.handle(webRequest));
55499
+ return { html: await response2.text(), headers: Object.fromEntries(response2.headers) };
55500
+ }, { revalidate: route.revalidate, tags: route.tags || [] });
55501
+ }
55502
+ if (cachedResult) {
55503
+ res.writeHead(200, cachedResult.headers || { "Content-Type": "text/html" });
55504
+ res.end(cachedResult.html);
55505
+ return;
55506
+ }
55507
+ const response = await withSecurityScope(() => mod.handle(webRequest));
55508
+ const headers2 = Object.fromEntries(response.headers);
55509
+ if (!headers2["content-type"] && !headers2["Content-Type"]) headers2["Content-Type"] = "text/html";
55510
+ if (response.body && typeof response.body.getReader === "function") {
55511
+ res.writeHead(response.status, headers2);
55512
+ const reader = response.body.getReader();
55513
+ const pump = () => {
55514
+ reader.read().then(({ done, value }) => {
55515
+ if (done) {
55516
+ res.end();
55517
+ return;
55518
+ }
55519
+ res.write(value);
55520
+ pump();
55521
+ }).catch(() => res.end());
55522
+ };
55523
+ pump();
55524
+ } else {
55525
+ const body = await response.text();
55526
+ res.writeHead(response.status, headers2);
55527
+ res.end(body);
55528
+ }
55137
55529
  return;
55138
- }
55139
- if (err.name === "NotFoundError") {
55140
- res.writeHead(404, { "Content-Type": "text/html" });
55141
- res.end(notFoundHtml || renderDefaultNotFoundPage({ url: url.pathname, headExtra: bakedHeadExtra }));
55530
+ } catch (e) {
55531
+ const err = e instanceof Error ? e : new Error(String(e));
55532
+ if (err.name === "Redirect") {
55533
+ const redirect2 = err;
55534
+ res.writeHead(Number(redirect2.status) || 302, { Location: typeof redirect2.url === "string" ? redirect2.url : "/" });
55535
+ res.end();
55536
+ return;
55537
+ }
55538
+ if (err.name === "NotFoundError") {
55539
+ res.writeHead(404, { "Content-Type": "text/html" });
55540
+ res.end(notFoundHtml || renderDefaultNotFoundPage({ url: url.pathname, headExtra: bakedHeadExtra }));
55541
+ return;
55542
+ }
55543
+ console.error("vesk ssr error:", err.message);
55544
+ await reportServerError(err, {
55545
+ url: url.pathname + url.search,
55546
+ routePath: route.path,
55547
+ target: "node",
55548
+ status: 500,
55549
+ buildConfig
55550
+ });
55551
+ if (eventsMod) {
55552
+ await executeError(err, { url: url.href, routePath: route.path, target: "node", status: 500 }, eventsMod);
55553
+ }
55554
+ const expose = process.env.NODE_ENV !== "production";
55555
+ const errorHtml = await renderBoundaryFile("error.vsk", url.pathname, {
55556
+ error: expose ? err.message : "Internal Server Error",
55557
+ stack: expose ? err.stack : "",
55558
+ statusCode: 500,
55559
+ url: url.pathname
55560
+ });
55561
+ res.writeHead(500, { "Content-Type": "text/html" });
55562
+ res.end(errorHtml || renderDefaultErrorPage({ message: process.env.NODE_ENV !== "production" ? err.message : void 0, url: url.pathname, headExtra: bakedHeadExtra }));
55142
55563
  return;
55564
+ } finally {
55565
+ globalThis.fetch = origFetch;
55143
55566
  }
55144
- console.error("vesk ssr error:", err.message);
55145
- await reportServerError(err, {
55146
- url: url.pathname + url.search,
55147
- routePath: route.path,
55148
- target: "node",
55149
- status: 500,
55150
- buildConfig
55151
- });
55152
- if (eventsMod) {
55153
- await executeError(err, { url: url.href, routePath: route.path, target: "node", status: 500 }, eventsMod);
55154
- }
55155
- const expose = process.env.NODE_ENV !== "production";
55156
- const errorHtml = await renderBoundaryFile("error.vsk", url.pathname, {
55157
- error: expose ? err.message : "Internal Server Error",
55158
- stack: expose ? err.stack : "",
55159
- statusCode: 500,
55160
- url: url.pathname
55161
- });
55162
- res.writeHead(500, { "Content-Type": "text/html" });
55163
- res.end(errorHtml || renderDefaultErrorPage({ message: process.env.NODE_ENV !== "production" ? err.message : void 0, url: url.pathname, headExtra: bakedHeadExtra }));
55164
- return;
55165
- } finally {
55166
- globalThis.fetch = origFetch;
55167
55567
  }
55168
55568
  }
55169
55569
  }
55170
55570
  }
55571
+ res.writeHead(404, { "Content-Type": "text/html" });
55572
+ res.end(notFoundHtml || renderDefaultNotFoundPage({ url: url.pathname, headExtra: bakedHeadExtra }));
55573
+ } finally {
55574
+ globalThis.__vesk_request = __outerRequest;
55171
55575
  }
55172
- res.writeHead(404, { "Content-Type": "text/html" });
55173
- res.end(notFoundHtml || renderDefaultNotFoundPage({ url: url.pathname, headExtra: bakedHeadExtra }));
55174
55576
  });
55175
55577
  try {
55176
55578
  await eventsMod?.executeStart?.({ server, port, host });
@@ -56403,6 +56805,10 @@ var Ctx2 = class {
56403
56805
  markerless = true;
56404
56806
  inTryBody = false;
56405
56807
  claimStatic = false;
56808
+ // Markerless only: the next real claim carries a compiler-generated static
56809
+ // class descriptor so a same-tag but structurally different SSR slot is
56810
+ // substituted instead of adopted (e.g. an empty-state <div> vs a list <div>).
56811
+ descriptorClaim = false;
56406
56812
  // While set, the next StaticNode claimed in hydrate mode uses `__root` (the
56407
56813
  // item element already claimed by key) instead of walking for a new element.
56408
56814
  rootClaim = false;
@@ -56592,6 +56998,18 @@ var PROPERTY_ATTRS2 = {
56592
56998
  option: /* @__PURE__ */ new Set(["selected"]),
56593
56999
  progress: /* @__PURE__ */ new Set(["value"])
56594
57000
  };
57001
+ function staticClassDescriptor2(node) {
57002
+ const hasDynamicClass = node.children.some((child) => child instanceof DynamicBinding && child.kind === "attribute" && child.target === "class");
57003
+ if (hasDynamicClass)
57004
+ return null;
57005
+ const attr = node.attributes.find((a) => a.name === "class");
57006
+ if (!attr)
57007
+ return null;
57008
+ const value = attr.value.trim();
57009
+ if (!value)
57010
+ return null;
57011
+ return JSON.stringify({ class: value });
57012
+ }
56595
57013
  function emitStatic2(ctx2, node, tracked2, effectsVar, skipK = 0, regionBudget) {
56596
57014
  const el = ctx2.n();
56597
57015
  if (ctx2.hydrate) {
@@ -56603,7 +57021,11 @@ function emitStatic2(ctx2, node, tracked2, effectsVar, skipK = 0, regionBudget)
56603
57021
  ctx2.rootClaim = false;
56604
57022
  const skipExpr = regionBudget && ctx2.markerless ? markerlessSkipExpr2(regionBudget, skipK) : skipK;
56605
57023
  const skipArg = ctx2.markerless ? `, ${skipExpr}` : "";
56606
- const claimedExpr = rootClaim ? `__root || document.createElement(${JSON.stringify(node.tag)})` : `${ctx2.walker}.nextElement(${JSON.stringify(node.tag)}${skipArg})`;
57024
+ const wantsDescriptor = ctx2.markerless && ctx2.descriptorClaim;
57025
+ ctx2.descriptorClaim = false;
57026
+ const descriptor = wantsDescriptor && !rootClaim ? staticClassDescriptor2(node) : null;
57027
+ const descriptorArg = descriptor ? `, ${descriptor}` : "";
57028
+ const claimedExpr = rootClaim ? `__root || document.createElement(${JSON.stringify(node.tag)})` : `${ctx2.walker}.nextElement(${JSON.stringify(node.tag)}${skipArg}${descriptorArg})`;
56607
57029
  ctx2.push(`const ${el} = ${claimedExpr};`);
56608
57030
  if (regionBudget && ctx2.markerless)
56609
57031
  ctx2.push(`${regionBudget} = 0;`);
@@ -57046,6 +57468,7 @@ function emitComponentCall2(ctx2, node, tracked2, effectsVar, parentVar, compPre
57046
57468
  }
57047
57469
  const callArgs = () => plainTarget ? `reactiveProps({ ${propsEntries.join(", ")} })` : `{ ${propsEntries.join(", ")} }`;
57048
57470
  if (ctx2.hydrate) {
57471
+ ctx2.descriptorClaim = false;
57049
57472
  const access = calleeExpr ?? (ctx2.importedNames.has(node.componentName) ? node.componentName : `${ctx2.hydrateRegistry}[${JSON.stringify(node.componentName)}]`);
57050
57473
  if (!calleeExpr && !ctx2.importedNames.has(node.componentName)) {
57051
57474
  ctx2.push(`if (${access} == null) throw new Error(${JSON.stringify(`Component "${node.componentName}" was not found while rendering. Declare it with the \`component\` keyword, import it, or register it in the component registry.`)});`);
@@ -57287,13 +57710,14 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57287
57710
  const hyd = ctx2.hydrate;
57288
57711
  const parent = parentVar || "$root";
57289
57712
  const budget = hyd ? regionBudgetVar2(ctx2, skipK, regionBudget) : null;
57713
+ const rid = regionMarkerId(node);
57290
57714
  const isOpaque = (n) => !!n && typeof n.condition !== "undefined";
57291
57715
  if (hyd && node.alternateNodes.length === 1 && isOpaque(node.alternateNodes[0])) {
57292
57716
  const chain = [];
57293
57717
  let cur = node;
57294
57718
  let finalElse = null;
57295
57719
  while (cur) {
57296
- chain.push({ cond: transformTracked2(cur.condition, tracked2), nodes: cur.consequentNodes });
57720
+ chain.push({ cond: transformTracked2(cur.condition, tracked2), nodes: cur.consequentNodes, id: regionMarkerId(cur) });
57297
57721
  if (cur.alternateNodes.length === 1 && isOpaque(cur.alternateNodes[0])) {
57298
57722
  cur = cur.alternateNodes[0];
57299
57723
  } else {
@@ -57317,6 +57741,9 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57317
57741
  ctx2.push(`const ${rn} = ${fnOpen2}`);
57318
57742
  const cl = ctx2.n();
57319
57743
  ctx2.push(indent3(`const ${cl} = [];`));
57744
+ const savedDescriptor = ctx2.descriptorClaim;
57745
+ if (hyd && ctx2.markerless)
57746
+ ctx2.descriptorClaim = true;
57320
57747
  for (const n of chain[i].nodes) {
57321
57748
  const savedClaim = ctx2.claimStatic;
57322
57749
  if (hyd)
@@ -57326,6 +57753,7 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57326
57753
  if (v)
57327
57754
  ctx2.push(indent3(`${cl}.push(${v});`));
57328
57755
  }
57756
+ ctx2.descriptorClaim = savedDescriptor;
57329
57757
  ctx2.push(indent3(`__place(${anchor2}, ${endAnchor2}, ${cl}, ${parent});`));
57330
57758
  ctx2.push(`};`);
57331
57759
  }
@@ -57335,6 +57763,9 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57335
57763
  ctx2.push(`const ${finalRender} = ${fnOpen2}`);
57336
57764
  const cl2 = ctx2.n();
57337
57765
  ctx2.push(indent3(`const ${cl2} = [];`));
57766
+ const savedDescriptor = ctx2.descriptorClaim;
57767
+ if (hyd && ctx2.markerless)
57768
+ ctx2.descriptorClaim = true;
57338
57769
  for (const n of finalElse) {
57339
57770
  const savedClaim = ctx2.claimStatic;
57340
57771
  if (hyd)
@@ -57344,27 +57775,39 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57344
57775
  if (v)
57345
57776
  ctx2.push(indent3(`${cl2}.push(${v});`));
57346
57777
  }
57778
+ ctx2.descriptorClaim = savedDescriptor;
57347
57779
  ctx2.push(indent3(`__place(${anchor2}, ${endAnchor2}, ${cl2}, ${parent});`));
57348
57780
  ctx2.push(`};`);
57349
57781
  }
57350
- let init = `if (${chain[0].cond}) { ${asyncKw2}${renderNames[0]}(); }`;
57351
- for (let i = 1; i < chain.length; i++)
57352
- init += ` else if (${chain[i].cond}) { ${asyncKw2}${renderNames[i]}(); }`;
57353
- if (finalRender)
57354
- init += ` else { ${asyncKw2}${finalRender}(); }`;
57355
- ctx2.push(init);
57356
57782
  let branchInitFallback = finalRender ? `${chain.length}` : "-1";
57357
57783
  for (let i = chain.length - 1; i >= 0; i--) {
57358
57784
  branchInitFallback = `(${chain[i].cond} ? ${i} : ${branchInitFallback})`;
57359
57785
  }
57360
57786
  const branchInit = `(${branchInitFallback})`;
57787
+ const branchSnapshot = ctx2.n();
57788
+ ctx2.push(`const ${branchSnapshot} = ${branchInit};`);
57789
+ if (!ctx2.markerless) {
57790
+ for (let i = 0; i < chain.length; i++) {
57791
+ ctx2.push(`if (__hydrate) __reconcileRegion(${parent}, '${chain[i].id}', ${branchSnapshot} === ${i} ? 0 : 1, ${ctx2.walker});`);
57792
+ }
57793
+ } else {
57794
+ const chainBranches = chain.map((c) => c.nodes);
57795
+ if (finalElse)
57796
+ chainBranches.push(finalElse);
57797
+ emitStructuralRegionDiscard2(ctx2, chainBranches, branchSnapshot, budget);
57798
+ }
57799
+ let init = `if (${branchSnapshot} === 0) { ${asyncKw2}${renderNames[0]}(); }`;
57800
+ for (let i = 1; i < chain.length; i++)
57801
+ init += ` else if (${branchSnapshot} === ${i}) { ${asyncKw2}${renderNames[i]}(); }`;
57802
+ if (finalRender)
57803
+ init += ` else { ${asyncKw2}${finalRender}(); }`;
57804
+ ctx2.push(init);
57361
57805
  let effInner = `if (__new === 0) { ${asyncKw2}${renderNames[0]}(); }`;
57362
57806
  for (let i = 1; i < chain.length; i++)
57363
57807
  effInner += ` else if (__new === ${i}) { ${asyncKw2}${renderNames[i]}(); }`;
57364
57808
  if (finalRender)
57365
57809
  effInner += ` else { ${asyncKw2}${finalRender}(); }`;
57366
57810
  const effBody = `effect(${ctx2.isAsyncScope ? "async () => {" : "() => {"}
57367
- if (__first) { __first = false; __iv = ${branchInit}; return; }
57368
57811
  const __new = ${branchInit};
57369
57812
  if (__new !== __iv) {
57370
57813
  for (const e of ${effectsVar2}) destroy_block(e);
@@ -57376,14 +57819,12 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57376
57819
  }, true);`;
57377
57820
  if (effTarget) {
57378
57821
  ctx2.push(`${effTarget}.push((() => {
57379
- let __iv = ${branchInit};
57380
- let __first = true;
57822
+ let __iv = ${branchSnapshot};
57381
57823
  return ${effBody}
57382
57824
  })());`);
57383
57825
  } else {
57384
57826
  ctx2.effects.push(`{
57385
- let __iv = ${branchInit};
57386
- let __first = true;
57827
+ let __iv = ${branchSnapshot};
57387
57828
  ${effBody}
57388
57829
  }`);
57389
57830
  }
@@ -57411,6 +57852,9 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57411
57852
  ctx2.push(indent3(`const ${conFrag} = document.createDocumentFragment();`));
57412
57853
  if (hyd)
57413
57854
  ctx2.push(indent3(`const __cl = [];`));
57855
+ const savedConDescriptor = ctx2.descriptorClaim;
57856
+ if (hyd && ctx2.markerless)
57857
+ ctx2.descriptorClaim = true;
57414
57858
  for (const n of node.consequentNodes) {
57415
57859
  const savedClaim = ctx2.claimStatic;
57416
57860
  if (hyd)
@@ -57424,6 +57868,7 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57424
57868
  ctx2.push(indent3(`${conFrag}.appendChild(${v});`));
57425
57869
  }
57426
57870
  }
57871
+ ctx2.descriptorClaim = savedConDescriptor;
57427
57872
  if (hyd)
57428
57873
  ctx2.push(indent3(`__place(${anchor}, ${endAnchor}, __cl, ${parent});`));
57429
57874
  else
@@ -57440,6 +57885,9 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57440
57885
  ctx2.push(indent3(`const ${altFrag} = document.createDocumentFragment();`));
57441
57886
  if (hyd)
57442
57887
  ctx2.push(indent3(`const __cl = [];`));
57888
+ const savedAltDescriptor = ctx2.descriptorClaim;
57889
+ if (hyd && ctx2.markerless)
57890
+ ctx2.descriptorClaim = true;
57443
57891
  for (const n of node.alternateNodes) {
57444
57892
  const savedAltClaim = ctx2.claimStatic;
57445
57893
  if (hyd)
@@ -57453,6 +57901,7 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57453
57901
  ctx2.push(indent3(`${altFrag}.appendChild(${v});`));
57454
57902
  }
57455
57903
  }
57904
+ ctx2.descriptorClaim = savedAltDescriptor;
57456
57905
  if (hyd)
57457
57906
  ctx2.push(indent3(`__place(${anchor}, ${endAnchor}, __cl, ${parent});`));
57458
57907
  else
@@ -57461,10 +57910,15 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57461
57910
  }
57462
57911
  if (!hyd)
57463
57912
  ctx2.push(`${parent}.appendChild(${endAnchor});`);
57464
- ctx2.push(`if (${condExpr}) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : ""));
57913
+ const condSnapshot = ctx2.n();
57914
+ ctx2.push(`const ${condSnapshot} = ${condExpr};`);
57915
+ if (hyd && !ctx2.markerless)
57916
+ ctx2.push(`if (__hydrate) __reconcileRegion(${parent}, '${rid}', ${condSnapshot} ? 0 : 1, ${ctx2.walker});`);
57917
+ if (hyd && ctx2.markerless)
57918
+ emitStructuralRegionDiscard2(ctx2, [node.consequentNodes, node.alternateNodes], hasElse ? `(${condSnapshot} ? 0 : 1)` : `(${condSnapshot} ? 0 : -1)`, budget);
57919
+ ctx2.push(`if (${condSnapshot}) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : ""));
57465
57920
  const renderBranch = `if (__nv) { ${asyncKw}${conRenderName}(); }` + (hasElse ? ` else { ${asyncKw}${altRenderName}(); }` : "");
57466
57921
  const effectBody = `effect(${ctx2.isAsyncScope ? "async () => {" : "() => {"}
57467
- if (__first) { __first = false; __iv = ${condExpr}; return; }
57468
57922
  const __nv = ${condExpr};
57469
57923
  if (__nv !== __iv) {
57470
57924
  for (const e of ${effectsVar}) destroy_block(e);
@@ -57478,14 +57932,12 @@ function emitOpaque2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regi
57478
57932
  return null;
57479
57933
  if (effTarget) {
57480
57934
  ctx2.push(`${effTarget}.push((() => {
57481
- let __iv = ${condExpr};
57482
- let __first = true;
57935
+ let __iv = ${condSnapshot};
57483
57936
  return ${effectBody}
57484
57937
  })());`);
57485
57938
  } else {
57486
57939
  ctx2.effects.push(`{
57487
- let __iv = ${condExpr};
57488
- let __first = true;
57940
+ let __iv = ${condSnapshot};
57489
57941
  ${effectBody}
57490
57942
  }`);
57491
57943
  }
@@ -57920,29 +58372,26 @@ function emitMap2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionB
57920
58372
  let emptyRenderName = null;
57921
58373
  if (node.alternateNodes.length > 0) {
57922
58374
  emptyRenderName = ctx2.n();
57923
- const emptySig = !hyd ? ctx2.isAsyncScope ? "async () => {" : "() => {" : ctx2.isAsyncScope ? "async (__cl) => {" : "(__cl) => {";
58375
+ const emptyClaims = ctx2.hydrate;
58376
+ const emptySig = !emptyClaims ? ctx2.isAsyncScope ? "async () => {" : "() => {" : ctx2.isAsyncScope ? "async (__cl) => {" : "(__cl) => {";
57924
58377
  ctx2.push(`const ${emptyRenderName} = ${emptySig}`);
57925
58378
  ctx2.push(indent3(`const __p = ${anchor}.parentNode;`));
57926
58379
  const frag = ctx2.n();
57927
- if (!hyd)
58380
+ if (!emptyClaims)
57928
58381
  ctx2.push(indent3(`const ${frag} = document.createDocumentFragment();`));
57929
58382
  const savedClaim = ctx2.claimStatic;
57930
- const savedHydrate = ctx2.hydrate;
57931
- if (hydKeyed)
57932
- ctx2.hydrate = false;
57933
58383
  for (const n of node.alternateNodes) {
57934
58384
  ctx2.claimStatic = true;
57935
- const v = emitNode2(ctx2, n, tracked2, effectsVar, hyd ? void 0 : frag, "__components", 0, budget || void 0);
58385
+ const v = emitNode2(ctx2, n, tracked2, effectsVar, emptyClaims ? void 0 : frag, "__components", 0, budget || void 0);
57936
58386
  if (v) {
57937
- if (hyd)
58387
+ if (emptyClaims)
57938
58388
  ctx2.push(indent3(`if (__cl) __cl.push(${v}); else __p.insertBefore(${v}, ${endAnchor});`));
57939
58389
  else
57940
58390
  ctx2.push(indent3(`${frag}.appendChild(${v});`));
57941
58391
  }
57942
58392
  }
57943
58393
  ctx2.claimStatic = savedClaim;
57944
- ctx2.hydrate = savedHydrate;
57945
- if (!hyd)
58394
+ if (!emptyClaims)
57946
58395
  ctx2.push(indent3(`if (${frag}.childNodes.length > 0) __p.insertBefore(${frag}, ${endAnchor});`));
57947
58396
  ctx2.push(`};`);
57948
58397
  }
@@ -57964,8 +58413,13 @@ function emitMap2(ctx2, node, tracked2, effTarget, parentVar, skipK = 0, regionB
57964
58413
  }
57965
58414
  if (emptyRenderName) {
57966
58415
  const isEmptyVar = ctx2.n();
58416
+ const collectVar = hydKeyed ? ctx2.n() : null;
57967
58417
  ctx2.push(`let ${isEmptyVar} = !${hasItems}();`);
57968
- ctx2.push(`if (!${isEmptyVar}) { ${initList}(); } else { ${aw}${emptyRenderName}(); }`);
58418
+ if (collectVar)
58419
+ ctx2.push(`const ${collectVar} = [];`);
58420
+ ctx2.push(`if (!${isEmptyVar}) { ${initList}(); } else { ${aw}${emptyRenderName}(${collectVar || ""}); }`);
58421
+ if (collectVar)
58422
+ ctx2.push(`__place(${anchor}, ${endAnchor}, ${collectVar}, ${parent});`);
57969
58423
  if (!reactiveSource)
57970
58424
  return null;
57971
58425
  pushEffect(`let __first = true;`, `effect(${effOpen}
@@ -58044,7 +58498,7 @@ ${renderAllItems(" ", null)}
58044
58498
  __cleanup(${anchor}, ${endAnchor});
58045
58499
  if (__new) {
58046
58500
  ${renderAllItems(" ", null)}
58047
- } else { ${aw}${emptyRenderName}(${collectVar ? collectVar : ""}); }
58501
+ } else { ${aw}${emptyRenderName}(); }
58048
58502
  }, true)`);
58049
58503
  } else {
58050
58504
  const collectVar = hyd ? ctx2.n() : null;
@@ -58137,6 +58591,8 @@ function generateComponent2(comp, importedNames = /* @__PURE__ */ new Set(), hyd
58137
58591
  }
58138
58592
  }
58139
58593
  }
58594
+ if (ctx2.hydrate && ctx2.markerless)
58595
+ ctx2.descriptorClaim = true;
58140
58596
  for (const node of comp.body) {
58141
58597
  if (node instanceof TrackDecl) {
58142
58598
  if (deferredTrackDecls.has(node))
@@ -58227,6 +58683,33 @@ function buildComponentMap3(irRoot, hydrate = false, alloc, markerless = true) {
58227
58683
  const code = generateComponent2(comp, directNames, hydrate, asyncComps, linkNames, selfClaimNames, alloc, markerless);
58228
58684
  mapLines.push(`${registry}[${JSON.stringify(comp.name)}] = ${code};`);
58229
58685
  }
58686
+ if (hydrate && !markerless) {
58687
+ mapLines.push(`function __reconcileRegion(parent, id, branch, walker) {`);
58688
+ mapLines.push(` if (!parent) return;`);
58689
+ mapLines.push(` let start = null;`);
58690
+ mapLines.push(` let end = null;`);
58691
+ mapLines.push(` for (let n = parent.firstChild; n; n = n.nextSibling) {`);
58692
+ mapLines.push(` if (n.nodeType !== 8) continue;`);
58693
+ mapLines.push(` const text = n.textContent || '';`);
58694
+ mapLines.push(` if (text === 'vesk-r:' + id + ':0' || text === 'vesk-r:' + id + ':1') start = n;`);
58695
+ mapLines.push(` else if (text === 'vesk-r-end:' + id) end = n;`);
58696
+ mapLines.push(` if (start && end) break;`);
58697
+ mapLines.push(` }`);
58698
+ mapLines.push(` if (!start || !end) return;`);
58699
+ mapLines.push(` const ssrBranch = (start.textContent || '').slice(-2) === ':1' ? 1 : 0;`);
58700
+ mapLines.push(` if (ssrBranch !== branch) {`);
58701
+ mapLines.push(` let n = start.nextSibling;`);
58702
+ mapLines.push(` while (n && n !== end) {`);
58703
+ mapLines.push(` const next = n.nextSibling;`);
58704
+ mapLines.push(` n.remove();`);
58705
+ mapLines.push(` n = next;`);
58706
+ mapLines.push(` }`);
58707
+ mapLines.push(` if (walker && walker.retireDetached) walker.retireDetached();`);
58708
+ mapLines.push(` }`);
58709
+ mapLines.push(` start.remove();`);
58710
+ mapLines.push(` end.remove();`);
58711
+ mapLines.push(`}`);
58712
+ }
58230
58713
  mapLines.push(`function __cleanup(start, end) {`);
58231
58714
  mapLines.push(` let n = start.nextSibling;`);
58232
58715
  mapLines.push(` while (n && n !== end) {`);
@@ -58291,6 +58774,50 @@ function ssrResidueEstimate2(node) {
58291
58774
  }
58292
58775
  return 0;
58293
58776
  }
58777
+ function firstBranchRoot2(nodes) {
58778
+ for (const n of nodes) {
58779
+ if (n instanceof StaticNode)
58780
+ return { tag: n.tag, descriptor: staticClassDescriptor2(n) };
58781
+ if (n instanceof ComponentCall || n instanceof ComponentRef)
58782
+ return null;
58783
+ if (n instanceof OpaqueDynamicRegion)
58784
+ return null;
58785
+ if (n instanceof MapRegion || n instanceof ForLoop || n instanceof WhileLoop) {
58786
+ const child = firstBranchRoot2(n.bodyTemplate);
58787
+ if (child)
58788
+ return child;
58789
+ }
58790
+ if (n instanceof SwitchBlock) {
58791
+ for (const c of n.cases) {
58792
+ const child = firstBranchRoot2(c.body);
58793
+ if (child)
58794
+ return child;
58795
+ }
58796
+ }
58797
+ if (n instanceof TryCatch) {
58798
+ const child = firstBranchRoot2(n.bodyTemplate) || firstBranchRoot2(n.catchBody);
58799
+ if (child)
58800
+ return child;
58801
+ }
58802
+ }
58803
+ return null;
58804
+ }
58805
+ function structuralRegionMetadata2(branches) {
58806
+ const parts = branches.map((nodes) => {
58807
+ const first = firstBranchRoot2(nodes);
58808
+ const tag = first ? JSON.stringify(first.tag) : "undefined";
58809
+ const descriptor = first && first.descriptor ? first.descriptor : "null";
58810
+ return `{ tag: ${tag}, descriptor: ${descriptor}, count: ${ssrResidueEstimate2(nodes)} }`;
58811
+ });
58812
+ return `[${parts.join(", ")}]`;
58813
+ }
58814
+ function emitStructuralRegionDiscard2(ctx2, branches, selectedExpr, budget) {
58815
+ if (!ctx2.hydrate || !ctx2.markerless)
58816
+ return;
58817
+ const offset2 = budget ? `, ${budget}` : "";
58818
+ const consume = budget ? ` ${budget} = 0;` : "";
58819
+ ctx2.push(`if (${ctx2.walker} && typeof ${ctx2.walker}.discardStructuralRegion === 'function' && ${ctx2.walker}.discardStructuralRegion(${structuralRegionMetadata2(branches)}, ${selectedExpr}${offset2})) {${consume}}`);
58820
+ }
58294
58821
  function isStaticIR2(body) {
58295
58822
  for (const node of body) {
58296
58823
  if (node instanceof StaticNode) {
@@ -59903,12 +60430,24 @@ function fileUnchanged2(filePath, cached) {
59903
60430
  return false;
59904
60431
  }
59905
60432
  }
59906
- function buildRouterOpts2(options) {
60433
+ function hasServerMiddleware2(nodes) {
60434
+ for (const node of nodes) {
60435
+ if (node.hasMiddleware)
60436
+ return true;
60437
+ if (node.children?.length && hasServerMiddleware2(node.children))
60438
+ return true;
60439
+ }
60440
+ return false;
60441
+ }
60442
+ function buildRouterOpts2(options, serverMiddleware) {
59907
60443
  const ttl = options?.routeDataCache;
60444
+ const opts = [];
60445
+ if (serverMiddleware)
60446
+ opts.push("serverMiddleware: true");
59908
60447
  if (typeof ttl === "number" && ttl > 0) {
59909
- return `, { routeDataCache: ${ttl} }`;
60448
+ opts.push(`routeDataCache: ${ttl}`);
59910
60449
  }
59911
- return "";
60450
+ return opts.length ? `, { ${opts.join(", ")} }` : "";
59912
60451
  }
59913
60452
  function findRuntimeSrc3(appDir) {
59914
60453
  const monorepoRoot = resolve24(__dirname7, "..", "..", "..");
@@ -59964,7 +60503,7 @@ function isAnyImport2(node) {
59964
60503
  return node.type === "ImportDeclaration";
59965
60504
  }
59966
60505
  function isRuntimePreamble2(node) {
59967
- if (node.type === "FunctionDeclaration" && (node.id?.name === "__cleanup" || node.id?.name === "__place")) {
60506
+ if (node.type === "FunctionDeclaration" && (node.id?.name === "__cleanup" || node.id?.name === "__place" || node.id?.name === "__reconcileRegion")) {
59968
60507
  return true;
59969
60508
  }
59970
60509
  if (node.type === "VariableDeclaration") {
@@ -61198,12 +61737,13 @@ async function buildMainBundle2(routeTree, runtimeDir, codeSplit, mono, hmr, imp
61198
61737
  ` : runtimeCode + "\n";
61199
61738
  const cleanupFn = "function __cleanup(start, end) {\n let n = start.nextSibling;\n while (n && n !== end) {\n const next = n.nextSibling;\n n.remove();\n n = next;\n }\n}\n";
61200
61739
  const placeFn = "function __place(start, end, nodes, fallback) {\n if (start.parentNode !== null) {\n const p = start.parentNode;\n for (let i = 0; i < nodes.length; i++) p.insertBefore(nodes[i], end);\n return;\n }\n if (nodes.length > 0 && nodes[0].parentNode) {\n const p = nodes[0].parentNode;\n p.insertBefore(start, nodes[0]);\n p.insertBefore(end, nodes[nodes.length - 1].nextSibling);\n // Client-surplus nodes (SSR rendered fewer items than the client data)\n // are freshly claimed and still detached \u2014 move them into the region in\n // client order before `end`, instead of stranding them off-parent.\n for (let i = 0; i < nodes.length; i++) {\n if (nodes[i].parentNode === null) p.insertBefore(nodes[i], end);\n }\n return;\n }\n fallback.appendChild(start);\n fallback.appendChild(end);\n for (let i = 0; i < nodes.length; i++) fallback.insertBefore(nodes[i], end);\n}\n";
61740
+ const reconcileRegionFn = "function __reconcileRegion(parent, id, branch, walker) {\n if (!parent) return;\n let start = null;\n let end = null;\n for (let n = parent.firstChild; n; n = n.nextSibling) {\n if (n.nodeType !== 8) continue;\n const text = n.textContent || '';\n if (text === 'vesk-r:' + id + ':0' || text === 'vesk-r:' + id + ':1') start = n;\n else if (text === 'vesk-r-end:' + id) end = n;\n if (start && end) break;\n }\n if (!start || !end) return;\n const ssrBranch = (start.textContent || '').slice(-2) === ':1' ? 1 : 0;\n if (ssrBranch !== branch) {\n let n = start.nextSibling;\n while (n && n !== end) {\n const next = n.nextSibling;\n n.remove();\n n = next;\n }\n if (walker && walker.retireDetached) walker.retireDetached();\n }\n start.remove();\n end.remove();\n}\n";
61201
61741
  const updateComponentsFn = "function __updateComponents(nodes) {\n for (const n of nodes) {\n if (n._pageName && __components[n._pageName]) n.page = __components[n._pageName];\n if (n._layoutName && __components[n._layoutName]) n.layout = __components[n._layoutName];\n if (n._errorName && __components[n._errorName]) n.error = __components[n._errorName];\n if (n._notFoundName && __components[n._notFoundName]) n.notFound = __components[n._notFoundName];\n if (n._offlineName && __components[n._offlineName]) n.offline = __components[n._offlineName];\n if (n._networkName && __components[n._networkName]) n.network = __components[n._networkName];\n if (n.children) __updateComponents(n.children);\n }\n}\n";
61202
61742
  const routeTreeJson = JSON.stringify(routeTree);
61203
61743
  if (codeSplit) {
61204
61744
  const resolveNamesFn = "function __resolveNames(nodes) {\n for (const n of nodes) {\n if (n.chunk) n._chunk = n.chunk;\n if (n.chunkError) n._chunkError = n.chunkError;\n if (typeof n.page === 'string') n._pageName = n.page;\n if (typeof n.layout === 'string') n._layoutName = n.layout;\n if (typeof n.error === 'string') n._errorName = n.error;\n if (typeof n.notFound === 'string') n._notFoundName = n.notFound;\n if (typeof n.offline === 'string') n._offlineName = n.offline;\n if (typeof n.network === 'string') n._networkName = n.network;\n if (n.children) __resolveNames(n.children);\n }\n}\n";
61205
61745
  const pendCode = "const __pendChunks = [];\nconst __currentPath = typeof window !== 'undefined' ? window.location.pathname : '/';\nif (typeof matchRoute === 'function') {\n const __currentMatch = matchRoute(__routeTree, __currentPath);\n if (__currentMatch) {\n for (const n of __currentMatch.matchChain) {\n if (n._chunk && !__pendChunks.includes(n._chunk)) __pendChunks.push(n._chunk);\n }\n }\n}\n";
61206
- const routerOpts2 = buildRouterOpts2({ routeDataCache });
61746
+ const routerOpts2 = buildRouterOpts2({ routeDataCache }, hasServerMiddleware2(routeTree));
61207
61747
  const startRouterCode = `const __startRouter = function() {
61208
61748
  __updateComponents(__routeTree);
61209
61749
  const __router = createFileRouter(__routeTree${routerOpts2});
@@ -61242,14 +61782,14 @@ if (__pendChunks.length > 0 && typeof ensureChunk === 'function') {
61242
61782
  ];
61243
61783
  const importedSet = new Set(allRuntimeImports);
61244
61784
  const runtimeGlobals2 = globalNames.filter((n) => importedSet.has(n)).map((n) => `globalThis.${n} = ${n};
61245
- `).join("") + "globalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\n\n";
61785
+ `).join("") + "globalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\nglobalThis.__reconcileRegion = __reconcileRegion;\n\n";
61246
61786
  const extraGlobals = [...runtimeImportNames || []].filter((n) => n && n !== "default").map((n) => `globalThis.${n} = ${n};
61247
61787
  `).join("");
61248
61788
  const code2 = preamble + "const __components = globalThis.__components || (globalThis.__components = {});\nconst __hydrators = globalThis.__hydrators || (globalThis.__hydrators = {});\nconst __runtime_comps = __components;\n\n" + runtimeGlobals2 + extraGlobals + // Shared app modules run HERE: after the runtime bindings are published,
61249
61789
  // before anything can request a route chunk. Earlier (at the top of the
61250
61790
  // bundle) `globalThis.track` was still undefined, so every module-scope
61251
61791
  // cell in a store was created against a missing runtime.
61252
- (sharedModuleBundle ? sharedModuleBundle + "\n" : "") + cleanupFn + placeFn + "globalThis.__components = __components;\n" + resolveNamesFn + updateComponentsFn + "const __routeTree = " + routeTreeJson + ";\n__resolveNames(__routeTree);\n" + pendCode + startRouterCode;
61792
+ (sharedModuleBundle ? sharedModuleBundle + "\n" : "") + cleanupFn + placeFn + reconcileRegionFn + "globalThis.__components = __components;\n" + resolveNamesFn + updateComponentsFn + "const __routeTree = " + routeTreeJson + ";\n__resolveNames(__routeTree);\n" + pendCode + startRouterCode;
61253
61793
  return hmr ? appendHmrGlobals2(code2) : code2;
61254
61794
  }
61255
61795
  const componentLines = mono?.componentLines || [];
@@ -61258,8 +61798,8 @@ if (__pendChunks.length > 0 && typeof ensureChunk === 'function') {
61258
61798
  const hydratorAliasLines = mono?.hydratorAliasLines || [];
61259
61799
  const aliasCode = aliasLines.length > 0 ? aliasLines.join("\n") + "\n" : "";
61260
61800
  const hydratorAliasCode = hydratorAliasLines.length > 0 ? hydratorAliasLines.join("\n") + "\n" : "";
61261
- const routerOpts = buildRouterOpts2({ routeDataCache });
61262
- const code = preamble + "const __components = {};\nconst __hydrators = {};\nconst __runtime_comps = __components;\n\n" + componentLines.join("\n\n") + "\n" + aliasCode + hydratorLines.join("\n\n") + "\n" + hydratorAliasCode + cleanupFn + placeFn + "globalThis.__components = __components;\nglobalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\n" + allRuntimeImports.map((n) => `globalThis.${n} = ${n};
61801
+ const routerOpts = buildRouterOpts2({ routeDataCache }, hasServerMiddleware2(routeTree));
61802
+ const code = preamble + "const __components = {};\nconst __hydrators = {};\nconst __runtime_comps = __components;\n\n" + componentLines.join("\n\n") + "\n" + aliasCode + hydratorLines.join("\n\n") + "\n" + hydratorAliasCode + cleanupFn + placeFn + reconcileRegionFn + "globalThis.__components = __components;\nglobalThis.__runtime_comps = __runtime_comps;\nglobalThis.__cleanup = __cleanup;\nglobalThis.__place = __place;\nglobalThis.__reconcileRegion = __reconcileRegion;\n" + allRuntimeImports.map((n) => `globalThis.${n} = ${n};
61263
61803
  `).join("") + "function __resolveNames(nodes) {\n for (const n of nodes) {\n if (typeof n.page === 'string') {\n n._pageName = n.page;\n n.page = __components[n.page];\n }\n if (typeof n.layout === 'string') {\n n._layoutName = n.layout;\n n.layout = __components[n.layout];\n }\n if (typeof n.error === 'string') n.error = __components[n.error];\n if (typeof n.notFound === 'string') n.notFound = __components[n.notFound];\n if (typeof n.offline === 'string') n.offline = __components[n.offline];\n if (typeof n.network === 'string') n.network = __components[n.network];\n if (n.children) __resolveNames(n.children);\n }\n}\n" + updateComponentsFn + "const __routeTree = " + routeTreeJson + `;
61264
61804
  __resolveNames(__routeTree);
61265
61805
  const __router = createFileRouter(__routeTree${routerOpts});
@@ -68827,6 +69367,28 @@ Object.defineProperty(__components, ${JSON.stringify(cname)}, { get: () => __com
68827
69367
  if (await handleActionRequest(req, res, { url, appDirPath, routeTree, security, maxBodyBytes, plugins: getActiveDevPlugins() })) {
68828
69368
  return;
68829
69369
  }
69370
+ if (url.pathname === "/_vesk/middleware") {
69371
+ const targetPath = url.searchParams.get("path") || "/";
69372
+ const targetUrl = new URL(targetPath, "http://localhost");
69373
+ const targetChain = collectMiddlewareChain(routeTree, targetUrl.pathname, appDirPath);
69374
+ const rawHeaders = {};
69375
+ for (const [k, v] of Object.entries(req.headers)) {
69376
+ rawHeaders[k] = Array.isArray(v) ? v.join(", ") : v || "";
69377
+ }
69378
+ const mwReq = new Request(targetUrl.href, { headers: rawHeaders, method: "GET" });
69379
+ const mwResult = await executeMiddlewareChain(targetChain, mwReq, {}, {
69380
+ plugins: getActiveDevPlugins(),
69381
+ onLast: async () => null
69382
+ });
69383
+ res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
69384
+ if (mwResult.response) {
69385
+ const location = mwResult.response.headers.get("location") || mwResult.response.headers.get("Location");
69386
+ res.end(JSON.stringify(location ? { redirect: location } : { allow: true }));
69387
+ return;
69388
+ }
69389
+ res.end(JSON.stringify(mwResult.rewriteUrl ? { rewrite: mwResult.rewriteUrl } : { allow: true }));
69390
+ return;
69391
+ }
68830
69392
  const mwChain = collectMiddlewareChain(routeTree, url.pathname, appDirPath);
68831
69393
  const apiDirPath = join28(appDirPath, "api");
68832
69394
  if (url.pathname.startsWith("/api") && existsSync44(apiDirPath)) {