@lunora/react 0.0.0 → 1.0.0-alpha.10

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 (34) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +152 -9
  3. package/__assets__/package-og.svg +14 -0
  4. package/dist/index.d.mts +556 -0
  5. package/dist/index.d.ts +556 -0
  6. package/dist/index.mjs +19 -0
  7. package/dist/packem_shared/AuthLoading-DtKgZT2Z.mjs +33 -0
  8. package/dist/packem_shared/CheckoutButton-CVSry8U1.mjs +185 -0
  9. package/dist/packem_shared/LunoraProvider-D38Xp16l.mjs +80 -0
  10. package/dist/packem_shared/cache-CAp1fVNL.mjs +75 -0
  11. package/dist/packem_shared/hydratePreloaded-B6OHn0eL.mjs +46 -0
  12. package/dist/packem_shared/lunoraQueryOptions-Cij4KWBK.mjs +16 -0
  13. package/dist/packem_shared/query-key-B5eRQCbR.mjs +13 -0
  14. package/dist/packem_shared/query-options.d-D4okOpO8.d.mts +38 -0
  15. package/dist/packem_shared/query-options.d-D4okOpO8.d.ts +38 -0
  16. package/dist/packem_shared/stable-key-CaKZv9lp.mjs +30 -0
  17. package/dist/packem_shared/use-paginated-core-DP72UNWn.mjs +176 -0
  18. package/dist/packem_shared/useAuth-CNUKtOOp.mjs +129 -0
  19. package/dist/packem_shared/useAuthState-BiGhtSCs.mjs +36 -0
  20. package/dist/packem_shared/useConnectionStatus-DRSY9ldm.mjs +30 -0
  21. package/dist/packem_shared/useFlag-Bg5DpkGv.mjs +224 -0
  22. package/dist/packem_shared/useInfiniteQuery-BBIDFXBN.mjs +97 -0
  23. package/dist/packem_shared/useMutation-CrvMXRsk.mjs +67 -0
  24. package/dist/packem_shared/useMutator-IIrLtDiM.mjs +47 -0
  25. package/dist/packem_shared/usePaginatedQuery-AQO3kdp1.mjs +46 -0
  26. package/dist/packem_shared/usePresence-D7jLuxj0.mjs +108 -0
  27. package/dist/packem_shared/useQuery-EB74gtBJ.mjs +42 -0
  28. package/dist/packem_shared/useRateLimit-DTEffQEi.mjs +64 -0
  29. package/dist/packem_shared/useStream-MdYnWDL_.mjs +125 -0
  30. package/dist/packem_shared/useSubscription-DSJuryrU.mjs +139 -0
  31. package/dist/server.d.mts +51 -0
  32. package/dist/server.d.ts +51 -0
  33. package/dist/server.mjs +31 -0
  34. package/package.json +60 -17
@@ -0,0 +1,556 @@
1
+ import { ReactNode, ReactElement } from 'react';
2
+ import { LunoraClient, OptimisticUpdate, User, ConnectionStatus, ReturnOf, ArgsOf, FunctionReference, MutatorHandle, Preloaded } from '@lunora/client';
3
+ export type { ArgsOf, FunctionReference, LunoraClient, MutatorHandle, MutatorTransaction, OptimisticLocalStore, OptimisticUpdate, Preloaded, ReturnOf, User } from '@lunora/client';
4
+ import { QueryClient } from '@tanstack/react-query';
5
+ export { type L as LunoraQueryOptions, l as lunoraQueryOptions } from "./packem_shared/query-options.d-D4okOpO8.mjs";
6
+ import { PaginationStatus } from '@lunora/client/pagination';
7
+ export type { PaginationResult, PaginationStatus } from '@lunora/client/pagination';
8
+ import { RateLimitStatus, RateLimitConfig } from '@lunora/ratelimit';
9
+ interface AuthGateProps {
10
+ children: ReactNode;
11
+ }
12
+ /** Renders `children` only once a token is set on the client (after hydration). */
13
+ declare const Authenticated: ({
14
+ children
15
+ }: AuthGateProps) => ReactNode;
16
+ /** Renders `children` only when auth has settled and no token is set. */
17
+ declare const Unauthenticated: ({
18
+ children
19
+ }: AuthGateProps) => ReactNode;
20
+ /** Renders `children` while auth is still settling (before hydration completes). */
21
+ declare const AuthLoading: ({
22
+ children
23
+ }: AuthGateProps) => ReactNode;
24
+ /**
25
+ * Resolved auth-gate state. `isLoading` covers the window before the client has
26
+ * hydrated — the server render and the first hydration render both report
27
+ * loading, so the markup agrees and no signed-out UI flashes in.
28
+ */
29
+ interface AuthState {
30
+ isAuthenticated: boolean;
31
+ isLoading: boolean;
32
+ }
33
+ /**
34
+ * Three-state auth status for gating UI. Reports `isLoading` until the client
35
+ * has hydrated, then `isAuthenticated` tracks whether a token is set on the
36
+ * shared client.
37
+ *
38
+ * Lunora auth is token-based and resolves synchronously once the token is
39
+ * known, so the loading window is hydration rather than a server round-trip —
40
+ * use it (via {@link AuthState}) to render a fallback while it settles.
41
+ */
42
+ declare const useAuthState: () => AuthState;
43
+ interface LunoraProviderProps {
44
+ children: ReactNode;
45
+ client: LunoraClient;
46
+ /**
47
+ * Bring-your-own QueryClient. When omitted, the provider creates one with
48
+ * defaults tuned for Lunora's push-driven model: `staleTime: Infinity` (the
49
+ * WS subscription is the only invalidation signal), `retry: 0` (failures
50
+ * route through the offline queue on the client), and `gcTime: 5min` (keep
51
+ * results around for a short return-to-view window).
52
+ *
53
+ * If a parent `<QueryClientProvider>` is already mounted, the provider
54
+ * uses *that* client and does NOT install an inner one (so apps with their
55
+ * own setup don't double-wrap).
56
+ */
57
+ queryClient?: QueryClient;
58
+ }
59
+ /**
60
+ * Provides both the {@link LunoraClient} and a TanStack `QueryClient` to the
61
+ * tree. The detection logic for a parent QueryClientProvider keeps this safe to
62
+ * drop into an app that already runs TanStack Query for its own purposes.
63
+ */
64
+ declare const LunoraProvider: ({
65
+ children,
66
+ client,
67
+ queryClient
68
+ }: LunoraProviderProps) => ReactElement;
69
+ /**
70
+ * Read the {@link LunoraClient} from the nearest `<LunoraProvider>`. Kept
71
+ * colocated with the provider for back-compat.
72
+ */
73
+ declare const useLunora: () => LunoraClient;
74
+ /**
75
+ * Client-safe mirror of `@lunora/payment`'s `Subscription`. Re-declared here
76
+ * (rather than imported) so this React entry never pulls in the server-only
77
+ * `@lunora/payment` module graph — the kit stays React + DOM only. Keep this in
78
+ * sync with `packages/payment/src/types.ts`.
79
+ */
80
+ interface Subscription {
81
+ readonly cancelAtPeriodEnd: boolean;
82
+ readonly createdAt: number;
83
+ readonly currentPeriodEnd?: number;
84
+ readonly id: string;
85
+ readonly priceId: string;
86
+ readonly provider: "polar" | "stripe";
87
+ readonly quantity: number;
88
+ readonly referenceId: string;
89
+ readonly state: "active" | "canceled" | "past_due" | "paused" | "trialing";
90
+ readonly updatedAt: number;
91
+ }
92
+ /** The `{ url }` shape every checkout/portal trigger resolves to. */
93
+ interface RedirectTarget {
94
+ readonly url: string;
95
+ }
96
+ /** A thunk the app supplies that calls its own Lunora action and resolves a redirect URL. */
97
+ type RedirectTrigger = () => Promise<RedirectTarget>;
98
+ interface UseCheckoutResult {
99
+ /** Run the trigger and redirect the browser to the resolved URL. Resolves once the redirect is issued; rejects on failure. */
100
+ checkout: () => Promise<void>;
101
+ /** The most recent failure, or `undefined`. */
102
+ error: Error | undefined;
103
+ /** `true` while the trigger is in flight (before the redirect is issued). */
104
+ pending: boolean;
105
+ }
106
+ /**
107
+ * Decoupled redirect-on-resolve primitive shared by `CheckoutButton` and
108
+ * `CustomerPortalButton`. The app passes a `trigger` thunk that calls its own
109
+ * Lunora action (the one wrapping `LunoraPayment.createCheckout` /
110
+ * `createPortalSession`) and resolves `{ url }`; this hook awaits it, flips
111
+ * `pending`, surfaces any `error`, and on success navigates via
112
+ * `location.assign(url)`.
113
+ *
114
+ * Mirrors Convex's `CheckoutLink` / `CustomerPortalLink` flow (trigger an action
115
+ * that returns a URL, then redirect) while staying agnostic of the app's
116
+ * function names.
117
+ */
118
+ declare const useCheckout: (trigger: RedirectTrigger) => UseCheckoutResult;
119
+ /**
120
+ * Presentational props shared by the redirect buttons. Kept to a curated set
121
+ * (rather than spreading arbitrary button attributes) so the component stays
122
+ * within the repo's `react/jsx-props-no-spreading` rule while covering the
123
+ * common styling / accessibility hooks.
124
+ */
125
+ interface RedirectButtonOwnProps {
126
+ /** Accessible label when the visible `children` are icon-only. */
127
+ "aria-label"?: string;
128
+ children?: ReactNode;
129
+ className?: string;
130
+ /** Force-disable the control regardless of pending state. */
131
+ disabled?: boolean;
132
+ /** Called with the failure when the trigger rejects. The error is also surfaced via `useCheckout`. */
133
+ onError?: (error: Error) => void;
134
+ title?: string;
135
+ }
136
+ interface CheckoutButtonProps extends RedirectButtonOwnProps {
137
+ /** Calls the app's checkout action and resolves the hosted-checkout `{ url }`. */
138
+ onCheckout: RedirectTrigger;
139
+ }
140
+ interface CustomerPortalButtonProps extends RedirectButtonOwnProps {
141
+ /** Calls the app's portal action and resolves the customer-portal `{ url }`. */
142
+ onPortal: RedirectTrigger;
143
+ }
144
+ /**
145
+ * Button that starts a hosted checkout. On click it awaits `onCheckout` (a thunk
146
+ * that calls the app's checkout action) and redirects to the returned URL,
147
+ * disabling itself while the request is in flight.
148
+ */
149
+ declare const CheckoutButton: ({
150
+ onCheckout,
151
+ ...rest
152
+ }: CheckoutButtonProps) => ReactNode;
153
+ /**
154
+ * Button that opens the provider's customer portal. On click it awaits
155
+ * `onPortal` (a thunk that calls the app's portal action) and redirects to the
156
+ * returned URL, disabling itself while the request is in flight.
157
+ */
158
+ declare const CustomerPortalButton: ({
159
+ onPortal,
160
+ ...rest
161
+ }: CustomerPortalButtonProps) => ReactNode;
162
+ interface UseQueryOptions {
163
+ shardKey?: string;
164
+ }
165
+ interface UseMutationCallOptions<TCurrent = unknown, TValue = unknown, TArgs = unknown> {
166
+ optimistic?: (current: TCurrent | undefined) => TValue;
167
+ /**
168
+ * Convex-parity multi-query optimistic update forwarded to
169
+ * `client.mutation`. Patches many subscribed queries at once via an
170
+ * `OptimisticLocalStore`, rolled back atomically on failure.
171
+ */
172
+ optimisticUpdate?: OptimisticUpdate<TArgs>;
173
+ shardKey?: string;
174
+ }
175
+ interface UseSubscriptionResult<T> {
176
+ data: T | undefined;
177
+ error: Error | undefined;
178
+ }
179
+ interface UsePaginatedQueryOptions {
180
+ /** Page size for the first page (and the default for `loadMore`). */
181
+ initialNumItems: number;
182
+ shardKey?: string;
183
+ }
184
+ interface UsePaginatedQueryResult<T> {
185
+ /** `true` while the first page or a `loadMore` page is in flight. */
186
+ isLoading: boolean;
187
+ /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
188
+ loadMore: (numberItems: number) => void;
189
+ /** Flattened items across every loaded page, in order. */
190
+ results: T[];
191
+ status: PaginationStatus;
192
+ }
193
+ interface UseInfiniteQueryOptions {
194
+ /** Page size for the first page (and the default for `fetchNextPage`). */
195
+ initialNumItems: number;
196
+ shardKey?: string;
197
+ }
198
+ interface UseInfiniteQueryResult<T> {
199
+ /** Request the next page. A no-op unless `status === "CanLoadMore"`. */
200
+ fetchNextPage: (numberItems?: number) => void;
201
+ /** `true` when the loaded tail reports it can load another page. */
202
+ hasNextPage: boolean;
203
+ /** `true` while a `fetchNextPage` page (beyond the first) is in flight. */
204
+ isFetchingNextPage: boolean;
205
+ /** `true` while the first page is in flight. */
206
+ isLoading: boolean;
207
+ /** One inner array per loaded page, in order; unresolved pages are omitted. */
208
+ pages: T[][];
209
+ status: PaginationStatus;
210
+ }
211
+ interface UseAuthResult {
212
+ setToken: (token: string | null) => void;
213
+ token: string | null;
214
+ user: User | null;
215
+ }
216
+ /**
217
+ * Token + identity plumbing. The token lives on the shared `LunoraClient`;
218
+ * `setToken(jwt)` after a sign-in makes subsequent RPC calls carry the
219
+ * `Authorization` header. `user` is resolved from better-auth's `get-session`
220
+ * endpoint via `client.getCurrentUser()` — fetched on mount and refetched
221
+ * whenever the token changes (`onAuthTokenChange`), and `null` when signed out.
222
+ *
223
+ * Multiple `useAuth` instances stay in sync: both `token` and `user` are read
224
+ * through `useSyncExternalStore` over the shared client (and a per-client
225
+ * identity store), so a `setToken` from one component re-renders every mounted
226
+ * hook with the freshly-resolved user.
227
+ */
228
+ declare const useAuth: () => UseAuthResult;
229
+ /**
230
+ * Reactive view of the client's aggregate live-socket status across all shard
231
+ * connections. Re-renders on every transition (`idle` → `connecting` →
232
+ * `connected` → `offline`). Use it to drive a connection indicator so an
233
+ * operator can tell a healthy live channel from a silently-dropped socket.
234
+ */
235
+ declare const useConnectionStatus: () => ConnectionStatus;
236
+ /** A targeting context merged on top of the app's default (`defineFlags({ identify })`). */
237
+ type FlagContext = Record<string, unknown>;
238
+ /** The value kinds a flag resolves to — OpenFeature's boolean / number / string / structured (JSON) flags. */
239
+ type FlagValue = boolean | number | string | {
240
+ [key: string]: unknown;
241
+ } | unknown[] | null;
242
+ /**
243
+ * Subscribe to a single feature flag, live over Lunora's WebSocket.
244
+ *
245
+ * Returns `defaultValue` until the first evaluation lands, then the server's
246
+ * resolved value — re-pushed whenever the provider re-evaluates (e.g. a flag is
247
+ * toggled in Cloudflare Flagship). The flag's kind is inferred from
248
+ * `defaultValue`'s runtime type, so `useFlag("dark", false)` reads a boolean and
249
+ * `useFlag("hero", "control")` a string. `context` supplies a per-call targeting
250
+ * context merged on top of the app's default `identify` targeting key.
251
+ *
252
+ * Evaluation runs through whatever OpenFeature provider the app wired in
253
+ * `lunora/flags.ts`; the read never throws — a provider error resolves the
254
+ * default (the same fail-open contract as server-side `ctx.flags`).
255
+ */
256
+ declare const useFlag: <T extends FlagValue>(key: string, defaultValue: T, context?: FlagContext) => T;
257
+ /**
258
+ * Subscribe to several feature flags at once, live over Lunora's WebSocket.
259
+ *
260
+ * Pass a record of `key → defaultValue`; each flag's kind is inferred from its
261
+ * default, and the result is the same-shaped record with resolved values (the
262
+ * defaults until each evaluation lands). A single `context` applies to every
263
+ * flag. This is the batched form of {@link useFlag} — one effect manages one
264
+ * subscription per key, so it stays rules-of-hooks-safe even as the flag set
265
+ * changes between renders.
266
+ */
267
+ declare const useFlags: <T extends Record<string, FlagValue>>(flags: T, context?: FlagContext) => T;
268
+ /** The args a paginated query exposes minus the framework-supplied page cursor. */
269
+ type PaginatedArgs<F> = Omit<ArgsOf<F>, "paginationOpts">;
270
+ /** The element type of the `page` array a paginated query returns. */
271
+ type PageItemOf<F> = ReturnOf<F> extends {
272
+ page: (infer T)[];
273
+ } ? T : unknown;
274
+ /**
275
+ * Subscribe to a reactively-paginated query and grow the feed page by page.
276
+ *
277
+ * The query function must accept a `paginationOpts: { numItems, cursor,
278
+ * endCursor }` arg and return a `PaginationResult` (the shape
279
+ * `ctx.db.query(...).paginate` yields). Pages are tracked as an ordered list of
280
+ * stable boundary cursors: each loaded page is a live subscription over a
281
+ * FIXED `(lower, upper]` range whose upper bound is the next page's lower bound.
282
+ * Because boundaries are shared stable cursors, inserting or deleting a row in
283
+ * the middle of the list grows/shrinks the affected page in place without
284
+ * duplicating or skipping rows across page boundaries — the bug the legacy
285
+ * "first N after the previous page's last row" model suffered under live edits.
286
+ *
287
+ * `loadMore` appends the next page off the open-ended tail's `continueCursor`;
288
+ * it is a no-op unless `status === "CanLoadMore"`. Background split/join
289
+ * maintenance keeps page sizes near `initialNumItems` as edits accumulate (see
290
+ * `use-paginated-core.ts`).
291
+ *
292
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
293
+ * feed to its first page. The public return shape (`results` / `status` /
294
+ * `loadMore`) is unchanged from the legacy keyset implementation.
295
+ */
296
+ declare const usePaginatedQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UsePaginatedQueryOptions) => UsePaginatedQueryResult<PageItemOf<F>>;
297
+ /**
298
+ * Subscribe to a reactively-paginated query and expose its pages discretely.
299
+ *
300
+ * Shares `usePaginatedQuery`'s reactive-pagination engine — pages are fixed
301
+ * `(lower, upper]` cursor ranges with shared stable boundaries, so a row
302
+ * inserted or deleted mid-list grows/shrinks the affected page without
303
+ * duplicating or skipping rows across boundaries — but keeps each page as its
304
+ * own inner array rather than flattening them, and adds the
305
+ * TanStack-Query-style `fetchNextPage` / `hasNextPage` / `isFetchingNextPage`
306
+ * shape. `fetchNextPage` appends the next page off the open-ended tail's
307
+ * `continueCursor`; it is a no-op unless `status === "CanLoadMore"`.
308
+ *
309
+ * Changing `fn`, the base `args`, `initialNumItems`, or `shardKey` resets the
310
+ * feed to its first page. The public return shape is unchanged from the legacy
311
+ * keyset implementation.
312
+ */
313
+ declare const useInfiniteQuery: <F extends FunctionReference>(function_: F, args: "skip" | PaginatedArgs<F>, options: UseInfiniteQueryOptions) => UseInfiniteQueryResult<PageItemOf<F>>;
314
+ type CallOptions<F extends FunctionReference> = UseMutationCallOptions<unknown, unknown, ArgsOf<F>>;
315
+ interface MutationHook<F extends FunctionReference> {
316
+ /** The latest invocation's resolved value, or `undefined` before the first success. */
317
+ data: ReturnOf<F> | undefined;
318
+ /** The latest invocation's error, or `null`. */
319
+ error: Error | null;
320
+ /** `true` when the latest invocation rejected. */
321
+ isError: boolean;
322
+ mutate: (args: ArgsOf<F>, options?: CallOptions<F>) => Promise<ReturnOf<F>>;
323
+ /** `true` while ANY invocation from this hook is in flight (ref-counted, so overlapping calls compose). */
324
+ pending: boolean;
325
+ /** Clear the latest `data`/`error` back to idle. */
326
+ reset: () => void;
327
+ /**
328
+ * Bind a Convex-parity multi-query optimistic update to this mutation.
329
+ * Returns a `{ mutate, pending, … }` whose `mutate` forwards `update` as the
330
+ * `optimisticUpdate` for every call — unless a per-call `optimisticUpdate`
331
+ * is supplied in the call options, which overrides the bound one.
332
+ */
333
+ withOptimisticUpdate: (update: OptimisticUpdate<ArgsOf<F>>) => MutationHook<F>;
334
+ }
335
+ /**
336
+ * Returns `{ mutate, pending, data, error, reset, withOptimisticUpdate }` for the
337
+ * given mutation reference. Prefer destructuring at the call site so the React
338
+ * linter can track dependencies on each field independently.
339
+ *
340
+ * Built on TanStack Query's mutation cache (the same cache the query hooks use),
341
+ * so it composes with Query Devtools and exposes the latest call's `data`/`error`
342
+ * plus `reset()`. `mutate` maps to `mutateAsync`, so it stays an awaitable that
343
+ * rejects on failure (rather than TanStack's fire-and-forget `mutate`).
344
+ *
345
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance
346
+ * (driven by the mutation's `onMutate`/`onSettled` lifecycle), so it flips back to
347
+ * `false` only once every concurrent call has settled — and a sibling component
348
+ * mutating the same function never affects it (TanStack's own `isPending` tracks
349
+ * just the latest invocation).
350
+ *
351
+ * Optimistic updates stay client-owned: the `optimistic` / `optimisticUpdate`
352
+ * call options pass straight through to `client.mutation`, which applies and
353
+ * rolls them back against the Lunora subscription cache (Convex parity) — not
354
+ * through TanStack's `onMutate`.
355
+ */
356
+ declare const useMutation: <F extends FunctionReference>(function_: F) => MutationHook<F>;
357
+ interface MutatorHook<TArgs> {
358
+ /** The latest invocation's error, or `undefined`. */
359
+ error: Error | undefined;
360
+ /** `true` when the latest invocation rejected. */
361
+ isError: boolean;
362
+ /** Run the mutator; resolves once the write is persisted, rejects on failure. */
363
+ mutate: (args: TArgs) => Promise<void>;
364
+ /** `true` while ANY invocation from this hook is in flight (ref-counted, so overlapping calls compose). */
365
+ pending: boolean;
366
+ /** Clear the latest `error` back to idle. */
367
+ reset: () => void;
368
+ }
369
+ /**
370
+ * Ergonomic `{ mutate, pending, error, isError, reset }` wrapper over a bound
371
+ * custom-mutator handle from `@lunora/db`'s `bindMutators`. The optimistic
372
+ * overlay and server-authoritative push are owned by the bound handle (and
373
+ * TanStack DB's optimistic-transaction layer rebases pending overlays on every
374
+ * sync tick) — this hook only surfaces React state for the in-flight/error
375
+ * lifecycle. Reads stay on the existing `useLiveQuery`; no new query hook is
376
+ * needed.
377
+ *
378
+ * `pending` is ref-counted across overlapping invocations of THIS hook instance,
379
+ * so it clears only once every concurrent call has settled.
380
+ */
381
+ declare const useMutator: <TArgs = Record<string, unknown>>(handle: MutatorHandle<TArgs>) => MutatorHook<TArgs>;
382
+ /**
383
+ * Hydrate a query from a {@link Preloaded} token produced by `preloadQuery`
384
+ * during SSR, then keep it live.
385
+ *
386
+ * The first render returns the preloaded value (TanStack's `initialData`),
387
+ * so the server markup and the initial client markup match — no hydration
388
+ * mismatch, no loading flash. After mount, a WS subscription attaches so
389
+ * later server pushes update the value just like `useQuery`.
390
+ *
391
+ * The {@link Preloaded} token's `value` seeds `initialData`; we don't need a
392
+ * full dehydrate/hydrate dance because the consumer hands us the resolved
393
+ * value directly. Apps that want to share a pre-populated QueryClient across
394
+ * many preloaded queries can pass their own `queryClient` to `LunoraProvider`
395
+ * and hydrate it themselves via TanStack's `hydrate(qc, dehydratedState)`.
396
+ */
397
+ declare const usePreloadedQuery: <T>(preloaded: Preloaded<T>) => T;
398
+ /**
399
+ * The PLAN4 §1 framework-neutral name for the preloaded-hydration handoff:
400
+ * `hydratePreloaded(preloaded)` seeds the SSR value on the first paint, then
401
+ * attaches a live WS subscription on mount. It is a thin alias of
402
+ * {@link usePreloadedQuery} so the React adapter exposes the same
403
+ * `hydratePreloaded` primitive every other adapter (Solid, Svelte, Vue) will,
404
+ * while existing callers of `usePreloadedQuery` keep working unchanged.
405
+ *
406
+ * It carries React's Rules-of-Hooks contract (it calls hooks internally), so
407
+ * call it like a hook — at the top level of a component, unconditionally.
408
+ */
409
+ declare const hydratePreloaded: <T>(preloaded: Preloaded<T>) => T;
410
+ /**
411
+ * `usePresence` — collaborative-awareness hook, the client half of the
412
+ * `@lunora/server` `definePresence` preset (Convex `@convex-dev/presence`
413
+ * parity).
414
+ *
415
+ * It drives the two presence functions the server component ships:
416
+ *
417
+ * - **heartbeat** (a mutation): called on mount, on a fixed interval, and again
418
+ * whenever the tab becomes visible, to upsert the caller's presence row and
419
+ * refresh its `lastSeen`. On unmount the interval is cleared. Each heartbeat
420
+ * carries the latest `data` from a ref, so `setData` takes effect on the next
421
+ * tick without re-subscribing or resetting the timer.
422
+ * - **listPresent** (a query): subscribed to over the live-query WS, so the
423
+ * present-list updates reactively. Because the server patches a single row per
424
+ * heartbeat, the client's **per-row subscription delta merge** applies just that
425
+ * row to the cached list instead of re-sending every member — the list stays
426
+ * cheap even with many participants heart-beating.
427
+ *
428
+ * `sessionId` defaults to a stable per-mount id (one row per tab); pass your own
429
+ * to dedupe across tabs by user. TTL/expiry is server-side: a member that stops
430
+ * heart-beating drops out of `listPresent` once `lastSeen` ages past the TTL, so
431
+ * the hook needs no client-side reaping.
432
+ *
433
+ * The two `FunctionReference`s come from your generated `api` (e.g.
434
+ * `api.presence.heartbeat` / `api.presence.listPresent`) — passed in so the hook
435
+ * stays decoupled from any specific app schema.
436
+ */
437
+ /**
438
+ * A heartbeat mutation reference: takes `{ roomId, sessionId, data? }` (the shape
439
+ * `definePresence().functions.heartbeat` registers).
440
+ */
441
+ type HeartbeatReference = FunctionReference<"mutation", {
442
+ data?: Record<string, unknown>;
443
+ roomId: string;
444
+ sessionId: string;
445
+ }>;
446
+ /**
447
+ * A listPresent query reference: takes `{ roomId }` and returns the array of
448
+ * present members.
449
+ */
450
+ type ListPresentReference = FunctionReference<"query", {
451
+ roomId: string;
452
+ }>;
453
+ interface UsePresenceOptions<H extends HeartbeatReference, L extends ListPresentReference> {
454
+ /** Awareness blob for the first heartbeat (selection, cursor, name, color…). */
455
+ data?: Record<string, unknown>;
456
+ /** The `api.*` reference for the presence heartbeat mutation. */
457
+ heartbeat: H;
458
+ /** Heartbeat cadence in ms. Defaults to 10s — keep it well under the server TTL. */
459
+ intervalMs?: number;
460
+ /** The `api.*` reference for the presence listPresent query. */
461
+ listPresent: L;
462
+ /**
463
+ * Stable id for this presence row. Defaults to a fresh per-mount id (one row
464
+ * per tab). Pass a user/connection id to control deduping.
465
+ */
466
+ sessionId?: string;
467
+ /** Forwarded to the heartbeat mutation / listPresent subscription when sharding by room. */
468
+ shardKey?: string;
469
+ }
470
+ interface UsePresenceResult<L extends ListPresentReference> {
471
+ /** The present members for the room, as `listPresent` returns them. `undefined` until the first push. */
472
+ present: ReturnOf<L> | undefined;
473
+ /** This mount's session id (generated when not supplied). */
474
+ sessionId: string;
475
+ /** Replace the awareness `data` sent with subsequent heartbeats, and heartbeat once now. */
476
+ setData: (data: Record<string, unknown> | undefined) => void;
477
+ }
478
+ declare const usePresence: <H extends HeartbeatReference, L extends ListPresentReference>(roomId: string, options: UsePresenceOptions<H, L>) => UsePresenceResult<L>;
479
+ /**
480
+ * Subscribe to a server query.
481
+ *
482
+ * Returns `undefined` until the first response lands. Pass `"skip"` for
483
+ * `args` to short-circuit the query (no network call, no subscription).
484
+ *
485
+ * Internally this routes through TanStack Query: the queryKey is
486
+ * `["lunora", fn.__lunoraRef, args, shardKey]` (TanStack hashes structurally
487
+ * so an args object built in a different key order still dedupes). The
488
+ * subscription registry shares a single WS subscription across every consumer
489
+ * of the same queryKey; pushes call `queryClient.setQueryData(...)`.
490
+ */
491
+ declare const useQuery: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => ReturnOf<F> | undefined;
492
+ interface UseRateLimitOptions {
493
+ /** Clock injection for tests. Defaults to `Date.now`. */
494
+ now?: () => number;
495
+ /**
496
+ * Re-render cadence in milliseconds while throttled, so `retryAfter` ticks
497
+ * down and `disabled` flips back automatically. Defaults to `1000`.
498
+ */
499
+ tickMs?: number;
500
+ }
501
+ interface UseRateLimitResult {
502
+ /** Would consuming `count` (default 1) succeed right now? Does not consume. */
503
+ check: (count?: number) => boolean;
504
+ /** Optimistically consume `count` (default 1) locally; mirrors the server algorithm. */
505
+ consume: (count?: number) => RateLimitStatus;
506
+ /** `true` while a single unit cannot be consumed — convenient for disabling a control. */
507
+ disabled: boolean;
508
+ /** `true` while a single unit can be consumed. */
509
+ ok: boolean;
510
+ /** Clear local accounting (e.g. after the server confirms a reset). */
511
+ reset: () => void;
512
+ /** Milliseconds until the next unit is available. `0` when `ok`. */
513
+ retryAfter: number;
514
+ }
515
+ /**
516
+ * Client-side mirror of a rate limit for instant UX — disable a button or show
517
+ * a countdown without a round-trip. It runs the same token-bucket / fixed-window
518
+ * math as `@lunora/ratelimit` on the server, so the prediction agrees with the
519
+ * authoritative check; the server remains the source of truth.
520
+ *
521
+ * `config` is read on every render; pass a stable reference (module constant or
522
+ * `useMemo`) so the `consume`/`check` callbacks keep a steady identity.
523
+ */
524
+ declare const useRateLimit: (config: RateLimitConfig, options?: UseRateLimitOptions) => UseRateLimitResult;
525
+ /** The lifecycle of a stream the hook is observing. */
526
+ type UseStreamStatus = "complete" | "error" | "idle" | "streaming";
527
+ interface UseStreamResult<T> {
528
+ /** Force-cancel the stream and resolve the iterator. Safe to call multiple times. */
529
+ cancel: () => void;
530
+ /** Chunks the server has pushed so far, in arrival order. */
531
+ chunks: ReadonlyArray<T>;
532
+ error: Error | undefined;
533
+ status: UseStreamStatus;
534
+ }
535
+ interface UseStreamOptions {
536
+ /** Forwarded to `client.stream()` — caps the in-flight chunk buffer. */
537
+ maxBuffer?: number;
538
+ shardKey?: string;
539
+ }
540
+ /**
541
+ * Subscribe to a streaming query. Returns the chunks pushed so far plus a
542
+ * lifecycle status and a cancel function. Changing `fn` or the serialized
543
+ * `args` resets the stream — the previous iterator is cancelled and a fresh
544
+ * one opens with empty `chunks`.
545
+ *
546
+ * Pass `"skip"` for `args` to keep the hook mounted without opening a stream
547
+ * (mirrors `useQuery` / `useSubscription`).
548
+ */
549
+ declare const useStream: <F extends FunctionReference<"stream">>(function_: F, args: "skip" | ArgsOf<F>, options?: UseStreamOptions) => UseStreamResult<ReturnOf<F>>;
550
+ /**
551
+ * Subscribe to a real-time stream from the server. Unlike `useQuery`, this
552
+ * hook does not issue an initial HTTP fetch — it only delivers values that
553
+ * the server pushes over the WS.
554
+ */
555
+ declare const useSubscription: <F extends FunctionReference>(function_: F, args: ArgsOf<F> | "skip", options?: UseQueryOptions) => UseSubscriptionResult<ReturnOf<F>>;
556
+ export { AuthLoading, type AuthState, Authenticated, CheckoutButton, type CheckoutButtonProps, CustomerPortalButton, type CustomerPortalButtonProps, type FlagContext, type FlagValue, type HeartbeatReference, type ListPresentReference, LunoraProvider, type LunoraProviderProps, type MutationHook, type MutatorHook, type PageItemOf, type PaginatedArgs, type RedirectTarget, type RedirectTrigger, type Subscription, Unauthenticated, type UseAuthResult, type UseCheckoutResult, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationCallOptions, type UsePaginatedQueryOptions, type UsePaginatedQueryResult, type UsePresenceOptions, type UsePresenceResult, type UseQueryOptions, type UseRateLimitOptions, type UseRateLimitResult, type UseStreamOptions, type UseStreamResult, type UseStreamStatus, type UseSubscriptionResult, hydratePreloaded, useAuth, useAuthState, useCheckout, useConnectionStatus, useFlag, useFlags, useInfiniteQuery, useLunora, useMutation, useMutator, usePaginatedQuery, usePreloadedQuery, usePresence, useQuery, useRateLimit, useStream, useSubscription };