@krate/runtime 0.5.0-rc.2 → 0.5.0-rc.3

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 (152) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +21 -3
  3. package/dist/actions.test.js +8 -410
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/after.test.js +58 -0
  7. package/dist/assets-static.d.ts +10 -1
  8. package/dist/assets-static.js +10 -2
  9. package/dist/base-path.js +4 -3
  10. package/dist/builtin-tags.d.ts +12 -0
  11. package/dist/builtin-tags.js +42 -0
  12. package/dist/builtin-tags.test.js +12 -0
  13. package/dist/cache-adapter.test.js +4 -203
  14. package/dist/cache-scope.d.ts +2 -0
  15. package/dist/cache.test.js +1 -197
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/dev-overlay.d.ts +54 -3
  19. package/dist/dev-overlay.js +469 -76
  20. package/dist/dom.js +3 -1
  21. package/dist/events.test.js +2 -407
  22. package/dist/handler-html.test.js +1 -202
  23. package/dist/handler-routing.js +3 -0
  24. package/dist/handler-segments.d.ts +6 -0
  25. package/dist/handler-segments.js +16 -2
  26. package/dist/handler-segments.test.js +8 -200
  27. package/dist/head-tags.d.ts +9 -0
  28. package/dist/head-tags.js +85 -1
  29. package/dist/head-tags.test.js +18 -125
  30. package/dist/index.d.ts +1 -5
  31. package/dist/index.js +3 -0
  32. package/dist/inline-action-token.test.js +31 -0
  33. package/dist/jsx-svg-types.test.js +58 -0
  34. package/dist/jsx-types.d.ts +92 -1
  35. package/dist/krate-core.js +1 -1
  36. package/dist/krate-dev.js +384 -65
  37. package/dist/krate-f-actions.js +1 -1
  38. package/dist/krate-f-navigation.js +1 -1
  39. package/dist/krate-f-router-lite.js +1 -1
  40. package/dist/krate-f-router.js +1 -1
  41. package/dist/krate-features.json +2 -0
  42. package/dist/krate-hydrate-lite.js +5 -5
  43. package/dist/krate-hydrate.js +5 -5
  44. package/dist/krate-runtime.js +5 -5
  45. package/dist/link-base-path.test.js +28 -0
  46. package/dist/node-server.test.js +1 -355
  47. package/dist/platform.d.ts +52 -0
  48. package/dist/platform.js +57 -0
  49. package/dist/platform.test.js +44 -0
  50. package/dist/router-nav.test.js +15 -444
  51. package/dist/router.js +39 -1
  52. package/dist/server-handler.d.ts +48 -0
  53. package/dist/server-handler.js +272 -16
  54. package/dist/server-handler.test.js +54 -388
  55. package/dist/server-renderer.test.js +0 -104
  56. package/dist/server.d.ts +15 -5
  57. package/dist/server.js +149 -22
  58. package/dist/server.test.js +52 -60
  59. package/dist/site-config.d.ts +13 -0
  60. package/dist/site-config.js +28 -0
  61. package/dist/site-config.test.js +30 -0
  62. package/dist/ssr-core-behavior.test.js +3 -515
  63. package/dist/testing.d.ts +59 -0
  64. package/dist/testing.js +88 -0
  65. package/dist/testing.test.js +73 -0
  66. package/package.json +9 -1
  67. package/dist/action-context.test.js +0 -72
  68. package/dist/base-path.test.js +0 -88
  69. package/dist/class-component.test.js +0 -462
  70. package/dist/class-helpers.test.js +0 -169
  71. package/dist/context.test.js +0 -57
  72. package/dist/derived.test.js +0 -140
  73. package/dist/dev-overlay.test.js +0 -165
  74. package/dist/discrete.test.js +0 -100
  75. package/dist/dom.test.d.ts +0 -1
  76. package/dist/dom.test.js +0 -39
  77. package/dist/effect-errors.test.d.ts +0 -1
  78. package/dist/effect-errors.test.js +0 -199
  79. package/dist/effects.test.d.ts +0 -1
  80. package/dist/effects.test.js +0 -485
  81. package/dist/handler-routing.test.d.ts +0 -1
  82. package/dist/handler-routing.test.js +0 -99
  83. package/dist/highlight-bind.test.d.ts +0 -1
  84. package/dist/highlight-bind.test.js +0 -124
  85. package/dist/highlight.test.d.ts +0 -1
  86. package/dist/highlight.test.js +0 -56
  87. package/dist/lanes.test.d.ts +0 -1
  88. package/dist/lanes.test.js +0 -59
  89. package/dist/list.test.d.ts +0 -1
  90. package/dist/list.test.js +0 -435
  91. package/dist/metadata.test.d.ts +0 -1
  92. package/dist/metadata.test.js +0 -167
  93. package/dist/navigation.test.d.ts +0 -1
  94. package/dist/navigation.test.js +0 -130
  95. package/dist/optimistic-lanes.test.d.ts +0 -1
  96. package/dist/optimistic-lanes.test.js +0 -45
  97. package/dist/patterns.test.d.ts +0 -1
  98. package/dist/patterns.test.js +0 -125
  99. package/dist/portal.test.d.ts +0 -1
  100. package/dist/portal.test.js +0 -99
  101. package/dist/react-effects.test.d.ts +0 -1
  102. package/dist/react-effects.test.js +0 -133
  103. package/dist/react-suspense.test.d.ts +0 -1
  104. package/dist/react-suspense.test.js +0 -194
  105. package/dist/react.test.d.ts +0 -1
  106. package/dist/react.test.js +0 -60
  107. package/dist/react19.test.d.ts +0 -1
  108. package/dist/react19.test.js +0 -176
  109. package/dist/reactivity-core.test.d.ts +0 -1
  110. package/dist/reactivity-core.test.js +0 -152
  111. package/dist/reconcile.test.d.ts +0 -1
  112. package/dist/reconcile.test.js +0 -110
  113. package/dist/refs.test.d.ts +0 -1
  114. package/dist/refs.test.js +0 -257
  115. package/dist/router-layout.test.d.ts +0 -1
  116. package/dist/router-layout.test.js +0 -249
  117. package/dist/router-slots.test.d.ts +0 -1
  118. package/dist/router-slots.test.js +0 -144
  119. package/dist/router-speculation.test.d.ts +0 -1
  120. package/dist/router-speculation.test.js +0 -25
  121. package/dist/router-styles.test.d.ts +0 -1
  122. package/dist/router-styles.test.js +0 -98
  123. package/dist/router.test.d.ts +0 -1
  124. package/dist/router.test.js +0 -36
  125. package/dist/server-async.test.d.ts +0 -1
  126. package/dist/server-async.test.js +0 -216
  127. package/dist/server-highlight.test.d.ts +0 -1
  128. package/dist/server-highlight.test.js +0 -32
  129. package/dist/signal-lanes.test.d.ts +0 -1
  130. package/dist/signal-lanes.test.js +0 -32
  131. package/dist/slots.test.d.ts +0 -1
  132. package/dist/slots.test.js +0 -187
  133. package/dist/snapshots.test.d.ts +0 -1
  134. package/dist/snapshots.test.js +0 -208
  135. package/dist/ssr-core.test.d.ts +0 -1
  136. package/dist/ssr-core.test.js +0 -324
  137. package/dist/static-memory.test.d.ts +0 -1
  138. package/dist/static-memory.test.js +0 -26
  139. package/dist/storage.test.d.ts +0 -1
  140. package/dist/storage.test.js +0 -46
  141. package/dist/suspense-actions.test.d.ts +0 -1
  142. package/dist/suspense-actions.test.js +0 -72
  143. package/dist/suspense.test.d.ts +0 -1
  144. package/dist/suspense.test.js +0 -556
  145. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  146. /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
  147. /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
  148. /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  149. /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
  150. /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
  151. /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
  152. /package/dist/{discrete.test.d.ts → testing.test.d.ts} +0 -0
@@ -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
  },
package/dist/base-path.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // The site base path, shared by the router, actions and link rendering. The
2
- // compiler sets `__KRATE_CFG__` in the page head; server bundles set it on
3
- // globalThis so server-rendered links get the same prefix.
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';
4
5
  /** The configured base path as "" or "/prefix" (no trailing slash). */
5
6
  export function basePath() {
6
- const cfg = globalThis.__KRATE_CFG__;
7
+ const cfg = siteConfig();
7
8
  const bp = (cfg && cfg.basePath) || '';
8
9
  if (!bp || bp === '/')
9
10
  return '';
@@ -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
+ }
@@ -0,0 +1,12 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import * as runtime from "./index.js";
3
+ describe("compiler-provided tags", () => {
4
+ it("are real exports of the runtime entry", () => {
5
+ for (const name of ["Head", "Link", "Image", "Script", "Style", "Icon", "Suspense", "SyntaxHighlight"]) {
6
+ expect(typeof runtime[name], name).toBe("function");
7
+ }
8
+ });
9
+ it("render nothing for head content in the client entry", () => {
10
+ expect(runtime.Head({ children: "x" })).toBeNull();
11
+ });
12
+ });
@@ -1,12 +1,11 @@
1
1
  // @vitest-environment node
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
3
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
- import { CacheGuard, MemoryAdapter, SharedDataCache, cacheSpecFromConfig, cacheSpecFromEnv, installCacheAdapter, loadCacheAdapter } from './cache-adapter';
4
+ import { CacheGuard } from './cache-adapter';
5
5
  import { RedisAdapter } from './cache-redis';
6
- import { SharedIsrStore, isrStoreFor } from './shared-isr';
7
- import { createSSRCore, MemoryIsrStore } from './ssr-core';
8
- import { cacheRuntime, installRenderStore, markNoStore, patchFetch } from './cache-scope';
9
- import { parseRedisURL } from './resp';
6
+ import { SharedIsrStore } from './shared-isr';
7
+ import { createSSRCore } from './ssr-core';
8
+ import { cacheRuntime, installRenderStore, markNoStore } from './cache-scope';
10
9
  import { startFakeRedis } from './test-redis';
11
10
  import { jsx } from './server';
12
11
  installRenderStore(new AsyncLocalStorage());
@@ -23,144 +22,8 @@ afterEach(async () => {
23
22
  });
24
23
  const url = () => `redis://127.0.0.1:${redis.port}/0`;
25
24
  const adapter = () => new RedisAdapter({ url: url(), timeoutMs: 200 });
26
- describe('parseRedisURL', () => {
27
- it('reads host, port, credentials, db and TLS', () => {
28
- expect(parseRedisURL('redis://u:p%40ss@cache.example:6380/2')).toMatchObject({ host: 'cache.example', port: 6380, username: 'u', password: 'p@ss', db: 2, tls: false });
29
- expect(parseRedisURL('rediss://cache.example')).toMatchObject({ port: 6379, tls: true });
30
- expect(() => parseRedisURL('http://x')).toThrow(/protocol/);
31
- });
32
- });
33
- describe('RedisAdapter', () => {
34
- it('stores values with a ttl and tags, and deletes by tag', async () => {
35
- const a = adapter();
36
- await a.set('one', '1', { ttlSeconds: 30, tags: ['t:a', 't:b'] });
37
- await a.set('two', '2', { tags: ['t:a'] });
38
- expect(await a.get('one')).toBe('1');
39
- expect(await a.get('missing')).toBeNull();
40
- expect((await a.keysByTag('t:a')).sort()).toEqual(['one', 'two']);
41
- expect(await a.deleteByTags(['t:a'])).toBe(2);
42
- expect(await a.get('one')).toBeNull();
43
- expect(await a.get('two')).toBeNull();
44
- expect(redis.commands.some((c) => c[0] === 'SET' && c[3] === 'EX' && c[4] === '30')).toBe(true);
45
- await a.close();
46
- });
47
- it('keeps apps apart with a prefix', async () => {
48
- const a = new RedisAdapter({ url: url(), prefix: 'one:' });
49
- const b = new RedisAdapter({ url: url(), prefix: 'two:' });
50
- await a.set('k', 'A');
51
- expect(await b.get('k')).toBeNull();
52
- expect(redis.keys()).toEqual(['one:k:k']);
53
- await a.close();
54
- await b.close();
55
- });
56
- it('authenticates', async () => {
57
- const guarded = await startFakeRedis({ password: 's3cret' });
58
- try {
59
- const ok = new RedisAdapter({ url: `redis://:s3cret@127.0.0.1:${guarded.port}` });
60
- await ok.set('k', 'v');
61
- expect(await ok.get('k')).toBe('v');
62
- const bad = new RedisAdapter({ url: `redis://:nope@127.0.0.1:${guarded.port}` });
63
- await expect(bad.get('k')).rejects.toThrow(/WRONGPASS/);
64
- await ok.close();
65
- await bad.close();
66
- }
67
- finally {
68
- await guarded.kill();
69
- }
70
- });
71
- it('delivers published messages to subscribers on other connections', async () => {
72
- const a = adapter();
73
- const b = adapter();
74
- const got = [];
75
- const stop = await b.subscribe('invalidate', (m) => got.push(m));
76
- await a.publish('invalidate', '{"tags":["x"]}');
77
- await vi.waitFor(() => expect(got).toEqual(['{"tags":["x"]}']));
78
- stop();
79
- await a.close();
80
- await b.close();
81
- });
82
- it('tells a subscriber to flush everything after its connection was lost', async () => {
83
- const a = adapter();
84
- const got = [];
85
- await a.subscribe('invalidate', (m) => got.push(m));
86
- await redis.kill();
87
- await redis.revive();
88
- await vi.waitFor(() => expect(got).toContain('*'), { timeout: 4000 });
89
- await a.close();
90
- });
91
- });
92
- describe('SharedIsrStore across instances', () => {
93
- const entry = (html, tags) => ({ html, timestamp: Date.now(), tags });
94
- it('serves what another instance stored and invalidates for both', async () => {
95
- const a = new SharedIsrStore(new CacheGuard(adapter()));
96
- const b = new SharedIsrStore(new CacheGuard(adapter()));
97
- await a.set('/p/[id]?id=1', entry('<p>1</p>', ['posts']));
98
- await a.set('/p/[id]?id=2', entry('<p>2</p>', ['users']));
99
- expect((await b.get('/p/[id]?id=1'))?.html).toBe('<p>1</p>');
100
- expect(await b.deleteTags(['posts'])).toBeGreaterThan(0);
101
- expect(await a.get('/p/[id]?id=1')).toBeUndefined();
102
- expect((await a.get('/p/[id]?id=2'))?.html).toBe('<p>2</p>');
103
- expect(await b.deleteRoute('/p/[id]')).toBeGreaterThan(0);
104
- expect(await a.get('/p/[id]?id=2')).toBeUndefined();
105
- });
106
- it('lists the variants of a route and deletes one params variant', async () => {
107
- const s = new SharedIsrStore(new CacheGuard(adapter()));
108
- await s.set('/p/[id]?id=1', entry('1'));
109
- await s.set('/p/[id]?id=1#q=a', entry('1a'));
110
- await s.set('/p/[id]?id=2', entry('2'));
111
- expect((await s.entriesForRoute('/p/[id]')).map(([k]) => k).sort()).toEqual(['/p/[id]?id=1', '/p/[id]?id=1#q=a', '/p/[id]?id=2']);
112
- await s.deleteVariant('/p/[id]', { id: '1' });
113
- expect((await s.entriesForRoute('/p/[id]')).map(([k]) => k)).toEqual(['/p/[id]?id=2']);
114
- });
115
- });
116
25
  describe('a cache that fails never fails a request', () => {
117
26
  const page = (route, extra = {}) => ({ route, source: route + '.tsx', mode: 'isr', bundlePath: route, revalidate: 60, ...extra });
118
- const core = (store, render) => createSSRCore({
119
- manifest: { pages: [page('/p')], regions: {} },
120
- isrStore: store,
121
- loadPageModule: async () => ({ default: () => jsx('p', { children: render() }) }),
122
- loadRuntimeRenderer: () => () => '',
123
- });
124
- it('renders when Redis is down, falls back to process memory, and recovers', async () => {
125
- let n = 0;
126
- const guard = new CacheGuard(adapter(), 100, 2, 300);
127
- const c = core(new SharedIsrStore(guard), () => `render ${++n}`);
128
- const req = { route: '/p', url: '/p', method: 'GET', headers: {} };
129
- expect((await c.renderPage(req)).cacheStatus).toBe('miss');
130
- expect((await c.renderPage(req)).cacheStatus).toBe('hit');
131
- await redis.kill();
132
- // Down: the page still renders (and is cached in memory for this instance).
133
- const down = await c.renderPage(req);
134
- expect(down.status).toBe(200);
135
- expect(down.html).toContain('<p>');
136
- for (let i = 0; i < 5; i++)
137
- expect((await c.renderPage(req)).status).toBe(200);
138
- expect(guard.healthy).toBe(false);
139
- await redis.revive();
140
- await vi.waitFor(async () => expect((await c.renderPage(req)).status).toBe(200));
141
- await new Promise((r) => setTimeout(r, 350));
142
- expect((await c.renderPage(req)).status).toBe(200);
143
- expect(guard.healthy).toBe(true);
144
- });
145
- it('gives up on a cache that hangs after the timeout instead of waiting', async () => {
146
- const never = () => new Promise(() => { });
147
- const hang = {
148
- name: 'hang',
149
- get: () => never(),
150
- set: () => never(),
151
- delete: () => never(),
152
- keysByTag: () => never(),
153
- deleteByTags: () => never(),
154
- publish: () => never(),
155
- subscribe: () => never(),
156
- close: async () => { },
157
- };
158
- const c = core(new SharedIsrStore(new CacheGuard(hang, 50)), () => 'x');
159
- const started = Date.now();
160
- const r = await c.renderPage({ route: '/p', url: '/p', method: 'GET', headers: {} });
161
- expect(r.status).toBe(200);
162
- expect(Date.now() - started).toBeLessThan(1500);
163
- });
164
27
  it('never stores a render that read per-user state', async () => {
165
28
  const store = new SharedIsrStore(new CacheGuard(adapter()));
166
29
  const c = createSSRCore({
@@ -180,65 +43,3 @@ describe('a cache that fails never fails a request', () => {
180
43
  expect(await store.get('/me')).toBeUndefined();
181
44
  });
182
45
  });
183
- describe('the shared data cache', () => {
184
- it('shares fetch responses between instances and invalidates them by tag', async () => {
185
- const shared = new SharedDataCache(new CacheGuard(adapter()));
186
- cacheRuntime().shared = shared;
187
- let upstream = 0;
188
- vi.stubGlobal('fetch', vi.fn(async () => new Response(`body-${++upstream}`)));
189
- cacheRuntime().fetchPatched = false;
190
- patchFetch();
191
- const read = async () => (await fetch('http://data/x', { next: { tags: ['x'], revalidate: 60 } })).text();
192
- expect(await read()).toBe('body-1');
193
- // Another instance (a fresh data store on the same Redis) sees the entry.
194
- const other = new SharedDataCache(new CacheGuard(adapter()));
195
- const hit = await other.get('fetch:' + JSON.stringify(['GET', 'http://data/x', []]));
196
- expect(hit.ok && hit.value).toBeTruthy();
197
- expect(await read()).toBe('body-1');
198
- expect(await other.deleteTags(['x'])).toBeGreaterThan(0);
199
- expect(await read()).toBe('body-2');
200
- vi.unstubAllGlobals();
201
- cacheRuntime().fetchPatched = false;
202
- });
203
- });
204
- describe('configuration', () => {
205
- it('loads the default (no adapter), redis, and a custom module', async () => {
206
- expect(await loadCacheAdapter(undefined)).toBeNull();
207
- expect(await loadCacheAdapter({ adapter: 'memory' })).toBeNull();
208
- const r = await loadCacheAdapter({ adapter: 'redis', url: url() });
209
- expect(r?.name).toBe('redis');
210
- await r?.close();
211
- await expect(loadCacheAdapter({ adapter: 'redis' })).rejects.toThrow(/cache\.url/);
212
- });
213
- it('reads the spec from KRATE_CACHE and from the bundled config', () => {
214
- expect(cacheSpecFromEnv({ KRATE_CACHE: '{"adapter":"redis","url":"redis://h"}' })).toEqual({ adapter: 'redis', url: 'redis://h' });
215
- expect(cacheSpecFromEnv({ KRATE_CACHE: 'not json' })).toBeUndefined();
216
- expect(cacheSpecFromEnv({})).toBeUndefined();
217
- const saved = process.env.MY_REDIS;
218
- process.env.MY_REDIS = 'redis://from-env';
219
- expect(cacheSpecFromConfig({ adapter: 'redis', urlEnv: 'MY_REDIS' })?.url).toBe('redis://from-env');
220
- expect(cacheSpecFromConfig({ adapter: 'memory' })).toBeUndefined();
221
- if (saved === undefined)
222
- delete process.env.MY_REDIS;
223
- else
224
- process.env.MY_REDIS = saved;
225
- });
226
- it('keeps the fallback store for a spec that fails to start', async () => {
227
- const fallback = new MemoryIsrStore(4);
228
- const setup = isrStoreFor({ adapter: 'redis' }, fallback);
229
- expect(await setup.ready).toBeNull();
230
- await setup.store.set('/a', { html: 'a', timestamp: 1 });
231
- expect((await setup.store.get('/a'))?.html).toBe('a');
232
- });
233
- it('accepts an adapter instance (serverless targets plug in their own)', async () => {
234
- const mem = new MemoryAdapter();
235
- const setup = isrStoreFor(mem, new MemoryIsrStore(4));
236
- expect(await setup.ready).toBe(mem);
237
- await setup.store.set('/a', { html: 'a', timestamp: 1, tags: ['t'] });
238
- expect(await mem.get('isr:/a')).toContain('"html":"a"');
239
- expect(await setup.store.deleteTags(['t'])).toBeGreaterThan(0);
240
- expect(await mem.get('isr:/a')).toBeNull();
241
- installCacheAdapter(mem);
242
- expect(cacheRuntime().shared).toBeTruthy();
243
- });
244
- });
@@ -42,6 +42,8 @@ export interface RevalidateScope {
42
42
  type: 'page' | 'layout';
43
43
  }>;
44
44
  tags: string[];
45
+ /** Tasks registered with after(); the host runs them once the response is sent. */
46
+ after?: Array<() => unknown>;
45
47
  }
46
48
  /** In-process data cache with tag index and FIFO bound. */
47
49
  export declare class DataCache {
@@ -1,7 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
- import { DataCache, cacheRuntime, currentRenderScope, installRenderStore, patchFetch, withCacheScope, } from './cache-scope.js';
4
- import { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
3
+ import { cacheRuntime, installRenderStore, patchFetch, withCacheScope, } from './cache-scope.js';
5
4
  const RUNTIME_KEY = Symbol.for('krate.cache.runtime');
6
5
  const REVALIDATE_KEY = Symbol.for('krate.revalidate.store');
7
6
  function resetRuntime() {
@@ -18,176 +17,6 @@ afterEach(() => {
18
17
  vi.unstubAllEnvs();
19
18
  delete globalThis._go_revalidate;
20
19
  });
21
- describe('DataCache', () => {
22
- it('indexes entries by tag and expires them', () => {
23
- vi.useFakeTimers();
24
- try {
25
- const c = new DataCache(10);
26
- c.set('a', 1, 10, ['t1']);
27
- c.set('b', 2, Infinity, ['t1', 't2']);
28
- c.set('c', 3, 1, []);
29
- expect(c.get('a')).toBe(1);
30
- vi.advanceTimersByTime(1500);
31
- expect(c.get('c')).toBeUndefined();
32
- expect(c.invalidateTags(['t2'])).toBe(1);
33
- expect(c.get('b')).toBeUndefined();
34
- expect(c.get('a')).toBe(1);
35
- expect(c.invalidateTags(['t1'])).toBe(1);
36
- expect(c.size).toBe(0);
37
- }
38
- finally {
39
- vi.useRealTimers();
40
- }
41
- });
42
- it('evicts the oldest entry when full', () => {
43
- const c = new DataCache(2);
44
- c.set('a', 1, 10, ['x']);
45
- c.set('b', 2, 10, []);
46
- c.set('c', 3, 10, []);
47
- expect(c.get('a')).toBeUndefined();
48
- expect(c.invalidateTags(['x'])).toBe(0);
49
- expect(c.size).toBe(2);
50
- });
51
- });
52
- describe('withCacheScope', () => {
53
- it('records tags and the smallest revalidate window across awaits', async () => {
54
- const cached = unstable_cache(async (n) => n * 2, ['double'], { tags: ['math'], revalidate: 30 });
55
- const other = unstable_cache(async () => 'x', ['other'], { tags: ['letters'], revalidate: 10 });
56
- const { result, scope, invalidated } = await withCacheScope('/p', async () => {
57
- const a = await cached(2);
58
- await new Promise((r) => setTimeout(r, 1));
59
- const b = await other();
60
- expect(currentRenderScope()?.route).toBe('/p');
61
- return `${a}${b}`;
62
- });
63
- expect(result).toBe('4x');
64
- expect([...scope.tags].sort()).toEqual(['letters', 'math']);
65
- expect(scope.revalidate).toBe(10);
66
- expect(scope.noStore).toBe(false);
67
- expect(invalidated).toBe(false);
68
- expect(currentRenderScope()).toBeUndefined();
69
- });
70
- it('keeps concurrent scopes apart', async () => {
71
- const tagged = (tag) => unstable_cache(async () => tag, [tag], { tags: [tag] });
72
- const [a, b] = await Promise.all([
73
- withCacheScope('/a', async () => {
74
- await new Promise((r) => setTimeout(r, 2));
75
- return tagged('a')();
76
- }),
77
- withCacheScope('/b', () => tagged('b')()),
78
- ]);
79
- expect([...a.scope.tags]).toEqual(['a']);
80
- expect([...b.scope.tags]).toEqual(['b']);
81
- });
82
- it('marks unstable_noStore renders and invalidations that land mid-render', async () => {
83
- const r1 = await withCacheScope('/n', () => {
84
- unstable_noStore();
85
- return 1;
86
- });
87
- expect(r1.scope.noStore).toBe(true);
88
- const r2 = await withCacheScope('/i', async () => {
89
- cacheRuntime().invalidate({ tags: ['z'] });
90
- return 2;
91
- });
92
- expect(r2.invalidated).toBe(true);
93
- });
94
- });
95
- describe('unstable_cache', () => {
96
- it('caches by key parts and arguments until the tag is revalidated', async () => {
97
- let calls = 0;
98
- const getPost = unstable_cache(async (id) => ({ id, n: ++calls }), ['post'], { tags: ['posts'] });
99
- expect(await getPost('a')).toEqual({ id: 'a', n: 1 });
100
- expect(await getPost('a')).toEqual({ id: 'a', n: 1 });
101
- expect(await getPost('b')).toEqual({ id: 'b', n: 2 });
102
- const scope = { kind: 'action', paths: [], tags: [] };
103
- const store = new AsyncLocalStorage();
104
- globalThis[REVALIDATE_KEY] = store;
105
- store.run(scope, () => revalidateTag('posts'));
106
- expect(scope.tags).toEqual(['posts']);
107
- expect(await getPost('a')).toEqual({ id: 'a', n: 3 });
108
- });
109
- it('dedupes concurrent misses', async () => {
110
- let calls = 0;
111
- const slow = unstable_cache(async () => {
112
- calls++;
113
- await new Promise((r) => setTimeout(r, 2));
114
- return calls;
115
- }, ['slow']);
116
- const [a, b] = await Promise.all([slow(), slow()]);
117
- expect(a).toBe(1);
118
- expect(b).toBe(1);
119
- expect(calls).toBe(1);
120
- });
121
- it('does not cache with revalidate 0 and rejects non-JSON results', async () => {
122
- let calls = 0;
123
- const fresh = unstable_cache(async () => ++calls, ['fresh'], { revalidate: 0 });
124
- await fresh();
125
- await fresh();
126
- expect(calls).toBe(2);
127
- const bad = unstable_cache(async () => undefined, ['bad']);
128
- await expect(bad()).rejects.toThrow(/JSON-serializable/);
129
- expect(() => unstable_cache(async () => 1, [], { revalidate: -1 })).toThrow(/revalidate/);
130
- });
131
- });
132
- describe('revalidatePath / revalidateTag', () => {
133
- it('queue on the request scope of an action or API route', () => {
134
- const scope = { kind: 'action', paths: [], tags: [] };
135
- const store = new AsyncLocalStorage();
136
- globalThis[REVALIDATE_KEY] = store;
137
- store.run(scope, () => {
138
- revalidatePath('/blog/[slug]');
139
- revalidatePath('/blog', 'layout');
140
- revalidateTag('posts');
141
- });
142
- expect(scope.paths).toEqual([
143
- { path: '/blog/[slug]', type: 'page' },
144
- { path: '/blog', type: 'layout' },
145
- ]);
146
- expect(scope.tags).toEqual(['posts']);
147
- });
148
- it('throw while a page renders', async () => {
149
- await expect(withCacheScope('/p', () => revalidateTag('x'))).rejects.toThrow(/while a page renders/);
150
- });
151
- it('throw outside the Krate server instead of doing nothing', () => {
152
- expect(() => revalidatePath('/x')).toThrow(/KRATE_HOST_URL is not set/);
153
- expect(() => revalidateTag('x')).toThrow(/KRATE_HOST_URL is not set/);
154
- });
155
- it('validate their arguments', () => {
156
- expect(() => revalidatePath('relative')).toThrow(TypeError);
157
- expect(() => revalidatePath('/x', 'tree')).toThrow(TypeError);
158
- expect(() => revalidateTag('')).toThrow(TypeError);
159
- });
160
- it('call the Go host synchronously in the embedded runtime', () => {
161
- const calls = [];
162
- globalThis._go_revalidate = (json) => {
163
- calls.push(json);
164
- return JSON.stringify({ revalidated: [], skipped: [{ target: '/about', reason: 'static page' }] });
165
- };
166
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => { });
167
- try {
168
- revalidatePath('/about');
169
- expect(JSON.parse(calls[0])).toEqual({ paths: [{ path: '/about', type: 'page' }], tags: [] });
170
- expect(warn).toHaveBeenCalledWith(expect.stringContaining('/about: static page'));
171
- }
172
- finally {
173
- warn.mockRestore();
174
- }
175
- globalThis._go_revalidate = () => JSON.stringify({ error: 'boom' });
176
- expect(() => revalidateTag('t')).toThrow(/boom/);
177
- });
178
- it('post to the host outside a request scope when the host is configured', async () => {
179
- vi.stubEnv('KRATE_HOST_URL', 'http://127.0.0.1:9');
180
- vi.stubEnv('KRATE_INTERNAL_SECRET', 's3cret');
181
- const fetchMock = vi.fn(async () => new Response(JSON.stringify({ revalidated: [], skipped: [] }), { status: 200 }));
182
- vi.stubGlobal('fetch', fetchMock);
183
- revalidateTag('posts');
184
- await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
185
- const [url, init] = fetchMock.mock.calls[0];
186
- expect(url).toBe('http://127.0.0.1:9/__krate/internal/revalidate');
187
- expect(init.headers['x-krate-internal']).toBe('s3cret');
188
- expect(JSON.parse(String(init.body))).toEqual({ paths: [], tags: ['posts'] });
189
- });
190
- });
191
20
  describe('patchFetch', () => {
192
21
  it('never replays Set-Cookie from a cached response', async () => {
193
22
  const base = vi.fn(async () => new Response('body', {
@@ -205,29 +34,4 @@ describe('patchFetch', () => {
205
34
  expect(second.result.headers.get('x-test')).toBe('yes');
206
35
  expect(base).toHaveBeenCalledTimes(1);
207
36
  });
208
- it('caches tagged GET responses, records tags, and bypasses no-store', async () => {
209
- let n = 0;
210
- const base = vi.fn(async () => new Response(`body-${++n}`, { status: 200, headers: { 'x-n': String(n) } }));
211
- vi.stubGlobal('fetch', base);
212
- cacheRuntime().fetchPatched = false;
213
- patchFetch();
214
- const read = () => fetch('http://data/posts', { next: { tags: ['posts'], revalidate: 60 } });
215
- const { result, scope } = await withCacheScope('/p', async () => (await read()).text());
216
- expect(result).toBe('body-1');
217
- expect([...scope.tags]).toEqual(['posts']);
218
- expect(scope.revalidate).toBe(60);
219
- expect(await (await read()).text()).toBe('body-1');
220
- expect(base).toHaveBeenCalledTimes(1);
221
- cacheRuntime().invalidate({ tags: ['posts'] });
222
- expect(await (await read()).text()).toBe('body-2');
223
- const ns = await withCacheScope('/q', async () => (await fetch('http://data/posts', { cache: 'no-store' })).text());
224
- expect(ns.result).toBe('body-3');
225
- expect(ns.scope.noStore).toBe(true);
226
- // Plain requests and non-GET requests are passed through uncached.
227
- await fetch('http://data/posts');
228
- await fetch('http://data/posts', { method: 'POST', next: { revalidate: 60 } });
229
- expect(base).toHaveBeenCalledTimes(5);
230
- const plainInit = base.mock.calls[4][1];
231
- expect(plainInit.next).toBeUndefined();
232
- });
233
37
  });
@@ -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
+ }