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

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 (78) 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/hints.d.ts +25 -2
  9. package/dist/hints.js +148 -74
  10. package/dist/index.d.ts +1 -0
  11. package/dist/krate-core.js +1 -1
  12. package/dist/krate-f-actions.js +1 -1
  13. package/dist/krate-f-list.js +1 -1
  14. package/dist/krate-f-navigation.js +1 -1
  15. package/dist/krate-features.json +24 -0
  16. package/dist/krate-hydrate-lite.js +5 -5
  17. package/dist/krate-hydrate.js +5 -5
  18. package/dist/krate-runtime.js +5 -5
  19. package/dist/list.d.ts +14 -4
  20. package/dist/list.js +4 -5
  21. package/dist/navigation-react.d.ts +13 -0
  22. package/dist/navigation-react.js +86 -0
  23. package/dist/navigation.d.ts +19 -0
  24. package/dist/navigation.js +35 -0
  25. package/dist/react-compat.d.ts +26 -0
  26. package/dist/react-compat.js +292 -0
  27. package/dist/server-handler.js +74 -6
  28. package/dist/server.d.ts +17 -10
  29. package/dist/server.js +400 -94
  30. package/package.json +15 -2
  31. package/dist/actions.test.d.ts +0 -1
  32. package/dist/actions.test.js +0 -75
  33. package/dist/after.test.d.ts +0 -1
  34. package/dist/after.test.js +0 -58
  35. package/dist/builtin-tags.test.d.ts +0 -1
  36. package/dist/builtin-tags.test.js +0 -12
  37. package/dist/cache-adapter.test.d.ts +0 -1
  38. package/dist/cache-adapter.test.js +0 -45
  39. package/dist/cache.test.d.ts +0 -1
  40. package/dist/cache.test.js +0 -37
  41. package/dist/events.test.d.ts +0 -1
  42. package/dist/events.test.js +0 -42
  43. package/dist/handler-html.test.d.ts +0 -1
  44. package/dist/handler-html.test.js +0 -55
  45. package/dist/handler-segments.test.d.ts +0 -1
  46. package/dist/handler-segments.test.js +0 -25
  47. package/dist/head-tags.test.d.ts +0 -1
  48. package/dist/head-tags.test.js +0 -24
  49. package/dist/inline-action-token.test.d.ts +0 -1
  50. package/dist/inline-action-token.test.js +0 -31
  51. package/dist/jsx-svg-types.test.d.ts +0 -1
  52. package/dist/jsx-svg-types.test.js +0 -58
  53. package/dist/link-base-path.test.d.ts +0 -1
  54. package/dist/link-base-path.test.js +0 -28
  55. package/dist/node-server.test.d.ts +0 -1
  56. package/dist/node-server.test.js +0 -138
  57. package/dist/platform.test.d.ts +0 -1
  58. package/dist/platform.test.js +0 -44
  59. package/dist/router-nav.test.d.ts +0 -1
  60. package/dist/router-nav.test.js +0 -130
  61. package/dist/server-handler.test.d.ts +0 -1
  62. package/dist/server-handler.test.js +0 -338
  63. package/dist/server-renderer.test.d.ts +0 -1
  64. package/dist/server-renderer.test.js +0 -162
  65. package/dist/server.test.d.ts +0 -1
  66. package/dist/server.test.js +0 -91
  67. package/dist/sha256.test.d.ts +0 -1
  68. package/dist/sha256.test.js +0 -13
  69. package/dist/signal.test.d.ts +0 -1
  70. package/dist/signal.test.js +0 -68
  71. package/dist/site-config.test.d.ts +0 -1
  72. package/dist/site-config.test.js +0 -30
  73. package/dist/slot.test.d.ts +0 -1
  74. package/dist/slot.test.js +0 -25
  75. package/dist/ssr-core-behavior.test.d.ts +0 -1
  76. package/dist/ssr-core-behavior.test.js +0 -108
  77. package/dist/testing.test.d.ts +0 -1
  78. package/dist/testing.test.js +0 -73
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.5.0-rc.5",
3
+ "version": "0.5.0-rc.6",
4
4
  "description": "Client-side runtime for Krate - signals, hydration, SPA router, resources, and context.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -38,6 +38,18 @@
38
38
  "types": "./dist/highlight.d.ts",
39
39
  "default": "./dist/highlight.js"
40
40
  },
41
+ "./hints": {
42
+ "types": "./dist/hints.d.ts",
43
+ "default": "./dist/hints.js"
44
+ },
45
+ "./react-compat": {
46
+ "types": "./dist/react-compat.d.ts",
47
+ "default": "./dist/react-compat.js"
48
+ },
49
+ "./navigation-react": {
50
+ "types": "./dist/navigation-react.d.ts",
51
+ "default": "./dist/navigation-react.js"
52
+ },
41
53
  "./cache": {
42
54
  "types": "./dist/cache.d.ts",
43
55
  "default": "./dist/cache.js"
@@ -108,7 +120,8 @@
108
120
  }
109
121
  },
110
122
  "files": [
111
- "dist"
123
+ "dist",
124
+ "!dist/**/*.test.*"
112
125
  ],
113
126
  "devDependencies": {
114
127
  "@types/node": "^26.2.0",
@@ -1 +0,0 @@
1
- export {};
@@ -1,75 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
- import { ServerActionError, __krateAction, getFormStatus, installActionForms, isServerAction, setActionTransitionRunner, stripActionURL, } from './actions.js';
3
- const tick = () => new Promise((r) => setTimeout(r, 0));
4
- function makeForm(html) {
5
- const host = document.createElement('div');
6
- host.innerHTML = html;
7
- document.body.appendChild(host);
8
- return host.querySelector('form');
9
- }
10
- function submit(form, submitter) {
11
- const ev = new Event('submit', { bubbles: true, cancelable: true });
12
- Object.defineProperty(ev, 'submitter', { value: submitter || null });
13
- form.dispatchEvent(ev);
14
- }
15
- function jsonResponse(body, status = 200) {
16
- return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
17
- }
18
- beforeEach(() => {
19
- document.body.innerHTML = '';
20
- installActionForms(document);
21
- });
22
- afterEach(() => {
23
- vi.unstubAllGlobals();
24
- setActionTransitionRunner(null);
25
- });
26
- describe('form actions', () => {
27
- it('posts server action forms as multipart and does not reload', async () => {
28
- const fetchMock = vi.fn(async () => jsonResponse({ ok: true, result: { saved: true } }));
29
- vi.stubGlobal('fetch', fetchMock);
30
- const form = makeForm('<form action="/__krate/action/a1" method="post" data-krate-action><input name="text" value="hi"></form>');
31
- submit(form);
32
- await tick();
33
- await tick();
34
- expect(fetchMock).toHaveBeenCalledTimes(1);
35
- const [url, init] = fetchMock.mock.calls[0];
36
- expect(url).toContain('/__krate/action/a1');
37
- expect(init.headers['x-krate-action']).toBe('fetch');
38
- expect(init.body).toBeInstanceOf(FormData);
39
- expect(init.body.get('text')).toBe('hi');
40
- expect(getFormStatus(form).pending).toBe(false);
41
- });
42
- it('keeps only the sealed closure token of an inline action in the posted URL', async () => {
43
- const fetchMock = vi.fn(async () => jsonResponse({ ok: true, result: null }));
44
- vi.stubGlobal('fetch', fetchMock);
45
- const args = encodeURIComponent(JSON.stringify(['k1.AbC_-123']));
46
- const form = makeForm(`<form action="/__krate/action/a1?__krate_args=${args}&__krate_return=%2Fx" method="post" data-krate-action></form>`);
47
- submit(form);
48
- await tick();
49
- await tick();
50
- const [url] = fetchMock.mock.calls[0];
51
- expect(url.replace(/^https?:\/\/[^/]+/, '')).toBe(`/__krate/action/a1?__krate_args=${args}`);
52
- expect(stripActionURL('/__krate/action/a2?__krate_args=%5B%7B%22n%22%3A1%7D%5D&__krate_return=%2Fx')).toBe('/__krate/action/a2');
53
- });
54
- });
55
- describe('server action proxies', () => {
56
- it('sends JSON args and returns the result', async () => {
57
- const fetchMock = vi.fn(async () => jsonResponse({ ok: true, result: { n: 2 } }));
58
- vi.stubGlobal('fetch', fetchMock);
59
- const save = __krateAction('a1');
60
- expect(isServerAction(save)).toBe(true);
61
- expect(save.actionUrl).toBe('/__krate/action/a1');
62
- await expect(save({ n: 1 })).resolves.toEqual({ n: 2 });
63
- const [, init] = fetchMock.mock.calls[0];
64
- expect(JSON.parse(String(init.body))).toEqual({ args: [{ n: 1 }] });
65
- expect(init.headers['content-type']).toBe('application/json');
66
- });
67
- it('rejects with the structured error envelope', async () => {
68
- vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: false, error: { message: 'An error occurred', digest: 'd1' } }, 500)));
69
- const err = (await __krateAction('a3')().catch((e) => e));
70
- expect(err).toBeInstanceOf(ServerActionError);
71
- expect(err.message).toBe('An error occurred');
72
- expect(err.digest).toBe('d1');
73
- expect(err.status).toBe(500);
74
- });
75
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,58 +0,0 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { afterEach, describe, expect, it, vi } from 'vitest';
3
- import { after, runAfterTasks } from './after.js';
4
- const STORE_KEY = Symbol.for('krate.revalidate.store');
5
- afterEach(() => {
6
- delete globalThis[STORE_KEY];
7
- });
8
- describe('after()', () => {
9
- it('queues tasks on the request scope instead of running them', async () => {
10
- const store = new AsyncLocalStorage();
11
- globalThis[STORE_KEY] = store;
12
- const scope = { kind: 'api', paths: [], tags: [] };
13
- const ran = [];
14
- store.run(scope, () => {
15
- after(() => ran.push('fn'));
16
- after(Promise.resolve().then(() => ran.push('promise')));
17
- });
18
- expect(scope.after).toHaveLength(2);
19
- await Promise.resolve();
20
- expect(ran).toEqual(['promise']);
21
- await runAfterTasks(scope);
22
- expect(ran).toEqual(['promise', 'fn']);
23
- expect(scope.after).toEqual([]);
24
- });
25
- it('keeps running later tasks when one throws', async () => {
26
- const err = vi.spyOn(console, 'error').mockImplementation(() => { });
27
- const scope = {
28
- kind: 'api',
29
- paths: [],
30
- tags: [],
31
- after: [
32
- () => {
33
- throw new Error('boom');
34
- },
35
- () => {
36
- ran = true;
37
- },
38
- ],
39
- };
40
- let ran = false;
41
- await runAfterTasks(scope);
42
- expect(ran).toBe(true);
43
- expect(err).toHaveBeenCalledOnce();
44
- err.mockRestore();
45
- });
46
- it('runs on a later turn when no request is active', async () => {
47
- let ran = false;
48
- after(() => {
49
- ran = true;
50
- });
51
- expect(ran).toBe(false);
52
- await new Promise((r) => setTimeout(r, 0));
53
- expect(ran).toBe(true);
54
- });
55
- it('rejects anything but a function or a promise', () => {
56
- expect(() => after(42)).toThrow(TypeError);
57
- });
58
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,12 +0,0 @@
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 +0,0 @@
1
- export {};
@@ -1,45 +0,0 @@
1
- // @vitest-environment node
2
- import { AsyncLocalStorage } from 'node:async_hooks';
3
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
- import { CacheGuard } from './cache-adapter';
5
- import { RedisAdapter } from './cache-redis';
6
- import { SharedIsrStore } from './shared-isr';
7
- import { createSSRCore } from './ssr-core';
8
- import { cacheRuntime, installRenderStore, markNoStore } from './cache-scope';
9
- import { startFakeRedis } from './test-redis';
10
- import { jsx } from './server';
11
- installRenderStore(new AsyncLocalStorage());
12
- let redis;
13
- beforeEach(async () => {
14
- redis = await startFakeRedis();
15
- vi.spyOn(console, 'warn').mockImplementation(() => { });
16
- vi.spyOn(console, 'error').mockImplementation(() => { });
17
- });
18
- afterEach(async () => {
19
- vi.restoreAllMocks();
20
- await redis.kill();
21
- cacheRuntime().shared = undefined;
22
- });
23
- const url = () => `redis://127.0.0.1:${redis.port}/0`;
24
- const adapter = () => new RedisAdapter({ url: url(), timeoutMs: 200 });
25
- describe('a cache that fails never fails a request', () => {
26
- const page = (route, extra = {}) => ({ route, source: route + '.tsx', mode: 'isr', bundlePath: route, revalidate: 60, ...extra });
27
- it('never stores a render that read per-user state', async () => {
28
- const store = new SharedIsrStore(new CacheGuard(adapter()));
29
- const c = createSSRCore({
30
- manifest: { pages: [page('/me')], regions: {} },
31
- isrStore: store,
32
- loadPageModule: async () => ({
33
- default: () => {
34
- markNoStore(); // cookies(), headers() and no-store fetches do this
35
- return jsx('p', { children: 'Hello Ada' });
36
- },
37
- }),
38
- loadRuntimeRenderer: () => () => '',
39
- });
40
- const r = await c.renderPage({ route: '/me', url: '/me', method: 'GET', headers: { cookie: 'sid=ada' } });
41
- expect(r.noStore).toBe(true);
42
- expect(redis.keys().filter((k) => k.includes('isr:'))).toEqual([]);
43
- expect(await store.get('/me')).toBeUndefined();
44
- });
45
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,37 +0,0 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
- import { cacheRuntime, installRenderStore, patchFetch, withCacheScope, } from './cache-scope.js';
4
- const RUNTIME_KEY = Symbol.for('krate.cache.runtime');
5
- const REVALIDATE_KEY = Symbol.for('krate.revalidate.store');
6
- function resetRuntime() {
7
- delete globalThis[RUNTIME_KEY];
8
- delete globalThis[REVALIDATE_KEY];
9
- installRenderStore(new AsyncLocalStorage());
10
- }
11
- beforeEach(() => {
12
- resetRuntime();
13
- vi.unstubAllEnvs();
14
- });
15
- afterEach(() => {
16
- vi.unstubAllGlobals();
17
- vi.unstubAllEnvs();
18
- delete globalThis._go_revalidate;
19
- });
20
- describe('patchFetch', () => {
21
- it('never replays Set-Cookie from a cached response', async () => {
22
- const base = vi.fn(async () => new Response('body', {
23
- status: 200,
24
- headers: { 'set-cookie': 'sid=secret', 'x-test': 'yes' },
25
- }));
26
- vi.stubGlobal('fetch', base);
27
- cacheRuntime().fetchPatched = false;
28
- patchFetch();
29
- const read = () => fetch('http://data/session', { next: { tags: ['session'], revalidate: 60 } });
30
- const first = await withCacheScope('/p', async () => read());
31
- expect(first.result.headers.get('x-test')).toBe('yes');
32
- const second = await withCacheScope('/p', async () => read());
33
- expect(second.result.headers.get('set-cookie')).toBeNull();
34
- expect(second.result.headers.get('x-test')).toBe('yes');
35
- expect(base).toHaveBeenCalledTimes(1);
36
- });
37
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,42 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
2
- import { krateOn, krateControl } from './events';
3
- import { createSignal } from './signal';
4
- function setup(html) {
5
- document.body.innerHTML = '<div id="root">' + html + '</div>';
6
- return document.getElementById('root');
7
- }
8
- function $(sel) {
9
- return document.querySelector(sel);
10
- }
11
- function fire(el, type, init = { bubbles: true, cancelable: true }) {
12
- const e = new Event(type, init);
13
- el.dispatchEvent(e);
14
- return e;
15
- }
16
- describe('delegated events', () => {
17
- beforeEach(() => {
18
- document.body.innerHTML = '';
19
- });
20
- it('runs capture handlers top-down, then bubble handlers bottom-up', () => {
21
- setup('<div id="a"><div id="b"><button id="c">x</button></div></div>');
22
- const log = [];
23
- for (const id of ['a', 'b', 'c']) {
24
- krateOn($('#' + id), 'onClickCapture', () => log.push(id + ':capture'));
25
- krateOn($('#' + id), 'onClick', () => log.push(id + ':bubble'));
26
- }
27
- $('#c').click();
28
- expect(log).toEqual(['a:capture', 'b:capture', 'c:capture', 'c:bubble', 'b:bubble', 'a:bubble']);
29
- });
30
- });
31
- describe('controlled form controls', () => {
32
- it('restores a controlled text input when the handler does not update state', async () => {
33
- setup('<input id="i" value="a">');
34
- const i = $('#i');
35
- const [v] = createSignal('a');
36
- krateControl(i, 'value', () => v());
37
- krateOn(i, 'onChange', () => { });
38
- i.value = 'ab';
39
- fire(i, 'input');
40
- expect(i.value).toBe('a');
41
- });
42
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,55 +0,0 @@
1
- // @vitest-environment node
2
- import { describe, expect, it } from "vitest";
3
- import { injectFlashNotice, regionReplaceScript, requestFlash, signFlash, } from "./handler-html.js";
4
- describe("regionReplaceScript", () => {
5
- const payloadOf = (script) => {
6
- const m = /var html=(".*?");var kinds=/s.exec(script);
7
- expect(m).not.toBeNull();
8
- return JSON.parse(m[1]);
9
- };
10
- it("embeds the HTML so it cannot close the script element or break the literal", () => {
11
- const html = `</script><script>alert(1)</script> & "q" \u2028 \u2029 <!-- x -->`;
12
- const script = regionReplaceScript("r1", html);
13
- // Only the wrapper's own tags may appear: the payload has no raw < or >.
14
- expect(script.match(/<\/script>/gi)).toHaveLength(1);
15
- expect(script.match(/<script/gi)).toHaveLength(1);
16
- expect(script).not.toContain("\u2028");
17
- expect(script).not.toContain("\u2029");
18
- expect(payloadOf(script)).toBe(html);
19
- });
20
- });
21
- const SECRET = "krate-test-flash-secret-0123456789";
22
- // The same vector is pinned in internal/build/serve_flash_test.go: what the Go
23
- // host signs verifies here, and what is signed here verifies there.
24
- const VECTOR_PAYLOAD = "eyJhIjoiYWN0MSIsInIiOnsiZXJyb3IiOiJOYW1lIGlzIHJlcXVpcmVkIn19";
25
- const VECTOR_COOKIE = VECTOR_PAYLOAD + ".zLQd73rhp1HN8J0vNvSeLqvlCqquygUX-mXuuN24dlY";
26
- async function flashCookie(payload, secret = SECRET) {
27
- const b64 = Buffer.from(JSON.stringify(payload), "utf-8").toString("base64url");
28
- return secret === null ? b64 : signFlash(secret, b64);
29
- }
30
- describe("requestFlash", () => {
31
- const payload = { a: "act1", r: { error: "Name is required" } };
32
- it("never trusts an unsigned, forged or foreign-signed cookie", async () => {
33
- const unsigned = await flashCookie(payload, null);
34
- expect(await requestFlash(`krate_flash=${unsigned}`, SECRET)).toBeNull();
35
- expect(await requestFlash(`krate_flash=${unsigned}.`, SECRET)).toBeNull();
36
- expect(await requestFlash(`krate_flash=${unsigned}.deadbeef`, SECRET)).toBeNull();
37
- expect(await requestFlash(`krate_flash=${await flashCookie(payload, "another-secret-another-secret")}`, SECRET)).toBeNull();
38
- // A valid signature does not carry over to a different payload.
39
- const sig = VECTOR_COOKIE.slice(VECTOR_COOKIE.indexOf(".") + 1);
40
- const other = Buffer.from(JSON.stringify({ a: "act1", r: { error: "Injected notice" } })).toString("base64url");
41
- expect(await requestFlash(`krate_flash=${other}.${sig}`, SECRET)).toBeNull();
42
- // Without a secret nothing is trusted, signed or not.
43
- expect(await requestFlash(`krate_flash=${VECTOR_COOKIE}`, null)).toBeNull();
44
- expect(await requestFlash(`krate_flash=${VECTOR_COOKIE}`, "")).toBeNull();
45
- });
46
- });
47
- describe("injectFlashNotice", () => {
48
- it("escapes the message, the action id and the cookie value", () => {
49
- const out = injectFlashNotice(`<form action="/__krate/action/a&quot;b"></form>`, 'v"><img src=x onerror=alert(1)>', { a: 'a&quot;b', r: "<script>alert(1)</script>" });
50
- expect(out).not.toContain("<script>");
51
- expect(out).not.toContain("<img src=x");
52
- expect(out).toContain("&lt;script&gt;");
53
- expect(out).toContain('role="alert"');
54
- });
55
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,25 +0,0 @@
1
- // @vitest-environment node
2
- import { describe, expect, it } from "vitest";
3
- import { fillServerError, lookupSegmentPage, newServerError, segmentRoute } from "./handler-segments.js";
4
- describe("request-time segment pages", () => {
5
- it("names the renderer route of a dynamic entry and only of that role", () => {
6
- const entries = [
7
- { key: "", dir: "", notFound: "404.html", error: "500.html", dynamic: ["notFound"] },
8
- { key: "blog", dir: "blog", notFound: "blog/404.html" },
9
- ];
10
- expect(lookupSegmentPage(entries, "notFound", "/x", false, "")).toEqual({ file: "404.html", key: "", params: {}, route: "/__404" });
11
- expect(lookupSegmentPage(entries, "error", "/x", false, "")?.route).toBeUndefined();
12
- expect(lookupSegmentPage(entries, "notFound", "/blog/x", true, "blog")?.route).toBeUndefined();
13
- expect(segmentRoute("shop/blog", "unauthorized")).toBe("/shop/blog/__401");
14
- });
15
- });
16
- describe("error prop", () => {
17
- it("is sanitized in production and escaped into the page", () => {
18
- const e = newServerError("secret <b>", "at x", "abc1234567", false);
19
- expect(e).toEqual({ name: "Error", message: "Internal Server Error", digest: "abc1234567" });
20
- const dev = newServerError("a<b>", "at y", "d", true);
21
- const out = fillServerError("<html><head></head><body>__KRATE_ERR_MESSAGE__|__KRATE_ERR_DIGEST__|__KRATE_ERR_STACK__</body></html>", dev);
22
- expect(out).toContain("a&lt;b&gt;|d|at y");
23
- expect(out).toContain('<script type="application/json" id="__krate_error">{"name":"Error","message":"a\\u003cb\\u003e","digest":"d","stack":"at y"}</script></head>');
24
- });
25
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,24 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { HEAD_CLOSE, HEAD_OPEN, mergeHead, setStartTagAttrs, splitDocTags, takeHead } from "./head-tags.js";
3
- const DOC = '<!DOCTYPE html><html lang="en"><head><title>Base</title></head><body class="base"><div id="root">x</div></body></html>';
4
- describe("document attributes from <Head>", () => {
5
- it("splits <html> and <body> out of a head fragment, later elements winning", () => {
6
- const { rest, html, body } = splitDocTags('<meta name="a" content="b"><html lang="fr" class="a"></html><html class="b"></html><body data-x="1"></body>');
7
- expect(rest).toBe('<meta name="a" content="b">');
8
- expect(Object.fromEntries(html)).toEqual({ lang: "fr", class: "b" });
9
- expect(Object.fromEntries(body)).toEqual({ "data-x": "1" });
10
- });
11
- it("sets attributes on the document elements and escapes values", () => {
12
- const out = mergeHead(DOC, "", '<html class="dark" data-q="a&quot;b"></html><body class="font-sans"></body>');
13
- expect(out).toContain('<html class="dark" data-q="a&quot;b" lang="en">');
14
- expect(out).toContain('<body class="font-sans">');
15
- expect(out).not.toContain("</html></html>");
16
- });
17
- it("keeps the other attributes of a start tag", () => {
18
- expect(setStartTagAttrs('<body a="1" b="2">', "body", new Map([["b", "3"]]))).toBe('<body a="1" b="3">');
19
- });
20
- it("flows from a request-time <Head> through takeHead", () => {
21
- const split = takeHead("<main>" + HEAD_OPEN + '<html class="dark"></html><title>T</title>' + HEAD_CLOSE + "</main>");
22
- expect(mergeHead(DOC, split.title, split.head)).toContain('<html class="dark" lang="en">');
23
- });
24
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,31 +0,0 @@
1
- import { createCipheriv, createHash, randomBytes } from 'node:crypto';
2
- import { describe, expect, it } from 'vitest';
3
- import { openInlineToken } from './server-handler.js';
4
- // The server renderer seals closed-over values of an inline server action
5
- // like this (see compiler/internal/build/inline_actions.go).
6
- function seal(id, values, secret) {
7
- const key = createHash('sha256').update('krate-inline-action\0' + secret).digest();
8
- const iv = randomBytes(12);
9
- const cipher = createCipheriv('aes-256-gcm', key, iv);
10
- cipher.setAAD(Buffer.from(id));
11
- const body = Buffer.concat([cipher.update(JSON.stringify(values), 'utf8'), cipher.final()]);
12
- return 'k1.' + Buffer.concat([iv, body, cipher.getAuthTag()]).toString('base64url');
13
- }
14
- const entry = { id: 'a1', export: 'inline_0', file: 'x.mjs', inline: true, captures: ['id', 'when', 'gone'] };
15
- describe('inline server action closure tokens', () => {
16
- it('opens a token sealed by the server renderer and restores special values', async () => {
17
- const token = seal('a1', ['p1', { $: 'd', v: '1970-01-01T00:00:00.000Z' }, { $: 'u' }], 'secret-secret-secret');
18
- const out = await openInlineToken(token, entry, 'secret-secret-secret');
19
- expect(out[0]).toBe('p1');
20
- expect(out[1]).toEqual(new Date(0));
21
- expect(out[2]).toBeUndefined();
22
- });
23
- it('rejects a token for another action, another key, or tampered bytes', async () => {
24
- const token = seal('a1', ['p1', 1, 2], 'secret-secret-secret');
25
- await expect(openInlineToken(token, { ...entry, id: 'a2' }, 'secret-secret-secret')).rejects.toThrow();
26
- await expect(openInlineToken(token, entry, 'another-secret-value')).rejects.toThrow();
27
- const flipped = token.slice(0, -4) + (token.endsWith('AAAA') ? 'BBBB' : 'AAAA');
28
- await expect(openInlineToken(flipped, entry, 'secret-secret-secret')).rejects.toThrow();
29
- await expect(openInlineToken(null, entry, 'secret-secret-secret')).rejects.toThrow();
30
- });
31
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,58 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import ts from 'typescript';
3
- import { resolve } from 'node:path';
4
- const typesFile = resolve(__dirname, 'jsx-types.ts');
5
- const virtual = resolve(__dirname, '__svg_fixture__.tsx');
6
- function check(source) {
7
- const options = {
8
- strict: true,
9
- noEmit: true,
10
- skipLibCheck: true,
11
- jsx: ts.JsxEmit.Preserve,
12
- target: ts.ScriptTarget.ES2020,
13
- module: ts.ModuleKind.ESNext,
14
- moduleResolution: ts.ModuleResolutionKind.Bundler,
15
- types: [],
16
- };
17
- const host = ts.createCompilerHost(options);
18
- const readFile = host.readFile.bind(host);
19
- const fileExists = host.fileExists.bind(host);
20
- const getSourceFile = host.getSourceFile.bind(host);
21
- host.fileExists = (f) => f === virtual || fileExists(f);
22
- host.readFile = (f) => (f === virtual ? source : readFile(f));
23
- host.getSourceFile = (f, lang, onError, shouldCreate) => f === virtual ? ts.createSourceFile(f, source, lang) : getSourceFile(f, lang, onError, shouldCreate);
24
- const program = ts.createProgram([typesFile, virtual], options, host);
25
- return ts
26
- .getPreEmitDiagnostics(program)
27
- .filter((d) => d.file?.fileName === virtual)
28
- .map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
29
- }
30
- describe('SVG JSX types', () => {
31
- it('accepts a pasted Figma/Illustrator export', () => {
32
- const errors = check(`
33
- export const Pasted = () => (
34
- <svg xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" xmlns:xlink="http://www.w3.org/1999/xlink"
35
- xmlSpace="preserve" xml:space="preserve" version="1.1" width="24" height="24" viewBox="0 0 24 24" fill="none" onClick={() => {}}>
36
- <defs>
37
- <linearGradient id="g" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="1">
38
- <stop offset="0" stopColor="#000" />
39
- </linearGradient>
40
- <clipPath id="c"><rect width="24" height="24" /></clipPath>
41
- <filter id="f"><feColorMatrix type="matrix" values="1 0 0 0 0" /><feGaussianBlur stdDeviation="2" /></filter>
42
- </defs>
43
- <g clipPath="url(#c)" filter="url(#f)">
44
- <use xlinkHref="#g" xlink:href="#g" />
45
- <ellipse cx="1" cy="1" rx="1" ry="1" />
46
- <text x="0" y="0"><tspan>hi</tspan></text>
47
- <path fillRule="evenodd" clipRule="evenodd" d="M0 0h24v24H0z" strokeLinecap="round" />
48
- </g>
49
- </svg>
50
- );
51
- `);
52
- expect(errors).toEqual([]);
53
- });
54
- it('still rejects unknown SVG attributes', () => {
55
- const errors = check(`export const Bad = () => <svg notAnAttribute="x" />;`);
56
- expect(errors.length).toBeGreaterThan(0);
57
- });
58
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,28 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
- import { Link, renderToString } from './server';
3
- import { h } from './dom';
4
- beforeEach(() => {
5
- globalThis.__KRATE_CFG__ = { basePath: '/app' };
6
- });
7
- afterEach(() => {
8
- delete globalThis.__KRATE_CFG__;
9
- });
10
- describe('<Link basePath={false}>', () => {
11
- it('server render: adds the base path by default and not when opted out', () => {
12
- const inSite = renderToString(Link({ href: '/pricing', children: 'a' }));
13
- expect(inSite).toContain('href="/app/pricing"');
14
- expect(inSite).toContain('data-krate-link');
15
- const outside = renderToString(Link({ href: '/pricing', basePath: false, children: 'a' }));
16
- expect(outside).toContain('href="/pricing"');
17
- expect(outside).toContain('data-krate-external');
18
- expect(outside).toContain('data-krate-no-base');
19
- expect(outside).not.toContain('data-krate-link');
20
- expect(outside).not.toContain('basePath');
21
- });
22
- it('client render: data-krate-no-base keeps the href as written', () => {
23
- const link = h('a', { href: '/pricing', 'data-krate-link': true }, 'a');
24
- expect(link.getAttribute('href')).toBe('/app/pricing');
25
- const outside = h('a', { href: '/pricing', 'data-krate-external': true, 'data-krate-no-base': true }, 'a');
26
- expect(outside.getAttribute('href')).toBe('/pricing');
27
- });
28
- });
@@ -1 +0,0 @@
1
- export {};