@krate/runtime 0.5.0-beta.3 → 0.5.0-rc.10

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 (219) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +496 -91
  22. package/dist/dom.d.ts +4 -0
  23. package/dist/dom.js +62 -16
  24. package/dist/effects.js +43 -10
  25. package/dist/events.d.ts +2 -0
  26. package/dist/events.js +18 -0
  27. package/dist/flight-props.d.ts +7 -0
  28. package/dist/flight-props.js +105 -0
  29. package/dist/handler-html.js +4 -4
  30. package/dist/handler-routing.d.ts +2 -23
  31. package/dist/handler-routing.js +9 -190
  32. package/dist/handler-segments.d.ts +6 -0
  33. package/dist/handler-segments.js +18 -4
  34. package/dist/head-tags.d.ts +9 -0
  35. package/dist/head-tags.js +93 -6
  36. package/dist/highlight-bind.js +1 -1
  37. package/dist/highlight.d.ts +3 -2
  38. package/dist/highlight.js +17 -12
  39. package/dist/hints.d.ts +25 -2
  40. package/dist/hints.js +147 -74
  41. package/dist/index.d.ts +2 -0
  42. package/dist/index.js +3 -0
  43. package/dist/island-swap.d.ts +47 -0
  44. package/dist/island-swap.js +635 -0
  45. package/dist/jsx-dev-runtime.d.ts +1 -1
  46. package/dist/jsx-types.d.ts +99 -3
  47. package/dist/krate-core.js +1 -1
  48. package/dist/krate-dev.js +407 -80
  49. package/dist/krate-f-actions.js +1 -1
  50. package/dist/krate-f-classes.js +1 -1
  51. package/dist/krate-f-highlight.js +1 -1
  52. package/dist/krate-f-list.js +1 -1
  53. package/dist/krate-f-navigation.js +1 -1
  54. package/dist/krate-f-router-lite.js +1 -1
  55. package/dist/krate-f-router.js +1 -1
  56. package/dist/krate-features.json +455 -0
  57. package/dist/krate-hydrate-lite.js +5 -5
  58. package/dist/krate-hydrate.js +5 -5
  59. package/dist/krate-island-swap.js +1 -0
  60. package/dist/krate-runtime.js +5 -5
  61. package/dist/krate-suspense.js +1 -1
  62. package/dist/list.d.ts +14 -4
  63. package/dist/list.js +30 -23
  64. package/dist/metadata.js +5 -2
  65. package/dist/navigation-react.d.ts +13 -0
  66. package/dist/navigation-react.js +86 -0
  67. package/dist/navigation.d.ts +19 -0
  68. package/dist/navigation.js +35 -0
  69. package/dist/node-server.js +3 -3
  70. package/dist/og.js +1 -1
  71. package/dist/platform.d.ts +52 -0
  72. package/dist/platform.js +57 -0
  73. package/dist/react-compat.d.ts +39 -0
  74. package/dist/react-compat.js +359 -0
  75. package/dist/react-server.d.ts +63 -0
  76. package/dist/react-server.js +125 -0
  77. package/dist/region-wire.d.ts +10 -0
  78. package/dist/region-wire.js +154 -0
  79. package/dist/request-context.js +1 -1
  80. package/dist/request-extras.d.ts +4 -0
  81. package/dist/request-extras.js +51 -0
  82. package/dist/resp.js +1 -1
  83. package/dist/route-source.d.ts +39 -0
  84. package/dist/route-source.js +532 -0
  85. package/dist/router-lite.js +3 -9
  86. package/dist/router.d.ts +1 -1
  87. package/dist/router.js +675 -100
  88. package/dist/server-handler.d.ts +69 -1
  89. package/dist/server-handler.js +515 -96
  90. package/dist/server-renderer.js +16 -7
  91. package/dist/server.d.ts +73 -16
  92. package/dist/server.js +619 -102
  93. package/dist/sha256.js +9 -9
  94. package/dist/signal.js +47 -20
  95. package/dist/site-config.d.ts +15 -0
  96. package/dist/site-config.js +28 -0
  97. package/dist/slot.d.ts +12 -0
  98. package/dist/slot.js +23 -0
  99. package/dist/ssr-core.d.ts +2 -0
  100. package/dist/ssr-core.js +12 -4
  101. package/dist/suspense.js +34 -2
  102. package/dist/testing.d.ts +62 -0
  103. package/dist/testing.js +90 -0
  104. package/dist/use-id.js +1 -1
  105. package/package.json +28 -3
  106. package/dist/action-context.test.d.ts +0 -1
  107. package/dist/action-context.test.js +0 -72
  108. package/dist/actions.test.d.ts +0 -1
  109. package/dist/actions.test.js +0 -477
  110. package/dist/cache-adapter.test.d.ts +0 -1
  111. package/dist/cache-adapter.test.js +0 -244
  112. package/dist/cache.test.d.ts +0 -1
  113. package/dist/cache.test.js +0 -233
  114. package/dist/class-component.test.d.ts +0 -1
  115. package/dist/class-component.test.js +0 -462
  116. package/dist/class-helpers.test.d.ts +0 -1
  117. package/dist/class-helpers.test.js +0 -169
  118. package/dist/context.test.d.ts +0 -1
  119. package/dist/context.test.js +0 -57
  120. package/dist/derived.test.d.ts +0 -1
  121. package/dist/derived.test.js +0 -140
  122. package/dist/dev-overlay.test.d.ts +0 -1
  123. package/dist/dev-overlay.test.js +0 -152
  124. package/dist/discrete.test.d.ts +0 -1
  125. package/dist/discrete.test.js +0 -100
  126. package/dist/dom.test.d.ts +0 -1
  127. package/dist/dom.test.js +0 -31
  128. package/dist/effect-errors.test.d.ts +0 -1
  129. package/dist/effect-errors.test.js +0 -163
  130. package/dist/effects.test.d.ts +0 -1
  131. package/dist/effects.test.js +0 -485
  132. package/dist/events.test.d.ts +0 -1
  133. package/dist/events.test.js +0 -447
  134. package/dist/handler-html.test.d.ts +0 -1
  135. package/dist/handler-html.test.js +0 -256
  136. package/dist/handler-routing.test.d.ts +0 -1
  137. package/dist/handler-routing.test.js +0 -99
  138. package/dist/handler-segments.test.d.ts +0 -1
  139. package/dist/handler-segments.test.js +0 -217
  140. package/dist/head-tags.test.d.ts +0 -1
  141. package/dist/head-tags.test.js +0 -131
  142. package/dist/highlight-bind.test.d.ts +0 -1
  143. package/dist/highlight-bind.test.js +0 -124
  144. package/dist/highlight.test.d.ts +0 -1
  145. package/dist/highlight.test.js +0 -56
  146. package/dist/lanes.test.d.ts +0 -1
  147. package/dist/lanes.test.js +0 -59
  148. package/dist/list.test.d.ts +0 -1
  149. package/dist/list.test.js +0 -344
  150. package/dist/metadata.test.d.ts +0 -1
  151. package/dist/metadata.test.js +0 -167
  152. package/dist/navigation.test.d.ts +0 -1
  153. package/dist/navigation.test.js +0 -130
  154. package/dist/node-server.test.d.ts +0 -1
  155. package/dist/node-server.test.js +0 -492
  156. package/dist/optimistic-lanes.test.d.ts +0 -1
  157. package/dist/optimistic-lanes.test.js +0 -45
  158. package/dist/patterns.test.d.ts +0 -1
  159. package/dist/patterns.test.js +0 -98
  160. package/dist/portal.test.d.ts +0 -1
  161. package/dist/portal.test.js +0 -99
  162. package/dist/react-effects.test.d.ts +0 -1
  163. package/dist/react-effects.test.js +0 -96
  164. package/dist/react-suspense.test.d.ts +0 -1
  165. package/dist/react-suspense.test.js +0 -194
  166. package/dist/react.test.d.ts +0 -1
  167. package/dist/react.test.js +0 -60
  168. package/dist/react19.test.d.ts +0 -1
  169. package/dist/react19.test.js +0 -176
  170. package/dist/reactivity-core.test.d.ts +0 -1
  171. package/dist/reactivity-core.test.js +0 -152
  172. package/dist/reconcile.test.d.ts +0 -1
  173. package/dist/reconcile.test.js +0 -110
  174. package/dist/refs.test.d.ts +0 -1
  175. package/dist/refs.test.js +0 -257
  176. package/dist/router-layout.test.d.ts +0 -1
  177. package/dist/router-layout.test.js +0 -249
  178. package/dist/router-nav.test.d.ts +0 -1
  179. package/dist/router-nav.test.js +0 -464
  180. package/dist/router-slots.test.d.ts +0 -1
  181. package/dist/router-slots.test.js +0 -144
  182. package/dist/router-speculation.test.d.ts +0 -1
  183. package/dist/router-speculation.test.js +0 -25
  184. package/dist/router-styles.test.d.ts +0 -1
  185. package/dist/router-styles.test.js +0 -98
  186. package/dist/router.test.d.ts +0 -1
  187. package/dist/router.test.js +0 -36
  188. package/dist/server-async.test.d.ts +0 -1
  189. package/dist/server-async.test.js +0 -216
  190. package/dist/server-handler.test.d.ts +0 -1
  191. package/dist/server-handler.test.js +0 -535
  192. package/dist/server-highlight.test.d.ts +0 -1
  193. package/dist/server-highlight.test.js +0 -32
  194. package/dist/server-renderer.test.d.ts +0 -1
  195. package/dist/server-renderer.test.js +0 -266
  196. package/dist/server.test.d.ts +0 -1
  197. package/dist/server.test.js +0 -88
  198. package/dist/sha256.test.d.ts +0 -1
  199. package/dist/sha256.test.js +0 -13
  200. package/dist/signal-lanes.test.d.ts +0 -1
  201. package/dist/signal-lanes.test.js +0 -32
  202. package/dist/signal.test.d.ts +0 -1
  203. package/dist/signal.test.js +0 -68
  204. package/dist/slots.test.d.ts +0 -1
  205. package/dist/slots.test.js +0 -169
  206. package/dist/snapshots.test.d.ts +0 -1
  207. package/dist/snapshots.test.js +0 -208
  208. package/dist/ssr-core-behavior.test.d.ts +0 -1
  209. package/dist/ssr-core-behavior.test.js +0 -620
  210. package/dist/ssr-core.test.d.ts +0 -1
  211. package/dist/ssr-core.test.js +0 -324
  212. package/dist/static-memory.test.d.ts +0 -1
  213. package/dist/static-memory.test.js +0 -26
  214. package/dist/storage.test.d.ts +0 -1
  215. package/dist/storage.test.js +0 -46
  216. package/dist/suspense-actions.test.d.ts +0 -1
  217. package/dist/suspense-actions.test.js +0 -72
  218. package/dist/suspense.test.d.ts +0 -1
  219. package/dist/suspense.test.js +0 -518
@@ -24,7 +24,7 @@ function withNextCookies(ctx) {
24
24
  get: (name) => {
25
25
  const v = jar.get(name);
26
26
  if (v === undefined || v === null)
27
- return undefined;
27
+ return;
28
28
  return typeof v === 'object' ? v : { name, value: String(v) };
29
29
  },
30
30
  getAll: () => jar.getAll(),
package/dist/actions.d.ts CHANGED
@@ -93,6 +93,13 @@ interface RunnableAction {
93
93
  (payload: unknown): unknown;
94
94
  __krateRun?: (payload: unknown) => Promise<boolean>;
95
95
  }
96
+ /**
97
+ * Drops the query of a native action URL: the no-JS leading args and return
98
+ * path are only for native posts. The one exception is the sealed closure
99
+ * token of an inline server action (`k1.` prefix), which the server needs to
100
+ * rebuild the values the function closed over.
101
+ */
102
+ export declare function stripActionURL(url: string): string;
96
103
  /**
97
104
  * Runs a form action: sets the form status, invokes the action with the form
98
105
  * data in an async transition, resets the form on success and reports errors.
package/dist/actions.js CHANGED
@@ -21,6 +21,7 @@
21
21
  * "revalidated":true?,"revalidation":{"paths":[...],"tags":[...]}?}
22
22
  * {"ok":false,"error":{"message":M,"digest":D}}
23
23
  */
24
+ import { basePath, withBase } from './base-path.js';
24
25
  import { createEffect, onCleanup, krateRunEvent, krateTransitionWrites } from './signal.js';
25
26
  /** Field and query parameter carrying the JSON leading arguments of a form call. */
26
27
  export const ACTION_ARGS_FIELD = '__krate_args';
@@ -34,10 +35,6 @@ export class ServerActionError extends Error {
34
35
  this.digest = digest;
35
36
  }
36
37
  }
37
- function basePath() {
38
- const cfg = globalThis.__KRATE_CFG__;
39
- return cfg && cfg.basePath ? cfg.basePath : '';
40
- }
41
38
  /** True for a server action proxy created by `__krateAction`. */
42
39
  export function isServerAction(value) {
43
40
  return typeof value === 'function' && typeof value.$$krateAction === 'string';
@@ -53,13 +50,19 @@ function navigateTo(url) {
53
50
  if (typeof nav === 'function')
54
51
  nav(safe);
55
52
  else if (typeof location !== 'undefined')
56
- location.assign(safe);
53
+ location.assign(withBase(safe));
54
+ }
55
+ /** Follows an absolute http(s) redirect the server marked external. */
56
+ function navigateExternal(url) {
57
+ if (typeof location === 'undefined' || !/^https?:\/\//i.test(url))
58
+ return;
59
+ location.assign(url);
57
60
  }
58
61
  /** Only same-origin absolute paths are followed after an action. */
59
62
  function safeRedirect(url) {
60
63
  if (!url || !url.startsWith('/') || url.startsWith('//'))
61
64
  return '';
62
- if (url.includes('\\') || /[\u0000-\u001f\u007f]/.test(url))
65
+ if (url.includes('\\') || /[\u0000-\u001F\u007F]/.test(url))
63
66
  return '';
64
67
  return url;
65
68
  }
@@ -130,7 +133,10 @@ export async function callServerAction(url, args) {
130
133
  dispatchRevalidate(payload.revalidation);
131
134
  if (typeof payload.redirect === 'string' && payload.redirect) {
132
135
  redirectsFollowed++;
133
- navigateTo(payload.redirect);
136
+ if (payload.external)
137
+ navigateExternal(payload.redirect);
138
+ else
139
+ navigateTo(payload.redirect);
134
140
  }
135
141
  return payload.result;
136
142
  }
@@ -393,10 +399,28 @@ function formDataFor(form, submitter) {
393
399
  }
394
400
  return fd;
395
401
  }
396
- function stripActionURL(url) {
397
- // The no-JS leading-args query is only for native posts.
402
+ /**
403
+ * Drops the query of a native action URL: the no-JS leading args and return
404
+ * path are only for native posts. The one exception is the sealed closure
405
+ * token of an inline server action (`k1.` prefix), which the server needs to
406
+ * rebuild the values the function closed over.
407
+ */
408
+ export function stripActionURL(url) {
398
409
  const i = url.indexOf('?');
399
- return i < 0 ? url : url.slice(0, i);
410
+ if (i === -1)
411
+ return url;
412
+ const base = url.slice(0, i);
413
+ try {
414
+ const raw = new URLSearchParams(url.slice(i + 1)).get(ACTION_ARGS_FIELD);
415
+ const leading = raw ? JSON.parse(raw) : null;
416
+ if (Array.isArray(leading) && typeof leading[0] === 'string' && leading[0].startsWith('k1.')) {
417
+ return base + '?' + ACTION_ARGS_FIELD + '=' + encodeURIComponent(JSON.stringify([leading[0]]));
418
+ }
419
+ }
420
+ catch {
421
+ // not a token: strip like any native query
422
+ }
423
+ return base;
400
424
  }
401
425
  /**
402
426
  * Runs a form action: sets the form status, invokes the action with the form
@@ -0,0 +1,28 @@
1
+ export type AfterTask = (() => unknown) | PromiseLike<unknown>;
2
+ export declare function after(task: AfterTask): void;
3
+ /** Runs and clears a scope's after() tasks in order; each failure is logged. */
4
+ export declare function runAfterTasks(scope: {
5
+ after?: Array<() => unknown>;
6
+ }): Promise<void>;
7
+ /** request.cookies on an API route's Request, shaped like Next's RequestCookies (read-only). */
8
+ export interface KrateRequestCookies {
9
+ get(name: string): {
10
+ name: string;
11
+ value: string;
12
+ } | undefined;
13
+ getAll(name?: string): Array<{
14
+ name: string;
15
+ value: string;
16
+ }>;
17
+ has(name: string): boolean;
18
+ }
19
+ /** request.nextUrl: the request URL plus Next's basePath and clone(). */
20
+ export interface KrateNextURL extends URL {
21
+ readonly basePath: string;
22
+ clone(): KrateNextURL;
23
+ }
24
+ /** The Request an API route handler receives: a web Request with Next-style cookies and nextUrl. */
25
+ export type KrateRequest = Request & {
26
+ readonly cookies: KrateRequestCookies;
27
+ readonly nextUrl: KrateNextURL;
28
+ };
package/dist/after.js ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `after(task)` mirrors `next/server`'s `after()`: it schedules work that runs
3
+ * once the response has been sent (logging, analytics, cache warming). Inside
4
+ * an API route the task is queued on the request and the server runs it after
5
+ * the response is flushed, in registration order. Errors are logged, never
6
+ * sent to the client. Where no request is active (the embedded runtime, tests)
7
+ * the task runs on a later microtask turn, right after the handler settles.
8
+ * On a serverless target the task is also handed to the platform's waitUntil
9
+ * (the Worker's ctx.waitUntil on cloudflare), so it outlives the response.
10
+ */
11
+ import { currentRevalidateScope } from './cache-scope.js';
12
+ import { platformWaitUntil } from './platform.js';
13
+ function toThunk(task) {
14
+ if (typeof task === 'function')
15
+ return task;
16
+ if (task && typeof task.then === 'function')
17
+ return () => task;
18
+ throw new TypeError('after() expects a function or a promise');
19
+ }
20
+ export function after(task) {
21
+ const thunk = toThunk(task);
22
+ const scope = currentRevalidateScope();
23
+ if (scope) {
24
+ (scope.after || (scope.after = [])).push(thunk);
25
+ return;
26
+ }
27
+ const run = Promise.resolve()
28
+ .then(thunk)
29
+ .catch((err) => console.error(`[krate] after() task failed: ${(err && err.stack) || err}`));
30
+ // Serverless platforms stop the instance once the response is sent unless
31
+ // waitUntil keeps it alive.
32
+ platformWaitUntil(run);
33
+ }
34
+ /** Runs and clears a scope's after() tasks in order; each failure is logged. */
35
+ export async function runAfterTasks(scope) {
36
+ const tasks = scope.after;
37
+ if (!tasks || tasks.length === 0)
38
+ return;
39
+ scope.after = [];
40
+ for (const t of tasks) {
41
+ try {
42
+ await t();
43
+ }
44
+ catch (err) {
45
+ console.error(`[krate] after() task failed: ${(err && err.stack) || err}`);
46
+ }
47
+ }
48
+ }
@@ -2,4 +2,13 @@ import type { StaticLayer } from "./server-handler.js";
2
2
  export interface AssetFetcher {
3
3
  fetch(request: Request): Promise<Response>;
4
4
  }
5
- export declare function createAssetsStaticLayer(assets: AssetFetcher): StaticLayer;
5
+ export interface AssetsStaticOptions {
6
+ /**
7
+ * Ask for a folder's index.html file by name. The generated wrangler config
8
+ * sets assets.html_handling to "none" for trailingSlash "ignore", so the
9
+ * platform no longer maps /x and /x/ to x/index.html or redirects between
10
+ * them; the layer does that mapping itself and both URLs serve the page.
11
+ */
12
+ directoryIndex?: boolean;
13
+ }
14
+ export declare function createAssetsStaticLayer(assets: AssetFetcher, options?: AssetsStaticOptions): StaticLayer;
@@ -1,7 +1,7 @@
1
1
  // A StaticLayer backed by a platform asset fetcher (Cloudflare's env.ASSETS).
2
2
  // Used when the Worker runs first and falls through to the uploaded assets.
3
3
  import { extName } from "./handler-routing.js";
4
- export function createAssetsStaticLayer(assets) {
4
+ export function createAssetsStaticLayer(assets, options = {}) {
5
5
  const probe = async (url, path) => {
6
6
  const u = new URL(url);
7
7
  u.pathname = path;
@@ -23,7 +23,15 @@ export function createAssetsStaticLayer(assets) {
23
23
  },
24
24
  async serve(request, urlPath) {
25
25
  origin = new URL(request.url).origin;
26
- void urlPath;
26
+ if (options.directoryIndex && extName(urlPath) === "") {
27
+ const rel = urlPath.replace(/^\/+|\/+$/g, "");
28
+ const u = new URL(request.url);
29
+ u.pathname = rel === "" ? "/index.html" : "/" + rel + "/index.html";
30
+ const indexed = await assets.fetch(new Request(u.toString(), request));
31
+ // A file without an extension (and no folder of that name) is still served as itself.
32
+ if (indexed.status !== 404)
33
+ return indexed;
34
+ }
27
35
  const res = await assets.fetch(request);
28
36
  return res.status === 404 ? null : res;
29
37
  },
@@ -0,0 +1,7 @@
1
+ /** The configured base path as "" or "/prefix" (no trailing slash). */
2
+ export declare function basePath(): string;
3
+ /**
4
+ * Prefixes a root-relative URL with the base path. Relative URLs, fragments,
5
+ * queries, absolute URLs and protocol-relative URLs are returned unchanged.
6
+ */
7
+ export declare function withBase(url: string): string;
@@ -0,0 +1,20 @@
1
+ // The site base path, shared by the router, actions and link rendering. The
2
+ // compiler writes the config into the page head (see site-config.ts); server
3
+ // bundles set it on globalThis so server-rendered links get the same prefix.
4
+ import { siteConfig } from './site-config.js';
5
+ /** The configured base path as "" or "/prefix" (no trailing slash). */
6
+ export function basePath() {
7
+ const cfg = siteConfig();
8
+ const bp = (cfg && cfg.basePath) || '';
9
+ if (!bp || bp === '/')
10
+ return '';
11
+ return '/' + bp.replace(/^\/+|\/+$/g, '');
12
+ }
13
+ /**
14
+ * Prefixes a root-relative URL with the base path. Relative URLs, fragments,
15
+ * queries, absolute URLs and protocol-relative URLs are returned unchanged.
16
+ */
17
+ export function withBase(url) {
18
+ const bp = basePath();
19
+ return bp && url.charCodeAt(0) === 47 && url.charCodeAt(1) !== 47 ? bp + url : url;
20
+ }
package/dist/boundary.js CHANGED
@@ -330,7 +330,7 @@ function disposeScopedOwners(gone) {
330
330
  const p = o.parent;
331
331
  if (p && !gone(p.scope)) {
332
332
  const i = p.children.indexOf(o);
333
- if (i >= 0)
333
+ if (i !== -1)
334
334
  p.children.splice(i, 1);
335
335
  }
336
336
  }
@@ -0,0 +1,12 @@
1
+ type Props = Record<string, unknown> & {
2
+ children?: unknown;
3
+ };
4
+ export declare const Head: typeof globalThis.Head;
5
+ export declare const Icon: typeof globalThis.Icon;
6
+ export declare const SyntaxHighlight: typeof globalThis.SyntaxHighlight;
7
+ export declare const Suspense: typeof globalThis.Suspense;
8
+ export declare const Link: typeof globalThis.Link;
9
+ export declare function Script(_props: Props): null;
10
+ export declare function Style(_props: Props): null;
11
+ export declare function Image(props: Props): unknown;
12
+ export {};
@@ -0,0 +1,42 @@
1
+ // Importable values for the tags the compiler provides (<Head>, <Link>, ...).
2
+ //
3
+ // A page or component normally uses them as globals and the compiler lowers
4
+ // them: <Head> children are hoisted into the document head, <Link> becomes an
5
+ // anchor wired for navigation. These values exist so that
6
+ // `import { Head } from "@krate/runtime"` resolves to a real export in every
7
+ // bundle that links the runtime (React islands, tooling). Request-time server
8
+ // bundles map the same names to the server renderer in @krate/runtime/server,
9
+ // so these client-side values never decide what the server writes.
10
+ import { h } from "./dom.js";
11
+ /** Head content is hoisted into the document at build time; nothing renders in place. */
12
+ function headTag(_props) {
13
+ return null;
14
+ }
15
+ function iconTag(_props) {
16
+ return null;
17
+ }
18
+ function syntaxHighlightTag(props) {
19
+ return h("pre", null, h("code", null, props.children));
20
+ }
21
+ function suspenseTag(props) {
22
+ return props.children ?? null;
23
+ }
24
+ function linkTag(props) {
25
+ const { children, prefetch: _prefetch, replace: _replace, scroll: _scroll, ...rest } = props;
26
+ return h("a", rest, children);
27
+ }
28
+ // The typed tags keep the prop types of their global declarations.
29
+ export const Head = headTag;
30
+ export const Icon = iconTag;
31
+ export const SyntaxHighlight = syntaxHighlightTag;
32
+ export const Suspense = suspenseTag;
33
+ export const Link = linkTag;
34
+ export function Script(_props) {
35
+ return null;
36
+ }
37
+ export function Style(_props) {
38
+ return null;
39
+ }
40
+ export function Image(props) {
41
+ return h("img", props);
42
+ }
@@ -165,7 +165,7 @@ export class MemoryAdapter {
165
165
  export async function loadCacheAdapter(spec) {
166
166
  if (!spec || !spec.adapter || spec.adapter === 'memory')
167
167
  return null;
168
- const opts = { ...(spec.options || {}), url: spec.url, prefix: spec.prefix, timeoutMs: spec.timeoutMs };
168
+ const opts = { ...spec.options, url: spec.url, prefix: spec.prefix, timeoutMs: spec.timeoutMs };
169
169
  if (spec.adapter === 'redis') {
170
170
  const { RedisAdapter } = await import('./cache-redis.js');
171
171
  if (!spec.url)
@@ -28,6 +28,10 @@ export interface CacheScope {
28
28
  revalidate: number;
29
29
  /** True when a read opted out of caching (no-store, revalidate 0, unstable_noStore). */
30
30
  noStore: boolean;
31
+ /** True when an error boundary caught a render error (the response is a 500 and uncacheable). */
32
+ errorCaught?: boolean;
33
+ /** Head tags the render asked for (react-dom preload, preconnect, ...), deduplicated. */
34
+ hints?: Set<string>;
31
35
  }
32
36
  /** Minimal AsyncLocalStorage shape (the Node class satisfies it). */
33
37
  export interface AsyncStore<T> {
@@ -42,6 +46,8 @@ export interface RevalidateScope {
42
46
  type: 'page' | 'layout';
43
47
  }>;
44
48
  tags: string[];
49
+ /** Tasks registered with after(); the host runs them once the response is sent. */
50
+ after?: Array<() => unknown>;
45
51
  }
46
52
  /** In-process data cache with tag index and FIFO bound. */
47
53
  export declare class DataCache {
@@ -116,6 +122,8 @@ export declare function routeDataTag(route: string): string;
116
122
  export declare function recordCacheRead(tags: readonly string[] | undefined, revalidate: number | false | undefined): void;
117
123
  /** Marks the current render as uncacheable. Outside a render it has no effect. */
118
124
  export declare function markNoStore(): void;
125
+ /** Marks the current render as having shown an error boundary's UI. */
126
+ export declare function markErrorCaught(): void;
119
127
  /**
120
128
  * Reads a JSON value from the data cache; undefined on a miss. With a shared
121
129
  * cache the instances' common store answers; when it cannot, this process's own
@@ -18,6 +18,7 @@
18
18
  * has no Node imports: the embedded QuickJS API runtime bundles it too, and
19
19
  * there the data cache is backed by the Go host (`_go_cache_get/_go_cache_set`).
20
20
  */
21
+ import { HEAD_CLOSE, HEAD_OPEN } from './head-tags.js';
21
22
  const STATE_KEY = Symbol.for('krate.cache.runtime');
22
23
  const REVALIDATE_STORE_KEY = Symbol.for('krate.revalidate.store');
23
24
  /** In-process data cache with tag index and FIFO bound. */
@@ -147,7 +148,11 @@ export async function withCacheScope(route, fn) {
147
148
  const scope = { route, tags: new Set(), revalidate: 0, noStore: false };
148
149
  const epoch = rt.epoch;
149
150
  const store = rt.renderStore;
150
- const result = store ? await store.run(scope, () => Promise.resolve().then(fn)) : await fn();
151
+ let result = store ? await store.run(scope, () => Promise.resolve().then(fn)) : await fn();
152
+ if (scope.hints && scope.hints.size && typeof result === 'string') {
153
+ // react-dom resource hints go to the head of the response like <Head> tags.
154
+ result = (HEAD_OPEN + [...scope.hints].join('') + HEAD_CLOSE + result);
155
+ }
151
156
  return { result, scope, invalidated: rt.epoch !== epoch };
152
157
  }
153
158
  /**
@@ -178,6 +183,14 @@ export function markNoStore() {
178
183
  if (scope)
179
184
  scope.noStore = true;
180
185
  }
186
+ /** Marks the current render as having shown an error boundary's UI. */
187
+ export function markErrorCaught() {
188
+ const scope = currentRenderScope();
189
+ if (scope) {
190
+ scope.errorCaught = true;
191
+ scope.noStore = true;
192
+ }
193
+ }
181
194
  // Data cache access. In QuickJS the Go host owns the cache (shared by every
182
195
  // VM worker and invalidated with the rest of the host's caches); values cross
183
196
  // the bridge as JSON.
@@ -0,0 +1,2 @@
1
+ export declare const env: Record<string, any>;
2
+ export declare function waitUntil(work: Promise<unknown>): void;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Stand-in for the `cloudflare:workers` module. Server bundles import
3
+ * `cloudflare:workers` through this specifier; the cloudflare deploy bundle
4
+ * replaces it with the real module, so on a Worker `env` is the genuine
5
+ * binding object. Everywhere else (`krate dev`, `krate serve`) it reads the
6
+ * request's platform and fails with a message naming the missing binding.
7
+ */
8
+ import { getPlatform } from './platform.js';
9
+ export const env = new Proxy({}, {
10
+ get(_t, key) {
11
+ const platform = getPlatform();
12
+ const bindings = platform.env;
13
+ if (key in bindings || typeof key === 'symbol')
14
+ return bindings[key];
15
+ throw new Error(`cloudflare:workers env.${String(key)} is not available here: Worker bindings exist only on the cloudflare target ` +
16
+ '(krate deploy --target cloudflare), not in krate dev or krate serve');
17
+ },
18
+ has: (_t, key) => key in getPlatform().env,
19
+ ownKeys: () => Reflect.ownKeys(getPlatform().env),
20
+ getOwnPropertyDescriptor: (_t, key) => {
21
+ const d = Reflect.getOwnPropertyDescriptor(getPlatform().env, key);
22
+ return d ? { ...d, configurable: true } : undefined;
23
+ },
24
+ });
25
+ export function waitUntil(work) {
26
+ getPlatform().ctx.waitUntil(work);
27
+ }
package/dist/context.d.ts CHANGED
@@ -53,3 +53,8 @@ export declare function createContext<T>(defaultValue: T): Context<T>;
53
53
  * the list runtime have no provider on the stack otherwise.
54
54
  */
55
55
  export declare function krateContextRows<A extends unknown[], R>(entries: Array<[Context<any>, () => unknown]>, render: (...args: A) => R): (...args: A) => R;
56
+ /**
57
+ * Runs fn with the given provider values (getters) on top of their context
58
+ * stacks, as if fn rendered inside those providers.
59
+ */
60
+ export declare function krateWithContexts<R>(entries: Array<[Context<any>, () => unknown]>, fn: () => R): R;
package/dist/context.js CHANGED
@@ -109,6 +109,8 @@ export function createContext(defaultValue) {
109
109
  ctx.id = id;
110
110
  ctx.defaultValue = defaultValue;
111
111
  ctx.Provider = Provider;
112
+ // Lets a custom renderer map a provider element back to its context.
113
+ Provider.__kctxOf = ctx;
112
114
  ctx.Consumer = Consumer;
113
115
  ctx.useContext = useContext;
114
116
  ctx.use = useContext;
@@ -123,21 +125,30 @@ export function createContext(defaultValue) {
123
125
  * the list runtime have no provider on the stack otherwise.
124
126
  */
125
127
  export function krateContextRows(entries, render) {
126
- return (...args) => {
127
- const pushed = [];
128
- for (const [ctx, get] of entries) {
129
- const stack = contextStack.get(ctx.id);
130
- if (!stack)
131
- continue;
132
- stack.push(new LiveContext(get));
133
- pushed.push(stack);
134
- }
135
- try {
136
- return render(...args);
137
- }
138
- finally {
139
- for (const stack of pushed)
140
- stack.pop();
141
- }
142
- };
128
+ const wrapped = (...args) => krateWithContexts(entries, () => render(...args));
129
+ // Renderers that evaluate the content later (a custom renderer's deferred
130
+ // components) read the entries to make the same providers visible again.
131
+ wrapped.__kctx = entries;
132
+ return wrapped;
133
+ }
134
+ /**
135
+ * Runs fn with the given provider values (getters) on top of their context
136
+ * stacks, as if fn rendered inside those providers.
137
+ */
138
+ export function krateWithContexts(entries, fn) {
139
+ const pushed = [];
140
+ for (const [ctx, get] of entries) {
141
+ const stack = contextStack.get(ctx.id);
142
+ if (!stack)
143
+ continue;
144
+ stack.push(new LiveContext(get));
145
+ pushed.push(stack);
146
+ }
147
+ try {
148
+ return fn();
149
+ }
150
+ finally {
151
+ for (let i = pushed.length - 1; i >= 0; i--)
152
+ pushed[i].pop();
153
+ }
143
154
  }
@@ -6,6 +6,8 @@
6
6
  * diagnostics (file:line:col + source + caret + hint) and client runtime errors,
7
7
  * forwards runtime errors back to the dev server, and offers open-in-editor.
8
8
  */
9
+ /** True inside a Krate Native window (`krate://app`, or `https://app.localhost` on Windows). */
10
+ export declare function isNativeOrigin(): boolean;
9
11
  interface MapSegment {
10
12
  genCol: number;
11
13
  src: number;
@@ -27,11 +29,60 @@ interface StackFrame {
27
29
  export declare function parseStackFrame(line: string): StackFrame | null;
28
30
  /** Rewrites each mappable frame of a stack trace to its original location. */
29
31
  export declare function symbolicateStack(stack: string): Promise<string>;
32
+ export declare function routeMatches(pattern: string, pathname: string, basePath?: string): boolean;
30
33
  /**
31
- * Route matcher: a segment starting with `[` matches anything; `[...x]` matches
32
- * the rest. Exported (pure) for testing.
34
+ * Splits a buffer of Krate frames (u32 length, JSON, u16 blob count, blobs)
35
+ * into its complete JSON values. `rest` is the incomplete tail to prepend to
36
+ * the next chunk. Exported (pure) for testing.
33
37
  */
34
- export declare function routeMatches(pattern: string, pathname: string, basePath?: string): boolean;
38
+ export declare function parseFrames(buf: Uint8Array): {
39
+ values: unknown[];
40
+ rest: Uint8Array;
41
+ };
42
+ /** The host-side stack a KrateError carries in dev (`data.stack`), or "". */
43
+ export declare function hostStackOf(reason: unknown): string;
44
+ interface HostEvent {
45
+ seq: number;
46
+ kind: string;
47
+ fn: string;
48
+ id?: number;
49
+ time?: string;
50
+ durNs?: number;
51
+ code?: string;
52
+ message?: string;
53
+ }
54
+ /** One line of the Host panel. Exported (pure) for testing. */
55
+ export declare function hostEventLine(ev: HostEvent): string;
56
+ /** The memstat report the shell serves at /__krate/dev/memory (bytes). */
57
+ export interface MemoryReport {
58
+ os?: string;
59
+ source?: string;
60
+ procs?: {
61
+ pid: number;
62
+ name?: string;
63
+ role: string;
64
+ rss?: number;
65
+ pss: number;
66
+ privateDirty: number;
67
+ }[];
68
+ total?: {
69
+ pss: number;
70
+ privateDirty: number;
71
+ rss?: number;
72
+ };
73
+ notes?: string[];
74
+ }
75
+ /** Format a byte count for the Memory panel. Exported (pure) for testing. */
76
+ export declare function formatBytes(n: number): string;
77
+ /**
78
+ * The JS heap of this page, or null where the engine does not expose it.
79
+ * Chromium has performance.memory; WebKit (the engine of the Linux and macOS
80
+ * webviews) has no heap size API, so the panel shows the web process row
81
+ * (PSS and private dirty, which include the JS heap) instead.
82
+ */
83
+ export declare function jsHeapBytes(): number | null;
84
+ /** The rows of the Memory panel as [label, value] pairs. Exported (pure) for testing. */
85
+ export declare function memoryRows(rep: MemoryReport | null, domNodes: number, heap: number | null): [string, string][];
35
86
  /** Initialise the dev overlay. Safe to call more than once. */
36
87
  export declare function initDevOverlay(): void;
37
88
  export {};