@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.2
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.
- package/dist/action-context.d.ts +5 -1
- package/dist/action-context.js +33 -3
- package/dist/action-context.test.js +26 -1
- package/dist/actions.d.ts +12 -1
- package/dist/actions.js +84 -4
- package/dist/actions.test.js +61 -1
- package/dist/assets-static.d.ts +5 -0
- package/dist/assets-static.js +31 -0
- package/dist/boundary.d.ts +12 -0
- package/dist/boundary.js +53 -13
- package/dist/cache-adapter.d.ts +113 -0
- package/dist/cache-adapter.js +217 -0
- package/dist/cache-adapter.test.d.ts +1 -0
- package/dist/cache-adapter.test.js +244 -0
- package/dist/cache-redis.d.ts +27 -0
- package/dist/cache-redis.js +110 -0
- package/dist/cache-scope.d.ts +25 -9
- package/dist/cache-scope.js +64 -13
- package/dist/cache.d.ts +1 -0
- package/dist/cache.js +3 -3
- package/dist/cache.test.js +16 -0
- package/dist/class-component.js +6 -0
- package/dist/class-component.test.js +53 -2
- package/dist/class-helpers.d.ts +4 -4
- package/dist/class-helpers.js +357 -32
- package/dist/class-helpers.test.d.ts +1 -0
- package/dist/class-helpers.test.js +169 -0
- package/dist/context.d.ts +16 -2
- package/dist/context.js +44 -3
- package/dist/dev-overlay.js +85 -12
- package/dist/dev-overlay.test.js +22 -0
- package/dist/dom.d.ts +15 -0
- package/dist/dom.js +97 -3
- package/dist/effect-errors.test.d.ts +1 -0
- package/dist/effect-errors.test.js +163 -0
- package/dist/effects.d.ts +8 -0
- package/dist/effects.js +13 -0
- package/dist/error-overlay.js +7 -7
- package/dist/handler-html.d.ts +63 -0
- package/dist/handler-html.js +285 -0
- package/dist/handler-html.test.d.ts +1 -0
- package/dist/handler-html.test.js +256 -0
- package/dist/handler-routing.d.ts +83 -0
- package/dist/handler-routing.js +579 -0
- package/dist/handler-routing.test.d.ts +1 -0
- package/dist/handler-routing.test.js +99 -0
- package/dist/handler-segments.d.ts +43 -0
- package/dist/handler-segments.js +115 -0
- package/dist/handler-segments.test.d.ts +1 -0
- package/dist/handler-segments.test.js +217 -0
- package/dist/head-tags.d.ts +51 -0
- package/dist/head-tags.js +329 -0
- package/dist/head-tags.test.d.ts +1 -0
- package/dist/head-tags.test.js +131 -0
- package/dist/highlight-bind.d.ts +42 -0
- package/dist/highlight-bind.js +176 -0
- package/dist/highlight-bind.test.d.ts +1 -0
- package/dist/highlight-bind.test.js +124 -0
- package/dist/highlight.d.ts +93 -0
- package/dist/highlight.js +426 -0
- package/dist/highlight.test.d.ts +1 -0
- package/dist/highlight.test.js +56 -0
- package/dist/hints.d.ts +19 -0
- package/dist/hints.js +97 -0
- package/dist/hook-args.d.ts +7 -0
- package/dist/hook-args.js +10 -0
- package/dist/htmlspec-attributes.d.ts +1 -0
- package/dist/htmlspec-attributes.js +159 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/jsx-types.d.ts +11 -0
- package/dist/krate-core.js +2 -0
- package/dist/krate-dev.js +75 -12
- package/dist/krate-f-actions.js +2 -0
- package/dist/krate-f-classes.js +8 -0
- package/dist/krate-f-helpers.js +2 -0
- package/dist/krate-f-highlight.js +2 -0
- package/dist/krate-f-list.js +2 -0
- package/dist/krate-f-navigation.js +2 -0
- package/dist/krate-f-router-lite.js +2 -0
- package/dist/krate-f-router.js +2 -0
- package/dist/krate-features.json +493 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/list.js +4 -2
- package/dist/metadata-routes.d.ts +75 -0
- package/dist/metadata-routes.js +76 -0
- package/dist/metadata.d.ts +222 -0
- package/dist/metadata.js +452 -0
- package/dist/metadata.test.d.ts +1 -0
- package/dist/metadata.test.js +167 -0
- package/dist/navigation-server.d.ts +27 -0
- package/dist/navigation-server.js +90 -0
- package/dist/navigation.d.ts +37 -0
- package/dist/navigation.js +195 -0
- package/dist/navigation.test.d.ts +1 -0
- package/dist/navigation.test.js +130 -0
- package/dist/node-server.d.ts +22 -0
- package/dist/node-server.js +436 -0
- package/dist/node-server.test.d.ts +1 -0
- package/dist/node-server.test.js +492 -0
- package/dist/og-files.d.ts +2 -0
- package/dist/og-files.js +19 -0
- package/dist/og.d.ts +56 -0
- package/dist/og.js +156 -0
- package/dist/patterns.test.d.ts +1 -0
- package/dist/patterns.test.js +98 -0
- package/dist/react.d.ts +47 -0
- package/dist/react.js +59 -1
- package/dist/react19.test.d.ts +1 -0
- package/dist/react19.test.js +176 -0
- package/dist/reactivity-core.test.d.ts +1 -0
- package/dist/reactivity-core.test.js +152 -0
- package/dist/reconcile.js +4 -2
- package/dist/request-context.d.ts +23 -0
- package/dist/request-context.js +45 -0
- package/dist/resp.d.ts +55 -0
- package/dist/resp.js +239 -0
- package/dist/router-layout.test.js +70 -0
- package/dist/router-nav.test.js +65 -0
- package/dist/router-speculation.test.d.ts +1 -0
- package/dist/router-speculation.test.js +25 -0
- package/dist/router-styles.test.d.ts +1 -0
- package/dist/router-styles.test.js +98 -0
- package/dist/router.js +175 -36
- package/dist/segmented-lru.d.ts +19 -0
- package/dist/segmented-lru.js +87 -0
- package/dist/server-async.test.js +43 -1
- package/dist/server-handler.d.ts +165 -0
- package/dist/server-handler.js +1826 -0
- package/dist/server-handler.test.d.ts +1 -0
- package/dist/server-handler.test.js +522 -0
- package/dist/server-highlight.test.d.ts +1 -0
- package/dist/server-highlight.test.js +32 -0
- package/dist/server-renderer.js +165 -720
- package/dist/server-renderer.test.d.ts +1 -0
- package/dist/server-renderer.test.js +266 -0
- package/dist/server.d.ts +13 -1
- package/dist/server.js +131 -16
- package/dist/server.test.js +20 -0
- package/dist/sha256.d.ts +1 -0
- package/dist/sha256.js +66 -0
- package/dist/sha256.test.d.ts +1 -0
- package/dist/sha256.test.js +13 -0
- package/dist/shared-isr.d.ts +31 -0
- package/dist/shared-isr.js +142 -0
- package/dist/signal.d.ts +3 -2
- package/dist/signal.js +163 -23
- package/dist/slots.js +12 -1
- package/dist/ssr-core-behavior.test.d.ts +1 -0
- package/dist/ssr-core-behavior.test.js +620 -0
- package/dist/ssr-core.d.ts +175 -0
- package/dist/ssr-core.js +940 -0
- package/dist/ssr-core.test.d.ts +1 -0
- package/dist/ssr-core.test.js +324 -0
- package/dist/static-memory.d.ts +3 -0
- package/dist/static-memory.js +47 -0
- package/dist/static-memory.test.d.ts +1 -0
- package/dist/static-memory.test.js +26 -0
- package/dist/test-redis.d.ts +12 -0
- package/dist/test-redis.js +131 -0
- package/dist/use-id.d.ts +8 -0
- package/dist/use-id.js +40 -0
- package/package.json +30 -2
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach } from 'vitest';
|
|
2
|
+
import { createSignal, createEffect, createMemo, disposeAll, krateFlushSync, onCleanup } from './signal';
|
|
3
|
+
const tick = () => new Promise((r) => setTimeout(r, 0));
|
|
4
|
+
describe('effect update loops', () => {
|
|
5
|
+
beforeEach(() => disposeAll());
|
|
6
|
+
it('throws Maximum update depth exceeded for two effects that feed each other', () => {
|
|
7
|
+
const [a, setA] = createSignal(0);
|
|
8
|
+
const [b, setB] = createSignal(0);
|
|
9
|
+
createEffect(() => setB(a() + 1));
|
|
10
|
+
createEffect(() => setA(b() + 1));
|
|
11
|
+
expect(() => krateFlushSync()).toThrow(/Maximum update depth exceeded/);
|
|
12
|
+
// The queue was dropped: nothing is pending and later writes still work.
|
|
13
|
+
expect(() => krateFlushSync()).not.toThrow();
|
|
14
|
+
let seen = -1;
|
|
15
|
+
createEffect(() => {
|
|
16
|
+
seen = 1;
|
|
17
|
+
});
|
|
18
|
+
expect(seen).toBe(1);
|
|
19
|
+
});
|
|
20
|
+
it('keeps the event loop responsive after the loop is reported', async () => {
|
|
21
|
+
const [a, setA] = createSignal(0);
|
|
22
|
+
const [b, setB] = createSignal(0);
|
|
23
|
+
createEffect(() => setB(a() + 1));
|
|
24
|
+
createEffect(() => setA(b() + 1));
|
|
25
|
+
try {
|
|
26
|
+
krateFlushSync();
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// reported
|
|
30
|
+
}
|
|
31
|
+
let ticked = false;
|
|
32
|
+
setTimeout(() => (ticked = true), 0);
|
|
33
|
+
await tick();
|
|
34
|
+
expect(ticked).toBe(true);
|
|
35
|
+
});
|
|
36
|
+
it('names the looping effect in the message', () => {
|
|
37
|
+
const [a, setA] = createSignal(0);
|
|
38
|
+
createEffect(function bumpCounter() {
|
|
39
|
+
setA(a() + 1);
|
|
40
|
+
});
|
|
41
|
+
// A self-write only reruns once; add a partner to make it loop.
|
|
42
|
+
const [b, setB] = createSignal(0);
|
|
43
|
+
createEffect(function ping() {
|
|
44
|
+
setB(a() + 1);
|
|
45
|
+
});
|
|
46
|
+
createEffect(function pong() {
|
|
47
|
+
setA(b() + 1);
|
|
48
|
+
});
|
|
49
|
+
expect(() => krateFlushSync()).toThrow(/ping|pong|bumpCounter/);
|
|
50
|
+
});
|
|
51
|
+
it('still settles a long but finite cascade', () => {
|
|
52
|
+
const sigs = Array.from({ length: 30 }, () => createSignal(0));
|
|
53
|
+
for (let i = 1; i < sigs.length; i++) {
|
|
54
|
+
createEffect(() => sigs[i][1](sigs[i - 1][0]() + 1));
|
|
55
|
+
}
|
|
56
|
+
sigs[0][1](1);
|
|
57
|
+
krateFlushSync();
|
|
58
|
+
expect(sigs[29][0]()).toBe(30);
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
describe('effect dependency tracking', () => {
|
|
62
|
+
beforeEach(() => disposeAll());
|
|
63
|
+
it('drops dependencies the last run did not read', () => {
|
|
64
|
+
const [cond, setCond] = createSignal(true);
|
|
65
|
+
const [x, setX] = createSignal(0);
|
|
66
|
+
const [y] = createSignal(0);
|
|
67
|
+
let runs = 0;
|
|
68
|
+
createEffect(() => {
|
|
69
|
+
runs++;
|
|
70
|
+
cond() ? x() : y();
|
|
71
|
+
});
|
|
72
|
+
expect(runs).toBe(1);
|
|
73
|
+
setCond(false);
|
|
74
|
+
krateFlushSync();
|
|
75
|
+
expect(runs).toBe(2);
|
|
76
|
+
setX(5);
|
|
77
|
+
krateFlushSync();
|
|
78
|
+
setX(6);
|
|
79
|
+
krateFlushSync();
|
|
80
|
+
expect(runs).toBe(2);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
describe('nested effects', () => {
|
|
84
|
+
beforeEach(() => disposeAll());
|
|
85
|
+
it('disposes an inner effect when the parent effect re-runs', () => {
|
|
86
|
+
const [a, setA] = createSignal(0);
|
|
87
|
+
const [b, setB] = createSignal(0);
|
|
88
|
+
let innerRuns = 0;
|
|
89
|
+
createEffect(() => {
|
|
90
|
+
a();
|
|
91
|
+
createEffect(() => {
|
|
92
|
+
b();
|
|
93
|
+
innerRuns++;
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
expect(innerRuns).toBe(1);
|
|
97
|
+
setA(1);
|
|
98
|
+
krateFlushSync();
|
|
99
|
+
setA(2);
|
|
100
|
+
krateFlushSync();
|
|
101
|
+
expect(innerRuns).toBe(3);
|
|
102
|
+
innerRuns = 0;
|
|
103
|
+
setB(1);
|
|
104
|
+
krateFlushSync();
|
|
105
|
+
expect(innerRuns).toBe(1);
|
|
106
|
+
});
|
|
107
|
+
it('runs the inner effect cleanup when the parent re-runs', () => {
|
|
108
|
+
const [a, setA] = createSignal(0);
|
|
109
|
+
const log = [];
|
|
110
|
+
createEffect(() => {
|
|
111
|
+
const v = a();
|
|
112
|
+
createEffect(() => {
|
|
113
|
+
onCleanup(() => log.push('clean' + v));
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
setA(1);
|
|
117
|
+
krateFlushSync();
|
|
118
|
+
expect(log).toEqual(['clean0']);
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
describe('createMemo', () => {
|
|
122
|
+
beforeEach(() => disposeAll());
|
|
123
|
+
it('is current on a synchronous read after a write', () => {
|
|
124
|
+
const [a, setA] = createSignal(1);
|
|
125
|
+
const m = createMemo(() => a() * 10);
|
|
126
|
+
expect(m()).toBe(10);
|
|
127
|
+
setA(5);
|
|
128
|
+
expect(m()).toBe(50);
|
|
129
|
+
});
|
|
130
|
+
it('memoizes between writes and propagates to effects once', () => {
|
|
131
|
+
const [a, setA] = createSignal(1);
|
|
132
|
+
let computes = 0;
|
|
133
|
+
const m = createMemo(() => {
|
|
134
|
+
computes++;
|
|
135
|
+
return a() % 2;
|
|
136
|
+
});
|
|
137
|
+
let runs = 0;
|
|
138
|
+
createEffect(() => {
|
|
139
|
+
m();
|
|
140
|
+
runs++;
|
|
141
|
+
});
|
|
142
|
+
expect(m()).toBe(1);
|
|
143
|
+
expect(m()).toBe(1);
|
|
144
|
+
expect(computes).toBe(1);
|
|
145
|
+
setA(3);
|
|
146
|
+
krateFlushSync();
|
|
147
|
+
expect(runs).toBe(1);
|
|
148
|
+
setA(4);
|
|
149
|
+
krateFlushSync();
|
|
150
|
+
expect(runs).toBe(2);
|
|
151
|
+
});
|
|
152
|
+
});
|
package/dist/reconcile.js
CHANGED
|
@@ -173,8 +173,9 @@ function syncAttributes(oldEl, newEl) {
|
|
|
173
173
|
oldEl.setAttribute(name, value);
|
|
174
174
|
}
|
|
175
175
|
}
|
|
176
|
-
// Pass 2: remove attributes no longer present.
|
|
177
|
-
|
|
176
|
+
// Pass 2: remove attributes no longer present. Iterate backwards because
|
|
177
|
+
// removing an attribute shifts the live NamedNodeMap left.
|
|
178
|
+
for (let i = oldEl.attributes.length - 1; i >= 0; i--) {
|
|
178
179
|
const name = oldEl.attributes[i].name;
|
|
179
180
|
if (!newNames.has(name)) {
|
|
180
181
|
oldEl.removeAttribute(name);
|
|
@@ -336,6 +337,7 @@ export function reconcileTrees(oldRoot, newRoot) {
|
|
|
336
337
|
if (oldEl.tagName !== newEl.tagName) {
|
|
337
338
|
const imported = document.importNode(newRoot, true);
|
|
338
339
|
if (oldEl.parentNode) {
|
|
340
|
+
disposeNode(oldEl);
|
|
339
341
|
oldEl.parentNode.replaceChild(imported, oldEl);
|
|
340
342
|
}
|
|
341
343
|
return;
|
|
@@ -58,5 +58,28 @@ export interface NotFoundSignal extends Error {
|
|
|
58
58
|
export declare function notFound(): never;
|
|
59
59
|
/** isNotFoundSignal reports whether err was thrown by notFound(). */
|
|
60
60
|
export declare function isNotFoundSignal(err: unknown): boolean;
|
|
61
|
+
/** Thrown by forbidden() and unauthorized(); the host answers 403 or 401. */
|
|
62
|
+
export interface HTTPFallbackSignal extends Error {
|
|
63
|
+
__krateHTTPStatus: 401 | 403;
|
|
64
|
+
digest: string;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Stops rendering and responds with 403 and the nearest forbidden page
|
|
68
|
+
* (forbidden.tsx or 403.tsx). Works in pages, layouts, async server
|
|
69
|
+
* components, server actions and API routes.
|
|
70
|
+
*/
|
|
71
|
+
export declare function forbidden(): never;
|
|
72
|
+
/**
|
|
73
|
+
* Stops rendering and responds with 401 and the nearest unauthorized page
|
|
74
|
+
* (unauthorized.tsx or 401.tsx). Works wherever forbidden() does.
|
|
75
|
+
*/
|
|
76
|
+
export declare function unauthorized(): never;
|
|
77
|
+
/**
|
|
78
|
+
* accessDeniedStatus returns 403 or 401 when err was thrown by forbidden() or
|
|
79
|
+
* unauthorized() (or the matching Next.js digest), else 0.
|
|
80
|
+
*/
|
|
81
|
+
export declare function accessDeniedStatus(err: unknown): 401 | 403 | 0;
|
|
82
|
+
/** httpFallbackStatus is 404, 403 or 401 for notFound(), forbidden() and unauthorized() signals, else 0. */
|
|
83
|
+
export declare function httpFallbackStatus(err: unknown): 401 | 403 | 404 | 0;
|
|
61
84
|
/** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
|
|
62
85
|
export declare function redirectTarget(err: unknown): string;
|
package/dist/request-context.js
CHANGED
|
@@ -89,6 +89,51 @@ export function isNotFoundSignal(err) {
|
|
|
89
89
|
return e.__krateNotFound === true || e.digest === 'NEXT_NOT_FOUND' || e.message === 'NEXT_NOT_FOUND' ||
|
|
90
90
|
(typeof e.digest === 'string' && e.digest.startsWith('NEXT_HTTP_ERROR_FALLBACK;404'));
|
|
91
91
|
}
|
|
92
|
+
function httpFallback(status) {
|
|
93
|
+
const err = new Error(status === 403 ? 'NEXT_FORBIDDEN' : 'NEXT_UNAUTHORIZED');
|
|
94
|
+
err.__krateHTTPStatus = status;
|
|
95
|
+
err.digest = 'NEXT_HTTP_ERROR_FALLBACK;' + status;
|
|
96
|
+
throw err;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Stops rendering and responds with 403 and the nearest forbidden page
|
|
100
|
+
* (forbidden.tsx or 403.tsx). Works in pages, layouts, async server
|
|
101
|
+
* components, server actions and API routes.
|
|
102
|
+
*/
|
|
103
|
+
export function forbidden() {
|
|
104
|
+
return httpFallback(403);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Stops rendering and responds with 401 and the nearest unauthorized page
|
|
108
|
+
* (unauthorized.tsx or 401.tsx). Works wherever forbidden() does.
|
|
109
|
+
*/
|
|
110
|
+
export function unauthorized() {
|
|
111
|
+
return httpFallback(401);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* accessDeniedStatus returns 403 or 401 when err was thrown by forbidden() or
|
|
115
|
+
* unauthorized() (or the matching Next.js digest), else 0.
|
|
116
|
+
*/
|
|
117
|
+
export function accessDeniedStatus(err) {
|
|
118
|
+
if (!err || typeof err !== 'object')
|
|
119
|
+
return 0;
|
|
120
|
+
const e = err;
|
|
121
|
+
if (e.__krateHTTPStatus === 403 || e.__krateHTTPStatus === 401)
|
|
122
|
+
return e.__krateHTTPStatus;
|
|
123
|
+
if (typeof e.digest === 'string') {
|
|
124
|
+
if (e.digest === 'NEXT_HTTP_ERROR_FALLBACK;403')
|
|
125
|
+
return 403;
|
|
126
|
+
if (e.digest === 'NEXT_HTTP_ERROR_FALLBACK;401')
|
|
127
|
+
return 401;
|
|
128
|
+
}
|
|
129
|
+
return 0;
|
|
130
|
+
}
|
|
131
|
+
/** httpFallbackStatus is 404, 403 or 401 for notFound(), forbidden() and unauthorized() signals, else 0. */
|
|
132
|
+
export function httpFallbackStatus(err) {
|
|
133
|
+
if (isNotFoundSignal(err))
|
|
134
|
+
return 404;
|
|
135
|
+
return accessDeniedStatus(err);
|
|
136
|
+
}
|
|
92
137
|
/** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
|
|
93
138
|
export function redirectTarget(err) {
|
|
94
139
|
if (!err || typeof err !== 'object')
|
package/dist/resp.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export type RespValue = string | number | null | RespValue[] | Buffer;
|
|
2
|
+
export declare class RespError extends Error {
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
export interface RespOptions {
|
|
6
|
+
host: string;
|
|
7
|
+
port: number;
|
|
8
|
+
tls?: boolean;
|
|
9
|
+
username?: string;
|
|
10
|
+
password?: string;
|
|
11
|
+
db?: number;
|
|
12
|
+
/** Milliseconds to wait for a connection (default 1000). */
|
|
13
|
+
connectTimeoutMs?: number;
|
|
14
|
+
/** Milliseconds to wait for one reply (default 1000). */
|
|
15
|
+
commandTimeoutMs?: number;
|
|
16
|
+
}
|
|
17
|
+
/** Parses redis://[user:password@]host[:port][/db] and rediss:// (TLS) URLs. */
|
|
18
|
+
export declare function parseRedisURL(url: string): RespOptions;
|
|
19
|
+
/** Encodes a command as a RESP array of bulk strings. */
|
|
20
|
+
export declare function encodeCommand(args: Array<string | number | Buffer>): Buffer;
|
|
21
|
+
/** Incremental reply parser: push chunks, take complete replies. */
|
|
22
|
+
export declare class RespParser {
|
|
23
|
+
private buf;
|
|
24
|
+
push(chunk: Buffer): void;
|
|
25
|
+
/** The next complete reply, or undefined when more bytes are needed. */
|
|
26
|
+
next(): RespValue | RespError | undefined;
|
|
27
|
+
private line;
|
|
28
|
+
private parse;
|
|
29
|
+
}
|
|
30
|
+
/** One connection: commands are written in order and answered in order. */
|
|
31
|
+
export declare class RespConnection {
|
|
32
|
+
private readonly opts;
|
|
33
|
+
private socket;
|
|
34
|
+
private connecting;
|
|
35
|
+
private pending;
|
|
36
|
+
private parser;
|
|
37
|
+
private closed;
|
|
38
|
+
/** Called with each pushed pub/sub message (type, channel, payload). */
|
|
39
|
+
onPush?: (kind: string, channel: string, payload: string) => void;
|
|
40
|
+
/** Called after the socket dropped (not after close()). */
|
|
41
|
+
onDisconnect?: (err?: Error) => void;
|
|
42
|
+
constructor(opts: RespOptions);
|
|
43
|
+
private connect;
|
|
44
|
+
private attach;
|
|
45
|
+
private settle;
|
|
46
|
+
private handshake;
|
|
47
|
+
private write;
|
|
48
|
+
/** Sends a command and resolves with its reply. */
|
|
49
|
+
command(...args: Array<string | number | Buffer>): Promise<RespValue>;
|
|
50
|
+
/** Writes a command without waiting for a reply (pub/sub subscribe uses pushes). */
|
|
51
|
+
send(...args: Array<string | number | Buffer>): Promise<void>;
|
|
52
|
+
/** Opens the connection now (used by the subscriber to reconnect). */
|
|
53
|
+
ensure(): Promise<void>;
|
|
54
|
+
close(): void;
|
|
55
|
+
}
|
package/dist/resp.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// A small RESP2 client over node:net / node:tls, enough for the Redis cache
|
|
2
|
+
// adapter: pipelined commands with a timeout each, automatic reconnects, and a
|
|
3
|
+
// subscriber connection for pub/sub. No dependency.
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import tls from 'node:tls';
|
|
6
|
+
export class RespError extends Error {
|
|
7
|
+
constructor(message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'RespError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Parses redis://[user:password@]host[:port][/db] and rediss:// (TLS) URLs. */
|
|
13
|
+
export function parseRedisURL(url) {
|
|
14
|
+
const u = new URL(url);
|
|
15
|
+
if (u.protocol !== 'redis:' && u.protocol !== 'rediss:')
|
|
16
|
+
throw new Error(`unsupported cache URL protocol ${u.protocol}`);
|
|
17
|
+
const db = u.pathname.length > 1 ? parseInt(u.pathname.slice(1), 10) : undefined;
|
|
18
|
+
return {
|
|
19
|
+
host: u.hostname || '127.0.0.1',
|
|
20
|
+
port: u.port ? parseInt(u.port, 10) : 6379,
|
|
21
|
+
tls: u.protocol === 'rediss:',
|
|
22
|
+
username: u.username ? decodeURIComponent(u.username) : undefined,
|
|
23
|
+
password: u.password ? decodeURIComponent(u.password) : undefined,
|
|
24
|
+
db: db !== undefined && Number.isFinite(db) ? db : undefined,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Encodes a command as a RESP array of bulk strings. */
|
|
28
|
+
export function encodeCommand(args) {
|
|
29
|
+
const parts = [Buffer.from(`*${args.length}\r\n`)];
|
|
30
|
+
for (const a of args) {
|
|
31
|
+
const b = Buffer.isBuffer(a) ? a : Buffer.from(String(a));
|
|
32
|
+
parts.push(Buffer.from(`$${b.length}\r\n`), b, Buffer.from('\r\n'));
|
|
33
|
+
}
|
|
34
|
+
return Buffer.concat(parts);
|
|
35
|
+
}
|
|
36
|
+
/** Incremental reply parser: push chunks, take complete replies. */
|
|
37
|
+
export class RespParser {
|
|
38
|
+
constructor() {
|
|
39
|
+
this.buf = Buffer.alloc(0);
|
|
40
|
+
}
|
|
41
|
+
push(chunk) {
|
|
42
|
+
this.buf = this.buf.length === 0 ? chunk : Buffer.concat([this.buf, chunk]);
|
|
43
|
+
}
|
|
44
|
+
/** The next complete reply, or undefined when more bytes are needed. */
|
|
45
|
+
next() {
|
|
46
|
+
const r = this.parse(0);
|
|
47
|
+
if (!r)
|
|
48
|
+
return undefined;
|
|
49
|
+
this.buf = this.buf.subarray(r.end);
|
|
50
|
+
return r.value;
|
|
51
|
+
}
|
|
52
|
+
line(at) {
|
|
53
|
+
const i = this.buf.indexOf('\r\n', at);
|
|
54
|
+
if (i < 0)
|
|
55
|
+
return null;
|
|
56
|
+
return { text: this.buf.toString('utf8', at, i), end: i + 2 };
|
|
57
|
+
}
|
|
58
|
+
parse(at) {
|
|
59
|
+
if (at >= this.buf.length)
|
|
60
|
+
return null;
|
|
61
|
+
const type = String.fromCharCode(this.buf[at]);
|
|
62
|
+
const l = this.line(at + 1);
|
|
63
|
+
if (!l)
|
|
64
|
+
return null;
|
|
65
|
+
switch (type) {
|
|
66
|
+
case '+':
|
|
67
|
+
return { value: l.text, end: l.end };
|
|
68
|
+
case '-':
|
|
69
|
+
return { value: new RespError(l.text), end: l.end };
|
|
70
|
+
case ':':
|
|
71
|
+
return { value: parseInt(l.text, 10), end: l.end };
|
|
72
|
+
case '$': {
|
|
73
|
+
const n = parseInt(l.text, 10);
|
|
74
|
+
if (n < 0)
|
|
75
|
+
return { value: null, end: l.end };
|
|
76
|
+
if (this.buf.length < l.end + n + 2)
|
|
77
|
+
return null;
|
|
78
|
+
return { value: this.buf.toString('utf8', l.end, l.end + n), end: l.end + n + 2 };
|
|
79
|
+
}
|
|
80
|
+
case '*': {
|
|
81
|
+
const n = parseInt(l.text, 10);
|
|
82
|
+
if (n < 0)
|
|
83
|
+
return { value: null, end: l.end };
|
|
84
|
+
const items = [];
|
|
85
|
+
let pos = l.end;
|
|
86
|
+
for (let i = 0; i < n; i++) {
|
|
87
|
+
const r = this.parse(pos);
|
|
88
|
+
if (!r)
|
|
89
|
+
return null;
|
|
90
|
+
items.push(r.value instanceof RespError ? r.value.message : r.value);
|
|
91
|
+
pos = r.end;
|
|
92
|
+
}
|
|
93
|
+
return { value: items, end: pos };
|
|
94
|
+
}
|
|
95
|
+
default:
|
|
96
|
+
throw new RespError(`unexpected reply type ${JSON.stringify(type)}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** One connection: commands are written in order and answered in order. */
|
|
101
|
+
export class RespConnection {
|
|
102
|
+
constructor(opts) {
|
|
103
|
+
this.opts = opts;
|
|
104
|
+
this.socket = null;
|
|
105
|
+
this.connecting = null;
|
|
106
|
+
this.pending = [];
|
|
107
|
+
this.parser = new RespParser();
|
|
108
|
+
this.closed = false;
|
|
109
|
+
}
|
|
110
|
+
connect() {
|
|
111
|
+
if (this.socket)
|
|
112
|
+
return Promise.resolve(this.socket);
|
|
113
|
+
if (this.connecting)
|
|
114
|
+
return this.connecting;
|
|
115
|
+
const timeout = this.opts.connectTimeoutMs ?? 1000;
|
|
116
|
+
this.connecting = new Promise((resolve, reject) => {
|
|
117
|
+
const done = (err, s) => {
|
|
118
|
+
clearTimeout(timer);
|
|
119
|
+
this.connecting = null;
|
|
120
|
+
if (err)
|
|
121
|
+
reject(err);
|
|
122
|
+
else
|
|
123
|
+
resolve(s);
|
|
124
|
+
};
|
|
125
|
+
const s = this.opts.tls
|
|
126
|
+
? tls.connect({ host: this.opts.host, port: this.opts.port, servername: this.opts.host })
|
|
127
|
+
: net.connect({ host: this.opts.host, port: this.opts.port });
|
|
128
|
+
const timer = setTimeout(() => {
|
|
129
|
+
s.destroy();
|
|
130
|
+
done(new Error(`cache connection to ${this.opts.host}:${this.opts.port} timed out`));
|
|
131
|
+
}, timeout);
|
|
132
|
+
s.setNoDelay(true);
|
|
133
|
+
s.once('error', (e) => done(e));
|
|
134
|
+
s.once(this.opts.tls ? 'secureConnect' : 'connect', () => {
|
|
135
|
+
s.removeAllListeners('error');
|
|
136
|
+
this.attach(s);
|
|
137
|
+
this.handshake(s).then(() => done(null, s), (e) => {
|
|
138
|
+
s.destroy();
|
|
139
|
+
done(e instanceof Error ? e : new Error(String(e)));
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
return this.connecting;
|
|
144
|
+
}
|
|
145
|
+
attach(s) {
|
|
146
|
+
this.socket = s;
|
|
147
|
+
this.parser = new RespParser();
|
|
148
|
+
s.on('data', (chunk) => {
|
|
149
|
+
this.parser.push(chunk);
|
|
150
|
+
for (;;) {
|
|
151
|
+
let reply;
|
|
152
|
+
try {
|
|
153
|
+
reply = this.parser.next();
|
|
154
|
+
}
|
|
155
|
+
catch (e) {
|
|
156
|
+
s.destroy(e instanceof Error ? e : new Error(String(e)));
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (reply === undefined)
|
|
160
|
+
return;
|
|
161
|
+
// A subscriber connection (onPush set) only receives pushes.
|
|
162
|
+
if (this.onPush && Array.isArray(reply)) {
|
|
163
|
+
this.onPush(String(reply[0]), String(reply[1]), String(reply[2] ?? ''));
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
this.settle(reply);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
const drop = (err) => {
|
|
170
|
+
if (this.socket !== s)
|
|
171
|
+
return;
|
|
172
|
+
this.socket = null;
|
|
173
|
+
const pending = this.pending;
|
|
174
|
+
this.pending = [];
|
|
175
|
+
for (const p of pending) {
|
|
176
|
+
clearTimeout(p.timer);
|
|
177
|
+
p.reject(err || new Error('cache connection closed'));
|
|
178
|
+
}
|
|
179
|
+
if (!this.closed && this.onDisconnect)
|
|
180
|
+
this.onDisconnect(err);
|
|
181
|
+
};
|
|
182
|
+
s.on('error', (e) => drop(e));
|
|
183
|
+
s.on('close', () => drop());
|
|
184
|
+
}
|
|
185
|
+
settle(reply) {
|
|
186
|
+
const p = this.pending.shift();
|
|
187
|
+
if (!p)
|
|
188
|
+
return;
|
|
189
|
+
clearTimeout(p.timer);
|
|
190
|
+
if (reply instanceof RespError)
|
|
191
|
+
p.reject(reply);
|
|
192
|
+
else
|
|
193
|
+
p.resolve(reply);
|
|
194
|
+
}
|
|
195
|
+
async handshake(s) {
|
|
196
|
+
const send = (args) => this.write(s, args);
|
|
197
|
+
if (this.opts.password !== undefined) {
|
|
198
|
+
await send(this.opts.username ? ['AUTH', this.opts.username, this.opts.password] : ['AUTH', this.opts.password]);
|
|
199
|
+
}
|
|
200
|
+
if (this.opts.db)
|
|
201
|
+
await send(['SELECT', String(this.opts.db)]);
|
|
202
|
+
}
|
|
203
|
+
write(s, args) {
|
|
204
|
+
const timeout = this.opts.commandTimeoutMs ?? 1000;
|
|
205
|
+
return new Promise((resolve, reject) => {
|
|
206
|
+
const timer = setTimeout(() => {
|
|
207
|
+
// The reply order is unknown after a timeout: drop the connection.
|
|
208
|
+
s.destroy(new Error(`cache command ${String(args[0])} timed out after ${timeout}ms`));
|
|
209
|
+
}, timeout);
|
|
210
|
+
this.pending.push({ resolve, reject, timer });
|
|
211
|
+
s.write(encodeCommand(args), (err) => {
|
|
212
|
+
if (err)
|
|
213
|
+
s.destroy(err);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
/** Sends a command and resolves with its reply. */
|
|
218
|
+
async command(...args) {
|
|
219
|
+
if (this.closed)
|
|
220
|
+
throw new Error('cache connection is closed');
|
|
221
|
+
const s = await this.connect();
|
|
222
|
+
return this.write(s, args);
|
|
223
|
+
}
|
|
224
|
+
/** Writes a command without waiting for a reply (pub/sub subscribe uses pushes). */
|
|
225
|
+
async send(...args) {
|
|
226
|
+
const s = await this.connect();
|
|
227
|
+
s.write(encodeCommand(args));
|
|
228
|
+
}
|
|
229
|
+
/** Opens the connection now (used by the subscriber to reconnect). */
|
|
230
|
+
async ensure() {
|
|
231
|
+
await this.connect();
|
|
232
|
+
}
|
|
233
|
+
close() {
|
|
234
|
+
this.closed = true;
|
|
235
|
+
if (this.socket)
|
|
236
|
+
this.socket.destroy();
|
|
237
|
+
this.socket = null;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
@@ -89,6 +89,76 @@ describe('layout persistence', () => {
|
|
|
89
89
|
// The layout effect is still live.
|
|
90
90
|
expect(log).toEqual(['layout-cleanup', 'layout:1']);
|
|
91
91
|
});
|
|
92
|
+
it('shows a segment 404/500 page in place, keeps the layout, and hands over the server error data', async () => {
|
|
93
|
+
setup(shell('<main>Page A</main>'), [LAYOUT]);
|
|
94
|
+
const nav = document.getElementById('nav');
|
|
95
|
+
const errorBlock = '<script type="application/json" id="__krate_error">{"message":"Internal Server Error","digest":"abc1234567"}</script>';
|
|
96
|
+
const errDoc = doc('500', shell('<main id="err">Oops</main>'), [LAYOUT]).replace('</head>', errorBlock + '</head>');
|
|
97
|
+
fetch.mockImplementation(async (input) => {
|
|
98
|
+
const u = new URL(input, location.href);
|
|
99
|
+
const bodies = {
|
|
100
|
+
'/boom': [500, errDoc],
|
|
101
|
+
'/missing': [404, doc('404', shell('<main id="nf">Nothing here</main>'), [LAYOUT])],
|
|
102
|
+
'/fine': [200, doc('Fine', shell('<main>Fine</main>'), [LAYOUT])],
|
|
103
|
+
};
|
|
104
|
+
const hit = bodies[u.pathname];
|
|
105
|
+
return {
|
|
106
|
+
ok: !!hit && hit[0] < 400,
|
|
107
|
+
status: hit ? hit[0] : 404,
|
|
108
|
+
url: u.href,
|
|
109
|
+
headers: new Headers({ 'content-type': 'text/html' }),
|
|
110
|
+
text: async () => (hit ? hit[1] : ''),
|
|
111
|
+
};
|
|
112
|
+
});
|
|
113
|
+
await krateRouter.push('/boom');
|
|
114
|
+
expect(document.getElementById('err')).not.toBeNull();
|
|
115
|
+
expect(document.getElementById('nav')).toBe(nav);
|
|
116
|
+
expect(location.pathname).toBe('/boom');
|
|
117
|
+
const block = document.getElementById('__krate_error');
|
|
118
|
+
expect(JSON.parse(block.textContent).digest).toBe('abc1234567');
|
|
119
|
+
expect(document.querySelectorAll('#__krate_error')).toHaveLength(1);
|
|
120
|
+
// A 404 page swaps in the same way and the previous error data is dropped.
|
|
121
|
+
await krateRouter.push('/missing');
|
|
122
|
+
expect(document.getElementById('nf')).not.toBeNull();
|
|
123
|
+
expect(document.getElementById('nav')).toBe(nav);
|
|
124
|
+
expect(location.pathname).toBe('/missing');
|
|
125
|
+
expect(document.getElementById('__krate_error')).toBeNull();
|
|
126
|
+
// And an ordinary page after an error page leaves no stale data either.
|
|
127
|
+
await krateRouter.push('/boom');
|
|
128
|
+
expect(document.getElementById('__krate_error')).not.toBeNull();
|
|
129
|
+
await krateRouter.push('/fine');
|
|
130
|
+
expect(document.getElementById('__krate_error')).toBeNull();
|
|
131
|
+
expect(document.getElementById('nav')).toBe(nav);
|
|
132
|
+
});
|
|
133
|
+
describe('segment error boundaries', () => {
|
|
134
|
+
const ERR = { id: '_lerr_', k: 'error', d: 0, p: true };
|
|
135
|
+
const INNER = { id: '_linner_', k: 'layout', d: 0, p: true };
|
|
136
|
+
const nested = (page) => shell(`<!--kl:_lerr_--><section id="inner">Inner<!--kl:_linner_-->${page}<!--/kl:_linner_--></section><!--/kl:_lerr_-->`);
|
|
137
|
+
afterEach(() => {
|
|
138
|
+
delete globalThis.krateScopeFailed;
|
|
139
|
+
});
|
|
140
|
+
it('keeps the layouts below a healthy error boundary', async () => {
|
|
141
|
+
const chain = [LAYOUT, ERR, INNER];
|
|
142
|
+
setup(nested('<main>Page A</main>'), chain);
|
|
143
|
+
const inner = document.getElementById('inner');
|
|
144
|
+
routes['/b'] = doc('B', nested('<main>Page B</main>'), chain);
|
|
145
|
+
await krateRouter.push('/b');
|
|
146
|
+
expect(document.querySelector('main').textContent).toBe('Page B');
|
|
147
|
+
expect(document.getElementById('inner')).toBe(inner);
|
|
148
|
+
});
|
|
149
|
+
it('replaces a boundary that caught an error, and what is below it', async () => {
|
|
150
|
+
const chain = [LAYOUT, ERR, INNER];
|
|
151
|
+
setup(nested('<main>Page A</main>'), chain);
|
|
152
|
+
const inner = document.getElementById('inner');
|
|
153
|
+
const nav = document.getElementById('nav');
|
|
154
|
+
globalThis.krateScopeFailed = (scope) => scope === '_lerr_';
|
|
155
|
+
routes['/b'] = doc('B', nested('<main>Page B</main>'), chain);
|
|
156
|
+
await krateRouter.push('/b');
|
|
157
|
+
expect(document.querySelector('main').textContent).toBe('Page B');
|
|
158
|
+
expect(document.getElementById('inner')).not.toBe(inner);
|
|
159
|
+
expect(document.getElementById('nav')).toBe(nav);
|
|
160
|
+
});
|
|
161
|
+
});
|
|
92
162
|
it('remounts layouts the compiler marked as not persistable', async () => {
|
|
93
163
|
globalThis.__KRATE_CFG__ = { viewTransitions: false, dev: true };
|
|
94
164
|
const warn = vi.spyOn(console, 'warn').mockImplementation(() => { });
|