@hamur/adapter-svelte 0.0.0-stage → 0.0.2

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 (106) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +31 -2
  3. package/dist/chunks/browser-index-324qgh1c.js +190 -0
  4. package/dist/chunks/browser-index-evqp5a71.js +64 -0
  5. package/dist/chunks/browser-index-xc6081e3.js +9 -0
  6. package/dist/src/adapter.js +480 -0
  7. package/dist/src/index.js +1161 -0
  8. package/dist/src/runtime/client.js +65 -0
  9. package/dist/src/runtime/island.js +72 -0
  10. package/dist/src/runtime/server.js +142 -0
  11. package/dist/types/src/activation.d.ts +15 -0
  12. package/dist/types/src/adapter.d.ts +2 -0
  13. package/dist/types/src/async-data.d.ts +21 -0
  14. package/dist/types/src/boundary-error.d.ts +9 -0
  15. package/dist/types/src/client-only.d.ts +6 -0
  16. package/dist/types/src/context.d.ts +87 -0
  17. package/dist/types/src/deferred.svelte.d.ts +6 -0
  18. package/dist/types/src/effect.svelte.d.ts +2 -0
  19. package/dist/types/src/hydrating.d.ts +4 -0
  20. package/dist/types/src/index.d.ts +270 -0
  21. package/dist/types/src/island-html.d.ts +13 -0
  22. package/dist/types/src/keepalive.d.ts +11 -0
  23. package/dist/types/src/lazy-hydration.d.ts +25 -0
  24. package/dist/types/src/markdown-page.d.ts +9 -0
  25. package/dist/types/src/plugin.d.ts +52 -0
  26. package/dist/types/src/runtime/client.d.ts +12 -0
  27. package/dist/types/src/runtime/hmr.d.ts +28 -0
  28. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  29. package/dist/types/src/runtime/hydration.d.ts +8 -0
  30. package/dist/types/src/runtime/island.d.ts +8 -0
  31. package/dist/types/src/runtime/server.d.ts +12 -0
  32. package/dist/types/src/server-component.d.ts +3 -0
  33. package/dist/types/src/store.d.ts +7 -0
  34. package/dist/types/src/svg.d.ts +10 -0
  35. package/package.json +58 -4
  36. package/src/Announcer.svelte +26 -0
  37. package/src/Await.svelte +43 -0
  38. package/src/AwaitAsync.svelte +42 -0
  39. package/src/BodyAttrs.svelte +7 -0
  40. package/src/Caught.svelte +41 -0
  41. package/src/ClientComponent.svelte +35 -0
  42. package/src/ClientFallback.svelte +46 -0
  43. package/src/ClientOnly.svelte +22 -0
  44. package/src/DefaultErrorPage.svelte +15 -0
  45. package/src/DevOnly.svelte +12 -0
  46. package/src/ErrorBoundary.svelte +14 -0
  47. package/src/FallbackEffect.svelte +9 -0
  48. package/src/Form.svelte +96 -0
  49. package/src/HeadLink.svelte +7 -0
  50. package/src/HeadMeta.svelte +7 -0
  51. package/src/HeadScript.svelte +7 -0
  52. package/src/HeadStyle.svelte +7 -0
  53. package/src/HeadTitle.svelte +6 -0
  54. package/src/HtmlAttrs.svelte +7 -0
  55. package/src/HttpHeader.svelte +7 -0
  56. package/src/HttpStatusCode.svelte +7 -0
  57. package/src/Island.svelte +59 -0
  58. package/src/IslandChildren.svelte +7 -0
  59. package/src/KeptOutlet.svelte +46 -0
  60. package/src/KeptPage.svelte +55 -0
  61. package/src/LazyHydration.svelte +54 -0
  62. package/src/Link.svelte +209 -0
  63. package/src/LoadingIndicator.svelte +18 -0
  64. package/src/MarkdownNodes.svelte +36 -0
  65. package/src/MarkdownRenderer.svelte +20 -0
  66. package/src/MarkdownSlots.svelte +33 -0
  67. package/src/Navigate.svelte +10 -0
  68. package/src/Nest.svelte +83 -0
  69. package/src/Outlet.svelte +31 -0
  70. package/src/Rethrow.svelte +7 -0
  71. package/src/Root.svelte +29 -0
  72. package/src/RouteAnnouncer.svelte +47 -0
  73. package/src/Scoped.svelte +11 -0
  74. package/src/ServerComponent.svelte +19 -0
  75. package/src/ServerComponentClient.svelte +64 -0
  76. package/src/ServerIsland.svelte +26 -0
  77. package/src/Slotted.svelte +11 -0
  78. package/src/Thrown.svelte +9 -0
  79. package/src/Time.svelte +23 -0
  80. package/src/activation.ts +51 -0
  81. package/src/adapter.ts +24 -0
  82. package/src/async-data.ts +105 -0
  83. package/src/boundary-error.ts +77 -0
  84. package/src/client-only.ts +8 -0
  85. package/src/context.ts +227 -0
  86. package/src/deferred.svelte.ts +33 -0
  87. package/src/effect.svelte.ts +7 -0
  88. package/src/env.d.ts +3 -0
  89. package/src/hydrating.ts +18 -0
  90. package/src/index.ts +1337 -0
  91. package/src/island-html.ts +58 -0
  92. package/src/keepalive.ts +12 -0
  93. package/src/lazy-hydration.ts +89 -0
  94. package/src/markdown-page.ts +17 -0
  95. package/src/plugin.ts +558 -0
  96. package/src/runtime/client.ts +61 -0
  97. package/src/runtime/hmr.ts +177 -0
  98. package/src/runtime/hydration-dev.ts +22 -0
  99. package/src/runtime/hydration.ts +7 -0
  100. package/src/runtime/island.ts +94 -0
  101. package/src/runtime/server.ts +87 -0
  102. package/src/server-component.ts +13 -0
  103. package/src/store.ts +31 -0
  104. package/src/svelte.d.ts +5 -0
  105. package/src/svg.ts +30 -0
  106. package/src/webmcp.d.ts +18 -0
package/src/index.ts ADDED
@@ -0,0 +1,1337 @@
1
+ /// <reference path="./webmcp.d.ts" />
2
+ import { getContext, onDestroy, onMount, untrack } from "svelte"
3
+ import type { AppHooks, WebVitalMetric } from "hamur/app"
4
+ import { whenAppReady } from "hamur/adapter"
5
+ import { reportWebVitals, syncedState } from "hamur/app"
6
+ import type { SyncedStateOptions } from "hamur/app"
7
+ import { createSubscriber } from "svelte/reactivity"
8
+ import { clearAsyncData, createForm, useCookie as useCookieRef, withoutBase } from "hamur/app"
9
+ import {
10
+ callOnce as callOnceOf,
11
+ clearState as clearStateOf,
12
+ setResponseStatus as setResponseStatusOf,
13
+ useResponseHeader as responseHeaderOf,
14
+ useRequestEvent as requestEventOf,
15
+ useRequestFetch as requestFetchOf,
16
+ useRequestHeader as requestHeaderOf,
17
+ useRequestHeaders as requestHeadersOf,
18
+ useRequestURL as requestURLOf,
19
+ usePreviewMode as previewModeOf,
20
+ } from "hamur/app"
21
+ import type { PreviewMode } from "hamur/app"
22
+ import type { $Fetch, FetchCheckedInput, FetchInputField } from "hamur/app"
23
+ import type { StateKey } from "hamur/app"
24
+ import type { HamurEvent } from "hamur/server"
25
+ import {
26
+ IDLE_FORM_STATUS,
27
+ checkTransitionName,
28
+ createLoadingIndicator,
29
+ createRouteAnnouncer,
30
+ createAnnouncer,
31
+ announcerActions,
32
+ createActionRunner,
33
+ linkActionRunner,
34
+ restoredResult,
35
+ optimisticSource,
36
+ runtimeConfigOf,
37
+ siteConfigOf,
38
+ sanitizeHead,
39
+ seoMetaToHead,
40
+ navigationHook,
41
+ navigationBlocker,
42
+ routeGuard,
43
+ createBlocker,
44
+ registerSnapshot,
45
+ linkPending,
46
+ } from "hamur/adapter"
47
+ import type {
48
+ AnnouncerActions,
49
+ AnnouncerPoliteness,
50
+ AnnouncerState,
51
+ RouteAnnouncerActions,
52
+ RouteAnnouncerState,
53
+ LoadingIndicatorActions,
54
+ LoadingIndicatorOptions,
55
+ LoadingIndicatorState,
56
+ ActionOptions,
57
+ ActionRunner,
58
+ FormStatus,
59
+ FormStatusStore,
60
+ Handler,
61
+ AfterNavigateHook,
62
+ BeforeNavigateHook,
63
+ NavigateHook,
64
+ NavigationBlocker,
65
+ NavigationGuard,
66
+ Blocker,
67
+ ShouldBlock,
68
+ UseBlockerOptions,
69
+ SnapshotOptions,
70
+ } from "hamur/adapter"
71
+ import type { HandlerForm } from "hamur/app"
72
+ import {
73
+ createLinkSlot,
74
+ linkAttributes,
75
+ linkDefaultsOf,
76
+ linkPrefetchProps,
77
+ linkState,
78
+ relativeTarget,
79
+ resolveLinkTarget,
80
+ searchTarget,
81
+ } from "hamur/adapter"
82
+ import { prehydrate } from "hamur/adapter"
83
+ import type { CheckedTarget, LinkDefaults, LinkSlot, UseLinkOptions } from "hamur/adapter"
84
+ import type {
85
+ ActionFailure,
86
+ AppContext,
87
+ RouteLocation,
88
+ PendingRun,
89
+ PickFrom,
90
+ AsyncDataEntry,
91
+ ClientRuntimeConfig,
92
+ SiteConfig,
93
+ ErrorPageProps,
94
+ FetchData,
95
+ AsyncDataOptions,
96
+ AsyncDataStatus,
97
+ HeadEntry,
98
+ HeadInput,
99
+ HeadSafeInput,
100
+ SeoMetaInput,
101
+ UseCookieOptions,
102
+ HamurError,
103
+ } from "hamur/app"
104
+ import {
105
+ asyncDataArguments,
106
+ asyncDataKey,
107
+ stateArguments,
108
+ isHandlerReference,
109
+ isPending,
110
+ markWaiting,
111
+ resolveCallOptions,
112
+ } from "hamur/adapter"
113
+ import type {
114
+ RouteLoaderData,
115
+ UseDataArgs,
116
+ AsyncDataHandler,
117
+ FetchRequest,
118
+ GetCachedData,
119
+ GetCachedDataCause,
120
+ HandlerReference,
121
+ NavigationState,
122
+ RouteValue,
123
+ RouterApi,
124
+ } from "hamur/adapter"
125
+ import { defaultGetCachedData, fetchSlots, handlerSlots, keepCached, refreshCached, valueOf } from "./async-data.ts"
126
+ import { watch, watchPre } from "./effect.svelte.ts"
127
+ import {
128
+ ACTIVATION_KEY,
129
+ ERROR_KEY,
130
+ FORM_STATUS_KEY,
131
+ IDS_KEY,
132
+ LEVEL_KEY,
133
+ LINK_KEY,
134
+ APP_KEY,
135
+ NEVER_HYDRATED_KEY,
136
+ OUTLET_VALUE_KEY,
137
+ detachedHref,
138
+ errorOf,
139
+ nextId,
140
+ useAppState,
141
+ } from "./context.ts"
142
+ import { later, shown } from "./activation.ts"
143
+ import type { Activation } from "./activation.ts"
144
+ import type { AppState, Ids, Level } from "./context.ts"
145
+ import { track, type Source } from "./store.ts"
146
+
147
+ export { default as Link } from "./Link.svelte"
148
+ import LinkComponent from "./Link.svelte"
149
+ export { default as Form } from "./Form.svelte"
150
+ export { default as ClientFallback } from "./ClientFallback.svelte"
151
+ export { default as ClientOnly } from "./ClientOnly.svelte"
152
+ export { default as DevOnly } from "./DevOnly.svelte"
153
+ export { default as Await } from "./Await.svelte"
154
+ export { useDeferred } from "./deferred.svelte.ts"
155
+ export type { Deferred } from "./deferred.svelte.ts"
156
+ export { default as Navigate } from "./Navigate.svelte"
157
+ export { default as Time } from "./Time.svelte"
158
+ export { default as LoadingIndicator } from "./LoadingIndicator.svelte"
159
+ export { default as RouteAnnouncer } from "./RouteAnnouncer.svelte"
160
+ export { default as Announcer } from "./Announcer.svelte"
161
+ export { default as HttpHeader } from "./HttpHeader.svelte"
162
+ export { default as HeadTitle } from "./HeadTitle.svelte"
163
+ export { default as HeadMeta } from "./HeadMeta.svelte"
164
+ export { default as HeadLink } from "./HeadLink.svelte"
165
+ export { default as HeadScript } from "./HeadScript.svelte"
166
+ export { default as HeadStyle } from "./HeadStyle.svelte"
167
+ export { default as HtmlAttrs } from "./HtmlAttrs.svelte"
168
+ export { default as BodyAttrs } from "./BodyAttrs.svelte"
169
+ export { default as HttpStatusCode } from "./HttpStatusCode.svelte"
170
+ export { default as Outlet } from "./Outlet.svelte"
171
+ export { default as ErrorBoundary } from "./ErrorBoundary.svelte"
172
+ export { default as DefaultErrorPage } from "./DefaultErrorPage.svelte"
173
+ export {
174
+ addRouteMiddleware,
175
+ clearError,
176
+ disableScrollHandling,
177
+ forbidden,
178
+ navigateTo,
179
+ notFound,
180
+ permanentRedirect,
181
+ refreshCookie,
182
+ setPageLayout,
183
+ showError,
184
+ unauthorized,
185
+ } from "hamur/app"
186
+ export { defineLazyHydrationComponent } from "./lazy-hydration.ts"
187
+ export { default as Island } from "./Island.svelte"
188
+ export { default as ServerIsland } from "./ServerIsland.svelte"
189
+ export { default as MarkdownRenderer } from "./MarkdownRenderer.svelte"
190
+ import { layoutOf, layoutSegments, matchesOf, routeDataOf } from "hamur/adapter"
191
+ import { equalSearch, isOnline, pollInterval, resolveRelative, startPoll, subscribeOnline } from "hamur/adapter"
192
+ import type { SetSearch } from "hamur/adapter"
193
+ import { createAppUpdate } from "hamur/adapter"
194
+ import type { AppUpdateActions, AppUpdateState } from "hamur/adapter"
195
+ import type { MatchedRoute, RouteDataName, RouteDataOf, RouteError, RouteFor, RouteName } from "hamur/adapter"
196
+ export type { MatchedRoute, RouteDataName, RouteDataOf } from "hamur/adapter"
197
+ export type { NavigateToOptions, PickFrom } from "hamur/app"
198
+ export type { LoadingIndicatorProps } from "hamur/adapter"
199
+ export type { Blocker, BlockerArgs, SnapshotOptions, UseBlockerOptions } from "hamur/adapter"
200
+ export type {
201
+ AfterNavigateHook,
202
+ AsyncDataHandler,
203
+ BeforeNavigateHook,
204
+ ErrorBoundaryFallbackProps,
205
+ FetchRequest,
206
+ GetCachedData,
207
+ GetCachedDataCause,
208
+ NavigateHook,
209
+ NavigateOptions,
210
+ Navigation,
211
+ NavigationState,
212
+ NavigationType,
213
+ RouteValue,
214
+ RouterApi,
215
+ } from "hamur/adapter"
216
+ export type { LinkDefaults, LinkSlot, UseLinkOptions } from "hamur/adapter"
217
+
218
+ export function useRoute<N extends RouteName>(name: N): RouteFor<N>
219
+ export function useRoute<N extends RouteName = never>(): RouteFor<N>
220
+ export function useRoute(): RouteValue
221
+ export function useRoute(name?: string): RouteValue {
222
+ const read = useAppState("useRoute")
223
+ const level = getContext<Level | undefined>(LEVEL_KEY)
224
+ const route = () => level?.route ?? read().route
225
+ return {
226
+ get path() {
227
+ return route().path
228
+ },
229
+ get fullPath() {
230
+ return route().fullPath
231
+ },
232
+ get params() {
233
+ return route().params
234
+ },
235
+ get query() {
236
+ return route().query
237
+ },
238
+ get search() {
239
+ return route().search
240
+ },
241
+ get hash() {
242
+ return route().hash
243
+ },
244
+ get name() {
245
+ return route().name
246
+ },
247
+ get meta() {
248
+ return route().meta
249
+ },
250
+ get matched() {
251
+ return route().matched
252
+ },
253
+ get groups() {
254
+ return route().groups ?? []
255
+ },
256
+ get status() {
257
+ return route().status
258
+ },
259
+ get error() {
260
+ return route().error
261
+ },
262
+ get renderMode() {
263
+ return route().renderMode
264
+ },
265
+ get state() {
266
+ return route().state
267
+ },
268
+ get key() {
269
+ return route().key
270
+ },
271
+ get navigationType() {
272
+ return route().navigationType
273
+ },
274
+ get mask() {
275
+ return route().mask
276
+ },
277
+ } as RouteValue
278
+ }
279
+
280
+ export function useRouter(): RouterApi {
281
+ const read = useAppState("useRouter")
282
+ return new Proxy({} as RouterApi, {
283
+ get(_, name) {
284
+ const router = read().router
285
+ const value = Reflect.get(router, name)
286
+ return typeof value === "function" ? value.bind(router) : value
287
+ },
288
+ })
289
+ }
290
+
291
+ export function useData<T = unknown>(...unknownRoute: UseDataArgs<T>): { readonly value: RouteLoaderData<T> } {
292
+ const read = useAppState("useData")
293
+ const level = getContext<Level | undefined>(LEVEL_KEY)
294
+ return {
295
+ get value() {
296
+ const state = read()
297
+ const id = level?.id
298
+ return (id === undefined ? null : (state.data[id] ?? null)) as RouteLoaderData<T>
299
+ },
300
+ }
301
+ }
302
+
303
+ export function useRouteData<N extends RouteDataName>(name: N): { readonly value: RouteDataOf<N> } {
304
+ const read = useAppState("useRouteData")
305
+ return {
306
+ get value() {
307
+ const state = read()
308
+ return routeDataOf(state.route, state.data, name) as RouteDataOf<N>
309
+ },
310
+ }
311
+ }
312
+
313
+ export function useOutletContext<T = unknown>(): { readonly value: T } {
314
+ const above = getContext<{ readonly value: unknown } | undefined>(OUTLET_VALUE_KEY)
315
+ return {
316
+ get value() {
317
+ return above?.value as T
318
+ },
319
+ }
320
+ }
321
+
322
+ export function useLayoutSegments(): { readonly value: string[] } {
323
+ const read = useAppState("useLayoutSegments")
324
+ const level = getContext<Level | undefined>(LEVEL_KEY)
325
+ return {
326
+ get value() {
327
+ return layoutSegments(read().route, level?.id)
328
+ },
329
+ }
330
+ }
331
+
332
+ export function useLayoutSegment(): { readonly value: string | null } {
333
+ const segments = useLayoutSegments()
334
+ return {
335
+ get value() {
336
+ return segments.value[0] ?? null
337
+ },
338
+ }
339
+ }
340
+
341
+ export function useLayout(): { readonly value: { name: string | false; props: Record<string, unknown> } } {
342
+ const read = useAppState("useLayout")
343
+ return {
344
+ get value() {
345
+ return layoutOf(read())
346
+ },
347
+ }
348
+ }
349
+
350
+ export function useMatches(): { readonly value: MatchedRoute[] } {
351
+ const read = useAppState("useMatches")
352
+ return {
353
+ get value() {
354
+ const state = read()
355
+ return matchesOf(state.route, state.data)
356
+ },
357
+ }
358
+ }
359
+
360
+ export function useError(): { readonly value: RouteError | undefined }
361
+ export function useError(): { readonly value: ErrorPageProps | undefined } {
362
+ const read = useAppState("useError")
363
+ const own = getContext<ErrorPageProps | undefined>(ERROR_KEY)
364
+ return {
365
+ get value() {
366
+ return own ?? errorOf(read())
367
+ },
368
+ }
369
+ }
370
+
371
+ export function useApp(): AppContext {
372
+ return useAppState("useApp")().app
373
+ }
374
+
375
+ export function useRuntimeHook<K extends keyof AppHooks>(name: K, fn: AppHooks[K]): void {
376
+ onDestroy(useApp().hooks.hook(name, fn))
377
+ }
378
+
379
+ export function useReportWebVitals(fn: (metric: WebVitalMetric) => void | Promise<void>): void {
380
+ onDestroy(reportWebVitals(useApp(), fn))
381
+ }
382
+
383
+ export function onAppReady(fn: () => void | Promise<void>): void {
384
+ const app = useApp()
385
+ onMount(() => whenAppReady(app, fn))
386
+ }
387
+
388
+ export function onPrehydrate(fn: (el: Element) => void): string | undefined {
389
+ return prehydrate(useApp(), fn)
390
+ }
391
+
392
+ export function useRouteAnnouncer(): RouteAnnouncerState & RouteAnnouncerActions {
393
+ const store = createRouteAnnouncer(useApp())
394
+ const subscribe = createSubscriber((update) => store.subscribe(update))
395
+ const read = <K extends keyof RouteAnnouncerState>(key: K): RouteAnnouncerState[K] => {
396
+ subscribe()
397
+ return store.get()[key]
398
+ }
399
+ return {
400
+ get message() {
401
+ return read("message")
402
+ },
403
+ get politeness() {
404
+ return read("politeness")
405
+ },
406
+ set: store.set,
407
+ polite: store.polite,
408
+ assertive: store.assertive,
409
+ }
410
+ }
411
+
412
+ export function useAnnouncer({ politeness = "polite" }: { politeness?: AnnouncerPoliteness } = {}): Pick<
413
+ AnnouncerState,
414
+ "message" | "politeness"
415
+ > &
416
+ AnnouncerActions {
417
+ const store = createAnnouncer(useApp())
418
+ const subscribe = createSubscriber((update) => store.subscribe(update))
419
+ const read = <K extends "message" | "politeness">(key: K): AnnouncerState[K] => {
420
+ subscribe()
421
+ return store.get()[key]
422
+ }
423
+ return {
424
+ get message() {
425
+ return read("message")
426
+ },
427
+ get politeness() {
428
+ return read("politeness")
429
+ },
430
+ ...announcerActions(store, politeness),
431
+ }
432
+ }
433
+
434
+ export function useRequestEvent(): HamurEvent | undefined {
435
+ return requestEventOf(useApp())
436
+ }
437
+
438
+ /** Preview mode: enabled by the payload's `draft` or by `?preview=true` on the first URL; `state` is the app's own store for preview values. */
439
+ export function usePreviewMode(): PreviewMode {
440
+ return previewModeOf(useApp())
441
+ }
442
+
443
+ export function useRequestHeaders(names?: readonly string[]): Record<string, string> {
444
+ return requestHeadersOf(useApp(), names)
445
+ }
446
+
447
+ export function useRequestHeader(name: string): string | undefined {
448
+ return requestHeaderOf(useApp(), name)
449
+ }
450
+
451
+ export function useRequestURL(): URL {
452
+ return requestURLOf(useApp())
453
+ }
454
+
455
+ export function useRequestFetch(): $Fetch {
456
+ return requestFetchOf(useApp())
457
+ }
458
+
459
+ export function setResponseStatus(status: number, statusText?: string): void {
460
+ setResponseStatusOf(useApp(), status, statusText)
461
+ }
462
+
463
+ export function useResponseHeader(name: string): { value: string | undefined } {
464
+ const header = responseHeaderOf(useApp(), name)
465
+ return {
466
+ get value() {
467
+ return header.get()
468
+ },
469
+ set value(next: string | undefined) {
470
+ header.set(next)
471
+ },
472
+ }
473
+ }
474
+
475
+ export function useAsyncDataEntry<T = unknown>(key: string): { data: T | undefined }
476
+ export function useAsyncDataEntry<I, O>(fn: Handler<I, O>, input?: I): { data: O | undefined }
477
+ export function useAsyncDataEntry<T = unknown>(
478
+ target: string | HandlerReference,
479
+ input?: unknown,
480
+ ): { data: T | undefined } {
481
+ const key = typeof target === "string" ? target : asyncDataKey(target, input)
482
+ const store = useApp().asyncData
483
+ const subscribe = createSubscriber((update) => store.subscribe(key, update))
484
+ return {
485
+ get data() {
486
+ subscribe()
487
+ return store.get<T>(key)?.data
488
+ },
489
+ set data(next: T | undefined) {
490
+ store.setData(key, next)
491
+ },
492
+ }
493
+ }
494
+
495
+ export function clearState(keys?: Parameters<typeof clearStateOf>[1], options?: { reset?: boolean }): void {
496
+ clearStateOf(useApp(), keys, options)
497
+ }
498
+
499
+ export function callOnce(
500
+ key: string,
501
+ fn: () => unknown | Promise<unknown>,
502
+ options?: { mode?: "render" | "navigation" },
503
+ ): Promise<void> {
504
+ return callOnceOf(useApp(), key, fn, options)
505
+ }
506
+
507
+ export function useRuntimeConfig(): ClientRuntimeConfig {
508
+ return runtimeConfigOf(useApp())
509
+ }
510
+
511
+ export function useSiteConfig(): SiteConfig {
512
+ return siteConfigOf(useApp())
513
+ }
514
+
515
+ export const onBeforeNavigate = (fn: BeforeNavigateHook): void => onMount(() => navigationHook("before", fn))
516
+ export const onNavigate = (fn: NavigateHook): void => onMount(() => navigationHook("navigate", fn))
517
+ export const onAfterNavigate = (fn: AfterNavigateHook): void => onMount(() => navigationHook("after", fn))
518
+
519
+ /** Runs `fn` after the component mounts and each time its kept page is shown again. */
520
+ export function onPageActivated(fn: () => void): void {
521
+ const own = getContext<Activation | undefined>(ACTIVATION_KEY)
522
+ onMount(() => {
523
+ if (shown(own)) later(true, fn)
524
+ own?.on.add(fn)
525
+ return () => void own?.on.delete(fn)
526
+ })
527
+ }
528
+
529
+ /** Runs `fn` each time its kept page is hidden and when the component unmounts on screen. */
530
+ export function onPageDeactivated(fn: () => void): void {
531
+ const own = getContext<Activation | undefined>(ACTIVATION_KEY)
532
+ onMount(() => {
533
+ own?.off.add(fn)
534
+ return () => {
535
+ own?.off.delete(fn)
536
+ if (shown(own)) later(false, fn)
537
+ }
538
+ })
539
+ }
540
+
541
+ export function onBeforeRouteLeave(fn: NavigationGuard): void {
542
+ const level = getContext<Level | undefined>(LEVEL_KEY)
543
+ onMount(() => routeGuard("leave", level?.id, fn))
544
+ }
545
+
546
+ export function onBeforeRouteUpdate(fn: NavigationGuard): void {
547
+ const level = getContext<Level | undefined>(LEVEL_KEY)
548
+ onMount(() => routeGuard("update", level?.id, fn))
549
+ }
550
+
551
+ export const usePreventNavigate = (fn: NavigationBlocker): void => onMount(() => navigationBlocker(fn))
552
+
553
+ export function useBlocker(options: ShouldBlock | UseBlockerOptions): Blocker {
554
+ const store = createBlocker(options)
555
+ const subscribe = createSubscriber((update) => store.subscribe(update))
556
+ onMount(() => store.start())
557
+ watch(() => store.sync())
558
+ return {
559
+ get state() {
560
+ subscribe()
561
+ return store.get().state
562
+ },
563
+ get location() {
564
+ subscribe()
565
+ return store.get().location
566
+ },
567
+ proceed: () => store.get().proceed(),
568
+ reset: () => store.get().reset(),
569
+ }
570
+ }
571
+
572
+ export const useSnapshot = <T>(key: string, options: SnapshotOptions<T>): void =>
573
+ onMount(() => registerSnapshot(key, options))
574
+
575
+ export function useLoadingIndicator(
576
+ options?: LoadingIndicatorOptions,
577
+ ): LoadingIndicatorState & LoadingIndicatorActions {
578
+ const store = createLoadingIndicator(useApp(), options)
579
+ const navigation = useAppState("useLoadingIndicator")().navigation
580
+ const subscribe = createSubscriber((update) => store.subscribe(update))
581
+ onMount(() => store.follow(navigation))
582
+ const read = <K extends keyof LoadingIndicatorState>(key: K): LoadingIndicatorState[K] => {
583
+ subscribe()
584
+ return store.get()[key]
585
+ }
586
+ return {
587
+ get progress() {
588
+ return read("progress")
589
+ },
590
+ get isLoading() {
591
+ return read("isLoading")
592
+ },
593
+ get error() {
594
+ return read("error")
595
+ },
596
+ start: store.start,
597
+ finish: store.finish,
598
+ set: store.set,
599
+ clear: store.clear,
600
+ }
601
+ }
602
+
603
+ export function useAppUpdate(): AppUpdateState & AppUpdateActions {
604
+ const store = createAppUpdate(useApp())
605
+ const subscribe = createSubscriber((update) => store.subscribe(update))
606
+ const read = <K extends keyof AppUpdateState>(key: K): AppUpdateState[K] => {
607
+ subscribe()
608
+ return store.get()[key]
609
+ }
610
+ return {
611
+ get available() {
612
+ return read("available")
613
+ },
614
+ get buildId() {
615
+ return read("buildId")
616
+ },
617
+ get time() {
618
+ return read("time")
619
+ },
620
+ check: store.check,
621
+ }
622
+ }
623
+
624
+ export function useNavigation(): NavigationState {
625
+ const navigation = useAppState("useNavigation")().navigation
626
+ const subscribe = createSubscriber((update) => navigation.subscribe(update))
627
+ const read = <K extends keyof NavigationState>(key: K): NavigationState[K] => {
628
+ subscribe()
629
+ return navigation.get()[key]
630
+ }
631
+ return {
632
+ get state() {
633
+ return read("state")
634
+ },
635
+ get to() {
636
+ return read("to")
637
+ },
638
+ get type() {
639
+ return read("type")
640
+ },
641
+ get from() {
642
+ return read("from")
643
+ },
644
+ get complete() {
645
+ return read("complete")
646
+ },
647
+ get revalidation() {
648
+ return read("revalidation")
649
+ },
650
+ get pending() {
651
+ return read("pending")
652
+ },
653
+ }
654
+ }
655
+
656
+ /** A `Link` with `defaults` over `app.link`; a prop of the element wins. */
657
+ export function defineLink(defaults: LinkDefaults): typeof LinkComponent {
658
+ const bound = (anchor: unknown, props: object) =>
659
+ (LinkComponent as unknown as (anchor: unknown, props: object) => unknown)(
660
+ anchor,
661
+ new Proxy(props, {
662
+ get: (target, key, receiver) => (key === "defaults" ? defaults : Reflect.get(target, key, receiver)),
663
+ }),
664
+ )
665
+ return bound as never
666
+ }
667
+
668
+ /** The `LinkSlot` of a link to `to` as getters, for an element that renders its own `<a>`; `to` and `options` may be functions. `app.link` sets its defaults. */
669
+ export function useLink<T extends string = string>(
670
+ to: CheckedTarget<T> | RouteLocation | (() => CheckedTarget<T> | RouteLocation),
671
+ options?: UseLinkOptions | (() => UseLinkOptions),
672
+ ): Readonly<LinkSlot> {
673
+ const source = getContext<Source<AppState> | undefined>(APP_KEY)
674
+ const read = source && track(source)
675
+ const level = getContext<Level | undefined>(LEVEL_KEY)
676
+ const subscribeNavigation = createSubscriber((update) => source?.get().navigation?.subscribe(update) ?? (() => {}))
677
+ const slot = (): LinkSlot => {
678
+ subscribeNavigation()
679
+ const app = read?.()
680
+ const given = (typeof options === "function" ? options() : options) ?? {}
681
+ const base = (typeof to === "function" ? to() : to) as string | RouteLocation
682
+ const searched = app
683
+ ? searchTarget(relativeTarget(base, level?.route ?? app.route, given.relative), app.route, given.query as never)
684
+ : base
685
+ const { to: target } = resolveLinkTarget(app?.app, searched, given, app?.href, given.external)
686
+ const href = app ? app.href(target) : detachedHref(target)
687
+ const current = app
688
+ ? linkState(typeof target === "string" ? target : withoutBase(href, app.baseURL), app.route)
689
+ : { active: false, exact: false }
690
+ const defaults = linkDefaultsOf(app?.app)
691
+ return createLinkSlot({
692
+ href,
693
+ to: target,
694
+ attrs: linkAttributes({
695
+ href,
696
+ external: given.external,
697
+ ...linkPrefetchProps({}, defaults),
698
+ replace: given.replace,
699
+ viewTransition: given.viewTransition,
700
+ pendingClass: defaults.pendingClass,
701
+ trim: !!given.query,
702
+ ariaCurrent: current.exact ? "page" : undefined,
703
+ prefetchedClass: defaults.prefetchedClass,
704
+ scroll: given.scroll,
705
+ prefetchDelay: defaults.prefetchDelay,
706
+ externalRelAttribute: defaults.externalRelAttribute,
707
+ }),
708
+ active: current.active,
709
+ exact: current.exact,
710
+ pending: !!app && linkPending(href, app.navigation.get(), app.baseURL),
711
+ external: given.external,
712
+ options: {
713
+ replace: given.replace,
714
+ state: given.state,
715
+ viewTransition: given.viewTransition,
716
+ scroll: given.scroll === false ? false : undefined,
717
+ },
718
+ router: app?.router ?? null,
719
+ })
720
+ }
721
+ return {
722
+ get href() {
723
+ return slot().href
724
+ },
725
+ get attrs() {
726
+ return slot().attrs
727
+ },
728
+ get active() {
729
+ return slot().active
730
+ },
731
+ get exact() {
732
+ return slot().exact
733
+ },
734
+ get pending() {
735
+ return slot().pending
736
+ },
737
+ navigate: (event) => slot().navigate(event),
738
+ prefetch: () => slot().prefetch(),
739
+ }
740
+ }
741
+
742
+ /** Inside a `Link`'s children, whether a navigation to that link is in flight; `pending` is false anywhere else. */
743
+ export function useLinkStatus(): { readonly pending: boolean } {
744
+ const href = getContext<(() => string) | undefined>(LINK_KEY)
745
+ const app = getContext<Source<AppState> | undefined>(APP_KEY)?.get()
746
+ const navigation = app?.navigation
747
+ const subscribe = createSubscriber((update) => navigation?.subscribe(update) ?? (() => {}))
748
+ return {
749
+ get pending() {
750
+ subscribe()
751
+ return !!href && !!navigation && linkPending(href(), navigation.get(), app?.baseURL ?? "/")
752
+ },
753
+ }
754
+ }
755
+
756
+ export function useResolvedPath(
757
+ to: string | (() => string),
758
+ { relative }: { relative?: "route" } = {},
759
+ ): { readonly value: string } {
760
+ const route = useRoute()
761
+ return {
762
+ get value() {
763
+ return resolveRelative(typeof to === "function" ? to() : to, route, relative)
764
+ },
765
+ }
766
+ }
767
+
768
+ export function useSearch(): { readonly value: RouteValue["search"]; set: SetSearch }
769
+ export function useSearch<S>(select: (search: RouteValue["search"]) => S): { readonly value: S; set: SetSearch }
770
+ export function useSearch<S>(select?: (search: RouteValue["search"]) => S): {
771
+ readonly value: S | RouteValue["search"]
772
+ set: SetSearch
773
+ } {
774
+ const read = useAppState("useSearch")
775
+ const router = useRouter()
776
+ let shown: { search: unknown; value: S | RouteValue["search"] } | undefined
777
+ const set: SetSearch = (change, { replace = true } = {}) => {
778
+ const update = { query: (prev: RouteValue["search"]) => (typeof change === "function" ? change(prev) : change) }
779
+ return replace ? router.replace(update) : router.navigate(update)
780
+ }
781
+ return {
782
+ get value() {
783
+ const search = read().route.search
784
+ if (shown?.search === search) return shown.value
785
+ const next = select ? select(search) : search
786
+ shown = { search, value: shown && equalSearch(shown.value, next) ? shown.value : next }
787
+ return shown.value
788
+ },
789
+ set,
790
+ }
791
+ }
792
+
793
+ export function usePoll(ms: number, options: { keys?: string[] } = {}): void {
794
+ pollInterval(ms)
795
+ const router = useRouter()
796
+ onMount(() => startPoll(ms, () => (options.keys ? router.refresh(options.keys) : router.refresh())))
797
+ }
798
+
799
+ export function useOnline(): { readonly value: boolean } {
800
+ let mounted = false
801
+ const subscribe = createSubscriber((update) => {
802
+ mounted = true
803
+ update()
804
+ return subscribeOnline(() => update())
805
+ })
806
+ onMount(() => void (mounted = true))
807
+ return {
808
+ get value() {
809
+ subscribe()
810
+ return mounted ? isOnline() : true
811
+ },
812
+ }
813
+ }
814
+
815
+ export function useSyncedState<T>(key: string, initial: T, options: SyncedStateOptions = {}): { value: T } {
816
+ const state = syncedState(key, initial, options)
817
+ let mounted = false
818
+ const subscribe = createSubscriber((update) => {
819
+ mounted = true
820
+ const off = state.subscribe(() => update())
821
+ update()
822
+ return off
823
+ })
824
+ onMount(() => void (mounted = true))
825
+ return {
826
+ get value() {
827
+ subscribe()
828
+ return mounted ? state.get() : initial
829
+ },
830
+ set value(next: T) {
831
+ state.set(next)
832
+ },
833
+ }
834
+ }
835
+
836
+ export function useId(): string {
837
+ const ids = getContext<Ids | undefined>(IDS_KEY)
838
+ if (!ids) throw new Error("useId() must be called inside a Hamur app")
839
+ return nextId(ids)
840
+ }
841
+
842
+ export function useHydrated(): { readonly current: boolean } {
843
+ const app = useApp()
844
+ const subscribe = createSubscriber((update) => app.hooks.hook("app:mounted", () => update()))
845
+ return {
846
+ get current() {
847
+ subscribe()
848
+ return !isServer && !app.asyncData.hydrating
849
+ },
850
+ }
851
+ }
852
+
853
+ export function useFormStatus(): Readonly<FormStatus> {
854
+ const store = getContext<FormStatusStore | null | undefined>(FORM_STATUS_KEY)
855
+ const subscribe = createSubscriber((update) => store?.subscribe(update))
856
+ const read = () => {
857
+ subscribe()
858
+ return store ? store.get() : IDLE_FORM_STATUS
859
+ }
860
+ return {
861
+ get pending() {
862
+ return read().pending
863
+ },
864
+ get data() {
865
+ return read().data
866
+ },
867
+ get action() {
868
+ return read().action
869
+ },
870
+ }
871
+ }
872
+
873
+ export function useForm<I, O>(fn: Handler<I, O>): HandlerForm<I, O> {
874
+ const read = useAppState("useForm")
875
+ const form: HandlerForm<I, O> = createForm(fn, {
876
+ app: untrack(read).app,
877
+ submitted: () => untrack(read),
878
+ track: () => subscribe(),
879
+ })
880
+ const subscribe = createSubscriber((update) => form.subscribe(update))
881
+ return form
882
+ }
883
+
884
+ export function useAction<I, O>(
885
+ fn: Handler<I, O>,
886
+ options: ActionOptions<O> & { instance?: string | number } = {},
887
+ ): {
888
+ readonly run: ActionRunner<I, O>["run"]
889
+ readonly state: O | undefined
890
+ readonly pending: boolean
891
+ readonly error: HamurError | undefined
892
+ readonly failure: ActionFailure | undefined
893
+ reset(): void
894
+ } {
895
+ const read = useAppState("useAction")
896
+ const { handlerState } = untrack(read)
897
+ const { instance } = options
898
+ const runner = createActionRunner(fn, {
899
+ app: untrack(read).app,
900
+ instance,
901
+ options: () => options,
902
+ refresh: () => read().router.refresh(),
903
+ restored: restoredResult<O>(handlerState, fn.id, instance),
904
+ })
905
+ const below = getContext<FormStatusStore | null | undefined>(FORM_STATUS_KEY)
906
+ onDestroy(
907
+ below ? below.owner.link(fn.id, runner, instance) : linkActionRunner(untrack(read).app, fn.id, runner, instance),
908
+ )
909
+ const subscribe = createSubscriber((update) => runner.subscribe(update))
910
+ const action = { run: runner.run, reset: runner.reset }
911
+ for (const field of ["state", "pending", "error", "failure"] as const)
912
+ Object.defineProperty(action, field, {
913
+ get: () => {
914
+ subscribe()
915
+ return runner.get()[field]
916
+ },
917
+ enumerable: true,
918
+ })
919
+ return action as ReturnType<typeof useAction<I, O>>
920
+ }
921
+
922
+ export function useOptimistic<T, A = PendingRun>(
923
+ value: T | (() => T),
924
+ reduce: (current: T, pending: A[]) => T,
925
+ ): { readonly value: T } {
926
+ const source = optimisticSource(useAppState("useOptimistic")().app)
927
+ const subscribe = createSubscriber((update) => source.subscribe(update))
928
+ return {
929
+ get value() {
930
+ subscribe()
931
+ const current = typeof value === "function" ? (value as () => T)() : value
932
+ const pending = source.get()
933
+ return pending.length ? reduce(current, pending as unknown as A[]) : current
934
+ },
935
+ }
936
+ }
937
+
938
+ export function useHead(input: HeadInput | (() => HeadInput)): void {
939
+ const read = useAppState("useHead")
940
+ const resolve = () => (typeof input === "function" ? input() : input)
941
+ const head = read().head
942
+ if (typeof document === "undefined") {
943
+ head.push(resolve())
944
+ return
945
+ }
946
+ let entry: HeadEntry | undefined
947
+ watchPre(() => {
948
+ entry = head.push(untrack(resolve))
949
+ return () => {
950
+ entry?.dispose()
951
+ entry = undefined
952
+ head.apply()
953
+ }
954
+ })
955
+ watch(() => {
956
+ entry?.patch(resolve())
957
+ head.apply()
958
+ })
959
+ }
960
+
961
+ export function useSeoMeta(input: SeoMetaInput | (() => SeoMetaInput)): void {
962
+ useHead(() => seoMetaToHead(typeof input === "function" ? input() : input))
963
+ }
964
+
965
+ type ServerHeadInput = Omit<HeadInput, "title" | "titleTemplate">
966
+ type ServerSeoMetaInput = Omit<SeoMetaInput, "title" | "titleTemplate">
967
+
968
+ export function useHeadSafe(input: HeadSafeInput | (() => HeadSafeInput)): void {
969
+ useHead(() => sanitizeHead(typeof input === "function" ? input() : input))
970
+ }
971
+
972
+ export function useServerHead(input: ServerHeadInput | (() => ServerHeadInput)): void {
973
+ if (typeof document !== "undefined") return
974
+ useAppState("useServerHead")().head.push(typeof input === "function" ? input() : input, { server: true })
975
+ }
976
+
977
+ export function useServerSeoMeta(input: ServerSeoMetaInput | (() => ServerSeoMetaInput)): void {
978
+ useServerHead(() => seoMetaToHead(typeof input === "function" ? input() : input))
979
+ }
980
+
981
+ export function useState<T>(key: StateKey<T>): { value: T }
982
+ export function useState<T = unknown>(key: string, init?: T | (() => T)): { value: T }
983
+ export function useState<T = unknown>(...args: unknown[]): { value: T } {
984
+ const { key, init } = stateArguments(args) as { key: string; init: T | (() => T) | undefined }
985
+ const store = useAppState("useState")().app.state
986
+ if (!store) throw new Error("useState() needs the app state store")
987
+ store.use(key, init)
988
+ const subscribe = createSubscriber((update) => store.subscribe(key, update))
989
+ return {
990
+ get value() {
991
+ subscribe()
992
+ return store.get<T>(key) as T
993
+ },
994
+ set value(next: T) {
995
+ store.set(key, next)
996
+ },
997
+ }
998
+ }
999
+
1000
+ export function useCookie<T = string>(
1001
+ name: string,
1002
+ options: Omit<UseCookieOptions<T>, "app"> & { default: () => T },
1003
+ ): { value: T }
1004
+ export function useCookie<T = string>(
1005
+ name: string,
1006
+ options?: Omit<UseCookieOptions<T>, "app">,
1007
+ ): { value: T | undefined }
1008
+ export function useCookie<T = string>(
1009
+ name: string,
1010
+ options: Omit<UseCookieOptions<T>, "app"> = {},
1011
+ ): { value: T | undefined } {
1012
+ const cookie = useCookieRef<T>(name, { ...options, app: useApp() })
1013
+ const subscribe = createSubscriber((update) => cookie.subscribe(() => update()))
1014
+ return {
1015
+ get value() {
1016
+ subscribe()
1017
+ return cookie.get()
1018
+ },
1019
+ set value(next: T | undefined) {
1020
+ cookie.set(next)
1021
+ },
1022
+ }
1023
+ }
1024
+
1025
+ export interface UseAsyncDataOptions<T = unknown, R = T, K extends keyof T & string = never, D = T> extends Omit<
1026
+ AsyncDataOptions<T, R, D>,
1027
+ "pick"
1028
+ > {
1029
+ /** Getters whose change re-runs the handler. `false` is accepted and does nothing: nothing watches implicitly. */
1030
+ watch?: ReadonlyArray<() => unknown> | false
1031
+ getCachedData?: GetCachedData<T>
1032
+ /** Top-level keys of an object result to keep. */
1033
+ pick?: readonly K[]
1034
+ }
1035
+
1036
+ export interface UseAsyncDataResult<T, D = undefined> {
1037
+ readonly data: T | D
1038
+ readonly error: HamurError | undefined
1039
+ readonly status: AsyncDataStatus
1040
+ /** `status === "pending"`, or `idle` without data under `app.asyncData.pendingWhenIdle`. */
1041
+ readonly pending: boolean
1042
+ refresh(): Promise<void>
1043
+ /** The same function as `refresh`. */
1044
+ execute(): Promise<void>
1045
+ /** Resets the entry of the current key to `idle` (`clearAsyncData`). */
1046
+ clear(): void
1047
+ }
1048
+
1049
+ export interface UseFetchOptions<T = unknown, R = T, K extends keyof T & string = never, D = T>
1050
+ extends FetchRequest, UseAsyncDataOptions<T, R, K, D> {
1051
+ /** The store key, instead of the one derived from the url and the request. */
1052
+ key?: string
1053
+ }
1054
+
1055
+ const isServer = typeof document === "undefined"
1056
+
1057
+ export function useAsyncData<I, R, T = R, K extends keyof T & string = never, D = T>(
1058
+ fn: Handler<I, R>,
1059
+ input: NoInfer<I> | (() => NoInfer<I>) | undefined,
1060
+ options: UseAsyncDataOptions<T, R, K, D> & { default: () => D },
1061
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1062
+ export function useAsyncData<I, R, T = R, K extends keyof T & string = never>(
1063
+ fn: Handler<I, R>,
1064
+ input?: NoInfer<I> | (() => NoInfer<I>),
1065
+ options?: UseAsyncDataOptions<T, R, K, undefined>,
1066
+ ): UseAsyncDataResult<PickFrom<T, K>>
1067
+ export function useAsyncData<T = unknown, R = T, K extends keyof T & string = never, D = T>(
1068
+ key: string | (() => string),
1069
+ handler: AsyncDataHandler<R>,
1070
+ options: UseAsyncDataOptions<T, R, K, D> & { default: () => D },
1071
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1072
+ export function useAsyncData<T = unknown, R = T, K extends keyof T & string = never>(
1073
+ key: string | (() => string),
1074
+ handler: AsyncDataHandler<R>,
1075
+ options?: UseAsyncDataOptions<T, R, K, undefined>,
1076
+ ): UseAsyncDataResult<PickFrom<T, K>>
1077
+ export function useAsyncData(...args: unknown[]): UseAsyncDataResult<any, any> {
1078
+ const [first, second, given] = asyncDataArguments("useAsyncData", args) as [
1079
+ string | (() => string) | HandlerReference,
1080
+ unknown,
1081
+ UseAsyncDataOptions<any, any, any, any> | undefined,
1082
+ ]
1083
+ const options = given ?? {}
1084
+ if (!isHandlerReference(first))
1085
+ return keyedAsyncData(first as string | (() => string), () => second as AsyncDataHandler<unknown>, options)
1086
+ const { keyOf, handlerFor } = handlerSlots<unknown>(useApp(), first as HandlerReference, second)
1087
+ return keyedAsyncData(keyOf, handlerFor, options)
1088
+ }
1089
+
1090
+ function keyedAsyncData<T, R, K extends keyof T & string = never, D = T>(
1091
+ key: string | (() => string),
1092
+ handlerFor: (key: string) => AsyncDataHandler<R>,
1093
+ options: UseAsyncDataOptions<T, R, K, D>,
1094
+ ): UseAsyncDataResult<PickFrom<T, K>, D> {
1095
+ const app = useApp()
1096
+ const store = app.asyncData
1097
+ const never = getContext<boolean | undefined>(NEVER_HYDRATED_KEY) === true
1098
+ const {
1099
+ server,
1100
+ lazy,
1101
+ default: init,
1102
+ transform,
1103
+ immediate,
1104
+ dedupe,
1105
+ pick,
1106
+ watch: sources,
1107
+ getCachedData = defaultGetCachedData,
1108
+ } = options
1109
+ const settings = {
1110
+ server,
1111
+ lazy,
1112
+ default: init as AsyncDataOptions<T, R>["default"],
1113
+ transform,
1114
+ immediate,
1115
+ dedupe,
1116
+ pick,
1117
+ }
1118
+ const fetchWith = (name: string, cached: T | undefined) => {
1119
+ store.neverHydrated(name, never)
1120
+ keepCached(app, name, getCachedData)
1121
+ return store.fetch<T, R>(name, handlerFor(name), { ...settings, cached })
1122
+ }
1123
+ const initial = (name: string) => fetchWith(name, getCachedData(name, app, { cause: "initial" }))
1124
+ const again = (cause: GetCachedDataCause) =>
1125
+ refreshCached(app, active, handlerFor(active), settings, getCachedData, cause)
1126
+ let active = valueOf(key)
1127
+ if (initial(active).status === "pending" && isServer) markWaiting(store)
1128
+ const hold = (name: string) => (isServer ? () => {} : store.subscribe(name, () => {}))
1129
+ let held = hold(active)
1130
+ let unhook = store.onRefresh(active, () => again("refresh:hook"))
1131
+ onDestroy(() => unhook())
1132
+ if (!isServer) onDestroy(() => held())
1133
+ const idle: AsyncDataEntry<T> = {
1134
+ data: init?.() as T | undefined,
1135
+ error: undefined,
1136
+ status: "idle",
1137
+ promise: undefined,
1138
+ }
1139
+ let rekey: (() => void) | undefined
1140
+ const subscribe = createSubscriber((update) => {
1141
+ let unsubscribe = store.subscribe(active, update)
1142
+ rekey = () => {
1143
+ unsubscribe()
1144
+ unsubscribe = store.subscribe(active, update)
1145
+ update()
1146
+ }
1147
+ return () => {
1148
+ unsubscribe()
1149
+ rekey = undefined
1150
+ }
1151
+ })
1152
+ const read = () => {
1153
+ subscribe()
1154
+ return store.get<T>(active) ?? idle
1155
+ }
1156
+ if (typeof key === "function") {
1157
+ watchPre(() => {
1158
+ const next = key()
1159
+ if (next === active) return
1160
+ active = next
1161
+ untrack(() => initial(next))
1162
+ const previous = held
1163
+ held = hold(next)
1164
+ unhook()
1165
+ unhook = store.onRefresh(next, () => again("refresh:hook"))
1166
+ previous()
1167
+ rekey?.()
1168
+ })
1169
+ }
1170
+ if (sources && sources.length) {
1171
+ let first = true
1172
+ watch(() => {
1173
+ for (const source of sources) source()
1174
+ if (first) first = false
1175
+ else void again("watch")
1176
+ })
1177
+ }
1178
+ const refresh = () => again("refresh:manual")
1179
+ return {
1180
+ get data() {
1181
+ return read().data as PickFrom<T, K> | D
1182
+ },
1183
+ get error() {
1184
+ return read().error
1185
+ },
1186
+ get status() {
1187
+ return read().status
1188
+ },
1189
+ get pending() {
1190
+ return isPending(app, read())
1191
+ },
1192
+ refresh,
1193
+ execute: refresh,
1194
+ clear: () => clearAsyncData(app, active),
1195
+ }
1196
+ }
1197
+
1198
+ /** What a literal `useFetch` call is checked against; any other call stays loose. */
1199
+ type FetchInput<X> = X extends { key: infer K extends string; input: infer I }
1200
+ ? FetchInputField<I, K, I | (() => I)>
1201
+ : unknown
1202
+ type Unkeyed<O, X> = X extends { key: infer K extends string } ? Omit<O, K> : O
1203
+ type FetchCall<U extends string, M extends string, B extends string | undefined> = {
1204
+ method?: M | string
1205
+ baseURL?: B | string
1206
+ } & FetchInput<FetchCheckedInput<U, M, B>>
1207
+
1208
+ export function useFetch<
1209
+ U extends string,
1210
+ M extends string = "GET",
1211
+ K extends keyof FetchData<U, M> & string = never,
1212
+ D = undefined,
1213
+ B extends string | undefined = undefined,
1214
+ >(
1215
+ url: U | (() => U),
1216
+ options?: Unkeyed<UseFetchOptions<FetchData<U, M>, FetchData<U, M>, K, D>, FetchCheckedInput<U, M, B>> &
1217
+ FetchCall<U, M, B>,
1218
+ ): UseAsyncDataResult<PickFrom<FetchData<U, M>, K>, D>
1219
+ export function useFetch<
1220
+ T = unknown,
1221
+ R = T,
1222
+ K extends keyof T & string = never,
1223
+ D = T,
1224
+ U extends string = string,
1225
+ M extends string = "GET",
1226
+ B extends string | undefined = undefined,
1227
+ >(
1228
+ url: U | (() => U),
1229
+ options: Unkeyed<UseFetchOptions<T, R, K, D>, FetchCheckedInput<U, M, B>> & { default: () => D } & FetchCall<U, M, B>,
1230
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1231
+ export function useFetch<
1232
+ T = unknown,
1233
+ R = T,
1234
+ K extends keyof T & string = never,
1235
+ U extends string = string,
1236
+ M extends string = "GET",
1237
+ B extends string | undefined = undefined,
1238
+ >(
1239
+ url: U | (() => U),
1240
+ options?: Unkeyed<UseFetchOptions<T, R, K, undefined>, FetchCheckedInput<U, M, B>> & FetchCall<U, M, B>,
1241
+ ): UseAsyncDataResult<PickFrom<T, K>>
1242
+ export function useFetch<T = unknown, R = T, K extends keyof T & string = never, D = T>(
1243
+ url: string | (() => string),
1244
+ options: UseFetchOptions<T, R, K, D> = {},
1245
+ ): UseAsyncDataResult<PickFrom<T, K>, D> {
1246
+ return fetchWith<T, R, K, D>(undefined, url, options)
1247
+ }
1248
+
1249
+ function fetchWith<T, R, K extends keyof T & string, D>(
1250
+ client: $Fetch | undefined,
1251
+ url: string | (() => string),
1252
+ options: UseFetchOptions<T, R, K, D>,
1253
+ ): UseAsyncDataResult<PickFrom<T, K>, D> {
1254
+ const {
1255
+ key,
1256
+ server,
1257
+ lazy,
1258
+ default: init,
1259
+ transform,
1260
+ immediate,
1261
+ dedupe,
1262
+ pick,
1263
+ watch: sources,
1264
+ getCachedData,
1265
+ ...rest
1266
+ } = options
1267
+ const { keyOf, handlerFor } = fetchSlots<R>(url, rest, client ?? useApp().fetch, key)
1268
+ return keyedAsyncData<T, R, K, D>(keyOf, handlerFor, {
1269
+ server,
1270
+ lazy,
1271
+ default: init,
1272
+ transform,
1273
+ immediate,
1274
+ dedupe,
1275
+ pick,
1276
+ watch: sources,
1277
+ getCachedData,
1278
+ })
1279
+ }
1280
+
1281
+ /** `createUseFetch` defaults change what a call sends (method, body, query, baseURL), so its calls check nothing. */
1282
+ interface UseFetchLoose {
1283
+ <U extends string, M extends string = "GET", K extends keyof FetchData<U, M> & string = never, D = undefined>(
1284
+ url: U | (() => U),
1285
+ options?: UseFetchOptions<FetchData<U, M>, FetchData<U, M>, K, D> & { method?: M },
1286
+ ): UseAsyncDataResult<PickFrom<FetchData<U, M>, K>, D>
1287
+ <T = unknown, R = T, K extends keyof T & string = never, D = T>(
1288
+ url: string | (() => string),
1289
+ options: UseFetchOptions<T, R, K, D> & { default: () => D },
1290
+ ): UseAsyncDataResult<PickFrom<T, K>, D>
1291
+ <T = unknown, R = T, K extends keyof T & string = never>(
1292
+ url: string | (() => string),
1293
+ options?: UseFetchOptions<T, R, K, undefined>,
1294
+ ): UseAsyncDataResult<PickFrom<T, K>>
1295
+ }
1296
+
1297
+ type AnyFetchOptions = UseFetchOptions<any, any, any, any>
1298
+
1299
+ /** `useFetch` with `defaults` under every call's options; `$fetch` replaces the request-bound client, e.g. a `$fetch.create` one. */
1300
+ export function createUseFetch(
1301
+ defaults: AnyFetchOptions | ((options: AnyFetchOptions) => AnyFetchOptions),
1302
+ { $fetch: client }: { $fetch?: $Fetch } = {},
1303
+ ): UseFetchLoose {
1304
+ return ((url: string | (() => string), options?: AnyFetchOptions) =>
1305
+ fetchWith(client, url, resolveCallOptions(defaults, options))) as unknown as UseFetchLoose
1306
+ }
1307
+
1308
+ /** `useAsyncData` with `defaults` under every call's options. */
1309
+ export function createUseAsyncData(
1310
+ defaults:
1311
+ | UseAsyncDataOptions<any, any, any, any>
1312
+ | ((options: UseAsyncDataOptions<any, any, any, any>) => UseAsyncDataOptions<any, any, any, any>),
1313
+ ): typeof useAsyncData {
1314
+ return ((...args: unknown[]) => {
1315
+ const [first, second, options] = asyncDataArguments("useAsyncData", args)
1316
+ return useAsyncData(
1317
+ first as never,
1318
+ second as never,
1319
+ resolveCallOptions(defaults, options as UseAsyncDataOptions<any, any, any, any> | undefined),
1320
+ )
1321
+ }) as typeof useAsyncData
1322
+ }
1323
+
1324
+ export const useLazyFetch: typeof useFetch = ((url: string | (() => string), options?: AnyFetchOptions) =>
1325
+ useFetch(url, { ...options, lazy: true })) as typeof useFetch
1326
+
1327
+ export const useLazyAsyncData: typeof useAsyncData = ((...args: unknown[]) => {
1328
+ const [first, second, options] = asyncDataArguments("useLazyAsyncData", args)
1329
+ return useAsyncData(first as never, second as never, {
1330
+ ...(options as UseAsyncDataOptions<any, any, any, any>),
1331
+ lazy: true,
1332
+ })
1333
+ }) as typeof useAsyncData
1334
+
1335
+ export function transitionName(name: string): string {
1336
+ return `view-transition-name: ${checkTransitionName(name)}`
1337
+ }