@kayjs/kay 2.0.0-alpha.5 → 2.0.0-alpha.6

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.
package/src/cli/check.ts CHANGED
@@ -1,8 +1,9 @@
1
- // `kay check [dir]`: validates routes, Kay compiler rules, config, and runs TypeScript type-checking.
1
+ // `kay check [dir]`: validates routes, Kay compiler & island rules, config, and runs TypeScript type-checking.
2
2
 
3
+ import type { AstNode, ModuleAnalysis } from '../compiler/analyze'
3
4
  import { existsSync, readdirSync, readFileSync } from 'node:fs'
4
- import { join, relative, resolve } from 'node:path'
5
- import { analyzeModule } from '../compiler/index'
5
+ import { basename, dirname, join, relative, resolve } from 'node:path'
6
+ import { analyzeModule, walk } from '../compiler/analyze'
6
7
  import { loadConfig } from '../plugins/index'
7
8
 
8
9
  export interface CheckResult {
@@ -11,6 +12,35 @@ export interface CheckResult {
11
12
  errors: string[]
12
13
  }
13
14
 
15
+ const SERVER_ONLY_MODULES = new Set([
16
+ 'kay/server',
17
+ '@kayjs/kay/server',
18
+ 'bun:sqlite',
19
+ 'bun:ffi',
20
+ 'bun:dns',
21
+ 'node:fs',
22
+ 'node:fs/promises',
23
+ 'node:child_process',
24
+ 'node:net',
25
+ 'node:http',
26
+ 'node:https',
27
+ 'node:http2',
28
+ 'node:os',
29
+ 'node:worker_threads',
30
+ 'node:cluster',
31
+ 'node:dgram',
32
+ 'node:tls',
33
+ 'node:readline',
34
+ 'fs',
35
+ 'fs/promises',
36
+ 'child_process',
37
+ 'net',
38
+ 'http',
39
+ 'https',
40
+ ])
41
+
42
+ const SERIALIZABLE_NEW_CTORS = new Set(['Date', 'Map', 'Set', 'URL', 'RegExp'])
43
+
14
44
  function walkTsFiles(dir: string, out: string[] = []): string[] {
15
45
  if (!existsSync(dir))
16
46
  return out
@@ -28,14 +58,38 @@ function walkTsFiles(dir: string, out: string[] = []): string[] {
28
58
  return out
29
59
  }
30
60
 
61
+ function resolveLocalModule(fromFile: string, specifier: string): string | undefined {
62
+ if (!specifier.startsWith('.'))
63
+ return undefined
64
+ const base = resolve(dirname(fromFile), specifier)
65
+ for (const c of [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]) {
66
+ if (existsSync(c))
67
+ return c
68
+ }
69
+ return undefined
70
+ }
71
+
72
+ function normalizeRouteConflictKey(routesDir: string, file: string): string {
73
+ const rel = relative(routesDir, file).replace(/\\/g, '/').replace(/\.(tsx|ts)$/, '')
74
+ if (rel === 'index')
75
+ return '/'
76
+ const clean = rel.endsWith('/index') ? rel.slice(0, -'/index'.length) : rel
77
+ const norm = clean
78
+ .replace(/\[\.\.\.[^\]]+\]/g, '*')
79
+ .replace(/\[[^\]]+\]/g, ':')
80
+ return `/${norm}`
81
+ }
82
+
31
83
  export async function checkProject(rootDir: string, options: { skipTypecheck?: boolean } = {}): Promise<CheckResult> {
32
84
  const root = resolve(rootDir)
33
85
  const errors: string[] = []
34
86
 
35
87
  // 1. Validate kay.config.ts
36
88
  let routesDir = resolve(root, 'src/routes')
89
+ let plugins: Awaited<ReturnType<typeof loadConfig>>['plugins'] = []
37
90
  try {
38
91
  const cfg = await loadConfig(root)
92
+ plugins = cfg.plugins ?? []
39
93
  if (cfg.routesDir !== undefined)
40
94
  routesDir = resolve(root, cfg.routesDir)
41
95
  }
@@ -50,16 +104,123 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
50
104
  // 3. Parse & run Kay static compiler analysis across src/
51
105
  const srcDir = resolve(root, 'src')
52
106
  const files = walkTsFiles(existsSync(srcDir) ? srcDir : routesDir)
107
+ const analyses = new Map<string, ModuleAnalysis>()
108
+
53
109
  for (const file of files) {
54
110
  try {
55
111
  const code = readFileSync(file, 'utf8')
56
- analyzeModule(file, code)
112
+ analyses.set(file, analyzeModule(file, code))
57
113
  }
58
114
  catch (err) {
59
115
  errors.push(err instanceof Error ? err.message : String(err))
60
116
  }
61
117
  }
62
118
 
119
+ // 3b. Static guardrails: server-only imports in islands, non-serializable island props, route conflicts, missing paths()
120
+ const seenRoutes = new Map<string, string>()
121
+
122
+ for (const [file, analysis] of analyses) {
123
+ const rel = relative(root, file).replace(/\\/g, '/')
124
+
125
+ // Guardrail 1: server-only imports inside interactive islands
126
+ if (analysis.isInteractive) {
127
+ for (const imp of analysis.imports) {
128
+ if (SERVER_ONLY_MODULES.has(imp.source)) {
129
+ errors.push(
130
+ `kay check: ${rel}: interactive island imports server-only module "${imp.source}". Move server logic to a server action or async server component.`,
131
+ )
132
+ }
133
+ }
134
+ }
135
+
136
+ // Guardrail 2: non-serializable props (functions / unsupported class instances) passed from static server code into an island
137
+ if (!analysis.isInteractive && file.endsWith('.tsx')) {
138
+ const islandTags = new Set<string>()
139
+ for (const imp of analysis.imports) {
140
+ const target = resolveLocalModule(file, imp.source)
141
+ if (target === undefined)
142
+ continue
143
+ const targetAnalysis = analyses.get(target)
144
+ if (targetAnalysis?.isInteractive) {
145
+ for (const spec of imp.specifiers)
146
+ islandTags.add(spec.local)
147
+ }
148
+ }
149
+
150
+ if (islandTags.size > 0) {
151
+ walk(analysis.program, (node: AstNode) => {
152
+ if (node.type !== 'JSXOpeningElement' || node.name?.type !== 'JSXIdentifier')
153
+ return
154
+ const tag = node.name.name as string
155
+ if (!islandTags.has(tag))
156
+ return
157
+ for (const attr of (node.attributes ?? []) as AstNode[]) {
158
+ if (attr.type !== 'JSXAttribute' || attr.name?.type !== 'JSXIdentifier')
159
+ continue
160
+ const attrName = attr.name.name as string
161
+ if (attrName === 'key' || attrName === '$hydrate')
162
+ continue
163
+ if (attr.value?.type !== 'JSXExpressionContainer')
164
+ continue
165
+ const expr = attr.value.expression as AstNode | undefined
166
+ if (expr === undefined)
167
+ continue
168
+ if (expr.type === 'ArrowFunctionExpression' || expr.type === 'FunctionExpression') {
169
+ errors.push(
170
+ `kay check: ${rel}: cannot pass function prop "${attrName}" from a server component into island <${tag}>. Define the handler inside the island or pass serializable data.`,
171
+ )
172
+ }
173
+ else if (expr.type === 'NewExpression' && expr.callee?.type === 'Identifier' && !SERIALIZABLE_NEW_CTORS.has(expr.callee.name as string)) {
174
+ errors.push(
175
+ `kay check: ${rel}: cannot pass non-serializable \`new ${expr.callee.name}()\` prop "${attrName}" into island <${tag}>.`,
176
+ )
177
+ }
178
+ }
179
+ })
180
+ }
181
+ }
182
+
183
+ // Route-specific guardrails
184
+ const relFromRoutes = relative(routesDir, file)
185
+ const isRouteFile = !relFromRoutes.startsWith('..') && !basename(file).startsWith('_')
186
+ if (isRouteFile) {
187
+ const conflictKey = normalizeRouteConflictKey(routesDir, file)
188
+ const prev = seenRoutes.get(conflictKey)
189
+ if (prev !== undefined) {
190
+ errors.push(`kay check: conflicting routes "${prev}" and "${rel}" both match "${conflictKey}".`)
191
+ }
192
+ else {
193
+ seenRoutes.set(conflictKey, rel)
194
+ }
195
+
196
+ // Guardrail 4: dynamic prerender = true route missing paths()
197
+ if (analysis.hasPrerender && (conflictKey.includes(':') || conflictKey.includes('*')) && !analysis.hasPaths) {
198
+ errors.push(`kay check: ${rel}: dynamic route exports \`prerender = true\` without exporting \`paths()\`.`)
199
+ }
200
+ }
201
+ }
202
+
203
+ // 3c. Run plugin check(ctx) hooks
204
+ if (plugins && plugins.length > 0) {
205
+ const pluginCtx = {
206
+ root,
207
+ routesDir,
208
+ error(message: string) {
209
+ errors.push(message)
210
+ },
211
+ }
212
+ for (const plugin of plugins) {
213
+ if (plugin.check !== undefined) {
214
+ try {
215
+ await plugin.check(pluginCtx)
216
+ }
217
+ catch (err) {
218
+ errors.push(`${plugin.name}: ${err instanceof Error ? err.message : String(err)}`)
219
+ }
220
+ }
221
+ }
222
+ }
223
+
63
224
  // 4. Run TypeScript check (`tsgo` preferred, fallback to `tsc`) when tsconfig.json exists
64
225
  const tsconfigPath = join(root, 'tsconfig.json')
65
226
  if (!options.skipTypecheck && existsSync(tsconfigPath)) {
package/src/cli/index.ts CHANGED
@@ -60,10 +60,11 @@ else if (cmd === 'check') {
60
60
  }
61
61
  else if (cmd === 'build') {
62
62
  const isStatic = hasFlag('--static')
63
+ const analyze = hasFlag('--analyze')
63
64
  const compileFlag = flagValue('--compile')
64
65
  const compile = compileFlag === undefined ? undefined : (compileFlag === '' ? true : compileFlag)
65
66
  const t0 = performance.now()
66
- const manifest = await build({ root, static: isStatic, compile })
67
+ const manifest = await build({ root, static: isStatic, compile, analyze })
67
68
  const ms = (performance.now() - t0).toFixed(1)
68
69
  console.log(`kay build done in ${ms} ms (${manifest.routes.length} routes, ${manifest.assets.length} client assets, ${manifest.actions.length} actions)`)
69
70
  }
package/src/cli/new.ts CHANGED
@@ -15,7 +15,7 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
15
15
  const root = resolve(targetDir)
16
16
  const name = basename(root).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'kay-app'
17
17
  const template: ScaffoldTemplate = options.template ?? 'minimal'
18
- const kayVersion = options.kayVersion ?? '^2.0.0-alpha.5'
18
+ const kayVersion = options.kayVersion ?? '^2.0.0-alpha.6'
19
19
 
20
20
  if (existsSync(root) && readdirSync(root).length > 0 && !options.force)
21
21
  throw new Error(`kay new: directory "${root}" is not empty (pass --force to overwrite)`)
package/src/dev/index.ts CHANGED
@@ -1,10 +1,11 @@
1
- // kay dev: fast incremental rebuild (~5-10 ms) + in-place server hot swap + SSE browser live reload.
1
+ // kay dev: incremental cached rebuilds, serialized rebuild queue, CSS hot-swap, SSE error push, and live config reload.
2
2
 
3
3
  import type { FSWatcher } from 'node:fs'
4
4
  import type { KayApp } from '../server/index'
5
- import { existsSync, rmSync, watch } from 'node:fs'
5
+ import { existsSync, rmSync, statSync, watch } from 'node:fs'
6
6
  import { join, resolve } from 'node:path'
7
- import { build } from '../build/index'
7
+ import { build, createBuildCache } from '../build/index'
8
+ import { loadConfig } from '../plugins/index'
8
9
  import { createServer } from '../server/index'
9
10
 
10
11
  export interface DevServerOptions {
@@ -13,7 +14,7 @@ export interface DevServerOptions {
13
14
  routesDir?: string | undefined
14
15
  }
15
16
 
16
- const DEV_RELOAD_SCRIPT = `<script>(()=>{const s=new EventSource('/_kay/dev-events');s.onmessage=()=>location.reload();})();</script>`
17
+ const DEV_RELOAD_SCRIPT = `<script>(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource('/_kay/dev-events');s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map(urls.map(u=>[stem(u),u]));const old=[...document.querySelectorAll('link[rel="stylesheet"][href^="/_kay/"]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};})();</script>`
17
18
 
18
19
  function renderErrorOverlay(errText: string): string {
19
20
  const escaped = errText
@@ -23,7 +24,10 @@ function renderErrorOverlay(errText: string): string {
23
24
  return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Kay Dev Error</title><style>body{margin:0;min-height:100vh;background:#0d1117;color:#e6edf3;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;display:grid;place-items:center;padding:2rem}main{max-width:56rem;width:100%;background:#161b22;border:1px solid #f85149;border-radius:10px;padding:1.5rem 2rem;box-shadow:0 16px 48px rgba(0,0,0,.45)}h1{margin:0 0 1rem;color:#ff7b72;font-size:1.15rem}pre{margin:0;white-space:pre-wrap;word-break:break-word;line-height:1.5;font-size:.9rem;color:#ffa198}p{margin:1rem 0 0;font-size:.8rem;color:#8b949e}</style></head><body><main><h1>Kay Dev Build Error</h1><pre>${escaped}</pre><p>Save a fix to auto-reload.</p></main>${DEV_RELOAD_SCRIPT}</body></html>`
24
25
  }
25
26
 
26
- export async function devServer(options: DevServerOptions): Promise<{ url: string, stop: () => void }> {
27
+ type ChangeKind = 'css' | 'full' | 'config'
28
+
29
+ export async function devServer(options: DevServerOptions): Promise<{ url: string, stop: () => void, rebuild: () => Promise<void> }> {
30
+ const prevKayDev = process.env.KAY_DEV
27
31
  process.env.KAY_DEV = '1'
28
32
  const root = resolve(options.root)
29
33
  const srcDir = resolve(root, 'src')
@@ -31,53 +35,153 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
31
35
  const configPath = join(root, 'kay.config.ts')
32
36
  const devRoot = join(root, '.kay-dev')
33
37
  const port = options.port ?? 3000
38
+ const buildCache = createBuildCache()
39
+
34
40
  let buildNum = 0
35
41
  let currentApp: KayApp | undefined
36
42
  let lastError: string | undefined
43
+ let stopped = false
44
+
45
+ // Serialized rebuild queue: rapid saves coalesce instead of racing
46
+ let building = false
47
+ let pending = false
48
+ let pendingCssOnly = true
49
+ let pendingConfigReset = false
50
+ let inFlight: Promise<void> | undefined
51
+
37
52
  const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
38
53
  const encoder = new TextEncoder()
39
54
 
40
- async function rebuild(): Promise<void> {
55
+ function broadcast(payload: string): void {
56
+ const chunk = encoder.encode(`data: ${payload}\n\n`)
57
+ for (const c of clients) {
58
+ try {
59
+ c.enqueue(chunk)
60
+ }
61
+ catch {
62
+ clients.delete(c)
63
+ }
64
+ }
65
+ }
66
+
67
+ async function runSingleBuild(cssOnly: boolean, resetCache: boolean): Promise<void> {
68
+ if (stopped)
69
+ return
70
+ if (resetCache) {
71
+ buildCache.analyses.clear()
72
+ buildCache.domCompiled.clear()
73
+ buildCache.ssrCompiled.clear()
74
+ }
75
+ const hadError = lastError !== undefined
76
+ const hadApp = currentApp !== undefined
41
77
  const n = ++buildNum
42
78
  const outDir = `.kay-dev/b${n}`
43
79
  const t0 = performance.now()
44
80
  try {
45
- await build({ root, routesDir: options.routesDir, outDir, minify: false, prerender: false, copyPublic: false })
81
+ const manifest = await build({
82
+ root,
83
+ routesDir: options.routesDir,
84
+ outDir,
85
+ minify: false,
86
+ prerender: false,
87
+ copyPublic: false,
88
+ cache: buildCache,
89
+ })
46
90
  currentApp = await createServer({ root, outDir })
47
91
  lastError = undefined
48
92
  if (n > 2)
49
93
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
50
94
  console.log(`[kay dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
51
- for (const c of clients) {
52
- try {
53
- c.enqueue(encoder.encode(`data: reload\n\n`))
54
- }
55
- catch {
56
- clients.delete(c)
57
- }
58
- }
95
+ if (cssOnly && hadApp && !hadError && manifest.styles.length > 0)
96
+ broadcast(`css:${JSON.stringify(manifest.styles)}`)
97
+ else
98
+ broadcast('reload')
59
99
  }
60
100
  catch (err) {
61
101
  lastError = err instanceof Error ? err.stack ?? err.message : String(err)
62
102
  console.error(`[kay dev] build error:\n${lastError}`)
103
+ // Push reload over SSE so open browser tabs immediately display the error overlay
104
+ broadcast('reload')
63
105
  }
64
106
  }
65
107
 
66
- await rebuild()
108
+ function drainRebuilds(): Promise<void> {
109
+ if (building) {
110
+ pending = true
111
+ return inFlight ?? Promise.resolve()
112
+ }
113
+ building = true
114
+ const run = (async () => {
115
+ try {
116
+ do {
117
+ const cssOnly = pendingCssOnly
118
+ const resetCache = pendingConfigReset
119
+ pending = false
120
+ pendingCssOnly = true
121
+ pendingConfigReset = false
122
+ await runSingleBuild(cssOnly, resetCache)
123
+ } while (pending && !stopped)
124
+ }
125
+ finally {
126
+ building = false
127
+ inFlight = undefined
128
+ }
129
+ })()
130
+ inFlight = run
131
+ return run
132
+ }
133
+
134
+ // Initial build
135
+ pendingCssOnly = false
136
+ await drainRebuilds()
67
137
 
68
138
  let timer: ReturnType<typeof setTimeout> | undefined
69
- const scheduleRebuild = () => {
139
+ const scheduleRebuild = (kind: ChangeKind) => {
140
+ if (stopped)
141
+ return
142
+ if (kind === 'config') {
143
+ pendingConfigReset = true
144
+ pendingCssOnly = false
145
+ }
146
+ else if (kind === 'full') {
147
+ pendingCssOnly = false
148
+ }
70
149
  clearTimeout(timer)
71
- timer = setTimeout(() => void rebuild(), 40)
150
+ timer = setTimeout(() => {
151
+ void drainRebuilds()
152
+ }, 40)
72
153
  }
73
154
 
74
155
  const watchers: FSWatcher[] = []
75
- if (existsSync(srcDir))
76
- watchers.push(watch(srcDir, { recursive: true }, scheduleRebuild))
156
+ if (existsSync(srcDir)) {
157
+ watchers.push(watch(srcDir, { recursive: true }, (_ev, filename) => {
158
+ const name = typeof filename === 'string' ? filename : ''
159
+ const isCss = name.endsWith('.css') && !name.endsWith('.module.css')
160
+ scheduleRebuild(isCss ? 'css' : 'full')
161
+ }))
162
+ }
77
163
  if (existsSync(publicDir))
78
- watchers.push(watch(publicDir, { recursive: true }, scheduleRebuild))
164
+ watchers.push(watch(publicDir, { recursive: true }, () => scheduleRebuild('full')))
79
165
  if (existsSync(configPath))
80
- watchers.push(watch(configPath, scheduleRebuild))
166
+ watchers.push(watch(configPath, () => scheduleRebuild('config')))
167
+
168
+ // Watch plugin-declared extra paths (e.g. content/ or messages/ directories)
169
+ try {
170
+ const cfg = await loadConfig(root)
171
+ const watchedExtra = new Set<string>([srcDir, publicDir, configPath])
172
+ for (const plugin of cfg.plugins ?? []) {
173
+ const paths = typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? [])
174
+ for (const p of paths) {
175
+ const abs = resolve(root, p)
176
+ if (watchedExtra.has(abs) || !existsSync(abs))
177
+ continue
178
+ watchedExtra.add(abs)
179
+ const isDir = statSync(abs).isDirectory()
180
+ watchers.push(watch(abs, isDir ? { recursive: true } : {}, () => scheduleRebuild('full')))
181
+ }
182
+ }
183
+ }
184
+ catch {}
81
185
 
82
186
  const pingChunk = encoder.encode(': ping\n\n')
83
187
  const pingInterval = setInterval(() => {
@@ -151,13 +255,22 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
151
255
 
152
256
  return {
153
257
  url,
258
+ rebuild() {
259
+ pendingCssOnly = false
260
+ return drainRebuilds()
261
+ },
154
262
  stop() {
263
+ stopped = true
155
264
  clearTimeout(timer)
156
265
  clearInterval(pingInterval)
157
266
  for (const w of watchers)
158
267
  w.close()
159
268
  server.stop(true)
160
269
  rmSync(devRoot, { recursive: true, force: true })
270
+ if (prevKayDev === undefined)
271
+ delete process.env.KAY_DEV
272
+ else
273
+ process.env.KAY_DEV = prevKayDev
161
274
  },
162
275
  }
163
276
  }
package/src/dom/extras.ts CHANGED
@@ -120,6 +120,17 @@ function clearInserted(current: Node | Node[] | null): void {
120
120
  }
121
121
  }
122
122
 
123
+ function claimTextNode(claimed: Node | null, str: string): Text | undefined {
124
+ if (claimed === null || claimed.nodeType !== 3)
125
+ return undefined
126
+ const text = claimed as Text
127
+ if (text.data === str)
128
+ return text
129
+ if (str.length > 0 && text.data.endsWith(str))
130
+ return text.splitText(text.data.length - str.length)
131
+ return undefined
132
+ }
133
+
123
134
  export function insert(parent: Node, value: () => unknown, marker: Node | null = null): void {
124
135
  let current: Node | Node[] | null = null
125
136
  let textNode: Text | undefined
@@ -144,8 +155,14 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
144
155
  current = null
145
156
  }
146
157
  if (textNode === undefined) {
147
- textNode = document.createTextNode(str)
148
- parent.insertBefore(textNode, marker)
158
+ const claimed = claimTextNode(res.claimed, str)
159
+ if (claimed !== undefined) {
160
+ textNode = claimed
161
+ }
162
+ else {
163
+ textNode = document.createTextNode(str)
164
+ parent.insertBefore(textNode, marker)
165
+ }
149
166
  }
150
167
  else if (textNode.data !== str) {
151
168
  textNode.data = str
@@ -207,8 +224,8 @@ export function show(
207
224
  parent: Node,
208
225
  marker: Node | null,
209
226
  when: () => unknown,
210
- renderTrue: () => Node | null,
211
- renderFalse?: () => Node | null,
227
+ renderTrue: () => unknown,
228
+ renderFalse?: () => unknown,
212
229
  ): void {
213
230
  const parentOwner = getOwner()
214
231
  let branch: 0 | 1 | 2 = 0
@@ -242,17 +259,56 @@ export function show(
242
259
  const res = claimInsert(parent, marker, () => untrack(() => runWithOwner(owner, fn)))
243
260
  marker = res.marker
244
261
  const rendered = res.result
245
- if (rendered === null)
262
+ if (rendered == null || typeof rendered === 'boolean')
246
263
  return
247
264
 
248
- if (rendered.nodeType === 11) {
249
- nodes = Array.from(rendered.childNodes)
250
- parent.insertBefore(rendered, marker)
265
+ if (typeof rendered === 'string' || typeof rendered === 'number') {
266
+ const str = String(rendered)
267
+ if (str === '')
268
+ return
269
+ const text = claimTextNode(res.claimed, str) ?? document.createTextNode(str)
270
+ if (text.parentNode !== parent)
271
+ parent.insertBefore(text, marker)
272
+ nodes = [text]
273
+ return
251
274
  }
252
- else {
253
- nodes = [rendered]
254
- if (rendered.parentNode !== parent)
275
+
276
+ if (rendered instanceof Node) {
277
+ if (rendered.nodeType === 11) {
278
+ nodes = Array.from(rendered.childNodes)
255
279
  parent.insertBefore(rendered, marker)
280
+ }
281
+ else {
282
+ nodes = [rendered]
283
+ if (rendered.parentNode !== parent)
284
+ parent.insertBefore(rendered, marker)
285
+ }
286
+ return
287
+ }
288
+
289
+ if (Array.isArray(rendered)) {
290
+ const f = document.createDocumentFragment()
291
+ const list: Node[] = []
292
+ for (let i = 0; i < rendered.length; i++) {
293
+ const item = rendered[i]
294
+ if (item instanceof Node) {
295
+ if (item.nodeType === 11)
296
+ list.push(...Array.from(item.childNodes))
297
+ else
298
+ list.push(item)
299
+ f.appendChild(item)
300
+ }
301
+ else if (item != null && typeof item !== 'boolean') {
302
+ const str = String(item)
303
+ if (str !== '') {
304
+ const t = document.createTextNode(str)
305
+ list.push(t)
306
+ f.appendChild(t)
307
+ }
308
+ }
309
+ }
310
+ parent.insertBefore(f, marker)
311
+ nodes = list
256
312
  }
257
313
  })
258
314
  }
package/src/dom/index.ts CHANGED
@@ -27,9 +27,9 @@ export function claimLoop(parent: Node, fn: () => void, skip = 0): boolean {
27
27
  return true
28
28
  }
29
29
 
30
- export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T): { result: T, marker: Node | null } {
30
+ export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T): { result: T, marker: Node | null, claimed: Node | null } {
31
31
  if (!hydrating)
32
- return { result: fn(), marker }
32
+ return { result: fn(), marker, claimed: null }
33
33
 
34
34
  let claimed: Node | null = marker !== null ? marker : parent.lastChild
35
35
  let nextMarker = marker
@@ -45,7 +45,7 @@ export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T):
45
45
  const prevNode = hydrateNode
46
46
  hydrateNode = claimed
47
47
  try {
48
- return { result: fn(), marker: nextMarker }
48
+ return { result: fn(), marker: nextMarker, claimed }
49
49
  }
50
50
  finally {
51
51
  hydrateNode = prevNode