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

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 (84) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/compile-entry.ts +109 -109
  5. package/dist/build/entry-template.ts +156 -156
  6. package/dist/build/index.js +1724 -687
  7. package/dist/build/route-types.d.ts +3 -1
  8. package/dist/build/server-routes-entry.ts +36 -36
  9. package/dist/build/shared.d.ts +1 -0
  10. package/dist/build/ssg-cache.d.ts +1 -1
  11. package/dist/cli/index.js +1673 -658
  12. package/dist/client/link.js +883 -89
  13. package/dist/client/router/index.d.ts +4 -0
  14. package/dist/client/router/link-utils.d.ts +3 -1
  15. package/dist/client/router/navigation.d.ts +10 -0
  16. package/dist/client/router/provider.d.ts +1 -1
  17. package/dist/client/router/search/index.d.ts +18 -0
  18. package/dist/client/router/search-store.d.ts +21 -0
  19. package/dist/client/router/types.d.ts +14 -1
  20. package/dist/client/sync.d.ts +25 -0
  21. package/dist/client.d.ts +1 -0
  22. package/dist/client.js +44 -0
  23. package/dist/furin.d.ts +9 -1
  24. package/dist/furin.js +1578 -258
  25. package/dist/server/auto-invalidate/runtime.d.ts +1 -1
  26. package/dist/server/dev-page-plugin.d.ts +3 -0
  27. package/dist/server/render/assemble.d.ts +2 -0
  28. package/dist/server/render/isr.d.ts +2 -1
  29. package/dist/server/render/ssg.d.ts +3 -2
  30. package/dist/server/render/ssr.d.ts +5 -4
  31. package/dist/server/router/hmr.d.ts +4 -3
  32. package/dist/server/router/index.d.ts +1 -1
  33. package/dist/server/router/index.js +1 -2
  34. package/dist/server/router/index.ts +1 -2
  35. package/dist/server/router/plugin.d.ts +2 -1
  36. package/dist/server/router/schemas.d.ts +25 -17
  37. package/dist/server/sync/config.d.ts +6 -0
  38. package/dist/server/sync/index.d.ts +4 -0
  39. package/dist/server/sync/plugin.d.ts +369 -0
  40. package/dist/server/sync/stream.d.ts +47 -0
  41. package/dist/shared/search-params.d.ts +17 -0
  42. package/package.json +10 -5
  43. package/src/adapter/README.md +13 -13
  44. package/src/adapter/static.ts +23 -6
  45. package/src/build/client.ts +152 -149
  46. package/src/build/compile-entry.ts +109 -109
  47. package/src/build/entry-template.ts +156 -156
  48. package/src/build/hydrate.ts +340 -331
  49. package/src/build/index.ts +152 -152
  50. package/src/build/route-types.ts +145 -115
  51. package/src/build/scan-server.ts +95 -95
  52. package/src/build/server-routes-entry.ts +36 -36
  53. package/src/build/shared.ts +80 -78
  54. package/src/build/ssg-cache.ts +32 -31
  55. package/src/build/types.ts +89 -89
  56. package/src/client/link.tsx +13 -4
  57. package/src/client/router/context.ts +2 -0
  58. package/src/client/router/index.ts +9 -0
  59. package/src/client/router/link-utils.ts +184 -180
  60. package/src/client/router/navigation.ts +61 -0
  61. package/src/client/router/provider.tsx +804 -723
  62. package/src/client/router/search/index.ts +99 -0
  63. package/src/client/router/search-store.ts +86 -0
  64. package/src/client/router/types.ts +276 -263
  65. package/src/client/sync.ts +98 -0
  66. package/src/client.ts +369 -355
  67. package/src/furin.ts +465 -437
  68. package/src/server/auto-invalidate/runtime.ts +134 -133
  69. package/src/server/dev-page-plugin.ts +454 -449
  70. package/src/server/render/assemble.ts +160 -133
  71. package/src/server/render/isr.ts +323 -295
  72. package/src/server/render/not-found.ts +2 -0
  73. package/src/server/render/ssg.ts +15 -4
  74. package/src/server/render/ssr.ts +585 -545
  75. package/src/server/router/hmr.ts +14 -10
  76. package/src/server/router/index.ts +1 -2
  77. package/src/server/router/patterns.ts +5 -0
  78. package/src/server/router/plugin.ts +384 -401
  79. package/src/server/router/schemas.ts +172 -57
  80. package/src/server/sync/config.ts +29 -0
  81. package/src/server/sync/index.ts +14 -0
  82. package/src/server/sync/plugin.ts +108 -0
  83. package/src/server/sync/stream.ts +144 -0
  84. package/src/shared/search-params.ts +182 -0
@@ -2,6 +2,10 @@ export { buildPageElement, buildRouterTree } from "./boundary-tree.tsx";
2
2
  export { CLIENT_FALLBACK_ROUTER, RouterContext, useRouter } from "./context.ts";
3
3
  export { generateHistoryKey, getHistoryKey, isStaleDeployResponse, SCROLL_STORAGE_KEY, saveScrollPosition, } from "./history.ts";
4
4
  export { applyRevalidateHeader, buildHref, normalizeHref, normalizePath, shouldAutoRefreshPath, shouldInterceptClick, shouldRefetch, stripHashFromHref, TRAILING_SLASHES_RE, toLogical, } from "./link-utils.ts";
5
+ export type { Navigate, NavigateInput } from "./navigation.ts";
6
+ export { useNavigate } from "./navigation.ts";
5
7
  export { RouterProvider } from "./provider.tsx";
8
+ export type { SearchStore, SearchStoreSnapshot } from "./search-store.ts";
9
+ export { createSearchStore, FALLBACK_SEARCH_STORE, SearchStoreContext, searchSnapshotFromRouterContext, } from "./search-store.ts";
6
10
  export { buildDataEndpoint, buildNotFoundPageElement, classifySpaResponse, detectStaticMode, parsePageResponse, pickDeepestNotFound, } from "./spa-response.ts";
7
11
  export type { CacheEntry, ClientRoute, ClientSegmentBoundary, LinkProps, LoadedClientRoute, PreloadStrategy, RootBoundaryOptions, RouteManifest, RouterContextValue, RouterProviderProps, RouterState, RouteSearch, RouteTo, SpaResponseKind, } from "./types.ts";
@@ -1,3 +1,4 @@
1
+ import { type SearchParamsInput } from "../../shared/search-params.ts";
1
2
  import type { CacheEntry } from "./types.ts";
2
3
  /** Strips one or more trailing slashes — used by `buildDataEndpoint` in static mode. */
3
4
  export declare const TRAILING_SLASHES_RE: RegExp;
@@ -7,12 +8,13 @@ export declare const TRAILING_SLASHES_RE: RegExp;
7
8
  *
8
9
  * @internal Exported for unit testing only.
9
10
  */
10
- export declare function buildHref(to: string, search: Record<string, unknown> | null | undefined, hash: string | undefined): string;
11
+ export declare function buildHref(to: string, search: SearchParamsInput | null | undefined, hash: string | undefined, searchDefaults?: SearchParamsInput): string;
11
12
  /**
12
13
  * Parses the `X-Furin-Revalidate` response header and calls `invalidate` for
13
14
  * each path entry. Header format: `"/path1,/path2:layout,/path3"`
14
15
  */
15
16
  export declare function applyRevalidateHeader(headers: Headers, invalidate: (path: string, type: "page" | "layout" | undefined) => void): void;
17
+ export declare function applyRevalidateEntries(entries: Iterable<string>, invalidate: (path: string, type: "page" | "layout" | undefined) => void): void;
16
18
  /**
17
19
  * Returns `true` when `currentPath` is targeted by at least one invalidation entry.
18
20
  *
@@ -0,0 +1,10 @@
1
+ import type { RouteSearch, RouteTo } from "./types.ts";
2
+ export interface NavigateInput<To extends RouteTo> {
3
+ hash?: string;
4
+ replace?: boolean;
5
+ resetScroll?: boolean;
6
+ search?: RouteSearch<To>;
7
+ to: To;
8
+ }
9
+ export type Navigate = <To extends RouteTo>(next: NavigateInput<To>) => Promise<void>;
10
+ export declare function useNavigate(): Navigate;
@@ -1,4 +1,4 @@
1
1
  import type React from "react";
2
2
  import type { CacheEntry, RouterProviderProps } from "./types.ts";
3
3
  export declare function setPrefetchCacheEntry(cache: Map<string, CacheEntry>, href: string, entry: CacheEntry, maxSize: number): void;
4
- export declare function RouterProvider({ routes, root, initialMatch, initialData, initialDigest, initialNotFound, autoRefresh, basePath, defaultPreload, defaultPreloadDelay, defaultPreloadStaleTime, prefetchCacheSize, }: RouterProviderProps): React.ReactElement;
4
+ export declare function RouterProvider({ routes, root, initialMatch, initialData, initialDigest, initialNotFound, autoRefresh, basePath, defaultPreload, defaultPreloadDelay, defaultPreloadStaleTime, prefetchCacheSize, syncStream, }: RouterProviderProps): React.ReactElement;
@@ -0,0 +1,18 @@
1
+ import type { RouteManifest as LinkRouteManifest, RouteSearch, RouteTo } from "@teyik0/furin/link";
2
+ export interface RouteManifest extends LinkRouteManifest {
3
+ }
4
+ export type SearchRouteTo = keyof LinkRouteManifest extends never ? RouteTo : (string & {}) | keyof LinkRouteManifest;
5
+ type SearchRouteSearch<To extends SearchRouteTo> = keyof LinkRouteManifest extends never ? RouteSearch<To & RouteTo> : To extends keyof LinkRouteManifest ? LinkRouteManifest[To] extends {
6
+ search?: infer S;
7
+ } ? S : undefined : undefined;
8
+ export type EmptyRouteSearch = Record<PropertyKey, never>;
9
+ export type ResolvedRouteSearch<To extends SearchRouteTo> = SearchRouteSearch<To> extends never | undefined ? EmptyRouteSearch : NonNullable<SearchRouteSearch<To>>;
10
+ export type SetSearchInput<To extends SearchRouteTo> = Partial<ResolvedRouteSearch<To>> | ((prev: ResolvedRouteSearch<To>) => Partial<ResolvedRouteSearch<To>>);
11
+ export interface SetSearchOptions {
12
+ replace?: boolean;
13
+ resetScroll?: boolean;
14
+ }
15
+ export type SetSearch<To extends SearchRouteTo> = (next: SetSearchInput<To>, opts?: SetSearchOptions) => Promise<void>;
16
+ export declare function useSearch<To extends SearchRouteTo>(_from: To): [ResolvedRouteSearch<To>, SetSearch<To>];
17
+ export declare function useSearch<To extends SearchRouteTo, TSelected>(_from: To, selector: (search: ResolvedRouteSearch<To>) => TSelected): [TSelected, SetSearch<To>];
18
+ export {};
@@ -0,0 +1,21 @@
1
+ import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
2
+ import type { RouterContextValue } from "./types.ts";
3
+ export interface SearchStoreSnapshot {
4
+ currentHref: string;
5
+ navigate: RouterContextValue["navigate"];
6
+ search: SearchParamsInput;
7
+ searchRoutes: SearchRouteMetadata[];
8
+ }
9
+ type SearchStoreListener = () => void;
10
+ export interface SearchStore {
11
+ flush: () => void;
12
+ getServerSnapshot: () => SearchStoreSnapshot;
13
+ getSnapshot: () => SearchStoreSnapshot;
14
+ setSnapshot: (next: SearchStoreSnapshot) => void;
15
+ subscribe: (listener: SearchStoreListener) => () => void;
16
+ }
17
+ export declare function createSearchStore(initialSnapshot: SearchStoreSnapshot): SearchStore;
18
+ export declare function searchSnapshotFromRouterContext(context: RouterContextValue): SearchStoreSnapshot;
19
+ export declare const FALLBACK_SEARCH_STORE: SearchStore;
20
+ export declare const SearchStoreContext: import("react").Context<SearchStore | null>;
21
+ export {};
@@ -2,6 +2,7 @@ import type React from "react";
2
2
  import type { RuntimeRoute } from "../../client.ts";
3
3
  import type { ErrorComponent } from "../../shared/error.ts";
4
4
  import type { NotFoundComponent } from "../../shared/not-found.ts";
5
+ import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
5
6
  /**
6
7
  * Augment this interface via declaration merging in furin-env.d.ts
7
8
  * to get type-safe `to` autocompletion and per-route `search` types on <Link>.
@@ -29,7 +30,9 @@ export type RouteTo = keyof RouteManifest extends never ? string : (string & {})
29
30
  * The typed search params for a given `to` pathname.
30
31
  * Falls back to a permissive record when RouteManifest is not augmented.
31
32
  */
32
- export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never ? Record<string, string | number | boolean | null | undefined> : To extends keyof RouteManifest ? RouteManifest[To] extends {
33
+ export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never ? SearchParamsInput : To extends keyof RouteManifest ? RouteManifest[To] extends {
34
+ searchInput?: infer I;
35
+ } ? I : RouteManifest[To] extends {
33
36
  search?: infer S;
34
37
  } ? S : undefined : undefined;
35
38
  export type PreloadStrategy = false | "intent" | "viewport" | "render";
@@ -113,6 +116,10 @@ export interface RouterContextValue {
113
116
  refresh: (opts?: {
114
117
  resetScroll?: boolean;
115
118
  }) => Promise<void>;
119
+ /** Current server-resolved query params for the rendered route. */
120
+ search: SearchParamsInput;
121
+ /** Route-level search defaults used to build clean hrefs without default params. */
122
+ searchRoutes: SearchRouteMetadata[];
116
123
  }
117
124
  /**
118
125
  * Client-side mirror of `SegmentBoundary` from router.ts. Unlike the server
@@ -136,6 +143,7 @@ export interface ClientRoute {
136
143
  pageRoute?: RuntimeRoute;
137
144
  pattern: string;
138
145
  regex: RegExp;
146
+ searchDefaults?: SearchParamsInput;
139
147
  /**
140
148
  * Per-segment boundary chain, ordered shallow→deep. Each `depth` maps 1:1
141
149
  * to the route-chain index used on the server side, so `buildPageElement`
@@ -197,6 +205,11 @@ export interface RouterProviderProps {
197
205
  prefetchCacheSize: number;
198
206
  root: RuntimeRoute | null;
199
207
  routes: ClientRoute[];
208
+ /**
209
+ * Optional internal SSE endpoint emitted by `furin({ sync: true })`.
210
+ * When present, RouterProvider listens for cross-client invalidations.
211
+ */
212
+ syncStream?: string | undefined;
200
213
  }
201
214
  /** @internal Router state held inside RouterProvider. Exported so CacheEntry can reference it. */
202
215
  export interface RouterState {
@@ -0,0 +1,25 @@
1
+ export interface SyncMutationHeaders {
2
+ "Idempotency-Key": string;
3
+ }
4
+ export interface SyncMutationOptions {
5
+ headers: SyncMutationHeaders;
6
+ }
7
+ export interface SyncMutationContext<TInput> {
8
+ idempotencyKey: string;
9
+ input: TInput;
10
+ }
11
+ export interface SyncMutationSuccessContext<TInput, TResult> extends SyncMutationContext<TInput> {
12
+ result: TResult;
13
+ }
14
+ export interface SyncMutationErrorContext<TInput, TResult> extends SyncMutationContext<TInput> {
15
+ error: unknown;
16
+ result?: TResult;
17
+ }
18
+ export interface UseSyncOptions<TInput, TResult> {
19
+ onError?: (ctx: SyncMutationErrorContext<TInput, TResult>) => Promise<void> | void;
20
+ onSuccess?: (ctx: SyncMutationSuccessContext<TInput, TResult>) => Promise<void> | void;
21
+ optimistic?: (ctx: SyncMutationContext<TInput>) => (() => void) | undefined;
22
+ }
23
+ export type SyncMutation<TInput, TResult> = (input: TInput, options: SyncMutationOptions) => Promise<TResult>;
24
+ export type SyncMutationRunner<TInput, TResult> = undefined extends TInput ? (input?: TInput) => Promise<TResult> : (input: TInput) => Promise<TResult>;
25
+ export declare function useSync<TInput, TResult>(mutation: SyncMutation<TInput, TResult>, options?: UseSyncOptions<TInput, TResult>): SyncMutationRunner<TInput, TResult>;
package/dist/client.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { Cookie, StatusMap } from "elysia";
2
2
  import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
3
3
  import type { RequestLogger } from "evlog";
4
+ export { type SyncMutation, type SyncMutationContext, type SyncMutationErrorContext, type SyncMutationHeaders, type SyncMutationOptions, type SyncMutationRunner, type SyncMutationSuccessContext, type UseSyncOptions, useSync, } from "./client/sync.ts";
4
5
  export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
5
6
  declare const UNSET: unique symbol;
6
7
  type Unset = typeof UNSET;
package/dist/client.js CHANGED
@@ -1,4 +1,47 @@
1
1
  // @bun
2
+ // src/client/sync.ts
3
+ import { useCallback } from "react";
4
+ function createIdempotencyKey() {
5
+ if (typeof globalThis.crypto?.randomUUID === "function") {
6
+ return globalThis.crypto.randomUUID();
7
+ }
8
+ return `${Date.now()}-${Math.random()}`;
9
+ }
10
+ function getResolvedError(result) {
11
+ if (!(typeof result === "object" && result !== null && ("error" in result))) {
12
+ return;
13
+ }
14
+ const error = result.error;
15
+ return error == null ? undefined : error;
16
+ }
17
+ function useSync(mutation, options) {
18
+ const optimistic = options?.optimistic;
19
+ const onError = options?.onError;
20
+ const onSuccess = options?.onSuccess;
21
+ const run = useCallback(async (input) => {
22
+ const idempotencyKey = createIdempotencyKey();
23
+ const rollback = optimistic?.({ idempotencyKey, input });
24
+ let result;
25
+ try {
26
+ result = await mutation(input, {
27
+ headers: { "Idempotency-Key": idempotencyKey }
28
+ });
29
+ } catch (error) {
30
+ rollback?.();
31
+ await onError?.({ error, idempotencyKey, input });
32
+ throw error;
33
+ }
34
+ const resolvedError = getResolvedError(result);
35
+ if (resolvedError !== undefined) {
36
+ rollback?.();
37
+ await onError?.({ error: resolvedError, idempotencyKey, input, result });
38
+ return result;
39
+ }
40
+ await onSuccess?.({ idempotencyKey, input, result });
41
+ return result;
42
+ }, [mutation, optimistic, onError, onSuccess]);
43
+ return run;
44
+ }
2
45
  // src/shared/await.tsx
3
46
  import { Component, createContext, createElement, use, useMemo } from "react";
4
47
  var AsyncErrorContext = createContext(undefined);
@@ -87,6 +130,7 @@ function isDeferred(v) {
87
130
  return typeof v === "object" && v !== null && Object.hasOwn(v, DEFERRED_BRAND) && v[DEFERRED_BRAND] === true;
88
131
  }
89
132
  export {
133
+ useSync,
90
134
  useAsyncValue,
91
135
  useAsyncError,
92
136
  isDeferred,
package/dist/furin.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Elysia } from "elysia";
2
2
  import { type EvlogElysiaOptions } from "evlog/elysia";
3
+ import { type FurinSyncOption } from "./server/sync/index.ts";
3
4
  export interface FurinCacheTags {
4
5
  }
5
6
  export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
@@ -17,7 +18,7 @@ export type CacheTag = keyof FurinCacheTags extends never ? string : keyof Furin
17
18
  * .listen(3000)
18
19
  * ```
19
20
  */
20
- export declare function furin({ pagesDir, logger, clientLogging, }: {
21
+ export declare function furin({ pagesDir, logger, clientLogging, sync, }: {
21
22
  pagesDir?: string;
22
23
  logger?: EvlogElysiaOptions;
23
24
  /**
@@ -27,6 +28,12 @@ export declare function furin({ pagesDir, logger, clientLogging, }: {
27
28
  * and unaffected.
28
29
  */
29
30
  clientLogging?: boolean;
31
+ /**
32
+ * Enables Furin's built-in sync event stream. The opinionated default mounts
33
+ * Server-Sent Events at `/_furin/sync`; pass an object only for constrained
34
+ * reverse-proxy deployments that need a custom internal path.
35
+ */
36
+ sync?: FurinSyncOption;
30
37
  }): Promise<Elysia<"", {
31
38
  decorator: {};
32
39
  store: {};
@@ -63,6 +70,7 @@ export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.t
63
70
  export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
64
71
  export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
65
72
  export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
73
+ export { furinSync, type SyncInput } from "./server/sync/index.ts";
66
74
  export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
67
75
  export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
68
76
  export type { NotFoundComponent, NotFoundOptions, NotFoundProps, } from "./shared/not-found.ts";