@hamur/adapter-solid 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 (72) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +35 -2
  3. package/dist/chunks/browser-index-8rhv2s58.js +14 -0
  4. package/dist/chunks/browser-index-b05qbzsh.js +165 -0
  5. package/dist/chunks/browser-index-n80jt19y.js +114 -0
  6. package/dist/chunks/browser-index-ncnkshd9.js +39 -0
  7. package/dist/chunks/browser-index-r4jwfgh7.js +407 -0
  8. package/dist/src/adapter.js +556 -0
  9. package/dist/src/error-page.js +466 -0
  10. package/dist/src/index.js +1535 -0
  11. package/dist/src/keepalive.js +6 -0
  12. package/dist/src/runtime/client.js +174 -0
  13. package/dist/src/runtime/island.js +58 -0
  14. package/dist/src/runtime/server.js +138 -0
  15. package/dist/types/src/activation.d.ts +15 -0
  16. package/dist/types/src/adapter.d.ts +4 -0
  17. package/dist/types/src/async-data.d.ts +21 -0
  18. package/dist/types/src/client-component.d.ts +10 -0
  19. package/dist/types/src/client-fallback.d.ts +2 -0
  20. package/dist/types/src/context.d.ts +89 -0
  21. package/dist/types/src/error-page.d.ts +1 -0
  22. package/dist/types/src/index.d.ts +392 -0
  23. package/dist/types/src/island-html.d.ts +13 -0
  24. package/dist/types/src/island.d.ts +20 -0
  25. package/dist/types/src/jsx-locator.d.ts +6 -0
  26. package/dist/types/src/keepalive.d.ts +30 -0
  27. package/dist/types/src/lazy-hydration.d.ts +13 -0
  28. package/dist/types/src/markdown-page.d.ts +9 -0
  29. package/dist/types/src/markdown.d.ts +13 -0
  30. package/dist/types/src/plugin.d.ts +44 -0
  31. package/dist/types/src/runtime/client.d.ts +13 -0
  32. package/dist/types/src/runtime/hmr-solid.d.ts +5 -0
  33. package/dist/types/src/runtime/hmr.d.ts +27 -0
  34. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  35. package/dist/types/src/runtime/hydration.d.ts +10 -0
  36. package/dist/types/src/runtime/island.d.ts +8 -0
  37. package/dist/types/src/runtime/portal.d.ts +13 -0
  38. package/dist/types/src/runtime/server.d.ts +14 -0
  39. package/dist/types/src/runtime/trusted.d.ts +2 -0
  40. package/dist/types/src/server-island.d.ts +10 -0
  41. package/dist/types/src/svg.d.ts +10 -0
  42. package/package.json +53 -4
  43. package/src/activation.ts +51 -0
  44. package/src/adapter.ts +42 -0
  45. package/src/async-data.ts +105 -0
  46. package/src/client-component.ts +40 -0
  47. package/src/client-fallback.ts +2 -0
  48. package/src/context.ts +495 -0
  49. package/src/env.d.ts +3 -0
  50. package/src/error-page.ts +1 -0
  51. package/src/index.ts +1900 -0
  52. package/src/island-html.ts +58 -0
  53. package/src/island.ts +55 -0
  54. package/src/jsx-locator.ts +199 -0
  55. package/src/keepalive.ts +147 -0
  56. package/src/lazy-hydration.ts +146 -0
  57. package/src/markdown-page.ts +18 -0
  58. package/src/markdown.ts +70 -0
  59. package/src/plugin.ts +310 -0
  60. package/src/runtime/client.ts +175 -0
  61. package/src/runtime/hmr-solid.ts +19 -0
  62. package/src/runtime/hmr.ts +231 -0
  63. package/src/runtime/hydration-dev.ts +41 -0
  64. package/src/runtime/hydration.ts +9 -0
  65. package/src/runtime/island.ts +66 -0
  66. package/src/runtime/portal.ts +64 -0
  67. package/src/runtime/server.ts +160 -0
  68. package/src/runtime/trusted.ts +16 -0
  69. package/src/server-island.ts +47 -0
  70. package/src/solid.d.ts +4 -0
  71. package/src/svg.ts +53 -0
  72. package/src/webmcp.d.ts +20 -0
@@ -0,0 +1,70 @@
1
+ import { createComponent, createMemo, type Component } from "solid-js"
2
+ import { dynamic, type JSX } from "@solidjs/web"
3
+ import { markdownLink, markdownProse, markdownView, type MdView } from "hamur/adapter"
4
+ import type { MarkdownDocument, MdNode } from "hamur/markdown"
5
+ // Read inside render only: index.ts re-exports this module, so `Link` is not bound while it loads.
6
+ import { Link } from "./index.ts"
7
+
8
+ export interface MarkdownRendererProps {
9
+ /** A Markdown AST node, a list of nodes, or a document, which renders its `ast`. */
10
+ value: MdNode | MdNode[] | MarkdownDocument
11
+ /** Components by Markdown component name (kebab case); each gets the node's props as written, `children` and a prop per named slot. */
12
+ components?: Record<string, Component<any>>
13
+ /** Renders `html` nodes, writing what it returns as their inner HTML; without it they are left out. A Markdown page under config `markdown.html` passes the core's Trusted Types writer. */
14
+ raw?: (html: string) => string
15
+ }
16
+
17
+ type Components = Record<string, Component<any>>
18
+
19
+ const VOID = new Set(["hr", "br", "img", "input"])
20
+ const elements = new Map<string, Component<Record<string, unknown>>>()
21
+
22
+ function element(tag: string): Component<Record<string, unknown>> {
23
+ let made = elements.get(tag)
24
+ if (!made) elements.set(tag, (made = dynamic(() => tag, { static: true }) as Component<Record<string, unknown>>))
25
+ return made
26
+ }
27
+
28
+ /** `children` stays a getter, so each child is created inside its parent, in the order hydration claims the nodes. */
29
+ function withChildren(
30
+ props: Record<string, unknown>,
31
+ children: (() => JSX.Element) | undefined,
32
+ ): Record<string, unknown> {
33
+ if (children) Object.defineProperty(props, "children", { get: children, enumerable: true })
34
+ return props
35
+ }
36
+
37
+ function render(view: MdView, raw: (html: string) => string, components: Components): JSX.Element {
38
+ if (typeof view === "string") return view
39
+ if ("html" in view)
40
+ return createComponent(element("hamur-html"), { style: "display:contents", innerHTML: raw(view.html) })
41
+ const nodes = (views: MdView[]) => () => views.map((child) => render(child, raw, components))
42
+ const children = nodes(view.children)
43
+ if ("component" in view) {
44
+ const component = Object.hasOwn(components, view.component) ? components[view.component] : undefined
45
+ if (component) {
46
+ const props: Record<string, unknown> = { ...view.props }
47
+ for (const [name, views] of Object.entries(view.slots))
48
+ Object.defineProperty(props, name, { get: nodes(views), enumerable: true })
49
+ return createComponent(component, withChildren(props, view.children.length ? children : undefined))
50
+ }
51
+ return view.attrs ? createComponent(element(view.component), withChildren({ ...view.attrs }, children)) : children()
52
+ }
53
+ const link = markdownLink(view)
54
+ if (link)
55
+ return createComponent(
56
+ Link as unknown as Component<Record<string, unknown>>,
57
+ withChildren({ ...link.attrs, to: link.to }, children),
58
+ )
59
+ return createComponent(element(view.tag), withChildren({ ...view.attrs }, VOID.has(view.tag) ? undefined : children))
60
+ }
61
+
62
+ /** Renders the Markdown AST through `dynamic`, an internal link as `Link`, a component node as its component in `components`. */
63
+ export function MarkdownRenderer(props: MarkdownRendererProps): JSX.Element {
64
+ return createMemo(() => {
65
+ const { value, components } = markdownProse(props.value, props.components ?? {})
66
+ return markdownView(value, { html: props.raw !== undefined, components }).map((view) =>
67
+ render(view, props.raw!, components),
68
+ )
69
+ }) as unknown as JSX.Element
70
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,310 @@
1
+ import { transformAsync } from "@babel/core"
2
+ import presetTypescript from "@babel/preset-typescript"
3
+ import solidBabel from "@solidjs/babel-plugin"
4
+ import { readFileSync, realpathSync } from "node:fs"
5
+ import { dirname, join, relative } from "node:path"
6
+ import type { AdapterBuildContext, AdapterTransform } from "hamur/adapter"
7
+ import { dropDevOnly } from "hamur/adapter/build"
8
+ import { locateJsx } from "./jsx-locator.ts"
9
+
10
+ const HMR_RUNTIME = join(import.meta.dir, "runtime/hmr.ts")
11
+ const PORTAL_RUNTIME = join(import.meta.dir, "runtime/portal.ts")
12
+ const CLIENT_RUNTIME = join(import.meta.dir, "runtime/client.ts")
13
+ const HYDRATION_DEV = join(import.meta.dir, "runtime/hydration-dev.ts")
14
+ const WEB_IMPORT = /^import\s*\{([^}]*)\}\s*from\s*(["'])@solidjs\/web\2;?/gm
15
+ const PORTAL_SPECIFIER = /^Portal(?:\s+as\s+[\w$]+)?$/
16
+ const SHIMS: Record<string, string> = {
17
+ "solid-js": join(import.meta.dir, "runtime/hmr-solid.ts"),
18
+ }
19
+ const ROUTE_MODULE = /(^|\/)((pages|layouts)\/|app\.[jt]sx$)/
20
+ const SIGNATURE_CALL = /\b(createSignal|createStore)\s*(?:<[^>]*>)?\s*\(/g
21
+ const SIGNATURE_ARGUMENTS = new Set(["createSignal", "createStore"])
22
+ const ARROW = String.raw`(?:async\s*)?(?:\((?:[^()]|\([^()]*\))*\)|[A-Za-z_$][\w$]*)\s*(?::[^=]+)?=>`
23
+ const DEFAULT_FUNCTION = /^export default (async )?function\b\s*([A-Za-z_$][\w$]*)?/m
24
+ const DEFAULT_ARROW = new RegExp(String.raw`^export default (?=${ARROW})`, "m")
25
+ const DEFAULT_NAME = /^export default ([A-Z][\w$]*)\s*;?\s*$/m
26
+ const DEFAULT_ANY = /^export default /m
27
+ const NAMED_FUNCTION = /^export function ([A-Z][\w$]*)(?=\s*[<(])/gm
28
+ const NAMED_CONST = new RegExp(
29
+ String.raw`^export const ([A-Z][\w$]*)(?=(?:\s*:[^=]+)?\s*=\s*(?:function\b|${ARROW}))`,
30
+ "gm",
31
+ )
32
+ /** A JSX tag or fragment: `<` not preceded by an identifier, `)`, `]` or `.` (generics, comparisons). */
33
+ const JSX = /(?<![\w$)\].])<(?:[A-Za-z][\w.:-]*(?=[\s/>])|>)/
34
+ const TOP_LEVEL = /^(?:export|import|const|let|var|function|class|async\s+function|interface|type)\b/m
35
+ /** Imports whose namespace says nothing about code: styles, assets, data and Hamur's own virtual modules. */
36
+ const NOT_A_MODULE =
37
+ /^#hamur\/|\.(?:css|scss|sass|less|styl|svg|png|jpe?g|gif|webp|avif|ico|json|txt|md|wasm|html)(?:\?.*)?$|\?/i
38
+ const BINDING = /(?:const|let|var)\s+(\[[^\]]*\]|\{[^}]*\}|[\w$]+)\s*(?::[^=;]+)?=\s*$/
39
+
40
+ /** From `start` to the next top-level statement: the declaration a match belongs to. */
41
+ function declaration(source: string, start: number): string {
42
+ const line = source.indexOf("\n", start)
43
+ if (line === -1) return source.slice(start)
44
+ const next = source.slice(line + 1).search(TOP_LEVEL)
45
+ return source.slice(start, next === -1 ? source.length : line + 1 + next)
46
+ }
47
+
48
+ /** The text inside the parentheses opening at `open`, strings skipped. */
49
+ function argumentsAt(source: string, open: number): string {
50
+ let depth = 0
51
+ let quote = ""
52
+ for (let i = open; i < source.length; i++) {
53
+ const char = source[i]
54
+ if (quote) {
55
+ if (char === "\\") i++
56
+ else if (char === quote) quote = ""
57
+ } else if (char === '"' || char === "'" || char === "`") quote = char
58
+ else if (char === "(") depth++
59
+ else if (char === ")" && --depth === 0) return source.slice(open + 1, i)
60
+ }
61
+ return source.slice(open + 1)
62
+ }
63
+
64
+ /**
65
+ * One `<binding>=<call>` entry per call in source order; the calls in `withArguments`
66
+ * also carry their arguments, so reordering or swapping two of them changes the signature.
67
+ */
68
+ export function refreshSignature(source: string, calls: RegExp, withArguments: ReadonlySet<string>): string {
69
+ const entries: string[] = []
70
+ for (const match of source.matchAll(calls)) {
71
+ const name = match[1]!
72
+ const binding = source.slice(Math.max(0, match.index - 200), match.index).match(BINDING)?.[1] ?? ""
73
+ const args = withArguments.has(name) ? `(${argumentsAt(source, match.index + match[0].length - 1)})` : ""
74
+ entries.push(`${binding}=${name}${args}`.replace(/\s+/g, " "))
75
+ }
76
+ return entries.join(";")
77
+ }
78
+
79
+ export interface RefreshOptions {
80
+ /** Path relative to `rootDir`, also the module's key in the hot runtime. */
81
+ id: string
82
+ /** Pages, layouts and `app.<ext>` accept themselves even with other exports (`meta`). */
83
+ route: boolean
84
+ runtime?: string
85
+ }
86
+
87
+ export interface RefreshResult {
88
+ code: string
89
+ signature: string
90
+ accepted: boolean
91
+ }
92
+
93
+ /**
94
+ * Wraps every component export in the hot runtime and bakes the module's refresh signature. A component is
95
+ * a capitalised function or arrow whose declaration renders JSX. Its binding stays the module's own (a hoisted
96
+ * `function` or a `let`) and is reassigned to the wrapper at the end, so the export, a circular importer and the
97
+ * module's other components all see the wrapper once the module has run.
98
+ */
99
+ export function refreshTransform(source: string, { id, route, runtime = HMR_RUNTIME }: RefreshOptions): RefreshResult {
100
+ const { exports, imports } = new Bun.Transpiler({ loader: "tsx" }).scan(source)
101
+ const dependencies = [
102
+ ...new Set(
103
+ imports
104
+ .filter(({ kind, path }) => kind === "import-statement" && !NOT_A_MODULE.test(path))
105
+ .map(({ path }) => path),
106
+ ),
107
+ ]
108
+ const signature = refreshSignature(source, SIGNATURE_CALL, SIGNATURE_ARGUMENTS)
109
+ const components = new Map<string, string>()
110
+ const renders = (text: string, at: number) => JSX.test(declaration(text, at))
111
+ let body = source.replace(NAMED_FUNCTION, (match, name: string, at: number, text: string) =>
112
+ renders(text, at) ? (components.set(name, name), `function ${name}`) : match,
113
+ )
114
+ body = body.replace(NAMED_CONST, (match, name: string, at: number, text: string) =>
115
+ renders(text, at) ? (components.set(name, name), `let ${name}`) : match,
116
+ )
117
+ const fn = body.match(DEFAULT_FUNCTION)
118
+ const named = body.match(DEFAULT_NAME)?.[1]
119
+ const declared = (name: string) => {
120
+ const at = body.search(
121
+ new RegExp(String.raw`^(?:async\s+)?function\s+${name}\b|^(?:const|let|var)\s+${name}\b`, "m"),
122
+ )
123
+ return at !== -1 && renders(body, at)
124
+ }
125
+ if (fn?.[2] && (route || renders(body, fn.index!))) {
126
+ body = body.replace(DEFAULT_FUNCTION, `${fn[1] ?? ""}function ${fn[2]}`)
127
+ components.set("default", fn[2])
128
+ } else if (
129
+ route
130
+ ? DEFAULT_ANY.test(body)
131
+ : (fn && renders(body, fn.index!)) ||
132
+ (DEFAULT_ARROW.test(body) && renders(body, body.search(DEFAULT_ARROW))) ||
133
+ (named !== undefined && declared(named))
134
+ ) {
135
+ body = body.replace(DEFAULT_ANY, "let __hamurDefault = ")
136
+ components.set("default", "__hamurDefault")
137
+ }
138
+ if (components.size === 0) return { code: source, signature: "", accepted: false }
139
+ const accepted = route || exports.every((name) => components.has(name))
140
+ const names = [...components]
141
+ return {
142
+ signature,
143
+ accepted,
144
+ code: [
145
+ `import { hotModule as __hamurHot } from ${JSON.stringify(runtime)};`,
146
+ ...dependencies.map((path, index) => `import * as __hamurDep${index} from ${JSON.stringify(path)};`),
147
+ body,
148
+ `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(", ")}]);`,
149
+ `if (import.meta.hot) import.meta.hot.data.hamur = __hamurMod;`,
150
+ ...names.map(([name, local]) => `${local} = __hamurMod.component(${JSON.stringify(name)}, ${local});`),
151
+ `export { ${names.map(([name, local]) => (name === local ? name : `${local} as ${name}`)).join(", ")} };`,
152
+ `__hamurMod.commit();`,
153
+ ...(accepted ? [`if (import.meta.hot) import.meta.hot.accept();`] : []),
154
+ ].join("\n"),
155
+ }
156
+ }
157
+
158
+ /** The module's path relative to `rootDir` when it is an app source (not under `node_modules` or the build dir). */
159
+ export function appModuleId(rootDir: string, buildDir: string): (path: string) => string | undefined {
160
+ let real = rootDir
161
+ try {
162
+ real = realpathSync(rootDir)
163
+ } catch {}
164
+ const roots = [...new Set([rootDir, real])]
165
+ const build = relative(rootDir, buildDir)
166
+ const inBuild = (id: string) =>
167
+ build !== "" && !build.startsWith("..") && (id === build || id.startsWith(`${build}/`))
168
+ return (path) => {
169
+ if (path.includes("/node_modules/")) return undefined
170
+ for (const root of roots) {
171
+ const id = relative(root, path)
172
+ if (!id.startsWith("..") && !id.startsWith("/")) return inBuild(id) ? undefined : id
173
+ }
174
+ return undefined
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Points the `solid-js` import and export statements of an app module at the dev shim.
180
+ * Done on the source, not with `onResolve`: Bun's dev bundler re-sends a module an `onResolve` redirected, with the
181
+ * `solid-js` it re-exports, on every hot update of an importer, which evaluates a second Solid. Only statements that
182
+ * start a line are rewritten, so strings and comments keep their text.
183
+ */
184
+ export function shimImports(source: string): string {
185
+ return source.replace(
186
+ /^(\s*(?:(?:import|export)\b[^;'"`]*?\bfrom\s*|import\s*))(["'])(solid-js)\2/gm,
187
+ (_, statement: string, quote: string, specifier: string) => `${statement}${quote}${SHIMS[specifier]}${quote}`,
188
+ )
189
+ }
190
+
191
+ /** The server build takes `Portal` from the adapter, because @solidjs/web's server `Portal` renders nothing. */
192
+ export function serverPortal(code: string): string {
193
+ return code.replace(WEB_IMPORT, (statement, list: string) => {
194
+ const specifiers = list
195
+ .split(",")
196
+ .map((part) => part.trim())
197
+ .filter(Boolean)
198
+ const portal = specifiers.find((part) => PORTAL_SPECIFIER.test(part))
199
+ if (!portal) return statement
200
+ const rest = specifiers.filter((part) => part !== portal)
201
+ const own = `import { ${portal} } from ${JSON.stringify(PORTAL_RUNTIME)};`
202
+ return rest.length ? `import { ${rest.join(", ")} } from "@solidjs/web";\n${own}` : own
203
+ })
204
+ }
205
+
206
+ export async function compileSolid(path: string, source: string, target: "client" | "server"): Promise<string> {
207
+ const result = await transformAsync(source, {
208
+ filename: path,
209
+ babelrc: false,
210
+ configFile: false,
211
+ plugins: [
212
+ [solidBabel, { moduleName: "@solidjs/web", generate: target === "server" ? "ssr" : "dom", hydratable: true }],
213
+ ],
214
+ presets: [presetTypescript],
215
+ })
216
+ if (!result?.code) throw new Error(`Babel produced no output for ${path}`)
217
+ return target === "server" ? serverPortal(result.code) : result.code
218
+ }
219
+
220
+ export function solidPlugin({ target, dev, hmr, rootDir, buildDir }: AdapterBuildContext): AdapterTransform {
221
+ const hot = hmr && target === "client"
222
+ const appModule = appModuleId(rootDir, buildDir)
223
+ return {
224
+ name: `hamur-solid-${target}`,
225
+ filter: { id: /\.[jt]sx$/ },
226
+ async transform(code, { id: path }) {
227
+ if (path.includes("/node_modules/")) return undefined
228
+ let source = code
229
+ if (!dev) source = dropDevOnly(source, "@hamur/adapter-solid", "markup")
230
+ else {
231
+ const file = appModule(path)
232
+ if (file !== undefined) source = locateJsx(source, file)
233
+ }
234
+ if (hot) {
235
+ const id = appModule(path)
236
+ const layerRoute = id === undefined ? relative(rootDir, path) : undefined
237
+ if (id !== undefined) source = shimImports(refreshTransform(source, { id, route: ROUTE_MODULE.test(id) }).code)
238
+ else if (ROUTE_MODULE.test(layerRoute!))
239
+ source = shimImports(refreshTransform(source, { id: layerRoute!, route: true }).code)
240
+ }
241
+ return { code: await compileSolid(path, source, target), loader: "js" }
242
+ },
243
+ }
244
+ }
245
+
246
+ const DEV_CONDITIONS = new Set(["browser", "development", "import", "default"])
247
+ const SOLID_IMPORT = /(\bfrom\s*|\bimport\s*\(?\s*)(["'])(solid-js(?:\/internal)?|@solidjs\/(?:web|signals))\2/g
248
+
249
+ function exportTarget(target: unknown): string | undefined {
250
+ if (typeof target === "string") return target
251
+ if (target === null || typeof target !== "object") return undefined
252
+ for (const [condition, value] of Object.entries(target)) {
253
+ if (!DEV_CONDITIONS.has(condition)) continue
254
+ const found = exportTarget(value)
255
+ if (found !== undefined) return found
256
+ }
257
+ return undefined
258
+ }
259
+
260
+ /** The file each Solid specifier has under the `browser` and `development` conditions, read from its package's `exports`; `@solidjs/signals` is the one `solid-js` depends on. */
261
+ export function solidDevFiles(rootDir: string): Record<string, string> {
262
+ const solid = Bun.resolveSync("solid-js/package.json", rootDir)
263
+ const manifests: Record<string, string> = {
264
+ "solid-js": solid,
265
+ "@solidjs/web": Bun.resolveSync("@solidjs/web/package.json", rootDir),
266
+ "@solidjs/signals": Bun.resolveSync("@solidjs/signals/package.json", dirname(solid)),
267
+ }
268
+ const files: Record<string, string> = {}
269
+ for (const [specifier, name, subpath] of [
270
+ ["solid-js", "solid-js", "."],
271
+ ["solid-js/internal", "solid-js", "./internal"],
272
+ ["@solidjs/web", "@solidjs/web", "."],
273
+ ["@solidjs/signals", "@solidjs/signals", "."],
274
+ ] as const) {
275
+ const manifest = manifests[name]!
276
+ const { exports } = JSON.parse(readFileSync(manifest, "utf8")) as { exports: Record<string, unknown> }
277
+ const target = exportTarget(exports[subpath])
278
+ if (target === undefined) throw new Error(`${name} has no development build for ${specifier}`)
279
+ files[specifier] = join(dirname(manifest), target)
280
+ }
281
+ return files
282
+ }
283
+
284
+ /** In `hamur dev` every import of `solid-js`, `@solidjs/web` and `@solidjs/signals`, in the app, the adapter and other packages alike, reaches the development build, so one Solid runs and its devtools hooks exist. */
285
+ export function solidDevBuild({ rootDir }: AdapterBuildContext): AdapterTransform {
286
+ let files: Record<string, string> | undefined
287
+ return {
288
+ name: "hamur-solid-development",
289
+ filter: { id: /\.[cm]?[jt]sx?$/ },
290
+ transform(code) {
291
+ if (!code.includes("solid-js") && !code.includes("@solidjs/")) return undefined
292
+ files ??= solidDevFiles(rootDir)
293
+ const found = files
294
+ const contents = code.replace(
295
+ SOLID_IMPORT,
296
+ (_, head: string, quote: string, specifier: string) => `${head}${quote}${found[specifier]}${quote}`,
297
+ )
298
+ return contents === code ? undefined : contents
299
+ },
300
+ }
301
+ }
302
+
303
+ /** In `hamur dev` the client runtime imports `runtime/hydration-dev.ts` first, which feeds the hydration mismatch report; a build adds nothing. */
304
+ export function solidHydrationPlugin(): AdapterTransform {
305
+ return {
306
+ name: "hamur-solid-hydration",
307
+ filter: { id: new RegExp(`^${CLIENT_RUNTIME.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) },
308
+ transform: (code) => `import ${JSON.stringify(HYDRATION_DEV)}; ${code}`,
309
+ }
310
+ }
@@ -0,0 +1,175 @@
1
+ import {
2
+ Errored,
3
+ createComponent,
4
+ createEffect,
5
+ createMemo,
6
+ createSignal,
7
+ createUniqueId,
8
+ flush,
9
+ omit,
10
+ onCleanup,
11
+ untrack,
12
+ useContext,
13
+ } from "solid-js"
14
+ import type { Accessor, Component, Setter } from "solid-js"
15
+ import { clientFallbackIds } from "../client-fallback.ts"
16
+ import { dynamic, hydrate as hydrateRoot, render as renderRoot } from "@solidjs/web"
17
+ import type { JSX } from "@solidjs/web"
18
+ import { setAdapterInstance } from "hamur/adapter"
19
+ import type { ClientContext, ServerComponentView } from "hamur/adapter"
20
+ import {
21
+ fetchServerComponent,
22
+ reportClientError,
23
+ serverComponentAttributes,
24
+ serverComponentProps,
25
+ takeServerHTML,
26
+ } from "hamur/adapter"
27
+ import type { HeadEntry } from "hamur/app"
28
+ import { AppContext, Root, appState } from "../context.ts"
29
+ import { devHydration, type HydrationWatch } from "./hydration.ts"
30
+ import { trustTemplates } from "./trusted.ts"
31
+ import type { AppState } from "../context.ts"
32
+
33
+ export { installKeepAlive } from "../context.ts"
34
+
35
+ let setState: Setter<AppState> | undefined
36
+ let remount: (() => void) | undefined
37
+ let remounting: { error?: { thrown: unknown } } | undefined
38
+ let starting: Promise<void> | undefined
39
+ let hydrationWatch: HydrationWatch | undefined
40
+
41
+ export const hydrationCanBeAborted = true
42
+
43
+ const ServerComponentElement = dynamic(() => "hamur-component", { static: true }) as Component<Record<string, unknown>>
44
+
45
+ /**
46
+ * The root boundary, an `Errored` around `Root` that the server renders too (`guardedRoot`), so the hydration
47
+ * keys agree. A failure reports once and renders nothing; the next state tries the page again.
48
+ */
49
+ function guarded(ctx: ClientContext, state: Accessor<AppState>): JSX.Element {
50
+ return createComponent(Errored, {
51
+ fallback: (error: Accessor<unknown>, reset: () => void) => {
52
+ const thrown = untrack(error)
53
+ // The dev hot runtime reloads when its remount fails.
54
+ if (remounting) {
55
+ remounting.error ??= { thrown }
56
+ return undefined
57
+ }
58
+ hydrationWatch?.failed(thrown)
59
+ // Reported and reset after the flush that failed: the error page's update would otherwise flush inside it.
60
+ queueMicrotask(() => reportClientError(ctx.app, thrown, { render: true }))
61
+ createEffect(
62
+ state,
63
+ (current, previous) => {
64
+ if (current !== previous) queueMicrotask(reset)
65
+ },
66
+ { defer: true },
67
+ )
68
+ return undefined
69
+ },
70
+ get children() {
71
+ return createComponent(Root, { state })
72
+ },
73
+ })
74
+ }
75
+
76
+ function start(ctx: ClientContext, attach: (fn: () => JSX.Element, node: Element) => () => void): void {
77
+ trustTemplates()
78
+ const [state, set] = createSignal(appState(ctx))
79
+ setState = set
80
+ ;(ctx.app as AppState["app"]).error?.subscribe?.(() => set((current) => ({ ...current })))
81
+ const node = ctx.root
82
+ const mountRoot = (attachRoot: typeof attach) => {
83
+ const dispose = attachRoot(() => guarded(ctx, state), node)
84
+ remount = () => {
85
+ dispose()
86
+ node.textContent = ""
87
+ remounting = {}
88
+ try {
89
+ mountRoot((fn, target) => renderRoot(fn, target))
90
+ const failed = remounting.error
91
+ if (failed) throw failed.thrown
92
+ } finally {
93
+ remounting = undefined
94
+ }
95
+ }
96
+ }
97
+ mountRoot(attach)
98
+ }
99
+
100
+ /** Disposes the root and renders it again with the same app state; the dev hot runtime calls it after a swap. */
101
+ export function remountRoot(): void {
102
+ remount?.()
103
+ }
104
+
105
+ export async function hydrate(ctx: ClientContext): Promise<void> {
106
+ await (starting = setAdapterInstance(ctx.app, null))
107
+ for (const portal of document.querySelectorAll("[data-hamur-portal]")) portal.remove()
108
+ for (const id of Array.isArray(ctx.payload.clientFallback) ? ctx.payload.clientFallback : [])
109
+ clientFallbackIds.add(String(id))
110
+ hydrationWatch = devHydration.watch?.(ctx.root)
111
+ start(ctx, (fn, node) => hydrateRoot(fn, node))
112
+ hydrationWatch?.done(() => remount?.())
113
+ }
114
+
115
+ export async function mount(ctx: ClientContext): Promise<void> {
116
+ await (starting = setAdapterInstance(ctx.app, null))
117
+ start(ctx, (fn, node) => renderRoot(fn, node))
118
+ }
119
+
120
+ /** Solid batches a write until the microtask; the contract has the page in the DOM when `update` returns. */
121
+ export function update(ctx: ClientContext): void | Promise<void> {
122
+ if (!setState && starting) return starting.then(() => update(ctx))
123
+ if (!setState) throw new Error("update() called before hydrate() or mount()")
124
+ setState(appState(ctx))
125
+ flush()
126
+ }
127
+
128
+ export { clientComponent } from "../client-component.ts"
129
+
130
+ /** The client side of a server-only component: the server HTML, never hydrated; a new props text fetches it anew. */
131
+ export function serverComponent(name: string): Component<Record<string, unknown>> {
132
+ return (props) => {
133
+ const app = useContext(AppContext)!().app
134
+ const uid = createUniqueId()
135
+ const text = createMemo(() =>
136
+ serverComponentProps(name, { ...omit(props, "children") }, props.children !== undefined),
137
+ )
138
+ const taken = takeServerHTML(app, uid, name)
139
+ const [view, setView] = createSignal<ServerComponentView["html"]>(taken ?? "")
140
+ const [failed, setFailed] = createSignal<{ error: unknown }>()
141
+ let requested: string | undefined = taken === undefined ? undefined : ""
142
+ let head: HeadEntry | undefined
143
+ onCleanup(() => head?.dispose())
144
+ createEffect(text, (current) => {
145
+ if (requested === "") requested = current
146
+ if (current === requested) return
147
+ const controller = new AbortController()
148
+ fetchServerComponent(app, name, current, controller.signal).then(
149
+ (next) => {
150
+ if (controller.signal.aborted) return
151
+ head?.dispose()
152
+ head = next.head ? app.head.push(next.head) : undefined
153
+ requested = current
154
+ setView(() => next.html)
155
+ },
156
+ (error: unknown) => {
157
+ if (!controller.signal.aborted) setFailed({ error })
158
+ },
159
+ )
160
+ return () => controller.abort()
161
+ })
162
+ return createMemo(() => {
163
+ const thrown = failed()
164
+ if (thrown) throw thrown.error
165
+ return createComponent(ServerComponentElement, {
166
+ name,
167
+ uid,
168
+ ...serverComponentAttributes(name),
169
+ get innerHTML() {
170
+ return view()
171
+ },
172
+ })
173
+ }) as unknown as JSX.Element
174
+ }
175
+ }
@@ -0,0 +1,19 @@
1
+ import { createSignal as solidCreateSignal, createStore as solidCreateStore, snapshot } from "solid-js"
2
+ import { restored, track } from "./hmr.ts"
3
+
4
+ export * from "solid-js"
5
+
6
+ /** Dev only: app modules import `solid-js` from here, so a hot update starts from the last value; a function form is derived and computed again, so nothing of it is kept. */
7
+ export const createSignal = ((value?: unknown, ...rest: unknown[]) => {
8
+ if (typeof value === "function") return (solidCreateSignal as (...args: unknown[]) => unknown)(value, ...rest)
9
+ const signal = (solidCreateSignal as (...args: unknown[]) => [() => unknown, unknown])(restored(value), ...rest)
10
+ track(signal[0])
11
+ return signal
12
+ }) as typeof solidCreateSignal
13
+
14
+ export const createStore = ((value?: unknown, ...rest: unknown[]) => {
15
+ if (typeof value === "function") return (solidCreateStore as (...args: unknown[]) => unknown)(value, ...rest)
16
+ const store = (solidCreateStore as (...args: unknown[]) => [object, unknown])(restored(value), ...rest)
17
+ track(() => snapshot(store[0]))
18
+ return store
19
+ }) as typeof solidCreateStore