@teyik0/furin 0.2.0-alpha.3 → 0.2.0-alpha.4

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 (54) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/build/compile-entry.ts +109 -109
  4. package/dist/build/entry-template.ts +156 -156
  5. package/dist/build/server-routes-entry.ts +36 -36
  6. package/dist/cli/index.js +0 -0
  7. package/dist/client/link.js +163 -16
  8. package/dist/client/router/abort.d.ts +1 -0
  9. package/dist/client/router/sync-catch-up.d.ts +29 -0
  10. package/dist/furin.d.ts +1 -1
  11. package/dist/furin.js +499 -215
  12. package/dist/server/sync/adapter.d.ts +62 -0
  13. package/dist/server/sync/fingerprint.d.ts +6 -0
  14. package/dist/server/sync/index.d.ts +2 -2
  15. package/dist/server/sync/memory-adapter.d.ts +17 -0
  16. package/dist/server/sync/plugin.d.ts +12 -195
  17. package/dist/server/sync/response.d.ts +4 -0
  18. package/dist/server/sync/stream.d.ts +16 -4
  19. package/package.json +1 -1
  20. package/src/adapter/README.md +13 -13
  21. package/src/build/client.ts +152 -152
  22. package/src/build/compile-entry.ts +109 -109
  23. package/src/build/entry-template.ts +156 -156
  24. package/src/build/hydrate.ts +340 -340
  25. package/src/build/index.ts +152 -152
  26. package/src/build/route-types.ts +145 -145
  27. package/src/build/scan-server.ts +95 -95
  28. package/src/build/server-routes-entry.ts +36 -36
  29. package/src/build/shared.ts +80 -80
  30. package/src/build/ssg-cache.ts +32 -32
  31. package/src/build/types.ts +89 -89
  32. package/src/client/router/abort.ts +5 -0
  33. package/src/client/router/link-utils.ts +184 -184
  34. package/src/client/router/provider.tsx +883 -804
  35. package/src/client/router/sync-catch-up.ts +113 -0
  36. package/src/client/router/types.ts +276 -276
  37. package/src/client/sync.ts +98 -98
  38. package/src/client.ts +369 -369
  39. package/src/furin.ts +465 -465
  40. package/src/server/auto-invalidate/runtime.ts +134 -134
  41. package/src/server/dev-page-plugin.ts +454 -454
  42. package/src/server/render/assemble.ts +160 -160
  43. package/src/server/render/isr.ts +323 -323
  44. package/src/server/render/ssr.ts +591 -585
  45. package/src/server/router/plugin.ts +384 -384
  46. package/src/server/sync/adapter.ts +65 -0
  47. package/src/server/sync/config.ts +29 -29
  48. package/src/server/sync/fingerprint.ts +44 -0
  49. package/src/server/sync/index.ts +15 -14
  50. package/src/server/sync/memory-adapter.ts +196 -0
  51. package/src/server/sync/plugin.ts +200 -108
  52. package/src/server/sync/response.ts +77 -0
  53. package/src/server/sync/stream.ts +152 -144
  54. package/src/shared/deferred-ndjson.ts +7 -0
@@ -1,108 +1,200 @@
1
- import { type AfterHandler, Elysia } from "elysia";
2
- import {
3
- appendPendingInvalidationHeader,
4
- isSuccessfulMutationResponse,
5
- runInvalidationRules,
6
- } from "../auto-invalidate/runtime.ts";
7
- import type { InvalidationInput } from "../auto-invalidate/types.ts";
8
- import { publishSyncInvalidation } from "./stream.ts";
9
-
10
- export type SyncInput =
11
- | InvalidationInput
12
- | {
13
- invalidate: InvalidationInput;
14
- };
15
-
16
- type AnyHandlerContext = Parameters<AfterHandler>[0];
17
- interface IdempotencyContext {
18
- headers: {
19
- "idempotency-key"?: string | undefined;
20
- };
21
- request: Request;
22
- }
23
-
24
- function invalidationInputFromSync(input: SyncInput): InvalidationInput {
25
- if (input && typeof input === "object" && "invalidate" in input) {
26
- return input.invalidate;
27
- }
28
- return input;
29
- }
30
-
31
- function isMutationMethod(method: string): boolean {
32
- return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
33
- }
34
-
35
- function getIdempotencyKey(ctx: IdempotencyContext): string | undefined {
36
- const fromCtxHeaders = ctx.headers["idempotency-key"];
37
- if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
38
- return fromCtxHeaders;
39
- }
40
- const fromRequest = ctx.request.headers.get("Idempotency-Key");
41
- return fromRequest || undefined;
42
- }
43
-
44
- export function furinSync() {
45
- const idempotencyKeys = new Set<string>();
46
- const requestKeys = new WeakMap<Request, string>();
47
- return new Elysia({ name: "furin-sync" }).macro({
48
- sync(input: SyncInput) {
49
- const invalidate = invalidationInputFromSync(input);
50
- return {
51
- beforeHandle(ctx) {
52
- if (!isMutationMethod(ctx.request.method)) {
53
- return;
54
- }
55
- const key = getIdempotencyKey(ctx);
56
- if (!key) {
57
- return new Response("Missing Idempotency-Key header", {
58
- status: 428,
59
- headers: { "content-type": "text/plain; charset=utf-8" },
60
- });
61
- }
62
- const requestKey = `${ctx.request.method}:${new URL(ctx.request.url).pathname}:${key}`;
63
- if (idempotencyKeys.has(requestKey)) {
64
- return new Response("Duplicate Idempotency-Key header", {
65
- status: 409,
66
- headers: { "content-type": "text/plain; charset=utf-8" },
67
- });
68
- }
69
- idempotencyKeys.add(requestKey);
70
- requestKeys.set(ctx.request, requestKey);
71
- if (idempotencyKeys.size > 1000) {
72
- const oldest = idempotencyKeys.values().next().value;
73
- if (typeof oldest === "string") {
74
- idempotencyKeys.delete(oldest);
75
- }
76
- }
77
- },
78
- afterHandle(ctx: AnyHandlerContext) {
79
- if (!isSuccessfulMutationResponse(ctx)) {
80
- const requestKey = requestKeys.get(ctx.request);
81
- if (requestKey) {
82
- idempotencyKeys.delete(requestKey);
83
- requestKeys.delete(ctx.request);
84
- }
85
- return;
86
- }
87
- requestKeys.delete(ctx.request);
88
-
89
- runInvalidationRules(invalidate);
90
- const pending = appendPendingInvalidationHeader(ctx.set);
91
- if (pending.length === 0) {
92
- return;
93
- }
94
-
95
- ctx.set.headers["x-furin-sync"] = "1";
96
- publishSyncInvalidation(pending);
97
- },
98
- error({ request }) {
99
- const requestKey = requestKeys.get(request);
100
- if (requestKey) {
101
- idempotencyKeys.delete(requestKey);
102
- requestKeys.delete(request);
103
- }
104
- },
105
- };
106
- },
107
- });
108
- }
1
+ import { Elysia } from "elysia";
2
+ import {
3
+ appendPendingInvalidationHeader,
4
+ isSuccessfulMutationResponse,
5
+ runInvalidationRules,
6
+ } from "../auto-invalidate/runtime.ts";
7
+ import type { InvalidationInput } from "../auto-invalidate/types.ts";
8
+ import { getSyncStreamPath } from "./config.ts";
9
+ import { createMutationFingerprint } from "./fingerprint.ts";
10
+ import { memorySyncAdapter } from "./memory-adapter.ts";
11
+ import { replayResponse, storeResponse } from "./response.ts";
12
+
13
+ export type SyncRouteOption =
14
+ | false
15
+ | InvalidationInput
16
+ | {
17
+ invalidate: InvalidationInput;
18
+ };
19
+
20
+ /** @deprecated Use SyncRouteOption. */
21
+ export type SyncInput = Exclude<SyncRouteOption, false>;
22
+
23
+ interface RouteSyncMetadata {
24
+ disabled: boolean;
25
+ invalidate?: InvalidationInput;
26
+ }
27
+
28
+ interface ActiveMutation {
29
+ mutationId: string;
30
+ }
31
+
32
+ interface MutationContext {
33
+ body?: unknown;
34
+ headers: {
35
+ "idempotency-key"?: string | undefined;
36
+ };
37
+ request: Request;
38
+ }
39
+
40
+ const routeMetadata = new WeakMap<Request, RouteSyncMetadata>();
41
+ const activeMutations = new WeakMap<Request, ActiveMutation>();
42
+
43
+ function invalidationInputFromSync(input: Exclude<SyncRouteOption, false>): InvalidationInput {
44
+ if (input && typeof input === "object" && "invalidate" in input) {
45
+ return input.invalidate;
46
+ }
47
+ return input;
48
+ }
49
+
50
+ function isMutationMethod(method: string): boolean {
51
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
52
+ }
53
+
54
+ function getIdempotencyKey(ctx: MutationContext): string | undefined {
55
+ const fromCtxHeaders = ctx.headers["idempotency-key"];
56
+ if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
57
+ return fromCtxHeaders;
58
+ }
59
+ const fromRequest = ctx.request.headers.get("Idempotency-Key");
60
+ return fromRequest || undefined;
61
+ }
62
+
63
+ async function getPrincipalScope(request: Request): Promise<string> {
64
+ const authorization = request.headers.get("authorization");
65
+ const credentials = authorization
66
+ ? JSON.stringify(["authorization", authorization])
67
+ : JSON.stringify(["cookie", request.headers.get("cookie") ?? ""]);
68
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(credentials));
69
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
70
+ }
71
+
72
+ function supportsReplayBody(request: Request): boolean {
73
+ const contentType = request.headers.get("content-type")?.toLowerCase();
74
+ const mediaType = contentType?.split(";", 1)[0]?.trim();
75
+ return (
76
+ contentType === undefined ||
77
+ mediaType === "application/json" ||
78
+ (mediaType?.startsWith("application/") === true && mediaType.endsWith("+json")) ||
79
+ contentType.startsWith("application/x-www-form-urlencoded") ||
80
+ contentType.startsWith("text/")
81
+ );
82
+ }
83
+
84
+ function conflictResponse(reason: "in-progress" | "payload-mismatch"): Response {
85
+ const inProgress = reason === "in-progress";
86
+ return Response.json(
87
+ {
88
+ code: inProgress ? "FURIN_MUTATION_IN_PROGRESS" : "FURIN_IDEMPOTENCY_MISMATCH",
89
+ message: inProgress
90
+ ? "A mutation with this Idempotency-Key is still running."
91
+ : "The Idempotency-Key was already used with a different request.",
92
+ },
93
+ {
94
+ status: 409,
95
+ headers: inProgress ? { "retry-after": "1" } : undefined,
96
+ }
97
+ );
98
+ }
99
+
100
+ async function beginMutation(ctx: MutationContext): Promise<Response | undefined> {
101
+ if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
102
+ return;
103
+ }
104
+ const idempotencyKey = getIdempotencyKey(ctx);
105
+ if (!idempotencyKey) {
106
+ return new Response("Missing Idempotency-Key header", {
107
+ status: 428,
108
+ headers: { "content-type": "text/plain; charset=utf-8" },
109
+ });
110
+ }
111
+ if (!supportsReplayBody(ctx.request)) {
112
+ return Response.json(
113
+ {
114
+ code: "FURIN_UNSUPPORTED_SYNC_BODY",
115
+ message: "This request body cannot be replayed. Set sync: false on the route.",
116
+ },
117
+ { status: 415 }
118
+ );
119
+ }
120
+
121
+ const url = new URL(ctx.request.url);
122
+ const principal = await getPrincipalScope(ctx.request);
123
+ const key = `${ctx.request.method}:${url.pathname}:${idempotencyKey}`;
124
+ const fingerprint = await createMutationFingerprint({ body: ctx.body, request: ctx.request });
125
+ const result = await memorySyncAdapter.beginMutation({ fingerprint, key, principal });
126
+ if (result.kind === "replay") {
127
+ return replayResponse(result.response);
128
+ }
129
+ if (result.kind === "conflict") {
130
+ return conflictResponse(result.reason);
131
+ }
132
+ if (result.kind === "unavailable") {
133
+ return Response.json(
134
+ {
135
+ code: "FURIN_SYNC_CAPACITY_EXCEEDED",
136
+ message: "The mutation replay store is temporarily full.",
137
+ },
138
+ { headers: { "retry-after": "1" }, status: 503 }
139
+ );
140
+ }
141
+ activeMutations.set(ctx.request, { mutationId: result.mutationId });
142
+ }
143
+
144
+ async function abortMutation(request: Request): Promise<void> {
145
+ const active = activeMutations.get(request);
146
+ if (!active) {
147
+ return;
148
+ }
149
+ activeMutations.delete(request);
150
+ await memorySyncAdapter.abortMutation(active);
151
+ }
152
+
153
+ export function furinSync() {
154
+ return new Elysia({ name: "furin-sync" })
155
+ .macro({
156
+ sync(input: SyncRouteOption) {
157
+ return {
158
+ transform({ request }) {
159
+ routeMetadata.set(
160
+ request,
161
+ input === false
162
+ ? { disabled: true }
163
+ : { disabled: false, invalidate: invalidationInputFromSync(input) }
164
+ );
165
+ },
166
+ };
167
+ },
168
+ })
169
+ .onBeforeHandle({ as: "global" }, beginMutation)
170
+ .onAfterHandle({ as: "global" }, async (ctx) => {
171
+ const active = activeMutations.get(ctx.request);
172
+ if (!active) {
173
+ return;
174
+ }
175
+ if (!isSuccessfulMutationResponse(ctx)) {
176
+ await abortMutation(ctx.request);
177
+ return;
178
+ }
179
+
180
+ const invalidate = routeMetadata.get(ctx.request)?.invalidate;
181
+ if (invalidate) {
182
+ runInvalidationRules(invalidate);
183
+ }
184
+ const pending = appendPendingInvalidationHeader(ctx.set);
185
+ if (pending.length > 0) {
186
+ ctx.set.headers["x-furin-sync"] = "1";
187
+ }
188
+ const response = await storeResponse(ctx.responseValue, ctx.set);
189
+ await memorySyncAdapter.commitMutation({ ...active, response });
190
+ activeMutations.delete(ctx.request);
191
+
192
+ if (pending.length > 0) {
193
+ await memorySyncAdapter.appendChanges({
194
+ invalidations: pending,
195
+ path: getSyncStreamPath() ?? "/_furin/sync",
196
+ });
197
+ }
198
+ })
199
+ .onError({ as: "global" }, ({ request }) => abortMutation(request));
200
+ }
@@ -0,0 +1,77 @@
1
+ import { type Context, ElysiaCustomStatusResponse, StatusMap } from "elysia";
2
+ import type { StoredResponse } from "./adapter.ts";
3
+
4
+ const HOP_BY_HOP_HEADERS = new Set(["connection", "keep-alive", "transfer-encoding", "upgrade"]);
5
+
6
+ function statusCode(status: Context["set"]["status"]): number {
7
+ if (typeof status === "number") {
8
+ return status;
9
+ }
10
+ return status === undefined ? 200 : StatusMap[status];
11
+ }
12
+
13
+ function unwrapStatusResponse(value: unknown): { status: number; value: unknown } | undefined {
14
+ if (!(value instanceof ElysiaCustomStatusResponse)) {
15
+ return;
16
+ }
17
+ return { status: value.code, value: value.response };
18
+ }
19
+
20
+ function responseHeaders(headers: Context["set"]["headers"]): Headers {
21
+ const result = new Headers();
22
+ for (const [name, value] of Object.entries(headers)) {
23
+ if (value !== undefined && !HOP_BY_HOP_HEADERS.has(name.toLowerCase())) {
24
+ for (const entry of Array.isArray(value) ? value : [value]) {
25
+ result.append(name, String(entry));
26
+ }
27
+ }
28
+ }
29
+ return result;
30
+ }
31
+
32
+ export async function storeResponse(
33
+ responseValue: unknown,
34
+ set: Context["set"]
35
+ ): Promise<StoredResponse> {
36
+ if (responseValue instanceof Response) {
37
+ const clone = responseValue.clone();
38
+ const headers = [...clone.headers.entries()].filter(
39
+ ([name]) => !HOP_BY_HOP_HEADERS.has(name.toLowerCase())
40
+ );
41
+ return {
42
+ body: new Uint8Array(await clone.arrayBuffer()),
43
+ headers,
44
+ status: clone.status,
45
+ };
46
+ }
47
+
48
+ const headers = responseHeaders(set.headers);
49
+ const statusResponse = unwrapStatusResponse(responseValue);
50
+ const value = statusResponse?.value ?? responseValue;
51
+ let body: Uint8Array;
52
+ if (value === undefined || value === null) {
53
+ body = new Uint8Array();
54
+ } else if (typeof value === "string") {
55
+ headers.set("content-type", headers.get("content-type") ?? "text/plain;charset=utf-8");
56
+ body = new TextEncoder().encode(value);
57
+ } else {
58
+ headers.set("content-type", headers.get("content-type") ?? "application/json");
59
+ body = new TextEncoder().encode(JSON.stringify(value));
60
+ }
61
+ return {
62
+ body,
63
+ headers: [...headers.entries()],
64
+ status: statusResponse?.status ?? statusCode(set.status),
65
+ };
66
+ }
67
+
68
+ export function replayResponse(stored: StoredResponse): Response {
69
+ const body =
70
+ stored.status === 204 || stored.status === 205 || stored.status === 304
71
+ ? null
72
+ : stored.body.slice();
73
+ return new Response(body, {
74
+ headers: new Headers(stored.headers.map(([name, value]) => [name, value] as [string, string])),
75
+ status: stored.status,
76
+ });
77
+ }