@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
@@ -0,0 +1,65 @@
1
+ export interface StoredResponse {
2
+ body: Uint8Array;
3
+ headers: ReadonlyArray<readonly [string, string]>;
4
+ status: number;
5
+ }
6
+
7
+ export interface BeginMutationInput {
8
+ fingerprint: string;
9
+ key: string;
10
+ principal: string;
11
+ }
12
+
13
+ export type BeginMutationResult =
14
+ | { kind: "execute"; mutationId: string }
15
+ | { kind: "replay"; response: StoredResponse }
16
+ | { kind: "conflict"; reason: "in-progress" | "payload-mismatch" }
17
+ | { kind: "unavailable" };
18
+
19
+ export interface CommitMutationInput {
20
+ mutationId: string;
21
+ response: StoredResponse;
22
+ }
23
+
24
+ export interface AbortMutationInput {
25
+ mutationId: string;
26
+ }
27
+
28
+ export interface SyncChange {
29
+ cursor: string;
30
+ invalidations: readonly string[];
31
+ }
32
+
33
+ export interface AppendChangesInput {
34
+ invalidations: readonly string[];
35
+ path: string;
36
+ }
37
+
38
+ export interface AppendChangesResult {
39
+ change: SyncChange;
40
+ }
41
+
42
+ export interface ReadChangesInput {
43
+ after: string | undefined;
44
+ limit: number;
45
+ path: string;
46
+ }
47
+
48
+ export interface ChangePage {
49
+ changes: readonly SyncChange[];
50
+ cursor: string;
51
+ hasMore: boolean;
52
+ reset: boolean;
53
+ }
54
+
55
+ export type SyncChangeListener = (change: SyncChange) => void;
56
+ type MaybePromise<T> = Promise<T> | T;
57
+
58
+ export interface SyncAdapter {
59
+ abortMutation(input: AbortMutationInput): MaybePromise<void>;
60
+ appendChanges(input: AppendChangesInput): MaybePromise<AppendChangesResult>;
61
+ beginMutation(input: BeginMutationInput): MaybePromise<BeginMutationResult>;
62
+ commitMutation(input: CommitMutationInput): MaybePromise<void>;
63
+ readChanges(input: ReadChangesInput): MaybePromise<ChangePage>;
64
+ subscribe(path: string, listener: SyncChangeListener): () => void;
65
+ }
@@ -1,29 +1,29 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
-
3
- const SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
4
-
5
- const requestSyncStreamPath = new AsyncLocalStorage<string | undefined>();
6
-
7
- export type FurinSyncOption =
8
- | boolean
9
- | {
10
- streamPath?: string;
11
- };
12
-
13
- export function resolveSyncStreamPath(sync: FurinSyncOption | undefined): string | undefined {
14
- if (!sync) {
15
- return;
16
- }
17
- if (sync === true) {
18
- return SYNC_STREAM_DEFAULT_PATH;
19
- }
20
- return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
21
- }
22
-
23
- export function getSyncStreamPath(): string | undefined {
24
- return requestSyncStreamPath.getStore();
25
- }
26
-
27
- export function runWithSyncStreamPath<T>(path: string | undefined, fn: () => T): T {
28
- return requestSyncStreamPath.run(path, fn);
29
- }
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ const SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
4
+
5
+ const requestSyncStreamPath = new AsyncLocalStorage<string | undefined>();
6
+
7
+ export type FurinSyncOption =
8
+ | boolean
9
+ | {
10
+ streamPath?: string;
11
+ };
12
+
13
+ export function resolveSyncStreamPath(sync: FurinSyncOption | undefined): string | undefined {
14
+ if (!sync) {
15
+ return;
16
+ }
17
+ if (sync === true) {
18
+ return SYNC_STREAM_DEFAULT_PATH;
19
+ }
20
+ return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
21
+ }
22
+
23
+ export function getSyncStreamPath(): string | undefined {
24
+ return requestSyncStreamPath.getStore();
25
+ }
26
+
27
+ export function runWithSyncStreamPath<T>(path: string | undefined, fn: () => T): T {
28
+ return requestSyncStreamPath.run(path, fn);
29
+ }
@@ -0,0 +1,44 @@
1
+ interface FingerprintInput {
2
+ body: unknown;
3
+ request: Request;
4
+ }
5
+
6
+ function compareCodePoints(left: string, right: string): number {
7
+ if (left === right) {
8
+ return 0;
9
+ }
10
+ return left < right ? -1 : 1;
11
+ }
12
+
13
+ function canonicalize(value: unknown): unknown {
14
+ if (Array.isArray(value)) {
15
+ return value.map(canonicalize);
16
+ }
17
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
18
+ return Object.fromEntries(
19
+ Object.entries(value)
20
+ .sort(([left], [right]) => compareCodePoints(left, right))
21
+ .map(([key, entry]) => [key, canonicalize(entry)])
22
+ );
23
+ }
24
+ return value;
25
+ }
26
+
27
+ export async function createMutationFingerprint(input: FingerprintInput): Promise<string> {
28
+ const url = new URL(input.request.url);
29
+ const query = [...url.searchParams.entries()].sort(
30
+ ([leftKey, leftValue], [rightKey, rightValue]) =>
31
+ leftKey === rightKey
32
+ ? compareCodePoints(leftValue, rightValue)
33
+ : compareCodePoints(leftKey, rightKey)
34
+ );
35
+ const source = JSON.stringify({
36
+ body: canonicalize(input.body) ?? null,
37
+ contentType: input.request.headers.get("content-type") ?? "",
38
+ method: input.request.method,
39
+ pathname: url.pathname,
40
+ query,
41
+ });
42
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(source));
43
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
44
+ }
@@ -1,14 +1,15 @@
1
- // biome-ignore-all lint/performance/noBarrelFile: sync has a small public/internal surface
2
- export type { FurinSyncOption } from "./config.ts";
3
- export {
4
- getSyncStreamPath,
5
- resolveSyncStreamPath,
6
- runWithSyncStreamPath,
7
- } from "./config.ts";
8
- export { furinSync, type SyncInput } from "./plugin.ts";
9
- export {
10
- __resetSyncState,
11
- createSyncStreamPlugin,
12
- publishSyncInvalidation,
13
- type SyncInvalidationEvent,
14
- } from "./stream.ts";
1
+ // biome-ignore-all lint/performance/noBarrelFile: sync has a small public/internal surface
2
+ export type { FurinSyncOption } from "./config.ts";
3
+ export {
4
+ getSyncStreamPath,
5
+ resolveSyncStreamPath,
6
+ runWithSyncStreamPath,
7
+ } from "./config.ts";
8
+ export { furinSync, type SyncInput, type SyncRouteOption } from "./plugin.ts";
9
+ export {
10
+ __resetSyncState,
11
+ createSyncStreamPlugin,
12
+ publishSyncInvalidation,
13
+ type SyncChange,
14
+ type SyncChangePage,
15
+ } from "./stream.ts";
@@ -0,0 +1,196 @@
1
+ import type {
2
+ AbortMutationInput,
3
+ AppendChangesInput,
4
+ AppendChangesResult,
5
+ BeginMutationInput,
6
+ BeginMutationResult,
7
+ ChangePage,
8
+ CommitMutationInput,
9
+ ReadChangesInput,
10
+ StoredResponse,
11
+ SyncAdapter,
12
+ SyncChange,
13
+ SyncChangeListener,
14
+ } from "./adapter.ts";
15
+
16
+ const MAX_CHANGES = 1000;
17
+ const MAX_MUTATIONS = 10_000;
18
+ const MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
19
+
20
+ interface PendingMutation {
21
+ createdAt: number;
22
+ fingerprint: string;
23
+ mutationId: string;
24
+ state: "in-progress";
25
+ }
26
+
27
+ interface CompletedMutation {
28
+ createdAt: number;
29
+ fingerprint: string;
30
+ mutationId: string;
31
+ response: StoredResponse;
32
+ state: "succeeded";
33
+ }
34
+
35
+ type MutationEntry = CompletedMutation | PendingMutation;
36
+
37
+ interface ChangeState {
38
+ changes: SyncChange[];
39
+ listeners: Set<SyncChangeListener>;
40
+ nextCursor: number;
41
+ }
42
+
43
+ export class MemorySyncAdapter implements SyncAdapter {
44
+ private readonly changes = new Map<string, ChangeState>();
45
+ private readonly mutationKeys = new Map<string, string>();
46
+ private readonly mutations = new Map<string, MutationEntry>();
47
+
48
+ beginMutation(input: BeginMutationInput): BeginMutationResult {
49
+ this.evictMutations();
50
+ const mutationKey = `${input.principal}:${input.key}`;
51
+ const existingId = this.mutationKeys.get(mutationKey);
52
+ const existing = existingId ? this.mutations.get(existingId) : undefined;
53
+ if (existing) {
54
+ if (existing.fingerprint !== input.fingerprint) {
55
+ return { kind: "conflict", reason: "payload-mismatch" };
56
+ }
57
+ if (existing.state === "in-progress") {
58
+ return { kind: "conflict", reason: "in-progress" };
59
+ }
60
+ return { kind: "replay", response: existing.response };
61
+ }
62
+ if (this.mutations.size >= MAX_MUTATIONS) {
63
+ return { kind: "unavailable" };
64
+ }
65
+
66
+ const mutationId = crypto.randomUUID();
67
+ this.mutationKeys.set(mutationKey, mutationId);
68
+ this.mutations.set(mutationId, {
69
+ createdAt: Date.now(),
70
+ fingerprint: input.fingerprint,
71
+ mutationId,
72
+ state: "in-progress",
73
+ });
74
+ return { kind: "execute", mutationId };
75
+ }
76
+
77
+ commitMutation(input: CommitMutationInput): void {
78
+ const existing = this.mutations.get(input.mutationId);
79
+ if (!existing) {
80
+ return;
81
+ }
82
+ this.mutations.set(input.mutationId, {
83
+ ...existing,
84
+ response: input.response,
85
+ state: "succeeded",
86
+ });
87
+ }
88
+
89
+ abortMutation(input: AbortMutationInput): void {
90
+ const existing = this.mutations.get(input.mutationId);
91
+ if (!existing) {
92
+ return;
93
+ }
94
+ this.mutations.delete(input.mutationId);
95
+ for (const [key, mutationId] of this.mutationKeys) {
96
+ if (mutationId === input.mutationId) {
97
+ this.mutationKeys.delete(key);
98
+ break;
99
+ }
100
+ }
101
+ }
102
+
103
+ appendChanges(input: AppendChangesInput): AppendChangesResult {
104
+ const state = this.getChangeState(input.path);
105
+ const change: SyncChange = {
106
+ cursor: String(state.nextCursor),
107
+ invalidations: [...input.invalidations],
108
+ };
109
+ state.nextCursor += 1;
110
+ state.changes.push(change);
111
+ if (state.changes.length > MAX_CHANGES) {
112
+ state.changes.shift();
113
+ }
114
+ for (const listener of [...state.listeners]) {
115
+ listener(change);
116
+ }
117
+ return { change };
118
+ }
119
+
120
+ readChanges(input: ReadChangesInput): ChangePage {
121
+ const state = this.getChangeState(input.path);
122
+ const currentCursor = String(state.nextCursor - 1);
123
+ if (input.after === undefined) {
124
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
125
+ }
126
+
127
+ const after = Number.parseInt(input.after, 10);
128
+ const oldest = Number.parseInt(state.changes[0]?.cursor ?? currentCursor, 10);
129
+ if (after < oldest - 1) {
130
+ return {
131
+ changes: [{ cursor: currentCursor, invalidations: ["/:layout"] }],
132
+ cursor: currentCursor,
133
+ hasMore: false,
134
+ reset: true,
135
+ };
136
+ }
137
+ const available = state.changes.filter((change) => Number.parseInt(change.cursor, 10) > after);
138
+ const changes = available.slice(0, input.limit);
139
+ return {
140
+ changes,
141
+ cursor: changes.at(-1)?.cursor ?? input.after,
142
+ hasMore: available.length > changes.length,
143
+ reset: false,
144
+ };
145
+ }
146
+
147
+ subscribe(path: string, listener: SyncChangeListener): () => void {
148
+ const listeners = this.getChangeState(path).listeners;
149
+ listeners.add(listener);
150
+ return () => listeners.delete(listener);
151
+ }
152
+
153
+ reset(): void {
154
+ this.changes.clear();
155
+ this.mutationKeys.clear();
156
+ this.mutations.clear();
157
+ }
158
+
159
+ private evictMutations(): void {
160
+ const expiredBefore = Date.now() - MUTATION_TTL_MS;
161
+ for (const [mutationId, mutation] of this.mutations) {
162
+ if (mutation.createdAt < expiredBefore) {
163
+ this.deleteMutation(mutationId);
164
+ }
165
+ }
166
+ while (this.mutations.size >= MAX_MUTATIONS) {
167
+ const oldest = [...this.mutations.values()].find((entry) => entry.state === "succeeded");
168
+ if (!oldest) {
169
+ break;
170
+ }
171
+ this.deleteMutation(oldest.mutationId);
172
+ }
173
+ }
174
+
175
+ private deleteMutation(mutationId: string): void {
176
+ this.mutations.delete(mutationId);
177
+ for (const [key, storedId] of this.mutationKeys) {
178
+ if (storedId === mutationId) {
179
+ this.mutationKeys.delete(key);
180
+ return;
181
+ }
182
+ }
183
+ }
184
+
185
+ private getChangeState(path: string): ChangeState {
186
+ const existing = this.changes.get(path);
187
+ if (existing) {
188
+ return existing;
189
+ }
190
+ const state: ChangeState = { changes: [], listeners: new Set(), nextCursor: 1 };
191
+ this.changes.set(path, state);
192
+ return state;
193
+ }
194
+ }
195
+
196
+ export const memorySyncAdapter = new MemorySyncAdapter();