@krate/runtime 0.5.0-rc.5 → 0.5.0-rc.7

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 (98) hide show
  1. package/dist/actions.js +10 -1
  2. package/dist/cache-scope.d.ts +2 -0
  3. package/dist/cache-scope.js +6 -1
  4. package/dist/context.d.ts +5 -0
  5. package/dist/context.js +28 -17
  6. package/dist/flight-props.d.ts +7 -0
  7. package/dist/flight-props.js +105 -0
  8. package/dist/handler-routing.d.ts +2 -23
  9. package/dist/handler-routing.js +4 -188
  10. package/dist/head-tags.js +5 -2
  11. package/dist/highlight.d.ts +3 -2
  12. package/dist/highlight.js +12 -6
  13. package/dist/hints.d.ts +25 -2
  14. package/dist/hints.js +148 -74
  15. package/dist/index.d.ts +1 -0
  16. package/dist/island-swap.d.ts +45 -0
  17. package/dist/island-swap.js +608 -0
  18. package/dist/jsx-types.d.ts +7 -2
  19. package/dist/krate-core.js +1 -1
  20. package/dist/krate-f-actions.js +1 -1
  21. package/dist/krate-f-list.js +1 -1
  22. package/dist/krate-f-navigation.js +1 -1
  23. package/dist/krate-f-router-lite.js +1 -1
  24. package/dist/krate-f-router.js +1 -1
  25. package/dist/krate-features.json +452 -0
  26. package/dist/krate-hydrate-lite.js +5 -5
  27. package/dist/krate-hydrate.js +5 -5
  28. package/dist/krate-island-swap.js +1 -0
  29. package/dist/krate-runtime.js +5 -5
  30. package/dist/list.d.ts +14 -4
  31. package/dist/list.js +4 -5
  32. package/dist/navigation-react.d.ts +13 -0
  33. package/dist/navigation-react.js +86 -0
  34. package/dist/navigation.d.ts +19 -0
  35. package/dist/navigation.js +35 -0
  36. package/dist/react-compat.d.ts +39 -0
  37. package/dist/react-compat.js +359 -0
  38. package/dist/request-extras.d.ts +4 -0
  39. package/dist/request-extras.js +51 -0
  40. package/dist/route-source.d.ts +39 -0
  41. package/dist/route-source.js +532 -0
  42. package/dist/router.js +293 -23
  43. package/dist/server-handler.d.ts +20 -1
  44. package/dist/server-handler.js +208 -92
  45. package/dist/server.d.ts +24 -17
  46. package/dist/server.js +435 -101
  47. package/dist/site-config.d.ts +2 -0
  48. package/dist/testing.d.ts +4 -1
  49. package/dist/testing.js +3 -1
  50. package/package.json +15 -2
  51. package/dist/actions.test.d.ts +0 -1
  52. package/dist/actions.test.js +0 -75
  53. package/dist/after.test.d.ts +0 -1
  54. package/dist/after.test.js +0 -58
  55. package/dist/builtin-tags.test.d.ts +0 -1
  56. package/dist/builtin-tags.test.js +0 -12
  57. package/dist/cache-adapter.test.d.ts +0 -1
  58. package/dist/cache-adapter.test.js +0 -45
  59. package/dist/cache.test.d.ts +0 -1
  60. package/dist/cache.test.js +0 -37
  61. package/dist/events.test.d.ts +0 -1
  62. package/dist/events.test.js +0 -42
  63. package/dist/handler-html.test.d.ts +0 -1
  64. package/dist/handler-html.test.js +0 -55
  65. package/dist/handler-segments.test.d.ts +0 -1
  66. package/dist/handler-segments.test.js +0 -25
  67. package/dist/head-tags.test.d.ts +0 -1
  68. package/dist/head-tags.test.js +0 -24
  69. package/dist/inline-action-token.test.d.ts +0 -1
  70. package/dist/inline-action-token.test.js +0 -31
  71. package/dist/jsx-svg-types.test.d.ts +0 -1
  72. package/dist/jsx-svg-types.test.js +0 -58
  73. package/dist/link-base-path.test.d.ts +0 -1
  74. package/dist/link-base-path.test.js +0 -28
  75. package/dist/node-server.test.d.ts +0 -1
  76. package/dist/node-server.test.js +0 -138
  77. package/dist/platform.test.d.ts +0 -1
  78. package/dist/platform.test.js +0 -44
  79. package/dist/router-nav.test.d.ts +0 -1
  80. package/dist/router-nav.test.js +0 -130
  81. package/dist/server-handler.test.d.ts +0 -1
  82. package/dist/server-handler.test.js +0 -338
  83. package/dist/server-renderer.test.d.ts +0 -1
  84. package/dist/server-renderer.test.js +0 -162
  85. package/dist/server.test.d.ts +0 -1
  86. package/dist/server.test.js +0 -91
  87. package/dist/sha256.test.d.ts +0 -1
  88. package/dist/sha256.test.js +0 -13
  89. package/dist/signal.test.d.ts +0 -1
  90. package/dist/signal.test.js +0 -68
  91. package/dist/site-config.test.d.ts +0 -1
  92. package/dist/site-config.test.js +0 -30
  93. package/dist/slot.test.d.ts +0 -1
  94. package/dist/slot.test.js +0 -25
  95. package/dist/ssr-core-behavior.test.d.ts +0 -1
  96. package/dist/ssr-core-behavior.test.js +0 -108
  97. package/dist/testing.test.d.ts +0 -1
  98. package/dist/testing.test.js +0 -73
@@ -16,7 +16,9 @@ import { platformWaitUntil } from "./platform.js";
16
16
  import { cacheRuntime, installRenderStore, patchFetch } from "./cache-scope.js";
17
17
  import { allSuspense, canStreamOutOfOrder, FLASH_COOKIE, flashPayloadOf, injectFlashNotice, parseRegionShell, regionReplaceScript, requestFlash, signFlash, spliceShell, splitBodyScripts, } from "./handler-html.js";
18
18
  import { mergeHead } from "./head-tags.js";
19
- import { applyDynamicRouteParams, baseName, cleanPath, compareRouteSpecificity, compileMatcher, extName, goRedirect, headerSourceMatches, isDynamicPattern, isFileLikePath, isHTMLDocRequest, isInternalOutputPath, matchRedirect, matchRoutePattern, normalizeRoutePattern, requestRoute, rewriteDestination, rewriteTargetPath, staticCacheControl, } from "./handler-routing.js";
19
+ import { applyDynamicRouteParams, baseName, cleanPath, compareRouteSpecificity, compileMatcher, extName, goRedirect, IMMUTABLE_CACHE_CONTROL, isDynamicPattern, isFileLikePath, isHTMLDocRequest, isInternalOutputPath, matchRoutePattern, normalizeRoutePattern, requestRoute, rewriteTargetPath, staticCacheControl, } from "./handler-routing.js";
20
+ import { attachCookies } from "./request-extras.js";
21
+ import { buildDestination, compileMatcher as compileRuleMatcher, mergeRequestQuery } from "./route-source.js";
20
22
  import { lookupSegmentPage, newServerError, renderSegmentPage, SEGMENT_KIND_OF_STATUS, } from "./handler-segments.js";
21
23
  import { httpFallbackStatus } from "./request-context.js";
22
24
  import { sha256Hex as portableSha256Hex } from "./sha256.js";
@@ -86,6 +88,22 @@ function safeDecode(p) {
86
88
  return p;
87
89
  }
88
90
  }
91
+ /**
92
+ * The name/value pairs of a headers rule: an object, or Next's array of
93
+ * { key, value } where a repeated name (any case) keeps its last value.
94
+ */
95
+ export function ruleHeaderPairs(h) {
96
+ if (!Array.isArray(h))
97
+ return Object.entries(h);
98
+ const out = [];
99
+ for (const { key, value } of h) {
100
+ const at = out.findIndex(([k]) => k.toLowerCase() === String(key).toLowerCase());
101
+ if (at >= 0)
102
+ out.splice(at, 1);
103
+ out.push([String(key), String(value)]);
104
+ }
105
+ return out;
106
+ }
89
107
  function textResponse(rs, status, body, contentType = "text/plain; charset=utf-8") {
90
108
  rs.res.set("Content-Type", contentType);
91
109
  return finish(rs, status, body);
@@ -143,54 +161,6 @@ function isHTTPSRequest(headers) {
143
161
  function isStaticAssetPath(p) {
144
162
  return STATIC_ASSET_EXTS.has(extName(p).toLowerCase());
145
163
  }
146
- function requestCookiesOf(headers) {
147
- const jar = new Map();
148
- for (const part of String(headers.get("cookie") || "").split(";")) {
149
- const i = part.indexOf("=");
150
- if (i <= 0)
151
- continue;
152
- const name = part.slice(0, i).trim();
153
- if (!name || jar.has(name))
154
- continue;
155
- // Same parsing as the action context and the Node sidecar: unquote, then percent-decode.
156
- let value = part.slice(i + 1).trim();
157
- if (value.startsWith('"') && value.endsWith('"'))
158
- value = value.slice(1, -1);
159
- try {
160
- value = decodeURIComponent(value);
161
- }
162
- catch {
163
- // keep the raw value
164
- }
165
- jar.set(name, value);
166
- }
167
- return jar;
168
- }
169
- function attachCookies(request, basePath = "") {
170
- try {
171
- const jar = requestCookiesOf(request.headers);
172
- Object.defineProperty(request, "cookies", {
173
- value: {
174
- get: (n) => (jar.has(String(n)) ? { name: String(n), value: jar.get(String(n)) } : undefined),
175
- getAll: (n) => [...jar].filter(([k]) => n === undefined || k === String(n)).map(([name, value]) => ({ name, value })),
176
- has: (n) => jar.has(String(n)),
177
- },
178
- enumerable: false,
179
- });
180
- Object.defineProperty(request, "nextUrl", { value: makeNextUrl(request.url, basePath), enumerable: false });
181
- }
182
- catch {
183
- // frozen request objects keep working without the cookies accessor
184
- }
185
- return request;
186
- }
187
- /** A URL carrying Next's NextURL extras: basePath (pathname never includes it) and clone(). */
188
- function makeNextUrl(href, basePath) {
189
- const u = new URL(href);
190
- Object.defineProperty(u, "basePath", { value: basePath, enumerable: false });
191
- Object.defineProperty(u, "clone", { value: () => makeNextUrl(u.href, basePath), enumerable: false });
192
- return u;
193
- }
194
164
  const sleepMicrotask = () => Promise.resolve();
195
165
  const PLATFORMS = {
196
166
  node: { forwardedHostProto: false, clientIP: [] },
@@ -467,15 +437,23 @@ export function createKrateHandler(options) {
467
437
  let next = false;
468
438
  let rewrite = "";
469
439
  const hdrs = [];
440
+ let keep = null;
441
+ const vals = new Map();
470
442
  for (const [k, v] of headerPairs(result.headers)) {
471
443
  if (k === "x-middleware-next")
472
444
  next = true;
473
445
  else if (k === "x-middleware-rewrite")
474
446
  rewrite = v;
447
+ else if (k === "x-middleware-override-headers")
448
+ keep = new Set(v.split(",").map((n) => n.trim().toLowerCase()).filter(Boolean));
449
+ else if (k.startsWith("x-middleware-request-"))
450
+ vals.set(k.slice("x-middleware-request-".length), v);
475
451
  else
476
452
  hdrs.push([k, v]);
477
453
  }
478
454
  if (next || rewrite) {
455
+ if (keep)
456
+ overrideRequestHeaders(rs, keep, vals);
479
457
  writeHeaderPairs(rs.res, hdrs);
480
458
  if (rewrite)
481
459
  applyRewrite(rs, rewrite);
@@ -488,6 +466,23 @@ export function createKrateHandler(options) {
488
466
  status = 500;
489
467
  return finish(rs, status, rs.method === "HEAD" || !body ? null : body);
490
468
  }
469
+ /** NextResponse.next({ request: { headers } }): the downstream request keeps only the listed headers, with the given values. */
470
+ function overrideRequestHeaders(rs, keep, vals) {
471
+ const edit = (h) => {
472
+ const out = new Headers();
473
+ h.forEach((v, k) => {
474
+ if (keep.has(k.toLowerCase()))
475
+ out.set(k, v);
476
+ });
477
+ for (const [k, v] of vals)
478
+ if (keep.has(k) && k !== "host")
479
+ out.set(k, v);
480
+ return out;
481
+ };
482
+ const shared = rs.headers === rs.request.headers;
483
+ rs.request = new Request(rs.request, { headers: edit(rs.request.headers) });
484
+ rs.headers = shared ? rs.request.headers : edit(rs.headers);
485
+ }
491
486
  function middlewareFailed(rs, err) {
492
487
  console.error(`[krate] middleware error: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
493
488
  // Fail closed: continuing would turn a broken auth check into an unauthenticated request.
@@ -650,19 +645,22 @@ export function createKrateHandler(options) {
650
645
  return custom404(rs, page);
651
646
  return notFoundText(rs, true);
652
647
  }
653
- /** trailingSlash "never": a page URL ending in a slash redirects to the slashless URL. */
648
+ /**
649
+ * trailingSlash "never": a path ending in "/" (pages, files, API routes, any
650
+ * method) gets a 308 to the slashless path before config redirects and
651
+ * middleware, as in Next (mirrors slashlessTarget in serve_pages.go). The
652
+ * not-found page's URLs and internal routes are left alone.
653
+ */
654
654
  function redirectToSlashless(rs) {
655
655
  const p = rs.path;
656
- if (slashMode !== "never" || p.length < 2 || !p.endsWith("/") || notFoundPageURL(p))
657
- return null;
658
- if (rs.method !== "GET" && rs.method !== "HEAD")
656
+ if (slashMode !== "never" || p.length < 2 || !p.endsWith("/") || p.startsWith("/__krate") || p === "/healthz" || p === "/readyz" || notFoundPageURL(p))
659
657
  return null;
660
- const trimmed = p.replace(/\/+$/, "");
661
- if (trimmed === "" || isFileLikePath(trimmed) || trimmed === "/api" || trimmed.startsWith("/api/") || trimmed.startsWith("/__krate"))
658
+ // "//evil.example/" must not become a scheme-relative Location.
659
+ const target = "/" + rs.rawPath.replace(/\/+$/, "").replace(/^[\/\\]+/, "");
660
+ if (target === "/")
662
661
  return null;
663
- // "../" keeps a segment such as "ftp:3232235777" from parsing as an absolute URL.
664
- rs.res.set("Location", "../" + baseName(trimmed) + (rs.search || ""));
665
- return finish(rs, 301, null);
662
+ rs.res.set("Location", target + (rs.search || ""));
663
+ return finish(rs, 308, null);
666
664
  }
667
665
  function redirectToCanonicalSlash(rs) {
668
666
  if (slashMode !== "always")
@@ -712,7 +710,9 @@ export function createKrateHandler(options) {
712
710
  return answerNotFoundPageURL(rs);
713
711
  if (p.endsWith(".map"))
714
712
  rs.res.set("Content-Type", "application/json; charset=utf-8");
715
- rs.res.set("Cache-Control", staticCacheControl(p, hashed));
713
+ // A Cache-Control from a headers rule wins (public/ files cached longer).
714
+ if (!rs.res.has("Cache-Control"))
715
+ rs.res.set("Cache-Control", staticCacheControl(p, hashed));
716
716
  let closedPattern = "";
717
717
  if (!(await staticRouteExists(p))) {
718
718
  for (const t of templates) {
@@ -1069,16 +1069,36 @@ export function createKrateHandler(options) {
1069
1069
  return new Response(null, { status: 200, headers: rs.res });
1070
1070
  return new Response(body, { status: 200, headers: rs.res });
1071
1071
  }
1072
- // Redirects and rewrites
1073
- // Under a base path, basePath: false rules match the full path before the
1074
- // base is stripped (see handle) and stay out of this list.
1075
- const insideRedirects = basePath ? cfg.redirects.filter((rd) => rd.basePath !== false) : cfg.redirects;
1076
- const outsideRedirects = basePath ? cfg.redirects.filter((rd) => rd.basePath === false) : [];
1072
+ function compileRules(rules, kind) {
1073
+ const out = [];
1074
+ for (const rule of rules) {
1075
+ try {
1076
+ out.push({ rule, matcher: compileRuleMatcher(rule.source, kind, rule.has, rule.missing) });
1077
+ }
1078
+ catch (err) {
1079
+ console.error(`[krate] skipped ${kind} rule ${JSON.stringify(rule.source)}: ${err.message}`);
1080
+ }
1081
+ }
1082
+ return out;
1083
+ }
1084
+ const insideRedirects = compileRules(basePath ? cfg.redirects.filter((rd) => rd.basePath !== false) : cfg.redirects, "redirect");
1085
+ const outsideRedirects = compileRules(basePath ? cfg.redirects.filter((rd) => rd.basePath === false) : [], "redirect");
1086
+ const rewriteRules = compileRules(cfg.rewrites, "rewrite");
1087
+ const headerRules = compileRules(cfg.headers, "header");
1088
+ function condRequest(rs) {
1089
+ return { headers: rs.headers, url: new URL(rs.request.url) };
1090
+ }
1091
+ /** Answers the first redirect whose source and conditions match; the request query is carried over. */
1077
1092
  function configRedirect(rs, p, rules) {
1078
- for (const rd of rules) {
1079
- if (matchRedirect(p, rd.source)) {
1080
- const dest = rewriteDestination(p, rd.source, rd.destination);
1081
- return goRedirect(dest, p, rs.method, rd.permanent ? 301 : 302, rs.res);
1093
+ if (!rules.length)
1094
+ return null;
1095
+ const creq = condRequest(rs);
1096
+ for (const { rule, matcher } of rules) {
1097
+ const m = matcher.match(p, creq);
1098
+ if (m) {
1099
+ const dest = mergeRequestQuery(buildDestination(rule.destination, m), rs.search);
1100
+ const status = rule.statusCode || (rule.permanent ? 301 : 302);
1101
+ return goRedirect(dest, p, rs.method, status, rs.res);
1082
1102
  }
1083
1103
  }
1084
1104
  return null;
@@ -1094,16 +1114,30 @@ export function createKrateHandler(options) {
1094
1114
  }
1095
1115
  async function redirectRewriteHandler(rs) {
1096
1116
  const p = rs.path;
1097
- const redirected = configRedirect(rs, p, insideRedirects);
1098
- if (redirected)
1099
- return redirected;
1100
- for (const rw of cfg.rewrites) {
1101
- if (matchRedirect(p, rw.source)) {
1102
- const rewritten = rewriteDestination(p, rw.source, rw.destination);
1117
+ if (rewriteRules.length) {
1118
+ const creq = condRequest(rs);
1119
+ for (const { rule, matcher } of rewriteRules) {
1120
+ const m = matcher.match(p, creq);
1121
+ if (!m)
1122
+ continue;
1123
+ let rewritten = buildDestination(rule.destination, m);
1124
+ let rewrittenQuery = "";
1125
+ const q = rewritten.indexOf("?");
1126
+ if (q >= 0) {
1127
+ rewrittenQuery = rewritten.slice(q);
1128
+ rewritten = rewritten.slice(0, q);
1129
+ }
1103
1130
  rs.path = rewriteTargetPath(safeDecode(rewritten));
1131
+ if (rewrittenQuery) {
1132
+ const merged = mergeRequestQuery(rewrittenQuery, rs.search);
1133
+ rs.search = merged === "?" ? "" : merged;
1134
+ }
1104
1135
  break;
1105
1136
  }
1106
1137
  }
1138
+ // A rewrite onto an API route is answered by the API handler (mux sent this request down the page chain).
1139
+ if (rs.path === "/api" || rs.path.startsWith("/api/"))
1140
+ return apiHandler(rs);
1107
1141
  return pageHandler(rs);
1108
1142
  }
1109
1143
  // API routes
@@ -1130,12 +1164,15 @@ export function createKrateHandler(options) {
1130
1164
  continue;
1131
1165
  const rest = k.slice(prefix.length);
1132
1166
  const i = rest.indexOf("/");
1167
+ // A name can be both a route file and a directory ([id].ts next to [id]/download.ts).
1133
1168
  if (i < 0)
1134
- out.set(rest, out.get(rest) || false);
1169
+ out.set(rest + "\0f", false);
1135
1170
  else
1136
- out.set(rest.slice(0, i), true);
1171
+ out.set(rest.slice(0, i) + "\0d", true);
1137
1172
  }
1138
- return [...out].sort((a, b) => strCmp(a[0], b[0])).map(([name, isDir]) => ({ name, isDir }));
1173
+ return [...out.keys()]
1174
+ .sort(strCmp)
1175
+ .map((k) => ({ name: k.slice(0, -2), isDir: out.get(k) }));
1139
1176
  }
1140
1177
  function strCmp(a, b) {
1141
1178
  return a < b ? -1 : a > b ? 1 : 0;
@@ -1148,6 +1185,9 @@ export function createKrateHandler(options) {
1148
1185
  const idx = join(dir, "index");
1149
1186
  return apiKeys.has(idx) ? idx : "";
1150
1187
  }
1188
+ // A static leaf wins over dynamic siblings at every depth.
1189
+ if (segs.length === 1 && apiKeys.has(join(dir, segs[0])))
1190
+ return join(dir, segs[0]);
1151
1191
  const next = join(dir, segs[0]);
1152
1192
  if (apiDirs.has(next)) {
1153
1193
  const hit = resolveDynamicAPIDir(next, segs.slice(1));
@@ -1492,7 +1532,7 @@ export function createKrateHandler(options) {
1492
1532
  }), basePath);
1493
1533
  const scope = { kind: "api", paths: [], tags: [] };
1494
1534
  const work = async () => {
1495
- const res = await revalidateStore.run(scope, async () => toResponse(await fn(request, { params: apiRouteParams(file, rs.path) })));
1535
+ const res = await revalidateStore.run(scope, () => runRoute(request, async () => toResponse(await fn(request, { params: apiRouteParams(file, rs.path) }))));
1496
1536
  await flushRevalidate(scope);
1497
1537
  return res;
1498
1538
  };
@@ -1629,6 +1669,29 @@ export function createKrateHandler(options) {
1629
1669
  };
1630
1670
  return { actionId: id, url: urlPath, method: "POST", headers, cookies, setCookies };
1631
1671
  }
1672
+ // Runs an API route inside the action store so headers(), cookies() and
1673
+ // redirect() work in it like in a server action: cookies it sets are added to
1674
+ // the response and a redirect() signal becomes a 307.
1675
+ async function runRoute(request, run) {
1676
+ const ctx = makeActionContext(request.headers, "", new URL(request.url).pathname);
1677
+ ctx.method = request.method;
1678
+ let out;
1679
+ try {
1680
+ out = await actionStore.run(ctx, run);
1681
+ }
1682
+ catch (e) {
1683
+ if (!e || typeof e.__krateRedirect !== "string")
1684
+ throw e;
1685
+ out = new Response(null, { status: 307, headers: { location: e.__krateRedirect, "cache-control": "no-store" } });
1686
+ }
1687
+ if (ctx.setCookies.length > 0) {
1688
+ const h = new Headers(out.headers);
1689
+ for (const c of ctx.setCookies)
1690
+ h.append("set-cookie", c);
1691
+ out = new Response(out.body, { status: out.status, statusText: out.statusText, headers: h });
1692
+ }
1693
+ return out;
1694
+ }
1632
1695
  function safeActionRedirect(value) {
1633
1696
  if (typeof value !== "string")
1634
1697
  return "";
@@ -1639,6 +1702,20 @@ export function createKrateHandler(options) {
1639
1702
  return "";
1640
1703
  return to;
1641
1704
  }
1705
+ // An absolute http(s) URL from a redirect() signal that marked itself external
1706
+ // (the OAuth redirect of @krate/auth signIn()). A redirect returned in an
1707
+ // action's result is never external.
1708
+ function safeExternalRedirect(value) {
1709
+ if (typeof value !== "string" || /[\u0000-\u001f\u007f\\]/.test(value))
1710
+ return "";
1711
+ try {
1712
+ const u = new URL(value.trim());
1713
+ return u.protocol === "https:" || u.protocol === "http:" ? u.href : "";
1714
+ }
1715
+ catch {
1716
+ return "";
1717
+ }
1718
+ }
1642
1719
  function sanitizeActionReturn(value, rs) {
1643
1720
  value = value.trim();
1644
1721
  if (!value)
@@ -1831,14 +1908,17 @@ export function createKrateHandler(options) {
1831
1908
  const scope = { kind: "action", paths: [], tags: [] };
1832
1909
  let result;
1833
1910
  let redirect = "";
1911
+ let external = false;
1834
1912
  let failure = null;
1835
1913
  let fallback = 0;
1836
1914
  try {
1837
1915
  result = await revalidateStore.run(scope, () => actionStore.run(ctx, () => fn(...args)));
1838
1916
  }
1839
1917
  catch (e) {
1840
- if (e && typeof e.__krateRedirect === "string")
1918
+ if (e && typeof e.__krateRedirect === "string") {
1841
1919
  redirect = e.__krateRedirect;
1920
+ external = e.__krateRedirectExternal === true;
1921
+ }
1842
1922
  else if ((fallback = httpFallbackStatus(e)))
1843
1923
  failure = null;
1844
1924
  else
@@ -1854,7 +1934,7 @@ export function createKrateHandler(options) {
1854
1934
  }
1855
1935
  if (!redirect && result && typeof result === "object" && typeof result.redirect === "string")
1856
1936
  redirect = result.redirect;
1857
- redirect = safeActionRedirect(redirect);
1937
+ redirect = external ? safeExternalRedirect(redirect) : safeActionRedirect(redirect);
1858
1938
  if (fallback && !failure)
1859
1939
  return withHeaders(rs, actionFallback(rs, fallback, fetchMode, ctx.setCookies, reqHeaders.get("x-krate-return") || ""));
1860
1940
  let body = "";
@@ -1862,6 +1942,8 @@ export function createKrateHandler(options) {
1862
1942
  const envelope = { ok: true, result: result === undefined ? null : result };
1863
1943
  if (redirect)
1864
1944
  envelope.redirect = redirect;
1945
+ if (redirect && external)
1946
+ envelope.external = true;
1865
1947
  if (revalidation) {
1866
1948
  envelope.revalidated = true;
1867
1949
  envelope.revalidation = revalidation;
@@ -1967,15 +2049,21 @@ export function createKrateHandler(options) {
1967
2049
  const blocked = await runMiddleware(rs2);
1968
2050
  if (blocked)
1969
2051
  return blocked;
1970
- // Checked on the requested URL, before a rewrite changes the internal path.
1971
- const slashless = redirectToSlashless(rs2);
1972
- if (slashless)
1973
- return slashless;
1974
2052
  return redirectRewriteHandler(rs2);
1975
2053
  });
1976
2054
  }
1977
2055
  async function mux(rs) {
1978
2056
  const p = rs.path;
2057
+ // trailingSlash "never", then config redirects, answer first: before
2058
+ // middleware, and for /api too.
2059
+ const slashless = redirectToSlashless(rs);
2060
+ if (slashless)
2061
+ return slashless;
2062
+ if (!(p.startsWith("/__krate/") || p === "/healthz" || p === "/readyz")) {
2063
+ const redirected = configRedirect(rs, p, insideRedirects);
2064
+ if (redirected)
2065
+ return redirected;
2066
+ }
1979
2067
  // net/http.ServeMux cleans the escaped path and redirects when it changed.
1980
2068
  const raw = rs.rawPath;
1981
2069
  const cleaned = cleanPath(raw) + (raw.endsWith("/") && raw !== "/" ? "/" : "");
@@ -2031,11 +2119,36 @@ export function createKrateHandler(options) {
2031
2119
  h.set("Strict-Transport-Security", sec.hsts);
2032
2120
  if (sec.csp)
2033
2121
  h.set("Content-Security-Policy", sec.csp);
2034
- for (const rule of cfg.headers) {
2035
- if (headerSourceMatches(rule.source, rs.path))
2036
- for (const [k, v] of Object.entries(rule.headers))
2037
- h.set(k, v);
2122
+ }
2123
+ /**
2124
+ * Applies the matching headers rules to the finished response, so they win
2125
+ * over a header a handler set (a file's Cache-Control) except the immutable
2126
+ * Cache-Control of a content-hashed asset.
2127
+ */
2128
+ function withHeaderRules(rs, path, res) {
2129
+ if (!headerRules.length)
2130
+ return res;
2131
+ const creq = condRequest(rs);
2132
+ let headers = null;
2133
+ for (const { rule, matcher } of headerRules) {
2134
+ if (!matcher.match(path, creq))
2135
+ continue;
2136
+ headers ?? (headers = new Headers(res.headers));
2137
+ const keepCache = headers.get("cache-control") === IMMUTABLE_CACHE_CONTROL;
2138
+ for (const [k, v] of ruleHeaderPairs(rule.headers)) {
2139
+ if (keepCache && k.toLowerCase() === "cache-control")
2140
+ continue;
2141
+ if (k.toLowerCase() === "vary") {
2142
+ if (!(headers.get("vary") || "").toLowerCase().includes(v.toLowerCase()))
2143
+ headers.append("Vary", v);
2144
+ }
2145
+ else
2146
+ headers.set(k, v);
2147
+ }
2038
2148
  }
2149
+ if (!headers)
2150
+ return res;
2151
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
2039
2152
  }
2040
2153
  /** corsMiddleware; returns a Response for a preflight. */
2041
2154
  function applyCORS(rs) {
@@ -2090,6 +2203,8 @@ export function createKrateHandler(options) {
2090
2203
  origin: requestOrigin(request, url),
2091
2204
  ctx,
2092
2205
  };
2206
+ let headerPath = rs.path;
2207
+ const finalize = (res) => withHeaderRules(rs, headerPath, res);
2093
2208
  try {
2094
2209
  // Mount under the base path: requests outside it redirect (GET/HEAD) or 404.
2095
2210
  // The app then sees base-less paths, so a root-relative Location it
@@ -2119,20 +2234,21 @@ export function createKrateHandler(options) {
2119
2234
  }
2120
2235
  }
2121
2236
  applySecurityAndHeaders(rs);
2237
+ headerPath = rs.path;
2122
2238
  const preflight = applyCORS(rs);
2123
2239
  if (preflight)
2124
- return mounted ? withBaseLocation(preflight) : preflight;
2240
+ return finalize(mounted ? withBaseLocation(preflight) : preflight);
2125
2241
  await sleepMicrotask();
2126
2242
  const res = await mux(rs);
2127
- return mounted ? withBaseLocation(res) : res;
2243
+ return finalize(mounted ? withBaseLocation(res) : res);
2128
2244
  }
2129
2245
  catch (err) {
2130
2246
  console.error(`[krate] panic recovered: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
2131
2247
  if (rs.path.startsWith("/api/")) {
2132
2248
  rs.res.set("Content-Type", "application/json");
2133
- return finish(rs, 500, '{"error":"Internal Server Error"}');
2249
+ return finalize(finish(rs, 500, '{"error":"Internal Server Error"}'));
2134
2250
  }
2135
- return httpError(rs, "Internal Server Error", 500);
2251
+ return finalize(httpError(rs, "Internal Server Error", 500));
2136
2252
  }
2137
2253
  }
2138
2254
  }
package/dist/server.d.ts CHANGED
@@ -30,14 +30,14 @@ interface RawHTML {
30
30
  export declare function goComponent(name: string, tier: string, baked: Record<string, string> | null | undefined, props: Record<string, any> | undefined, revalidate?: number): JSXNode;
31
31
  type JSXNode = string | number | boolean | null | undefined | JSXNode[] | JSXElement | RawHTML;
32
32
  interface JSXElement {
33
- type: string | Function;
33
+ type: string | Function | object | symbol;
34
34
  props: Record<string, any>;
35
35
  children: JSXNode[];
36
36
  }
37
37
  export declare function Fragment(_props: {
38
38
  children?: JSXNode;
39
39
  }): JSXNode;
40
- export declare function jsx(type: string | Function, props: Record<string, any>, _key?: string): JSXElement;
40
+ export declare function jsx(type: string | Function | object | symbol, props: Record<string, any>, _key?: string): JSXElement;
41
41
  export declare const jsxs: typeof jsx;
42
42
  /**
43
43
  * ServerErrorBoundary is the request-time form of a segment's error.tsx under
@@ -97,18 +97,30 @@ export declare function lazy<P = Record<string, any>>(loader: () => Promise<{
97
97
  } | ((props: P) => unknown)>): (props: P & {
98
98
  children?: JSXNode;
99
99
  }) => Promise<JSXNode>;
100
- type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null) => string;
100
+ type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null, fwd?: SlotValues, capture?: Record<string, SlotValues>) => string;
101
+ type SlotValues = {
102
+ k: string;
103
+ v: unknown;
104
+ }[];
105
+ export declare const ISLAND_OPEN = "krate-island:";
106
+ export declare const ISLAND_CLOSE = "<!--/krate-island-->";
101
107
  /**
102
108
  * clientBoundary wraps an export of a `"use client"` module, or a component
103
109
  * of a React package, for the server bundle of a page that renders server
104
110
  * components. The server renders the component's initial HTML (render) and,
105
- * when it hydrates, puts it in a <krate-island> marker carrying its
106
- * serialized props; the per-module client chunk at src hydrates it in the
107
- * browser. A component without state or effects (hydrate false, an icon)
108
- * is plain HTML. Children are rendered on the server and passed as HTML, or,
109
- * when they hold client components of their own, as a tree that keeps those
110
- * components in the same Preact tree. A namespace export (Radix's Dialog) is
111
- * wrapped member by member. With `flight` the children always travel as a
111
+ * when it hydrates, puts it between <!--krate-island:{...}--> (module,
112
+ * export, chunk and serialized props) and <!--/krate-island--> with no
113
+ * element around it; the per-module client chunk at src hydrates those nodes
114
+ * in the browser. A real-React island (flight) gets a <krate-island> element
115
+ * instead, preceded by a JSON script with its props, because createRoot needs
116
+ * a container. A component without state or effects (hydrate
117
+ * false, an icon) is plain HTML. Children are rendered on the server into the
118
+ * component's HTML and adopted there by the browser (see DeferredSlot), or,
119
+ * when they hold client components of their own, sent as a tree that keeps
120
+ * those components in the same Preact tree. The children of an asChild component
121
+ * always travel as a tree, with a server component at the top of a child run
122
+ * to the element it renders, so the component's Slot can clone it. A
123
+ * namespace export (Radix's Dialog) is wrapped member by member. With `flight` the children always travel as a
112
124
  * tree (a real-React island rebuilds them as elements, not HTML).
113
125
  */
114
126
  export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender, hydrate?: boolean, flight?: boolean): unknown;
@@ -117,13 +129,8 @@ export declare const HEAD_CLOSE = "<!--/krate-head-->";
117
129
  export declare function Head(props: {
118
130
  children?: JSXNode;
119
131
  }): JSXNode;
120
- export declare function Script(props: {
121
- src?: string;
122
- children?: string;
123
- }): JSXNode;
124
- export declare function Style(props: {
125
- children?: string;
126
- }): JSXNode;
132
+ export declare function Script(props: Record<string, any>): JSXNode;
133
+ export declare function Style(props: Record<string, any>): JSXNode;
127
134
  export declare function Link(props: {
128
135
  href?: string;
129
136
  prefetch?: boolean;