@hamur/adapter-preact 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 (68) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +35 -2
  3. package/dist/chunks/browser-index-89d71ade.js +118 -0
  4. package/dist/chunks/browser-index-ezte15pp.js +67 -0
  5. package/dist/chunks/browser-index-hsy7tnbg.js +21 -0
  6. package/dist/chunks/browser-index-k3m2axbw.js +274 -0
  7. package/dist/src/adapter.js +456 -0
  8. package/dist/src/error-page.js +391 -0
  9. package/dist/src/index.js +1506 -0
  10. package/dist/src/keepalive.js +6 -0
  11. package/dist/src/runtime/client.js +96 -0
  12. package/dist/src/runtime/island.js +33 -0
  13. package/dist/src/runtime/server.js +95 -0
  14. package/dist/types/src/activation.d.ts +15 -0
  15. package/dist/types/src/adapter.d.ts +2 -0
  16. package/dist/types/src/async-data.d.ts +13 -0
  17. package/dist/types/src/client-component.d.ts +11 -0
  18. package/dist/types/src/client-fallback.d.ts +2 -0
  19. package/dist/types/src/context.d.ts +81 -0
  20. package/dist/types/src/error-page.d.ts +1 -0
  21. package/dist/types/src/head.d.ts +5 -0
  22. package/dist/types/src/index.d.ts +429 -0
  23. package/dist/types/src/island-html.d.ts +13 -0
  24. package/dist/types/src/island.d.ts +19 -0
  25. package/dist/types/src/jsx-locator.d.ts +6 -0
  26. package/dist/types/src/keepalive.d.ts +26 -0
  27. package/dist/types/src/lazy-hydration.d.ts +12 -0
  28. package/dist/types/src/markdown-page.d.ts +9 -0
  29. package/dist/types/src/markdown.d.ts +12 -0
  30. package/dist/types/src/plugin.d.ts +36 -0
  31. package/dist/types/src/route-boundary.d.ts +41 -0
  32. package/dist/types/src/runtime/client.d.ts +10 -0
  33. package/dist/types/src/runtime/hmr.d.ts +31 -0
  34. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  35. package/dist/types/src/runtime/hydration.d.ts +8 -0
  36. package/dist/types/src/runtime/island.d.ts +8 -0
  37. package/dist/types/src/runtime/server.d.ts +11 -0
  38. package/dist/types/src/server-island.d.ts +10 -0
  39. package/dist/types/src/svg.d.ts +10 -0
  40. package/package.json +50 -4
  41. package/src/activation.ts +51 -0
  42. package/src/adapter.ts +35 -0
  43. package/src/async-data.ts +65 -0
  44. package/src/client-component.ts +23 -0
  45. package/src/client-fallback.ts +2 -0
  46. package/src/context.ts +372 -0
  47. package/src/env.d.ts +3 -0
  48. package/src/error-page.ts +1 -0
  49. package/src/head.ts +34 -0
  50. package/src/index.ts +1868 -0
  51. package/src/island-html.ts +58 -0
  52. package/src/island.ts +56 -0
  53. package/src/jsx-locator.ts +199 -0
  54. package/src/keepalive.ts +100 -0
  55. package/src/lazy-hydration.ts +101 -0
  56. package/src/markdown-page.ts +18 -0
  57. package/src/markdown.ts +58 -0
  58. package/src/plugin.ts +231 -0
  59. package/src/route-boundary.ts +51 -0
  60. package/src/runtime/client.ts +85 -0
  61. package/src/runtime/hmr.ts +141 -0
  62. package/src/runtime/hydration-dev.ts +8 -0
  63. package/src/runtime/hydration.ts +7 -0
  64. package/src/runtime/island.ts +37 -0
  65. package/src/runtime/server.ts +102 -0
  66. package/src/server-island.ts +35 -0
  67. package/src/svg.ts +27 -0
  68. package/src/webmcp.d.ts +18 -0
package/src/plugin.ts ADDED
@@ -0,0 +1,231 @@
1
+ import { realpathSync } from "node:fs"
2
+ import { join, relative } from "node:path"
3
+ import type { AdapterBuildContext, AdapterTransform } from "hamur/adapter"
4
+ import { dropDevOnly } from "hamur/adapter/build"
5
+ import { locateJsx } from "./jsx-locator.ts"
6
+
7
+ const HMR_RUNTIME = join(import.meta.dir, "runtime/hmr.ts")
8
+ const CLIENT_RUNTIME = join(import.meta.dir, "runtime/client.ts")
9
+ const HYDRATION_DEV = join(import.meta.dir, "runtime/hydration-dev.ts")
10
+ const ROUTE_MODULE = /(^|\/)((pages|layouts)\/|app\.[jt]sx$)/
11
+ const SIGNATURE_CALL = /\b(use[A-Z]\w*)\s*(?:<[^>]*>)?\s*\(/g
12
+ const SIGNATURE_ARGUMENTS = new Set(["useState", "useReducer"])
13
+ const ARROW = String.raw`(?:async\s*)?(?:\((?:[^()]|\([^()]*\))*\)|[A-Za-z_$][\w$]*)\s*(?::[^=]+)?=>`
14
+ const DEFAULT_FUNCTION = /^export default (async )?function\b\s*([A-Za-z_$][\w$]*)?/m
15
+ const DEFAULT_ARROW = new RegExp(String.raw`^export default (?=${ARROW})`, "m")
16
+ const DEFAULT_NAME = /^export default ([A-Z][\w$]*)\s*;?\s*$/m
17
+ const DEFAULT_ANY = /^export default /m
18
+ const NAMED_FUNCTION = /^export function ([A-Z][\w$]*)(?=\s*[<(])/gm
19
+ const NAMED_CONST = new RegExp(
20
+ String.raw`^export const ([A-Z][\w$]*)(?=(?:\s*:[^=]+)?\s*=\s*(?:function\b|${ARROW}))`,
21
+ "gm",
22
+ )
23
+ /** A JSX tag or fragment: `<` not preceded by an identifier, `)`, `]` or `.` (generics, comparisons). */
24
+ const JSX = /(?<![\w$)\].])<(?:[A-Za-z][\w.:-]*(?=[\s/>])|>)/
25
+ const TOP_LEVEL = /^(?:export|import|const|let|var|function|class|async\s+function|interface|type)\b/m
26
+ /** Imports whose namespace says nothing about code: styles, assets, data and Hamur's own virtual modules. */
27
+ const NOT_A_MODULE =
28
+ /^#hamur\/|\.(?:css|scss|sass|less|styl|svg|png|jpe?g|gif|webp|avif|ico|json|txt|md|wasm|html)(?:\?.*)?$|\?/i
29
+ const BINDING = /(?:const|let|var)\s+(\[[^\]]*\]|\{[^}]*\}|[\w$]+)\s*(?::[^=;]+)?=\s*$/
30
+
31
+ /** From `start` to the next top-level statement: the declaration a match belongs to. */
32
+ function declaration(source: string, start: number): string {
33
+ const line = source.indexOf("\n", start)
34
+ if (line === -1) return source.slice(start)
35
+ const next = source.slice(line + 1).search(TOP_LEVEL)
36
+ return source.slice(start, next === -1 ? source.length : line + 1 + next)
37
+ }
38
+
39
+ /** The text inside the parentheses opening at `open`, strings skipped. */
40
+ function argumentsAt(source: string, open: number): string {
41
+ let depth = 0
42
+ let quote = ""
43
+ for (let i = open; i < source.length; i++) {
44
+ const char = source[i]
45
+ if (quote) {
46
+ if (char === "\\") i++
47
+ else if (char === quote) quote = ""
48
+ } else if (char === '"' || char === "'" || char === "`") quote = char
49
+ else if (char === "(") depth++
50
+ else if (char === ")" && --depth === 0) return source.slice(open + 1, i)
51
+ }
52
+ return source.slice(open + 1)
53
+ }
54
+
55
+ /**
56
+ * One `<binding>=<call>` entry per call in source order; the calls in `withArguments`
57
+ * also carry their arguments, so reordering or swapping two of them changes the signature.
58
+ */
59
+ export function refreshSignature(source: string, calls: RegExp, withArguments: ReadonlySet<string>): string {
60
+ const entries: string[] = []
61
+ for (const match of source.matchAll(calls)) {
62
+ const name = match[1]!
63
+ const binding = source.slice(Math.max(0, match.index - 200), match.index).match(BINDING)?.[1] ?? ""
64
+ const args = withArguments.has(name) ? `(${argumentsAt(source, match.index + match[0].length - 1)})` : ""
65
+ entries.push(`${binding}=${name}${args}`.replace(/\s+/g, " "))
66
+ }
67
+ return entries.join(";")
68
+ }
69
+
70
+ export interface RefreshOptions {
71
+ /** Path relative to `rootDir`, also the module's key in the hot runtime. */
72
+ id: string
73
+ /** Pages, layouts and `app.<ext>` accept themselves even with other exports (`meta`). */
74
+ route: boolean
75
+ runtime?: string
76
+ }
77
+
78
+ export interface RefreshResult {
79
+ code: string
80
+ signature: string
81
+ accepted: boolean
82
+ }
83
+
84
+ /**
85
+ * Wraps every component export in the hot runtime and bakes the module's refresh signature. A component is
86
+ * a capitalised function or arrow whose declaration renders JSX. Its binding stays the module's own (a hoisted
87
+ * `function` or a `let`) and is reassigned to the wrapper at the end, so the export, a circular importer and the
88
+ * module's other components all see the wrapper once the module has run.
89
+ */
90
+ export function refreshTransform(source: string, { id, route, runtime = HMR_RUNTIME }: RefreshOptions): RefreshResult {
91
+ const { exports, imports } = new Bun.Transpiler({ loader: "tsx" }).scan(source)
92
+ const dependencies = [
93
+ ...new Set(
94
+ imports
95
+ .filter(({ kind, path }) => kind === "import-statement" && !NOT_A_MODULE.test(path))
96
+ .map(({ path }) => path),
97
+ ),
98
+ ]
99
+ const signature = refreshSignature(source, SIGNATURE_CALL, SIGNATURE_ARGUMENTS)
100
+ const components = new Map<string, string>()
101
+ const renders = (text: string, at: number) => JSX.test(declaration(text, at))
102
+ let body = source.replace(NAMED_FUNCTION, (match, name: string, at: number, text: string) =>
103
+ renders(text, at) ? (components.set(name, name), `function ${name}`) : match,
104
+ )
105
+ body = body.replace(NAMED_CONST, (match, name: string, at: number, text: string) =>
106
+ renders(text, at) ? (components.set(name, name), `let ${name}`) : match,
107
+ )
108
+ const fn = body.match(DEFAULT_FUNCTION)
109
+ const named = body.match(DEFAULT_NAME)?.[1]
110
+ const declared = (name: string) => {
111
+ const at = body.search(
112
+ new RegExp(String.raw`^(?:async\s+)?function\s+${name}\b|^(?:const|let|var)\s+${name}\b`, "m"),
113
+ )
114
+ return at !== -1 && renders(body, at)
115
+ }
116
+ if (fn?.[2] && (route || renders(body, fn.index!))) {
117
+ body = body.replace(DEFAULT_FUNCTION, `${fn[1] ?? ""}function ${fn[2]}`)
118
+ components.set("default", fn[2])
119
+ } else if (
120
+ route
121
+ ? DEFAULT_ANY.test(body)
122
+ : (fn && renders(body, fn.index!)) ||
123
+ (DEFAULT_ARROW.test(body) && renders(body, body.search(DEFAULT_ARROW))) ||
124
+ (named !== undefined && declared(named))
125
+ ) {
126
+ body = body.replace(DEFAULT_ANY, "let __hamurDefault = ")
127
+ components.set("default", "__hamurDefault")
128
+ }
129
+ if (components.size === 0) return { code: source, signature: "", accepted: false }
130
+ const accepted = route || exports.every((name) => components.has(name))
131
+ const names = [...components]
132
+ return {
133
+ signature,
134
+ accepted,
135
+ code: [
136
+ // the imports share the module's first line, so every source line keeps its number
137
+ `${[`import { hotModule as __hamurHot } from ${JSON.stringify(runtime)};`, ...dependencies.map((path, index) => `import * as __hamurDep${index} from ${JSON.stringify(path)};`)].join(" ")} ${body}`,
138
+ `const __hamurMod = __hamurHot(import.meta.hot ? import.meta.hot.data.hamur : undefined, ${JSON.stringify(id)}, ${JSON.stringify(signature)}, ${JSON.stringify(String(Bun.hash(source)))}, [${dependencies.map((_, index) => `__hamurDep${index}`).join(", ")}]);`,
139
+ `if (import.meta.hot) import.meta.hot.data.hamur = __hamurMod;`,
140
+ ...names.map(([name, local]) => `${local} = __hamurMod.component(${JSON.stringify(name)}, ${local});`),
141
+ `export { ${names.map(([name, local]) => (name === local ? name : `${local} as ${name}`)).join(", ")} };`,
142
+ `__hamurMod.commit();`,
143
+ ...(accepted ? [`if (import.meta.hot) import.meta.hot.accept();`] : []),
144
+ ].join("\n"),
145
+ }
146
+ }
147
+
148
+ /** The module's path relative to `rootDir` when it is an app source (not under `node_modules` or the build dir). */
149
+ export function appModuleId(rootDir: string, buildDir: string): (path: string) => string | undefined {
150
+ let real = rootDir
151
+ try {
152
+ real = realpathSync(rootDir)
153
+ } catch {}
154
+ const roots = [...new Set([rootDir, real])]
155
+ const build = relative(rootDir, buildDir)
156
+ const inBuild = (id: string) =>
157
+ build !== "" && !build.startsWith("..") && (id === build || id.startsWith(`${build}/`))
158
+ return (path) => {
159
+ if (path.includes("/node_modules/")) return undefined
160
+ for (const root of roots) {
161
+ const id = relative(root, path)
162
+ if (!id.startsWith("..") && !id.startsWith("/")) return inBuild(id) ? undefined : id
163
+ }
164
+ return undefined
165
+ }
166
+ }
167
+
168
+ // Bun's dev bundler gets no `jsx` config, so it would import react/jsx-dev-runtime.
169
+ export function preactPlugin(ctx: AdapterBuildContext): AdapterTransform {
170
+ const appModule = appModuleId(ctx.rootDir, ctx.buildDir)
171
+ return {
172
+ name: `hamur-preact-${ctx.target}`,
173
+ filter: { id: /\.[jt]sx$/ },
174
+ transform(code, { id: path }) {
175
+ if (path.includes("/node_modules/")) return undefined
176
+ let source = code
177
+ const id = appModule(path)
178
+ const layerRoute = id === undefined ? relative(ctx.rootDir, path) : undefined
179
+ if (ctx.hmr && id !== undefined) source = refreshTransform(source, { id, route: ROUTE_MODULE.test(id) }).code
180
+ else if (ctx.hmr && layerRoute !== undefined && ROUTE_MODULE.test(layerRoute))
181
+ source = refreshTransform(source, { id: layerRoute!, route: true }).code
182
+ return `/** @jsxImportSource preact */ ${source}`
183
+ },
184
+ }
185
+ }
186
+
187
+ /** The source locator: in `hamur dev`, each app component's root host element gets `data-hamur-src`, on the server and in the client alike. */
188
+ export function preactLocatorPlugin(ctx: AdapterBuildContext): AdapterTransform {
189
+ const appModule = appModuleId(ctx.rootDir, ctx.buildDir)
190
+ return {
191
+ name: `hamur-preact-locator-${ctx.target}`,
192
+ filter: { id: /\.[jt]sx$/ },
193
+ transform(code, { id }) {
194
+ const file = appModule(id)
195
+ if (file === undefined) return undefined
196
+ const located = locateJsx(code, file)
197
+ return located === code ? undefined : located
198
+ },
199
+ }
200
+ }
201
+
202
+ /** A production build empties the children of every `<DevOnly>` imported from `@hamur/adapter-preact`. */
203
+ export function preactProductionPlugin(ctx: AdapterBuildContext): AdapterTransform {
204
+ return {
205
+ name: `hamur-preact-production-${ctx.target}`,
206
+ filter: { id: /\.[jt]sx$/ },
207
+ transform(code, { id }) {
208
+ if (id.includes("/node_modules/")) return undefined
209
+ const contents = dropDevOnly(code, "@hamur/adapter-preact", "markup")
210
+ return contents === code ? undefined : contents
211
+ },
212
+ }
213
+ }
214
+
215
+ /** In `hamur dev` the client runtime imports `preact/debug` first, so Preact's devtools hooks are set before the first render; a build adds nothing. */
216
+ export function preactDebugPlugin(): AdapterTransform {
217
+ return {
218
+ name: "hamur-preact-debug",
219
+ filter: { id: new RegExp(`^${CLIENT_RUNTIME.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) },
220
+ transform: (code) => `import "preact/debug"; ${code}`,
221
+ }
222
+ }
223
+
224
+ /** In `hamur dev` the client runtime imports `runtime/hydration-dev.ts` first, which feeds the hydration mismatch report; a build adds nothing. */
225
+ export function preactHydrationPlugin(): AdapterTransform {
226
+ return {
227
+ name: "hamur-preact-hydration",
228
+ filter: { id: new RegExp(`^${CLIENT_RUNTIME.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) },
229
+ transform: (code) => `import ${JSON.stringify(HYDRATION_DEV)}; ${code}`,
230
+ }
231
+ }
@@ -0,0 +1,51 @@
1
+ import { Component } from "preact"
2
+ import type { ComponentChildren } from "preact"
3
+
4
+ interface Props {
5
+ resetOn: unknown
6
+ fallback: (error: unknown) => ComponentChildren
7
+ children?: ComponentChildren
8
+ }
9
+
10
+ interface Held {
11
+ failed: boolean
12
+ error: unknown
13
+ }
14
+
15
+ /** Shows its fallback for an error below it until `resetOn` is another object, which every navigation and update builds. */
16
+ export class RouteBoundary extends Component<Props, Held> {
17
+ state: Held = { failed: false, error: undefined }
18
+ private failedFor: unknown
19
+
20
+ static getDerivedStateFromError(error: unknown) {
21
+ return { failed: true, error }
22
+ }
23
+
24
+ render() {
25
+ if (this.state.failed) {
26
+ this.failedFor ??= this.props.resetOn
27
+ if (this.failedFor === this.props.resetOn) return this.props.fallback(this.state.error)
28
+ this.failedFor = undefined
29
+ this.state = { failed: false, error: undefined }
30
+ }
31
+ return this.props.children
32
+ }
33
+ }
34
+
35
+ /** Errors a route boundary's own render threw, which no route boundary above may catch. */
36
+ export const rethrown = new WeakSet<object>()
37
+
38
+ /** Marks an error that comes up from its children and throws it again to the next boundary. */
39
+ export class Guard extends Component<{ children?: ComponentChildren }, { failed: boolean; error: unknown }> {
40
+ state = { failed: false, error: undefined as unknown }
41
+
42
+ static getDerivedStateFromError(error: unknown) {
43
+ if (typeof error === "object" && error !== null) rethrown.add(error)
44
+ return { failed: true, error }
45
+ }
46
+
47
+ render() {
48
+ if (this.state.failed) throw this.state.error
49
+ return this.props.children
50
+ }
51
+ }
@@ -0,0 +1,85 @@
1
+ import { h, hydrate as hydrateInto, render } from "preact"
2
+ import type { ComponentChild } from "preact"
3
+ import { useContext, useEffect, useId, useRef, useState } from "preact/hooks"
4
+ import { setAdapterInstance } from "hamur/adapter"
5
+ import type { ClientContext } from "hamur/adapter"
6
+ import { fetchServerComponent, serverComponentAttributes, serverComponentProps, takeServerHTML } from "hamur/adapter"
7
+ import type { ServerComponentView } from "hamur/adapter"
8
+ import type { HeadEntry } from "hamur/app"
9
+ import { clientFallbackIds } from "../client-fallback.ts"
10
+ import { AppContextContext, RootBoundary, buildElement } from "../context.ts"
11
+ import { devHydration } from "./hydration.ts"
12
+
13
+ export { installKeepAlive } from "../context.ts"
14
+
15
+ let container: Element | undefined
16
+ let starting: Promise<void> | undefined
17
+
18
+ export const hydrationCanBeAborted = true
19
+
20
+ function element(ctx: ClientContext) {
21
+ return h(RootBoundary, { app: ctx.app, children: buildElement(ctx) })
22
+ }
23
+
24
+ export async function hydrate(ctx: ClientContext): Promise<void> {
25
+ await (starting = setAdapterInstance(ctx.app, null))
26
+ container = ctx.root
27
+ for (const id of Array.isArray(ctx.payload.clientFallback) ? ctx.payload.clientFallback : [])
28
+ clientFallbackIds.add(String(id))
29
+ const watch = devHydration.watch?.(container)
30
+ hydrateInto(element(ctx), container)
31
+ watch?.done()
32
+ }
33
+
34
+ export async function mount(ctx: ClientContext): Promise<void> {
35
+ await (starting = setAdapterInstance(ctx.app, null))
36
+ container = ctx.root
37
+ render(element(ctx), container)
38
+ }
39
+
40
+ export function update(ctx: ClientContext): void | Promise<void> {
41
+ if (!container && starting) return starting.then(() => update(ctx))
42
+ if (!container) throw new Error("update() called before hydrate() or mount()")
43
+ render(element(ctx), container)
44
+ }
45
+
46
+ export { clientComponent } from "../client-component.ts"
47
+
48
+ /** The client side of a server-only component: the server HTML, never hydrated; a new props text fetches it anew. */
49
+ export function serverComponent(name: string): (props: Record<string, unknown>) => ComponentChild {
50
+ function ServerComponent(props: Record<string, unknown>): ComponentChild {
51
+ const app = useContext(AppContextContext)!
52
+ const uid = useId()
53
+ const text = serverComponentProps(name, props, props.children !== undefined)
54
+ const [shown, setShown] = useState<{ text?: string; view: ServerComponentView; error?: unknown }>(() => {
55
+ const html = takeServerHTML(app, uid, name)
56
+ return html === undefined ? { view: { html: "" } } : { text, view: { html } }
57
+ })
58
+ const head = useRef<HeadEntry | undefined>(undefined)
59
+ useEffect(() => () => head.current?.dispose(), [])
60
+ useEffect(() => {
61
+ if (shown.text === text) return
62
+ const controller = new AbortController()
63
+ fetchServerComponent(app, name, text, controller.signal)
64
+ .then((view) => {
65
+ if (controller.signal.aborted) return
66
+ head.current?.dispose()
67
+ head.current = view.head ? app.head.push(view.head) : undefined
68
+ setShown({ text, view })
69
+ })
70
+ .catch((error: unknown) => {
71
+ if (!controller.signal.aborted) setShown((last) => ({ ...last, error }))
72
+ })
73
+ return () => controller.abort()
74
+ }, [text])
75
+ if (shown.error !== undefined) throw shown.error
76
+ return h("hamur-component", {
77
+ name,
78
+ uid,
79
+ ...serverComponentAttributes(name),
80
+ dangerouslySetInnerHTML: { __html: shown.view.html as string },
81
+ })
82
+ }
83
+ ServerComponent.displayName = `${name}.server`
84
+ return ServerComponent
85
+ }
@@ -0,0 +1,141 @@
1
+ import { h } from "preact"
2
+ import type { ComponentType, FunctionComponent } from "preact"
3
+ import { useEffect, useErrorBoundary, useState } from "preact/hooks"
4
+
5
+ interface Slot {
6
+ impl: ComponentType<any>
7
+ listeners: Set<() => void>
8
+ wrapper: FunctionComponent<any>
9
+ guard: FunctionComponent<any>
10
+ inner: FunctionComponent<any>
11
+ }
12
+
13
+ export interface HotModule {
14
+ readonly id: string
15
+ signature: string
16
+ version: string
17
+ /** The key of every guard: bumped to remount the module's components. */
18
+ generation: number
19
+ /** Set from a swap until the renders it caused are done: a render error below the wrapper then remounts, then reloads. */
20
+ swapped: boolean
21
+ retried: boolean
22
+ /** The namespaces of the modules it imports: a new one means that module ran again. */
23
+ dependencies: readonly unknown[]
24
+ next?: { signature: string; version: string; dependencies: readonly unknown[] }
25
+ slots: Map<string, Slot>
26
+ component<P>(name: string, impl: ComponentType<P>): ComponentType<P>
27
+ commit(): void
28
+ }
29
+
30
+ const queued = new Set<HotModule>()
31
+
32
+ const isThenable = (value: unknown) => typeof (value as PromiseLike<unknown> | null)?.then === "function"
33
+
34
+ function notify(module: HotModule): void {
35
+ for (const slot of module.slots.values()) for (const listener of slot.listeners) listener()
36
+ }
37
+
38
+ function flush(): void {
39
+ const modules = [...queued]
40
+ queued.clear()
41
+ for (const module of modules) {
42
+ const { signature, version, dependencies } = module.next!
43
+ const dependencyChanged =
44
+ version === module.version && dependencies.some((namespace, index) => namespace !== module.dependencies[index])
45
+ module.next = undefined
46
+ const reason =
47
+ signature !== module.signature ? "hook signature changed" : dependencyChanged ? "a dependency changed" : undefined
48
+ module.signature = signature
49
+ module.version = version
50
+ module.dependencies = dependencies
51
+ if (reason) {
52
+ module.generation++
53
+ console.info(`[hamur] hot: ${module.id} remounted (${reason})`)
54
+ }
55
+ module.swapped = true
56
+ module.retried = false
57
+ notify(module)
58
+ }
59
+ setTimeout(() => {
60
+ for (const module of modules) module.swapped = false
61
+ })
62
+ }
63
+
64
+ /** After a swap, a render error below the module's components remounts them once, then reloads. */
65
+ function recover(module: HotModule, error: unknown): void {
66
+ if (!module.swapped || isThenable(error)) throw error
67
+ if (module.retried) {
68
+ location.reload()
69
+ throw error
70
+ }
71
+ console.error(error)
72
+ module.retried = true
73
+ module.generation++
74
+ queueMicrotask(() => notify(module))
75
+ }
76
+
77
+ function createSlot(module: HotModule, impl: ComponentType<any>): Slot {
78
+ const slot: Slot = {
79
+ impl,
80
+ listeners: new Set(),
81
+ wrapper(props) {
82
+ const [, setVersion] = useState(0)
83
+ useEffect(() => {
84
+ const listener = () => setVersion((version) => version + 1)
85
+ slot.listeners.add(listener)
86
+ return () => void slot.listeners.delete(listener)
87
+ }, [])
88
+ return h(slot.guard, { ...props, key: module.generation })
89
+ },
90
+ guard(props) {
91
+ const [error] = useErrorBoundary((caught) => recover(module, caught))
92
+ return error ? null : h(slot.inner, props)
93
+ },
94
+ inner(this: unknown, props, context) {
95
+ const impl = slot.impl as ComponentType<any> & { prototype?: { render?: unknown; isReactComponent?: unknown } }
96
+ if (impl.prototype?.render || impl.prototype?.isReactComponent) return h(impl, props)
97
+ return (impl as FunctionComponent<any>).call(
98
+ this,
99
+ { ...(impl as { defaultProps?: object }).defaultProps, ...props },
100
+ context,
101
+ )
102
+ },
103
+ }
104
+ return slot
105
+ }
106
+
107
+ /** One per module version, `previous` is what the module's last version returned. */
108
+ export function hotModule(
109
+ previous: HotModule | undefined,
110
+ id: string,
111
+ signature: string,
112
+ version: string,
113
+ dependencies: readonly unknown[] = [],
114
+ ): HotModule {
115
+ if (previous) {
116
+ previous.next = { signature, version, dependencies }
117
+ return previous
118
+ }
119
+ const module: HotModule = {
120
+ id,
121
+ signature,
122
+ version,
123
+ dependencies,
124
+ generation: 0,
125
+ swapped: false,
126
+ retried: false,
127
+ slots: new Map(),
128
+ component(name, impl) {
129
+ let slot = module.slots.get(name)
130
+ if (slot) slot.impl = impl
131
+ else module.slots.set(name, (slot = createSlot(module, impl)))
132
+ return slot.wrapper as ComponentType<any>
133
+ },
134
+ commit() {
135
+ if (!module.next || queued.has(module)) return
136
+ if (queued.size === 0) queueMicrotask(flush)
137
+ queued.add(module)
138
+ },
139
+ }
140
+ return module
141
+ }
@@ -0,0 +1,8 @@
1
+ import { snapshotHydration } from "hamur/adapter/dev"
2
+ import { devHydration } from "./hydration.ts"
3
+
4
+ // Preact reports no mismatch; it rewrites a text that differs while it hydrates, so the DOM after shows it.
5
+ devHydration.watch = (root) => {
6
+ const snapshot = snapshotHydration(root)
7
+ return { done: () => void snapshot.compare() }
8
+ }
@@ -0,0 +1,7 @@
1
+ /** What `hydration-dev.ts` hands the client runtime in `hamur dev`; a production client never sets it. */
2
+ export interface HydrationWatch {
3
+ /** The root hydrated: its DOM is compared with the server markup saved before. */
4
+ done(): void
5
+ }
6
+
7
+ export const devHydration: { watch?: (root: Element) => HydrationWatch } = {}
@@ -0,0 +1,37 @@
1
+ import { h, hydrate, render } from "preact"
2
+ import type { IslandContext } from "hamur/adapter"
3
+ import { RootBoundary, islandElement } from "../context.ts"
4
+
5
+ const sources = new WeakMap<Element, { component: unknown; ctx: IslandContext }>()
6
+
7
+ const element = (component: unknown, props: Record<string, unknown>, ctx: IslandContext) =>
8
+ h(RootBoundary, { app: ctx.app, children: islandElement(component, props, ctx) })
9
+
10
+ /** Hydrates the island's server HTML in `el` as a root of its own. */
11
+ export function hydrateIsland(
12
+ el: Element,
13
+ component: unknown,
14
+ props: Record<string, unknown>,
15
+ ctx: IslandContext,
16
+ ): void {
17
+ sources.set(el, { component, ctx })
18
+ hydrate(element(component, props, ctx), el)
19
+ }
20
+
21
+ /** Renders the island into `el` in place of the fallback it holds. */
22
+ export function mountIsland(el: Element, component: unknown, props: Record<string, unknown>, ctx: IslandContext): void {
23
+ el.replaceChildren()
24
+ sources.set(el, { component, ctx })
25
+ render(element(component, props, ctx), el)
26
+ }
27
+
28
+ export function unmountIsland(el: Element): void {
29
+ sources.delete(el)
30
+ render(null, el)
31
+ }
32
+
33
+ /** Renders into the island's root again with new props, which keeps its state. */
34
+ export function updateIsland(el: Element, props: Record<string, unknown>): void {
35
+ const source = sources.get(el)
36
+ if (source) render(element(source.component, props, source.ctx), el)
37
+ }
@@ -0,0 +1,102 @@
1
+ import { h, options } from "preact"
2
+ import type { ComponentChild, ComponentType } from "preact"
3
+ import { useId } from "preact/hooks"
4
+ import { renderToString } from "preact-render-to-string"
5
+ import { renderToReadableStream } from "preact-render-to-string/stream"
6
+ import {
7
+ publicError,
8
+ renderInPasses,
9
+ serverComponentAttributes,
10
+ serverComponentProps,
11
+ setAdapterInstance,
12
+ } from "hamur/adapter"
13
+ import type { ComponentRenderContext, RenderContext, RenderResult } from "hamur/adapter"
14
+ import { buildElement, installKeepAlive, islandElement } from "../context.ts"
15
+ import { collectingIslands, islandsSettled, renderSettled } from "../island-html.ts"
16
+ import * as keepAlive from "../keepalive.ts"
17
+ import { lazyModules } from "../lazy-hydration.ts"
18
+
19
+ installKeepAlive(keepAlive)
20
+
21
+ ;(options as { errorBoundaries?: boolean }).errorBoundaries = true
22
+
23
+ export async function render(ctx: RenderContext): Promise<RenderResult> {
24
+ await setAdapterInstance(ctx.app, null)
25
+ return renderInPasses<RenderResult>({
26
+ app: ctx.app,
27
+ head: ctx.head,
28
+ render: async (head) => {
29
+ await lazyModules()
30
+ const element = buildElement({ ...ctx, head })
31
+ if (!ctx.stream) {
32
+ const pending: Promise<void>[] = []
33
+ const body = collectingIslands(pending, () => renderToString(element))
34
+ await islandsSettled(ctx.app, pending)
35
+ return { body }
36
+ }
37
+ const pending: Promise<void>[] = []
38
+ const stream = collectingIslands(pending, () =>
39
+ renderToReadableStream(element, ctx.nonce ? { nonce: ctx.nonce } : undefined),
40
+ )
41
+ stream.allReady.catch(() => {})
42
+ if (pending.length) {
43
+ await islandsSettled(ctx.app, pending)
44
+ return { body: stream }
45
+ }
46
+ return { body: await afterShell(stream, (error) => void publicError(ctx.app, error)) }
47
+ },
48
+ drop: ({ body }) => void (typeof body === "string" ? undefined : body.cancel()),
49
+ })
50
+ }
51
+
52
+ /** `component` as a root of its own, with each island inside it rendered in place. */
53
+ export async function renderComponent(
54
+ component: unknown,
55
+ props: Record<string, unknown>,
56
+ ctx: ComponentRenderContext,
57
+ ): Promise<{ html: string }> {
58
+ // `renderIsland` calls this inside the page's synchronous render, whose renderer state a nested render would overwrite.
59
+ await Promise.resolve()
60
+ await lazyModules()
61
+ return { html: await renderSettled(() => renderToString(islandElement(component, props, ctx))) }
62
+ }
63
+
64
+ /** The library rejects `allReady` on every render error and nothing awaits it, which is an unhandled rejection; the shell is read here so its throw reaches the caller. */
65
+ async function afterShell(
66
+ stream: ReadableStream<Uint8Array>,
67
+ late: (error: unknown) => void,
68
+ ): Promise<ReadableStream<Uint8Array>> {
69
+ const reader = stream.getReader()
70
+ const first = await reader.read()
71
+ if (first.done) return new ReadableStream({ start: (controller) => controller.close() })
72
+ return new ReadableStream<Uint8Array>({
73
+ start: (controller) => controller.enqueue(first.value),
74
+ async pull(controller) {
75
+ const chunk = await reader
76
+ .read()
77
+ .catch((error: unknown) => (late(error), { done: true as const, value: undefined }))
78
+ if (chunk.done) controller.close()
79
+ else controller.enqueue(chunk.value)
80
+ },
81
+ cancel: (reason) => reader.cancel(reason),
82
+ })
83
+ }
84
+
85
+ /** The server side of a client-only component renders nothing. */
86
+ export function clientComponent(): () => ComponentChild {
87
+ return () => null
88
+ }
89
+
90
+ /** The server side of a server-only component: the component itself inside `hamur-component`, its props checked as the client sends them. */
91
+ export function serverComponent(
92
+ name: string,
93
+ component: ComponentType<Record<string, unknown>>,
94
+ ): (props: Record<string, unknown>) => ComponentChild {
95
+ function ServerComponent(props: Record<string, unknown>): ComponentChild {
96
+ const uid = useId()
97
+ serverComponentProps(name, props, props.children !== undefined)
98
+ return h("hamur-component", { name, uid, ...serverComponentAttributes(name) }, h(component, props))
99
+ }
100
+ ServerComponent.displayName = `${name}.server`
101
+ return ServerComponent
102
+ }