@hamur/adapter-svelte 0.0.0-stage → 0.0.1

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 +43 -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
@@ -0,0 +1,23 @@
1
+ <script lang="ts">
2
+ import type { HTMLAttributes } from "svelte/elements"
3
+ import { timeAttributes, timeView, watchTime, type TimeInput } from "hamur/adapter"
4
+ import { useApp, useRoute } from "./index.ts"
5
+
6
+ type Props = TimeInput & Omit<HTMLAttributes<HTMLElement>, keyof TimeInput | "children">
7
+
8
+ let props: Props = $props()
9
+ const app = useApp()
10
+ const route = useRoute()
11
+ let now: number | undefined = $state()
12
+ const view = $derived(timeView(app, route.path, props, now))
13
+ const attributes = $derived(timeAttributes(props))
14
+ const interval = $derived(view.interval)
15
+ $effect(() => {
16
+ if (interval === undefined) return
17
+ return watchTime(interval, (next) => {
18
+ now = next
19
+ })
20
+ })
21
+ </script>
22
+
23
+ <time {...attributes} datetime={view.iso} data-locale={view.locale} data-time-zone={view.timeZone}>{view.text}</time>
@@ -0,0 +1,51 @@
1
+ /** The shown state of one keep-alive wrapper and the `onPageActivated`/`onPageDeactivated` functions under it. */
2
+ export interface Activation {
3
+ hidden: boolean
4
+ readonly parent: Activation | undefined
5
+ readonly children: Set<Activation>
6
+ readonly on: Set<() => void>
7
+ readonly off: Set<() => void>
8
+ }
9
+
10
+ export function activation(parent: Activation | undefined, hidden: boolean): Activation {
11
+ const own: Activation = { hidden, parent, children: new Set(), on: new Set(), off: new Set() }
12
+ parent?.children.add(own)
13
+ return own
14
+ }
15
+
16
+ export function detach(own: Activation): void {
17
+ own.parent?.children.delete(own)
18
+ }
19
+
20
+ /** Whether a page under `own` is on screen: no wrapper above it is hidden. */
21
+ export function shown(own: Activation | undefined): boolean {
22
+ return !own || (!own.hidden && shown(own.parent))
23
+ }
24
+
25
+ let queue: Array<{ shown: boolean; fn: () => void }> | undefined
26
+
27
+ /** Runs `fn` once the commit is done; within one commit every deactivation runs before any activation, so a hide comes before the show it makes room for. */
28
+ export function later(isShown: boolean, fn: () => void): void {
29
+ if (!queue) {
30
+ queue = []
31
+ queueMicrotask(() => {
32
+ const run = queue!
33
+ queue = undefined
34
+ for (const item of run) if (!item.shown) item.fn()
35
+ for (const item of run) if (item.shown) item.fn()
36
+ })
37
+ }
38
+ queue.push({ shown: isShown, fn })
39
+ }
40
+
41
+ function fire(own: Activation, isShown: boolean): void {
42
+ for (const fn of isShown ? own.on : own.off) later(isShown, fn)
43
+ for (const child of own.children) if (!child.hidden) fire(child, isShown)
44
+ }
45
+
46
+ export function setHidden(own: Activation, hidden: boolean): void {
47
+ if (own.hidden === hidden) return
48
+ const before = shown(own)
49
+ own.hidden = hidden
50
+ if (shown(own) !== before) fire(own, !before)
51
+ }
package/src/adapter.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { ADAPTER_CONTRACT, defineAdapter } from "hamur/adapter"
2
+ import { clientComponentModule, serverComponentModule } from "hamur/adapter/build"
3
+ import { svelteEsmEnv, svelteHydrationPlugin, sveltePlugin } from "./plugin.ts"
4
+ import { svgComponent } from "./svg.ts"
5
+ import { markdownComponent } from "./markdown-page.ts"
6
+
7
+ export default defineAdapter({
8
+ name: "svelte",
9
+ contract: ADAPTER_CONTRACT,
10
+ extensions: [".svelte"],
11
+ clientEntry: "@hamur/adapter-svelte/runtime/client",
12
+ serverEntry: "@hamur/adapter-svelte/runtime/server",
13
+ keepAliveOutlet: "@hamur/adapter-svelte/runtime/keepalive",
14
+ islandEntry: "@hamur/adapter-svelte/runtime/island",
15
+ errorPage: "@hamur/adapter-svelte/error-page",
16
+ plugins: (ctx) => [sveltePlugin(ctx)],
17
+ transforms: (ctx) => (ctx.target === "client" ? (ctx.dev ? [svelteHydrationPlugin()] : [svelteEsmEnv()]) : []),
18
+ peers: ["svelte"],
19
+ trustedTypesPolicies: ["svelte-trusted-html"],
20
+ svgComponent,
21
+ markdownComponent,
22
+ serverComponent: { module: (component) => serverComponentModule(component, "@hamur/adapter-svelte/runtime") },
23
+ clientComponent: { module: (component) => clientComponentModule(component, "@hamur/adapter-svelte/runtime") },
24
+ })
@@ -0,0 +1,105 @@
1
+ import { asyncDataKey, fetchKey, isPreviewMode } from "hamur/adapter"
2
+ import { $fetch } from "hamur/app"
3
+ import type { $Fetch, AppContext, AsyncDataOptions, FetchOptions } from "hamur/app"
4
+ import type { AsyncDataHandler, FetchRequest, GetCachedData, GetCachedDataCause, HandlerReference } from "hamur/adapter"
5
+
6
+ export const valueOf = <T>(value: T | (() => T)): T => (typeof value === "function" ? (value as () => T)() : value)
7
+
8
+ // A function is never a body to send, so a function `query` or `body` is a getter.
9
+ export function requestOf({ query, body, ...rest }: FetchRequest): FetchOptions {
10
+ const request: FetchOptions = rest
11
+ const resolvedQuery = valueOf(query)
12
+ const resolvedBody = valueOf(body)
13
+ if (resolvedQuery !== undefined) request.query = resolvedQuery
14
+ if (resolvedBody !== undefined) request.body = resolvedBody
15
+ return request
16
+ }
17
+
18
+ /** A getter `useFetch` key; each key's handler fetches the url and request that key was made from. */
19
+ export function fetchSlots<R>(
20
+ url: string | (() => string),
21
+ options: FetchRequest,
22
+ fetcher: $Fetch = $fetch,
23
+ fixedKey?: string,
24
+ ): { keyOf: () => string; handlerFor: (key: string) => AsyncDataHandler<R> } {
25
+ const requests = new Map<string, { url: string; request: FetchOptions }>()
26
+ return {
27
+ keyOf() {
28
+ const target = valueOf(url)
29
+ const request = requestOf(options)
30
+ const key = fixedKey ?? fetchKey(target, request)
31
+ requests.set(key, { url: target, request })
32
+ return key
33
+ },
34
+ handlerFor(key) {
35
+ const { url: target, request } = requests.get(key)!
36
+ return ({ signal }) => fetcher<R>(target, { ...request, signal: signalOf(request.signal, signal) })
37
+ },
38
+ }
39
+ }
40
+
41
+ /** The key of `useAsyncData(fn, input)` for the input as it reads now; each key's handler calls `fn` with the input that key was made from. */
42
+ export function handlerSlots<R>(
43
+ app: AppContext,
44
+ fn: HandlerReference,
45
+ input: unknown,
46
+ ): { keyOf: () => string; handlerFor: (key: string) => AsyncDataHandler<R> } {
47
+ const inputs = new Map<string, unknown>()
48
+ return {
49
+ keyOf() {
50
+ const value = valueOf(input)
51
+ const key = asyncDataKey(fn, value)
52
+ inputs.set(key, value)
53
+ return key
54
+ },
55
+ handlerFor(key) {
56
+ const value = inputs.get(key)
57
+ return ({ signal }) =>
58
+ (fn as (input: unknown, init: { signal: AbortSignal; event: AppContext["event"] }) => Promise<R>)(value, {
59
+ signal,
60
+ event: app.event,
61
+ })
62
+ },
63
+ }
64
+ }
65
+
66
+ /** The restored payload entry's data while the app hydrates, else `undefined`. */
67
+ export function defaultGetCachedData<T>(key: string, app: AppContext): T | undefined {
68
+ if (!app.asyncData.hydrating || isPreviewMode(app)) return undefined
69
+ const entry = app.asyncData.get<T>(key)
70
+ return entry?.status === "success" ? entry.data : undefined
71
+ }
72
+
73
+ /** `refresh()`, `execute()` and a `watch` change: ask `getCachedData` with their cause, run `handler` when it has nothing. */
74
+ export function refreshCached<T, R>(
75
+ app: AppContext,
76
+ key: string,
77
+ handler: AsyncDataHandler<R>,
78
+ options: AsyncDataOptions<T, R>,
79
+ getCachedData: GetCachedData<T>,
80
+ cause: GetCachedDataCause,
81
+ ): Promise<void> {
82
+ const cached = getCachedData(key, app, { cause })
83
+ if (cached !== undefined) {
84
+ app.asyncData.fetch<T, R>(key, handler, { ...options, cached })
85
+ return Promise.resolve()
86
+ }
87
+ if (!app.asyncData.has(key)) app.asyncData.fetch<T, R>(key, handler, { ...options, immediate: false })
88
+ return app.asyncData.refresh(key, handler)
89
+ }
90
+
91
+ const kept = new WeakMap<object, Set<string>>()
92
+
93
+ // Nuxt purges no entry whose caller reads it back through its own getCachedData: the entry is that cache.
94
+ export function keepCached<T>(app: AppContext, key: string, getCachedData: GetCachedData<T>): void {
95
+ if (getCachedData === defaultGetCachedData) return
96
+ let keys = kept.get(app.asyncData)
97
+ if (!keys) kept.set(app.asyncData, (keys = new Set()))
98
+ if (keys.has(key)) return
99
+ keys.add(key)
100
+ app.asyncData.subscribe(key, () => {})
101
+ }
102
+
103
+ /** The run's signal, combined with a `signal` the caller gave to `useFetch`. */
104
+ export const signalOf = (own: AbortSignal | undefined, run: AbortSignal): AbortSignal =>
105
+ own ? AbortSignal.any([own, run]) : run
@@ -0,0 +1,77 @@
1
+ import { createError } from "hamur/app"
2
+
3
+ const MARK = "$hamurError"
4
+
5
+ interface SerializedError {
6
+ [MARK]: true
7
+ name: string
8
+ message: string
9
+ status?: number
10
+ statusText?: string
11
+ data?: unknown
12
+ fatal?: true
13
+ failure?: true
14
+ }
15
+
16
+ /** Svelte writes the error into the HTML as JSON for the client's `failed` snippet, and an `Error` serializes to `{}`. */
17
+ const failures = new WeakSet<object>()
18
+
19
+ /** Marks an error a route boundary's own render threw: no route boundary above may catch it. */
20
+ export function markFailure<T>(error: T): T {
21
+ if (typeof error === "object" && error !== null) failures.add(error)
22
+ return error
23
+ }
24
+
25
+ export function isFailure(error: unknown): boolean {
26
+ return (
27
+ typeof error === "object" &&
28
+ error !== null &&
29
+ (failures.has(error) || failures.has((error as { cause?: object }).cause ?? {}))
30
+ )
31
+ }
32
+
33
+ export function serializeError(error: unknown): unknown {
34
+ if (!(error instanceof Error)) return error
35
+ const { status, statusText, data, fatal } = error as Error & {
36
+ status?: unknown
37
+ statusText?: unknown
38
+ data?: unknown
39
+ fatal?: unknown
40
+ }
41
+ const serialized: SerializedError = { [MARK]: true, name: error.name, message: error.message }
42
+ if (typeof status === "number") serialized.status = status
43
+ if (typeof statusText === "string") serialized.statusText = statusText
44
+ if (data !== undefined) serialized.data = data
45
+ if (fatal === true) serialized.fatal = true
46
+ if (isFailure(error)) serialized.failure = true
47
+ return serialized
48
+ }
49
+
50
+ /** Hydration hands the `failed` snippet the parsed JSON; this gives it an `Error` again, as every other adapter does. */
51
+ export function reviveError(value: unknown): unknown {
52
+ if (typeof value !== "object" || value === null || (value as Partial<SerializedError>)[MARK] !== true) return value
53
+ const { name, message, status, statusText, data, fatal, failure } = value as SerializedError
54
+ const revived =
55
+ typeof status === "number"
56
+ ? createError({
57
+ status,
58
+ message,
59
+ ...(statusText ? { statusText } : {}),
60
+ ...(data !== undefined ? { data } : {}),
61
+ ...(fatal ? { fatal } : {}),
62
+ })
63
+ : Object.assign(new Error(message), { name })
64
+ return failure ? markFailure(revived) : revived
65
+ }
66
+
67
+ const originals = new WeakMap<object, unknown>()
68
+
69
+ /** Server: remembers the error a serialized value stands for, which the failed snippet gets instead of the original. */
70
+ export function rememberOriginal<T>(serialized: T, original: unknown): T {
71
+ if (typeof serialized === "object" && serialized !== null) originals.set(serialized, original)
72
+ return serialized
73
+ }
74
+
75
+ export function originalOf(serialized: unknown): unknown {
76
+ return typeof serialized === "object" && serialized !== null ? originals.get(serialized) : undefined
77
+ }
@@ -0,0 +1,8 @@
1
+ import type { Snippet } from "svelte"
2
+
3
+ /** The context `ClientOnly` sets; a client-only component below renders its `fallback` while its chunk loads. */
4
+ export const CLIENT_ONLY = Symbol("hamur.clientOnly")
5
+
6
+ export interface ClientOnlyScope {
7
+ readonly fallback: Snippet | undefined
8
+ }
package/src/context.ts ADDED
@@ -0,0 +1,227 @@
1
+ import { createRawSnippet, getContext } from "svelte"
2
+ import type { Component } from "svelte"
3
+ import type { AppContext as HamurApp, ErrorPageProps, Head } from "hamur/app"
4
+ import type {
5
+ ClientContext,
6
+ NavigationState,
7
+ RenderContext,
8
+ RenderTree,
9
+ ResolvedRoute,
10
+ RouteValue,
11
+ RouterApi,
12
+ } from "hamur/adapter"
13
+ import { createRouterApi, type RouterSource } from "hamur/adapter"
14
+ import { routeStateOf, setServerHTML, SLOT_ELEMENT } from "hamur/adapter"
15
+ import { createSource, track } from "./store.ts"
16
+ import type { Source } from "./store.ts"
17
+ import Slotted from "./Slotted.svelte"
18
+ import { activation, detach, setHidden } from "./activation.ts"
19
+ import type { KeepAliveBase } from "./keepalive.ts"
20
+ import { withBase } from "hamur/app"
21
+ import type { RouteLocation } from "hamur/app"
22
+
23
+ export interface NavigationSource {
24
+ get(): NavigationState
25
+ subscribe(listener: () => void): () => void
26
+ }
27
+
28
+ export interface AppState {
29
+ route: RouteValue
30
+ router: RouterApi
31
+ baseURL: string
32
+ href: RenderContext["href"]
33
+ components: RenderTree["components"]
34
+ data: Record<string, unknown>
35
+ handlerState?: unknown
36
+ tree: RenderTree
37
+ head: Head
38
+ navigation: NavigationSource
39
+ app: HamurApp
40
+ context: RenderContext | ClientContext
41
+ }
42
+
43
+ export interface Level {
44
+ readonly id: string | undefined
45
+ readonly components: RenderTree["components"]
46
+ readonly index: number
47
+ readonly route?: RouteValue
48
+ }
49
+
50
+ export const APP_KEY = Symbol("hamur.app")
51
+ /** The list a server render's `Island`s record the islands still rendering in; Svelte's render may run after `render` returns. */
52
+ export const PENDING_ISLANDS_KEY = Symbol("hamur.pendingIslands")
53
+ export const LEVEL_KEY = Symbol("hamur.level")
54
+ /** `true` in the context of a `"never"` lazy part rendered on the server, so its async data stays out of the payload. */
55
+ export const NEVER_HYDRATED_KEY = Symbol("hamur.never-hydrated")
56
+ export const OUTLET_VALUE_KEY = Symbol("hamur.outlet-value")
57
+ export const FORM_STATUS_KEY = Symbol("hamur.form-status")
58
+ export const ERROR_KEY = Symbol("hamur.error")
59
+ export const LINK_KEY = Symbol("hamur.link")
60
+ export const ACTIVATION_KEY = Symbol("hamur.activation")
61
+ export const IDS_KEY = Symbol("hamur.ids")
62
+
63
+ /** The ids of one render root; a lazy part takes one id of its parent for its own `base`, so ids stay equal whatever renders on the server or the client. */
64
+ export interface Ids {
65
+ readonly base: string
66
+ next: number
67
+ }
68
+
69
+ export const rootIds = (prefix = ""): Ids => ({ base: `${prefix}s-`, next: 0 })
70
+
71
+ export function nextId(ids: Ids): string {
72
+ return `${ids.base}${ids.next++}`
73
+ }
74
+
75
+ export function detachedHref(to: string | RouteLocation): string {
76
+ if (typeof to !== "string") throw new Error(`Link to the route "${to.name}" must be rendered inside a Hamur app`)
77
+ return withBase(to, "/")
78
+ }
79
+
80
+ export function routerOf(
81
+ navigator: unknown,
82
+ baseURL = "/",
83
+ page?: Omit<RouterSource, "navigator" | "baseURL">,
84
+ ): RouterApi {
85
+ return createRouterApi({ ...page, navigator, baseURL })
86
+ }
87
+
88
+ const idle = { state: "idle", pending: false } as const
89
+
90
+ export function navigationOf(navigator: unknown): NavigationSource {
91
+ const source = navigator as Partial<NavigationSource> | undefined
92
+ return {
93
+ get: () => source?.get?.() ?? idle,
94
+ subscribe: (listener) => source?.subscribe?.(listener) ?? (() => {}),
95
+ }
96
+ }
97
+
98
+ export function routeValue(
99
+ ctx: Pick<RenderContext, "route"> & Partial<Pick<RenderContext, "app" | "payload" | "tree">>,
100
+ ): RouteValue {
101
+ const { route } = ctx
102
+ return {
103
+ path: route.path,
104
+ fullPath: route.fullPath,
105
+ params: route.params,
106
+ query: route.query,
107
+ search: route.search,
108
+ hash: route.hash,
109
+ name: route.name,
110
+ meta: route.meta,
111
+ matched: route.matched,
112
+ groups: route.groups ?? [],
113
+ ...routeStateOf(ctx),
114
+ } as RouteValue
115
+ }
116
+
117
+ export function appState(
118
+ ctx: Pick<RenderContext | ClientContext, "route" | "tree" | "payload" | "app" | "head" | "href"> & {
119
+ navigator?: unknown
120
+ baseURL?: string
121
+ },
122
+ ): AppState {
123
+ const { data = {} } = ctx.payload as { data?: Record<string, unknown> }
124
+ return {
125
+ route: routeValue(ctx),
126
+ router: routerOf(ctx.navigator, ctx.baseURL, ctx),
127
+ baseURL: ctx.baseURL ?? "/",
128
+ href: ctx.href,
129
+ components: ctx.tree.components,
130
+ data,
131
+ handlerState: (ctx.payload as { handlerState?: unknown }).handlerState,
132
+ tree: ctx.tree,
133
+ head: ctx.head,
134
+ navigation: navigationOf(ctx.navigator),
135
+ app: ctx.app,
136
+ context: ctx as RenderContext | ClientContext,
137
+ }
138
+ }
139
+
140
+ let keptComponent: Component<any> | undefined
141
+
142
+ /** The core's keep-alive feature loads the outlet (`Adapter.keepAliveOutlet`) and hands it to `installKeepAlive` before the first tree that holds kept units; it takes what it needs from the object it is built with, so its chunk imports nothing from the base. */
143
+ export function installKeepAlive(module: { default: Component<any> }): void {
144
+ keptComponent ??= module.default
145
+ }
146
+
147
+ export function keptOutlet(): Component<any> {
148
+ if (!keptComponent)
149
+ throw new Error(
150
+ "A tree with kept pages was rendered before the keep-alive part of the Svelte adapter was installed",
151
+ )
152
+ return keptComponent
153
+ }
154
+
155
+ export const keepAliveBase: KeepAliveBase = { APP_KEY, ACTIVATION_KEY, routeValue, activation, detach, setHidden }
156
+
157
+ /** An intercepting chain reads the intercepted route with the history entry of the page kept. */
158
+ export function interceptedRoute(page: AppState, slot: RenderTree): RouteValue {
159
+ const { state, key, navigationType } = page.route
160
+ return routeValue({ ...page.context, route: { ...slot.route!, state, key, navigationType }, tree: slot })
161
+ }
162
+
163
+ export function errorOf(state: AppState): ErrorPageProps | undefined {
164
+ const stored = state.app.error?.get()
165
+ if (stored) return stored
166
+ return state.tree.error ? state.route.error : undefined
167
+ }
168
+
169
+ export function appSource(ctx: Parameters<typeof appState>[0]): Source<AppState> {
170
+ return createSource(appState(ctx))
171
+ }
172
+
173
+ const ISLAND_ENTRY = "island"
174
+
175
+ /** The app state of an island's own root: one entry; a `Link` takes a path, as no route table ships. */
176
+ /**
177
+ * The island's children as its `children` snippet: the server writes their HTML; while hydrating, Svelte adopts the
178
+ * slot element the server wrote with its nodes, and the same HTML is written only into one Svelte creates anew.
179
+ */
180
+ function slotSnippet(uid: string, html: string) {
181
+ if (typeof document === "undefined")
182
+ return createRawSnippet(() => ({ render: () => `<${SLOT_ELEMENT} uid="${uid}">${html}</${SLOT_ELEMENT}>` }))
183
+ return createRawSnippet(() => ({
184
+ render: () => `<${SLOT_ELEMENT} uid="${uid}"></${SLOT_ELEMENT}>`,
185
+ setup(node: Element) {
186
+ if (html && !node.hasChildNodes()) setServerHTML(node, html)
187
+ },
188
+ }))
189
+ }
190
+
191
+ export function islandSource(
192
+ component: unknown,
193
+ props: Record<string, unknown>,
194
+ ctx: { app: HamurApp; route: ResolvedRoute; baseURL: string; idPrefix: string; slots?: { default?: string } },
195
+ kept: { slot?: ReturnType<typeof slotSnippet> } = {},
196
+ ): Source<AppState> {
197
+ const href = (to: string | RouteLocation) => {
198
+ if (typeof to !== "string")
199
+ throw new Error(`Link to the route "${to.name}" cannot render in an island; give it a path`)
200
+ return withBase(to, ctx.baseURL)
201
+ }
202
+ const slot = ctx.slots?.default
203
+ // The entry's own `children` are the tree's, so the island gets its slot from `Slotted`.
204
+ const entry =
205
+ slot === undefined
206
+ ? { id: ISLAND_ENTRY, component, props }
207
+ : {
208
+ id: ISLAND_ENTRY,
209
+ component: Slotted,
210
+ props: { component, props, slot: (kept.slot ??= slotSnippet(`s${ctx.idPrefix}`, slot)) },
211
+ }
212
+ return appSource({
213
+ app: ctx.app,
214
+ head: ctx.app.head,
215
+ route: ctx.route,
216
+ baseURL: ctx.baseURL,
217
+ href,
218
+ tree: { components: [entry] },
219
+ payload: {},
220
+ })
221
+ }
222
+
223
+ export function useAppState(name: string): () => AppState {
224
+ const source = getContext<Source<AppState> | undefined>(APP_KEY)
225
+ if (!source) throw new Error(`${name}() must be called inside a Hamur app`)
226
+ return track(source)
227
+ }
@@ -0,0 +1,33 @@
1
+ import { settledOf } from "hamur/adapter"
2
+ import type { Settled } from "hamur/adapter"
3
+
4
+ export interface Deferred<T> {
5
+ readonly current: T | undefined
6
+ readonly error: Error | undefined
7
+ readonly pending: boolean
8
+ }
9
+
10
+ const isThenable = (value: unknown): value is PromiseLike<unknown> =>
11
+ typeof (value as { then?: unknown } | null)?.then === "function"
12
+
13
+ export function useDeferred<T>(promise: T): Deferred<Awaited<T>> {
14
+ const known: Settled | undefined = isThenable(promise) ? settledOf(promise) : { status: "fulfilled", value: promise }
15
+ let state = $state.raw<Settled | undefined>(known)
16
+ if (!known && isThenable(promise)) {
17
+ promise.then(
18
+ (value) => void (state = { status: "fulfilled", value }),
19
+ (reason) => void (state = { status: "rejected", reason }),
20
+ )
21
+ }
22
+ return {
23
+ get current() {
24
+ return state?.status === "fulfilled" ? (state.value as Awaited<T>) : undefined
25
+ },
26
+ get error() {
27
+ return state?.status === "rejected" ? (state.reason as Error) : undefined
28
+ },
29
+ get pending() {
30
+ return state === undefined
31
+ },
32
+ }
33
+ }
@@ -0,0 +1,7 @@
1
+ export function watch(run: () => void | (() => void)): void {
2
+ $effect(run)
3
+ }
4
+
5
+ export function watchPre(run: () => void | (() => void)): void {
6
+ $effect.pre(run)
7
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ interface ImportMeta {
2
+ readonly dev?: boolean
3
+ }
@@ -0,0 +1,18 @@
1
+ let hydrating = false
2
+ // Hydrating a non-empty `{@html}` adopts the server nodes as they are; an empty one fails the whole root's hydration.
3
+ const ADOPT_SERVER_NODES = "<!---->"
4
+
5
+ /** Called around the `hydrate` of a root (the page's, an island's), so a part that keeps its server nodes does so only then. */
6
+ export function whileHydratingPage<T>(run: () => T): T {
7
+ hydrating = true
8
+ try {
9
+ return run()
10
+ } finally {
11
+ hydrating = false
12
+ }
13
+ }
14
+
15
+ /** The `{@html}` of a part that keeps its server nodes in the browser: the marker that adopts them while a root hydrates, else nothing. */
16
+ export function keptServerHTML(): string {
17
+ return hydrating ? ADOPT_SERVER_NODES : ""
18
+ }