@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,36 +1,36 @@
1
- import { writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { buildEntrySource, type BuildEntryOptions } from "./entry-template";
4
- import { ensureDir } from "./shared";
5
-
6
- /**
7
- * Generates `server.ts` — an intermediate entry used to produce `server.js`.
8
- *
9
- * Equivalent to `_compile-entry.ts` but for disk (non-binary) production builds:
10
- * 1. Statically imports every page module so Bun bundles them into server.js
11
- * 2. Sets production mode and registers everything in a single CompileContext
12
- * 3. Imports server.ts to boot the app
13
- *
14
- * This file is intermediate: `adapter/bun.ts` runs `Bun.build()` on it to produce
15
- * the self-contained `server.js` bundle, then deletes this file.
16
- */
17
- export function generateServerRoutesEntry(options: BuildEntryOptions): string {
18
- const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata, ssgCache } =
19
- options;
20
- ensureDir(outDir);
21
- const source = buildEntrySource({
22
- buildId,
23
- headerComment: "// Auto-generated by furin build — do not edit",
24
- rootPath,
25
- routes,
26
- serverEntry,
27
- rootConventions,
28
- routeMetadata,
29
- ssgCache,
30
- });
31
-
32
- // Named "server.ts" so Bun.build() outputs "server.js"
33
- const entryPath = join(outDir, "server.ts");
34
- writeFileSync(entryPath, source);
35
- return entryPath;
36
- }
1
+ import { writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { buildEntrySource, type BuildEntryOptions } from "./entry-template";
4
+ import { ensureDir } from "./shared";
5
+
6
+ /**
7
+ * Generates `server.ts` — an intermediate entry used to produce `server.js`.
8
+ *
9
+ * Equivalent to `_compile-entry.ts` but for disk (non-binary) production builds:
10
+ * 1. Statically imports every page module so Bun bundles them into server.js
11
+ * 2. Sets production mode and registers everything in a single CompileContext
12
+ * 3. Imports server.ts to boot the app
13
+ *
14
+ * This file is intermediate: `adapter/bun.ts` runs `Bun.build()` on it to produce
15
+ * the self-contained `server.js` bundle, then deletes this file.
16
+ */
17
+ export function generateServerRoutesEntry(options: BuildEntryOptions): string {
18
+ const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata, ssgCache } =
19
+ options;
20
+ ensureDir(outDir);
21
+ const source = buildEntrySource({
22
+ buildId,
23
+ headerComment: "// Auto-generated by furin build — do not edit",
24
+ rootPath,
25
+ routes,
26
+ serverEntry,
27
+ rootConventions,
28
+ routeMetadata,
29
+ ssgCache,
30
+ });
31
+
32
+ // Named "server.ts" so Bun.build() outputs "server.js"
33
+ const entryPath = join(outDir, "server.ts");
34
+ writeFileSync(entryPath, source);
35
+ return entryPath;
36
+ }
package/dist/cli/index.js CHANGED
File without changes
@@ -3278,6 +3278,11 @@ async function parseDeferredNdjson(stream, signal) {
3278
3278
  });
3279
3279
  }
3280
3280
  }
3281
+ for (const promise of Object.values(deferredPromises)) {
3282
+ promise.catch(() => {
3283
+ return;
3284
+ });
3285
+ }
3281
3286
  if (deferredKeys.length === 0) {
3282
3287
  cleanupAbortHandler();
3283
3288
  try {
@@ -3345,6 +3350,11 @@ async function readDeferredLines(readLine, resolvers) {
3345
3350
  }
3346
3351
  }
3347
3352
 
3353
+ // src/client/router/abort.ts
3354
+ function isAbortError(error) {
3355
+ return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
3356
+ }
3357
+
3348
3358
  // src/client/router/search-store.ts
3349
3359
  import { createContext as createContext2 } from "react";
3350
3360
  function searchSnapshotChanged(a, b) {
@@ -3473,6 +3483,78 @@ function detectStaticMode() {
3473
3483
  return meta?.content === "static";
3474
3484
  }
3475
3485
 
3486
+ // src/client/router/sync-catch-up.ts
3487
+ function createInvalidationRefresh(options) {
3488
+ let running;
3489
+ let requested = false;
3490
+ const refreshUntilCurrent = async () => {
3491
+ do {
3492
+ requested = false;
3493
+ try {
3494
+ await options.refresh();
3495
+ } catch (error) {
3496
+ if (!isAbortError(error)) {
3497
+ throw error;
3498
+ }
3499
+ }
3500
+ } while (requested);
3501
+ };
3502
+ return {
3503
+ run() {
3504
+ requested = true;
3505
+ if (!running) {
3506
+ running = refreshUntilCurrent().catch((error) => {
3507
+ if (!isAbortError(error)) {
3508
+ options.onError(error);
3509
+ }
3510
+ }).finally(() => {
3511
+ running = undefined;
3512
+ });
3513
+ }
3514
+ return running;
3515
+ }
3516
+ };
3517
+ }
3518
+ function createSyncCatchUp(options) {
3519
+ let currentCursor;
3520
+ let running;
3521
+ let requested = false;
3522
+ const readUntilCurrent = async () => {
3523
+ do {
3524
+ requested = false;
3525
+ let page;
3526
+ do {
3527
+ page = await options.fetchPage(currentCursor ?? "0");
3528
+ if (page.reset) {
3529
+ options.onInvalidations(["/:layout"]);
3530
+ currentCursor = page.cursor;
3531
+ break;
3532
+ }
3533
+ for (const change of page.changes) {
3534
+ options.onInvalidations(change.invalidations);
3535
+ }
3536
+ currentCursor = page.cursor;
3537
+ } while (page.hasMore);
3538
+ } while (requested);
3539
+ };
3540
+ return {
3541
+ async initialize() {
3542
+ const page = await options.fetchPage(undefined);
3543
+ currentCursor = page.cursor;
3544
+ },
3545
+ catchUp() {
3546
+ requested = true;
3547
+ if (!running) {
3548
+ running = readUntilCurrent().finally(() => {
3549
+ running = undefined;
3550
+ });
3551
+ }
3552
+ return running;
3553
+ },
3554
+ cursor: () => currentCursor
3555
+ };
3556
+ }
3557
+
3476
3558
  // src/client/router/provider.tsx
3477
3559
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
3478
3560
  var EMPTY_SEARCH = {};
@@ -3627,7 +3709,13 @@ function RouterProvider({
3627
3709
  }
3628
3710
  return { match: loadedMatch, data, title, finalHref };
3629
3711
  } catch (err) {
3630
- _log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
3712
+ if (!isAbortError(err)) {
3713
+ _log.error({
3714
+ action: "navigate_failed",
3715
+ href: basePath + logicalHref,
3716
+ error: String(err)
3717
+ });
3718
+ }
3631
3719
  return null;
3632
3720
  }
3633
3721
  }, [routes, basePath, resolveNoMatchState]);
@@ -3773,6 +3861,12 @@ function RouterProvider({
3773
3861
  invalidatePrefetch(logicalHref, "page");
3774
3862
  await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
3775
3863
  }, [navigate, invalidatePrefetch, basePath]);
3864
+ const invalidationRefresh = useMemo(() => createInvalidationRefresh({
3865
+ onError: (error) => {
3866
+ _log.warn({ action: "sync_refresh_failed", error: String(error) });
3867
+ },
3868
+ refresh: () => refresh(undefined)
3869
+ }), [refresh]);
3776
3870
  useEffect(() => {
3777
3871
  if (typeof window !== "undefined") {
3778
3872
  window.__FURIN_HMR_REFRESH__ = refresh;
@@ -3927,7 +4021,7 @@ function RouterProvider({
3927
4021
  if (autoRefresh && invalidated.length > 0) {
3928
4022
  const currentLogicalPath = normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
3929
4023
  if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
3930
- refresh(undefined);
4024
+ invalidationRefresh.run();
3931
4025
  }
3932
4026
  }
3933
4027
  return response;
@@ -3937,23 +4031,20 @@ function RouterProvider({
3937
4031
  return () => {
3938
4032
  window.fetch = originalFetch;
3939
4033
  };
3940
- }, [invalidatePrefetch, refresh, autoRefresh, basePath]);
4034
+ }, [invalidatePrefetch, invalidationRefresh, autoRefresh, basePath]);
3941
4035
  useEffect(() => {
3942
4036
  if (!syncStream || typeof window === "undefined" || typeof EventSource === "undefined") {
3943
4037
  return;
3944
4038
  }
3945
4039
  const streamUrl = syncStream.startsWith("/") ? `${basePath}${syncStream}` : `${basePath}/${syncStream}`;
3946
- const source = new EventSource(streamUrl);
3947
- const onInvalidate = (event) => {
3948
- let payload;
3949
- try {
3950
- payload = JSON.parse(event.data);
3951
- } catch {
3952
- _log.warn({ action: "sync_invalid_event", event: "furin.invalidate" });
4040
+ let source;
4041
+ let disposed = false;
4042
+ const applyInvalidations = (entries) => {
4043
+ if (disposed) {
3953
4044
  return;
3954
4045
  }
3955
4046
  const invalidations = [];
3956
- applyRevalidateEntries(payload.invalidations ?? [], (path, type) => {
4047
+ applyRevalidateEntries(entries, (path, type) => {
3957
4048
  const resolvedType = type ?? "page";
3958
4049
  invalidatePrefetch(path, resolvedType);
3959
4050
  invalidations.push({ path, type: resolvedType });
@@ -3961,16 +4052,72 @@ function RouterProvider({
3961
4052
  if (autoRefresh && invalidations.length > 0) {
3962
4053
  const currentLogicalPath = normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
3963
4054
  if (shouldAutoRefreshPath(currentLogicalPath, invalidations)) {
3964
- refresh(undefined);
4055
+ invalidationRefresh.run();
4056
+ }
4057
+ }
4058
+ };
4059
+ const catchUp = createSyncCatchUp({
4060
+ fetchPage: async (after) => {
4061
+ const url = new URL(`${streamUrl}/changes`, window.location.origin);
4062
+ if (after !== undefined) {
4063
+ url.searchParams.set("after", after);
3965
4064
  }
4065
+ const response = await window.fetch(url);
4066
+ if (!response.ok) {
4067
+ throw new Error(`Sync catch-up failed with status ${response.status}`);
4068
+ }
4069
+ return await response.json();
4070
+ },
4071
+ onInvalidations: applyInvalidations
4072
+ });
4073
+ const recover = () => {
4074
+ if (disposed) {
4075
+ return;
3966
4076
  }
4077
+ catchUp.catchUp().catch((error) => {
4078
+ if (!disposed) {
4079
+ _log.warn({ action: "sync_catch_up_failed", error: String(error) });
4080
+ }
4081
+ });
3967
4082
  };
3968
- source.addEventListener("furin.invalidate", onInvalidate);
4083
+ const onSync = (event) => {
4084
+ try {
4085
+ const payload = JSON.parse(event.data);
4086
+ if (typeof payload.cursor !== "string") {
4087
+ throw new Error("Missing sync cursor");
4088
+ }
4089
+ } catch {
4090
+ _log.warn({ action: "sync_invalid_event", event: "furin.sync" });
4091
+ return;
4092
+ }
4093
+ recover();
4094
+ };
4095
+ const connect = () => {
4096
+ if (disposed || source) {
4097
+ return;
4098
+ }
4099
+ source = new EventSource(streamUrl);
4100
+ source.addEventListener("furin.sync", onSync);
4101
+ };
4102
+ catchUp.initialize().then(() => {
4103
+ if (disposed) {
4104
+ return;
4105
+ }
4106
+ connect();
4107
+ recover();
4108
+ }).catch((error) => {
4109
+ if (disposed) {
4110
+ return;
4111
+ }
4112
+ _log.warn({ action: "sync_initialize_failed", error: String(error) });
4113
+ connect();
4114
+ });
3969
4115
  return () => {
3970
- source.removeEventListener("furin.invalidate", onInvalidate);
3971
- source.close();
4116
+ disposed = true;
4117
+ source?.removeEventListener("furin.sync", onSync);
4118
+ source?.close();
3972
4119
  };
3973
- }, [syncStream, basePath, invalidatePrefetch, refresh, autoRefresh]);
4120
+ }, [syncStream, basePath, invalidatePrefetch, invalidationRefresh, autoRefresh]);
3974
4121
  let pageElement;
3975
4122
  if (state.notFound || !state.match) {
3976
4123
  pageElement = buildNotFoundPageElement(state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries, state.notFound ?? {});
@@ -0,0 +1 @@
1
+ export declare function isAbortError(error: unknown): boolean;
@@ -0,0 +1,29 @@
1
+ export interface SyncChangePayload {
2
+ cursor: string;
3
+ invalidations: readonly string[];
4
+ }
5
+ export interface SyncChangePagePayload {
6
+ changes: readonly SyncChangePayload[];
7
+ cursor: string;
8
+ hasMore: boolean;
9
+ reset: boolean;
10
+ }
11
+ interface SyncCatchUpOptions {
12
+ fetchPage: (after: string | undefined) => Promise<SyncChangePagePayload>;
13
+ onInvalidations: (invalidations: readonly string[]) => void;
14
+ }
15
+ export interface SyncCatchUp {
16
+ catchUp(): Promise<void>;
17
+ cursor(): string | undefined;
18
+ initialize(): Promise<void>;
19
+ }
20
+ interface InvalidationRefreshOptions {
21
+ onError: (error: unknown) => void;
22
+ refresh: () => Promise<void>;
23
+ }
24
+ export interface InvalidationRefresh {
25
+ run(): Promise<void>;
26
+ }
27
+ export declare function createInvalidationRefresh(options: InvalidationRefreshOptions): InvalidationRefresh;
28
+ export declare function createSyncCatchUp(options: SyncCatchUpOptions): SyncCatchUp;
29
+ export {};
package/dist/furin.d.ts CHANGED
@@ -70,7 +70,7 @@ export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.t
70
70
  export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
71
71
  export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
72
72
  export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
73
- export { furinSync, type SyncInput } from "./server/sync/index.ts";
73
+ export { furinSync, type SyncInput, type SyncRouteOption } from "./server/sync/index.ts";
74
74
  export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
75
75
  export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
76
76
  export type { NotFoundComponent, NotFoundOptions, NotFoundProps, } from "./shared/not-found.ts";