@kayjs/kay 2.0.0-alpha.7 → 2.0.0-beta.0
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/package.json +1 -1
- package/src/build/compile.ts +15 -3
- package/src/build/index.ts +301 -49
- package/src/cli/check.ts +41 -37
- package/src/cli/index.ts +27 -11
- package/src/cli/new.ts +24 -8
- package/src/compiler/dom.ts +153 -30
- package/src/compiler/server-only.ts +62 -0
- package/src/compiler/ssr.ts +101 -22
- package/src/dev/index.ts +26 -7
- package/src/dom/extras.ts +85 -43
- package/src/dom/index.ts +110 -17
- package/src/dom/island.ts +67 -24
- package/src/dom/loop.ts +6 -1
- package/src/plugins/index.ts +8 -1
- package/src/reactivity/index.ts +141 -40
- package/src/reactivity/store.ts +5 -1
- package/src/server/action.ts +98 -26
- package/src/server/compress.ts +87 -8
- package/src/server/cookies.ts +15 -8
- package/src/server/http.ts +121 -6
- package/src/server/index.ts +453 -242
- package/src/server/router.ts +6 -1
- package/src/server/security.ts +76 -18
- package/src/ssr/context.ts +2 -1
- package/src/ssr/index.ts +88 -20
- package/src/test/index.ts +4 -0
package/src/compiler/ssr.ts
CHANGED
|
@@ -11,10 +11,14 @@ export function escapeStaticText(str: string): string {
|
|
|
11
11
|
|
|
12
12
|
const RAW_TEXT_ELEMENTS = new Set(['style', 'script'])
|
|
13
13
|
const CLOSE_STYLE_RE = /<\/(style)/gi
|
|
14
|
-
const
|
|
14
|
+
const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
|
|
15
15
|
|
|
16
16
|
function escapeRawText(str: string, tag: 'style' | 'script'): string {
|
|
17
|
-
|
|
17
|
+
if (tag === 'script') {
|
|
18
|
+
return str.replace(SCRIPT_UNSAFE_RE, (_, body: string) =>
|
|
19
|
+
body.charCodeAt(0) === 47 ? `<\\${body}` : `\\u003c${body}`)
|
|
20
|
+
}
|
|
21
|
+
return str.replace(CLOSE_STYLE_RE, '<\\/$1')
|
|
18
22
|
}
|
|
19
23
|
|
|
20
24
|
const VOID_ELEMENTS = new Set([
|
|
@@ -23,6 +27,41 @@ const VOID_ELEMENTS = new Set([
|
|
|
23
27
|
])
|
|
24
28
|
|
|
25
29
|
const EVENT_ATTR = /^on[A-Z]/
|
|
30
|
+
const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href'])
|
|
31
|
+
const UNSAFE_URL_RE = /^(?:javascript|vbscript):/i
|
|
32
|
+
const STRING_BOOL_ATTRS = new Set(['draggable', 'spellcheck', 'contenteditable'])
|
|
33
|
+
|
|
34
|
+
function isStringBoolAttr(name: string): boolean {
|
|
35
|
+
const lower = name.toLowerCase()
|
|
36
|
+
return lower.startsWith('aria-') || STRING_BOOL_ATTRS.has(lower)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isUnsafeUrlAttr(name: string, value: unknown): boolean {
|
|
40
|
+
if (!URL_ATTRS.has(name.toLowerCase()))
|
|
41
|
+
return false
|
|
42
|
+
return UNSAFE_URL_RE.test(String(value).replace(/[\u0000-\u0020]+/g, ''))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function containsDirectAwait(root: AstNode): boolean {
|
|
46
|
+
let found = false
|
|
47
|
+
walk(root, (child) => {
|
|
48
|
+
if (found)
|
|
49
|
+
return false
|
|
50
|
+
if (child !== root && (
|
|
51
|
+
child.type === 'FunctionDeclaration'
|
|
52
|
+
|| child.type === 'FunctionExpression'
|
|
53
|
+
|| child.type === 'ArrowFunctionExpression'
|
|
54
|
+
)) {
|
|
55
|
+
return false
|
|
56
|
+
}
|
|
57
|
+
if (child.type === 'AwaitExpression') {
|
|
58
|
+
found = true
|
|
59
|
+
return false
|
|
60
|
+
}
|
|
61
|
+
return undefined
|
|
62
|
+
})
|
|
63
|
+
return found
|
|
64
|
+
}
|
|
26
65
|
|
|
27
66
|
export interface IslandBinding {
|
|
28
67
|
id: string
|
|
@@ -33,6 +72,7 @@ export interface IslandBinding {
|
|
|
33
72
|
export interface CompileSsrOptions {
|
|
34
73
|
islands?: ReadonlyMap<string, IslandBinding> | undefined
|
|
35
74
|
isIsland?: boolean | undefined
|
|
75
|
+
emitMarkers?: boolean | undefined
|
|
36
76
|
analysis?: ModuleAnalysis | undefined
|
|
37
77
|
}
|
|
38
78
|
|
|
@@ -138,17 +178,23 @@ function isSimpleLiteral(node: AstNode): { ok: true, value: string | number | bo
|
|
|
138
178
|
|
|
139
179
|
function isStaticNullish(node: AstNode): boolean {
|
|
140
180
|
return (node.type === 'Identifier' && node.name === 'undefined')
|
|
141
|
-
|| (node.type === 'Literal' &&
|
|
181
|
+
|| (node.type === 'Literal' && node.value === null)
|
|
142
182
|
}
|
|
143
183
|
|
|
144
184
|
function formatStaticAttrBranch(attrName: string, node: AstNode): string | undefined {
|
|
145
185
|
if (isStaticNullish(node))
|
|
146
186
|
return '""'
|
|
147
187
|
if (node.type === 'Literal') {
|
|
148
|
-
if (node.value ===
|
|
149
|
-
|
|
150
|
-
|
|
188
|
+
if (typeof node.value === 'boolean') {
|
|
189
|
+
if (isStringBoolAttr(attrName))
|
|
190
|
+
return JSON.stringify(` ${attrName}="${node.value ? 'true' : 'false'}"`)
|
|
191
|
+
return node.value ? JSON.stringify(` ${attrName}`) : '""'
|
|
192
|
+
}
|
|
193
|
+
if (typeof node.value === 'string' || typeof node.value === 'number') {
|
|
194
|
+
if (isUnsafeUrlAttr(attrName, node.value))
|
|
195
|
+
return '""'
|
|
151
196
|
return JSON.stringify(` ${attrName}="${escapeStaticAttr(String(node.value))}"`)
|
|
197
|
+
}
|
|
152
198
|
}
|
|
153
199
|
return undefined
|
|
154
200
|
}
|
|
@@ -170,7 +216,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
170
216
|
}
|
|
171
217
|
|
|
172
218
|
const islands = options.islands
|
|
173
|
-
const
|
|
219
|
+
const emitMarkers = options.emitMarkers ?? options.isIsland ?? analysis.isInteractive
|
|
174
220
|
|
|
175
221
|
function compileSubExpression(node: AstNode): string {
|
|
176
222
|
let hasNestedJsx = false
|
|
@@ -230,10 +276,11 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
230
276
|
|
|
231
277
|
const name = rawName === 'className' ? 'class' : rawName === 'htmlFor' ? 'for' : rawName
|
|
232
278
|
if (attr.value === null) {
|
|
233
|
-
parts.pushStatic(` ${name}`)
|
|
279
|
+
parts.pushStatic(isStringBoolAttr(name) ? ` ${name}="true"` : ` ${name}`)
|
|
234
280
|
}
|
|
235
281
|
else if (attr.value.type === 'Literal') {
|
|
236
|
-
|
|
282
|
+
if (!isUnsafeUrlAttr(name, attr.value.value))
|
|
283
|
+
parts.pushStatic(` ${name}="${escapeStaticAttr(String(attr.value.value))}"`)
|
|
237
284
|
}
|
|
238
285
|
else if (attr.value.type === 'JSXExpressionContainer') {
|
|
239
286
|
const expr = attr.value.expression as AstNode
|
|
@@ -331,7 +378,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
331
378
|
&& expr.arguments?.length === 1
|
|
332
379
|
) {
|
|
333
380
|
const cb = expr.arguments[0] as AstNode
|
|
334
|
-
if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && cb.body !== null) {
|
|
381
|
+
if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && !cb.async && cb.body !== null) {
|
|
335
382
|
const body = (cb.body.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body) as AstNode
|
|
336
383
|
if (body.type === 'JSXElement' || body.type === 'JSXFragment') {
|
|
337
384
|
const target = compileSubExpression(expr.callee.object)
|
|
@@ -358,7 +405,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
358
405
|
pushStmt(
|
|
359
406
|
`const ${arrVar} = ${target}; if (${arrVar}) for (let ${idxVar} = 0; ${idxVar} < ${arrVar}.length; ${idxVar}++) { const ${itemParam} = ${arrVar}[${idxVar}]; ${innerStmts.join(' ')} }`,
|
|
360
407
|
)
|
|
361
|
-
if (
|
|
408
|
+
if (emitMarkers && !isLast)
|
|
362
409
|
parts.pushStatic('<!---->')
|
|
363
410
|
continue
|
|
364
411
|
}
|
|
@@ -383,13 +430,13 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
383
430
|
&& expr.arguments?.length === 1
|
|
384
431
|
) {
|
|
385
432
|
const cb = expr.arguments[0] as AstNode
|
|
386
|
-
if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && cb.body !== null) {
|
|
433
|
+
if ((cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') && !cb.async && cb.body !== null) {
|
|
387
434
|
const body = (cb.body.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body) as AstNode
|
|
388
435
|
if (body.type === 'JSXElement' || body.type === 'JSXFragment') {
|
|
389
436
|
const target = compileSubExpression(expr.callee.object)
|
|
390
437
|
const params = (cb.params as AstNode[]).map(p => code.slice(p.start, p.end)).join(', ')
|
|
391
438
|
const rendered = `${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(body)})`
|
|
392
|
-
return
|
|
439
|
+
return emitMarkers && !isLast ? `(${rendered}) + "<!---->"` : rendered
|
|
393
440
|
}
|
|
394
441
|
if (body.type === 'BlockStatement') {
|
|
395
442
|
let blockHasJsx = false
|
|
@@ -402,7 +449,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
402
449
|
})
|
|
403
450
|
if (blockHasJsx) {
|
|
404
451
|
const rendered = `${use('esc')}(${compileSubExpression(expr)})`
|
|
405
|
-
return
|
|
452
|
+
return emitMarkers && !isLast ? `(${rendered}) + "<!---->"` : rendered
|
|
406
453
|
}
|
|
407
454
|
}
|
|
408
455
|
}
|
|
@@ -412,7 +459,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
412
459
|
const right = unwrapParens(expr.right)
|
|
413
460
|
if (right.type === 'JSXElement' || right.type === 'JSXFragment') {
|
|
414
461
|
const left = compileSubExpression(expr.left)
|
|
415
|
-
const emptyVal =
|
|
462
|
+
const emptyVal = emitMarkers && !isLast ? '"<!---->"' : '""'
|
|
416
463
|
return `((${left}) ? (${compileJsxToStringExpr(right)}) : ${emptyVal})`
|
|
417
464
|
}
|
|
418
465
|
}
|
|
@@ -425,13 +472,13 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
425
472
|
const cons = compileExpressionAsString(consNode, false, true)
|
|
426
473
|
const alt = compileExpressionAsString(altNode, false, true)
|
|
427
474
|
const base = `((${test}) ? (${cons}) : (${alt}))`
|
|
428
|
-
return
|
|
475
|
+
return emitMarkers && !isLast ? `(${base} || "<!---->")` : base
|
|
429
476
|
}
|
|
430
477
|
}
|
|
431
478
|
|
|
432
479
|
const exprCode = compileSubExpression(expr)
|
|
433
480
|
const rendered = `${use('esc')}(${exprCode})`
|
|
434
|
-
if (
|
|
481
|
+
if (emitMarkers && hasSiblings)
|
|
435
482
|
return isLast ? `"<!---->" + ${rendered}` : `"<!---->" + ${rendered} + "<!---->"`
|
|
436
483
|
return rendered
|
|
437
484
|
}
|
|
@@ -526,7 +573,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
526
573
|
|
|
527
574
|
const childExpr = hasChildren ? compileJsxToStringExpr({ type: 'JSXFragment', children: childNodes }) : '""'
|
|
528
575
|
|
|
529
|
-
const islandInfo =
|
|
576
|
+
const islandInfo = islands?.get(tag)
|
|
530
577
|
if (islandInfo !== undefined) {
|
|
531
578
|
const propsCode = `{ ${propEntries.join(', ')} }`
|
|
532
579
|
const callPropsCode = hasChildren
|
|
@@ -534,8 +581,9 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
534
581
|
: propsCode
|
|
535
582
|
const resolvedHydrate = staticHydrate ?? (hydrateExpr === undefined ? islandInfo.defaultHydrate : undefined)
|
|
536
583
|
|
|
537
|
-
// Compile-time static island props fast path
|
|
538
|
-
|
|
584
|
+
// Compile-time static island props fast path (only when not inside an island-reachable component):
|
|
585
|
+
// 0 JSON.stringify / Object.keys / escAttr at runtime, while still incrementing island depth!
|
|
586
|
+
if (!emitMarkers && allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
|
|
539
587
|
const pAttr = Object.keys(staticPropsObj).length > 0
|
|
540
588
|
? ` p="${escapeStaticAttr(JSON.stringify(staticPropsObj))}"`
|
|
541
589
|
: ''
|
|
@@ -545,14 +593,43 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
545
593
|
const openTag = `<kay-island c="${escapeStaticAttr(islandInfo.chunk)}"${pAttr}${hAttr}>`
|
|
546
594
|
parts.pushStatic(openTag)
|
|
547
595
|
if (resolvedHydrate !== 'client')
|
|
548
|
-
parts.pushExpr(`${use('ssrChild')}(${tag}(${callPropsCode}))`)
|
|
596
|
+
parts.pushExpr(`${use('ssrInIsland')}(() => ${use('ssrChild')}(${tag}(${callPropsCode})))`)
|
|
549
597
|
parts.pushStatic('</kay-island>')
|
|
550
598
|
return
|
|
551
599
|
}
|
|
552
600
|
|
|
553
601
|
const hydrateArg = hydrateExpr ?? (islandInfo.defaultHydrate !== undefined ? JSON.stringify(islandInfo.defaultHydrate) : 'undefined')
|
|
602
|
+
if (allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
|
|
603
|
+
parts.pushExpr(
|
|
604
|
+
`${use('ssrIsland')}(${JSON.stringify(islandInfo.id)}, ${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callPropsCode})), ${propsCode}, ${hydrateArg})`,
|
|
605
|
+
)
|
|
606
|
+
return
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// Hoist dynamic island props into a single binding so expressions (side effects & await) evaluate once!
|
|
610
|
+
const pVar = `_p${loopCounter++}`
|
|
611
|
+
const argNames = [pVar]
|
|
612
|
+
const argExprs = [propsCode]
|
|
613
|
+
let callArg = pVar
|
|
614
|
+
if (hasChildren) {
|
|
615
|
+
let childSlotVal = childExpr
|
|
616
|
+
if (containsDirectAwait({ type: 'JSXFragment', children: childNodes })) {
|
|
617
|
+
const cVar = `_c${loopCounter++}`
|
|
618
|
+
argNames.push(cVar)
|
|
619
|
+
argExprs.push(childExpr)
|
|
620
|
+
childSlotVal = cVar
|
|
621
|
+
}
|
|
622
|
+
callArg = `{ ...${pVar}, children: ${use('raw')}("<kay-slot>" + (${childSlotVal}) + "</kay-slot>") }`
|
|
623
|
+
}
|
|
624
|
+
let hArg = hydrateArg
|
|
625
|
+
if (hydrateExpr !== undefined && staticHydrate === undefined) {
|
|
626
|
+
const hVar = `_h${loopCounter++}`
|
|
627
|
+
argNames.push(hVar)
|
|
628
|
+
argExprs.push(hydrateExpr)
|
|
629
|
+
hArg = hVar
|
|
630
|
+
}
|
|
554
631
|
parts.pushExpr(
|
|
555
|
-
|
|
632
|
+
`((${argNames.join(', ')}) => ${use('ssrIsland')}(${JSON.stringify(islandInfo.id)}, ${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callArg})), ${pVar}, ${hArg}))(${argExprs.join(', ')})`,
|
|
556
633
|
)
|
|
557
634
|
return
|
|
558
635
|
}
|
|
@@ -583,6 +660,8 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
583
660
|
return parts.toExpr()
|
|
584
661
|
|
|
585
662
|
flush()
|
|
663
|
+
if (containsDirectAwait(node))
|
|
664
|
+
return `(await (async () => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })())`
|
|
586
665
|
return `(() => { let ${bufVar} = ""; ${stmts.join(' ')} return ${bufVar}; })()`
|
|
587
666
|
}
|
|
588
667
|
|
package/src/dev/index.ts
CHANGED
|
@@ -6,15 +6,20 @@ import { existsSync, rmSync, statSync, watch } from 'node:fs'
|
|
|
6
6
|
import { join, resolve } from 'node:path'
|
|
7
7
|
import { build, createBuildCache } from '../build/index'
|
|
8
8
|
import { loadConfig } from '../plugins/index'
|
|
9
|
-
import {
|
|
9
|
+
import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
|
|
10
|
+
import { createServer, withCspHashes } from '../server/index'
|
|
10
11
|
|
|
11
12
|
export interface DevServerOptions {
|
|
12
13
|
root: string
|
|
13
14
|
port?: number | undefined
|
|
15
|
+
hostname?: string | undefined
|
|
14
16
|
routesDir?: string | undefined
|
|
17
|
+
maxRequestBodySize?: number | undefined
|
|
15
18
|
}
|
|
16
19
|
|
|
17
|
-
const
|
|
20
|
+
const DEV_RELOAD_JS = `(()=>{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();}};})();`
|
|
21
|
+
const DEV_RELOAD_SCRIPT = `<script>${DEV_RELOAD_JS}</script>`
|
|
22
|
+
const DEV_RELOAD_SCRIPT_HASH = `'sha256-${new Bun.CryptoHasher('sha256').update(DEV_RELOAD_JS).digest('base64')}'`
|
|
18
23
|
|
|
19
24
|
function renderErrorOverlay(errText: string): string {
|
|
20
25
|
const escaped = errText
|
|
@@ -35,6 +40,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
35
40
|
const configPath = join(root, 'kay.config.ts')
|
|
36
41
|
const devRoot = join(root, '.kay-dev')
|
|
37
42
|
const port = options.port ?? 3000
|
|
43
|
+
const hostname = options.hostname ?? '127.0.0.1'
|
|
38
44
|
const buildCache = createBuildCache()
|
|
39
45
|
|
|
40
46
|
let buildNum = 0
|
|
@@ -195,13 +201,18 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
195
201
|
}
|
|
196
202
|
}, 15_000)
|
|
197
203
|
|
|
204
|
+
const maxRequestBodySize = options.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
|
|
205
|
+
|
|
198
206
|
const server = Bun.serve({
|
|
199
207
|
port,
|
|
200
|
-
|
|
201
|
-
|
|
208
|
+
hostname,
|
|
209
|
+
idleTimeout: 30,
|
|
210
|
+
maxRequestBodySize,
|
|
211
|
+
async fetch(request, srv) {
|
|
202
212
|
const url = new URL(request.url)
|
|
203
213
|
|
|
204
214
|
if (url.pathname === '/_kay/dev-events') {
|
|
215
|
+
srv.timeout(request, 0)
|
|
205
216
|
let ctrl: ReadableStreamDefaultController<Uint8Array> | undefined
|
|
206
217
|
const stream = new ReadableStream<Uint8Array>({
|
|
207
218
|
start(controller) {
|
|
@@ -237,20 +248,28 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
237
248
|
})
|
|
238
249
|
}
|
|
239
250
|
|
|
240
|
-
const
|
|
251
|
+
const remoteIp = srv.requestIP(request)?.address
|
|
252
|
+
const res = await currentApp!.handle(request, remoteIp)
|
|
241
253
|
const ct = res.headers.get('content-type') ?? ''
|
|
254
|
+
if (ct.includes('text/event-stream'))
|
|
255
|
+
srv.timeout(request, 0)
|
|
242
256
|
if (ct.includes('text/html')) {
|
|
243
257
|
const html = await res.text()
|
|
244
258
|
const injected = html.includes('</body>')
|
|
245
259
|
? html.replace('</body>', `${DEV_RELOAD_SCRIPT}</body>`)
|
|
246
260
|
: html + DEV_RELOAD_SCRIPT
|
|
247
|
-
|
|
261
|
+
const headers = new Headers(res.headers)
|
|
262
|
+
const existingCsp = headers.get('content-security-policy')
|
|
263
|
+
if (existingCsp !== null)
|
|
264
|
+
headers.set('content-security-policy', withCspHashes(existingCsp, { scriptHashes: [DEV_RELOAD_SCRIPT_HASH] }))
|
|
265
|
+
return new Response(injected, { status: res.status, headers })
|
|
248
266
|
}
|
|
249
267
|
return res
|
|
250
268
|
},
|
|
251
269
|
})
|
|
252
270
|
|
|
253
|
-
const
|
|
271
|
+
const displayHost = hostname === '0.0.0.0' ? '127.0.0.1' : hostname
|
|
272
|
+
const url = `http://${displayHost}:${server.port}`
|
|
254
273
|
console.log(`[kay dev] listening on ${url}`)
|
|
255
274
|
|
|
256
275
|
return {
|
package/src/dom/extras.ts
CHANGED
|
@@ -2,20 +2,35 @@
|
|
|
2
2
|
// so Bun.build({ splitting: true }) keeps them out of minimal islands that don't use them.
|
|
3
3
|
|
|
4
4
|
import type { Owner } from '../reactivity/index'
|
|
5
|
-
import {
|
|
6
|
-
import { claimInsert, setAttr, setClass, setProp, setStyle } from './index'
|
|
5
|
+
import { createOwner, disposeOwner, effect, getOwner, runWithOwner, untrack } from '../reactivity/index'
|
|
6
|
+
import { claimInsert, setAttr, setClass, setProp, setStyle, skipRange } from './index'
|
|
7
|
+
|
|
8
|
+
const RAW_HTML = Symbol.for('kay.html')
|
|
9
|
+
|
|
10
|
+
function isRawHtml(value: unknown): value is { __html: string } {
|
|
11
|
+
return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[RAW_HTML] === true && '__html' in value
|
|
12
|
+
}
|
|
7
13
|
|
|
8
14
|
export function setInnerHtml(el: Element, value: unknown): void {
|
|
9
15
|
const html = value == null || value === false
|
|
10
16
|
? ''
|
|
11
|
-
: (
|
|
17
|
+
: isRawHtml(value)
|
|
18
|
+
? String(value.__html)
|
|
19
|
+
: String(value)
|
|
12
20
|
if (el.innerHTML !== html)
|
|
13
21
|
el.innerHTML = html
|
|
14
22
|
}
|
|
15
23
|
|
|
16
|
-
const
|
|
24
|
+
const VALID_ATTR_NAME = /^[A-Za-z_:][-\w:.]*$/
|
|
17
25
|
const SPREAD_DOM_PROPS = new Set(['value', 'checked', 'selected', 'muted', 'indeterminate'])
|
|
18
26
|
|
|
27
|
+
function isBlockedSpreadAttr(name: string): boolean {
|
|
28
|
+
if (!VALID_ATTR_NAME.test(name))
|
|
29
|
+
return true
|
|
30
|
+
const lower = name.toLowerCase()
|
|
31
|
+
return lower.startsWith('on') || lower === 'innerhtml' || lower === 'srcdoc'
|
|
32
|
+
}
|
|
33
|
+
|
|
19
34
|
export function omit(props: Record<string, unknown>, excluded: string[]): Record<string, unknown> {
|
|
20
35
|
const out: Record<string, unknown> = {}
|
|
21
36
|
const skip = new Set(excluded)
|
|
@@ -31,21 +46,6 @@ export function omit(props: Record<string, unknown>, excluded: string[]): Record
|
|
|
31
46
|
|
|
32
47
|
export function spread(el: Element, getProps: () => Record<string, unknown> | null | undefined): void {
|
|
33
48
|
let prevKeys: string[] = []
|
|
34
|
-
const listeners = new Map<string, (e: Event) => void>()
|
|
35
|
-
|
|
36
|
-
const removeListener = (ev: string) => {
|
|
37
|
-
const fn = listeners.get(ev)
|
|
38
|
-
if (fn !== undefined) {
|
|
39
|
-
el.removeEventListener(ev, fn)
|
|
40
|
-
listeners.delete(ev)
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
onCleanup(() => {
|
|
45
|
-
for (const [ev, fn] of listeners)
|
|
46
|
-
el.removeEventListener(ev, fn)
|
|
47
|
-
listeners.clear()
|
|
48
|
-
})
|
|
49
49
|
|
|
50
50
|
effect(() => {
|
|
51
51
|
const props = getProps() ?? {}
|
|
@@ -55,18 +55,16 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
|
|
|
55
55
|
const k = prevKeys[i]!
|
|
56
56
|
if (k in props)
|
|
57
57
|
continue
|
|
58
|
-
|
|
59
|
-
if (ev !== null) {
|
|
60
|
-
removeListener(ev[1]!.toLowerCase())
|
|
61
|
-
}
|
|
62
|
-
else if (k === 'class' || k === 'className') {
|
|
58
|
+
if (k === 'class' || k === 'className') {
|
|
63
59
|
setClass(el, '')
|
|
64
60
|
}
|
|
65
61
|
else if (k === 'style') {
|
|
66
62
|
setStyle(el as HTMLElement, null)
|
|
67
63
|
}
|
|
68
64
|
else if (k !== 'key' && k !== 'ref' && k !== '$hydrate' && k !== 'children') {
|
|
69
|
-
|
|
65
|
+
const name = k === 'htmlFor' ? 'for' : k
|
|
66
|
+
if (!isBlockedSpreadAttr(name))
|
|
67
|
+
el.removeAttribute(name)
|
|
70
68
|
}
|
|
71
69
|
}
|
|
72
70
|
|
|
@@ -80,21 +78,10 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
|
|
|
80
78
|
(v as (node: Element) => void)(el)
|
|
81
79
|
continue
|
|
82
80
|
}
|
|
83
|
-
const ev = SPREAD_EVENT_RE.exec(k)
|
|
84
|
-
if (ev !== null) {
|
|
85
|
-
const type = ev[1]!.toLowerCase()
|
|
86
|
-
removeListener(type)
|
|
87
|
-
if (typeof v === 'function') {
|
|
88
|
-
const wrapped = (e: Event) => batch(() => (v as (ev: Event) => void)(e))
|
|
89
|
-
listeners.set(type, wrapped)
|
|
90
|
-
el.addEventListener(type, wrapped)
|
|
91
|
-
}
|
|
92
|
-
continue
|
|
93
|
-
}
|
|
94
81
|
const name = k === 'className' ? 'class' : k === 'htmlFor' ? 'for' : k
|
|
95
|
-
if (name
|
|
96
|
-
|
|
97
|
-
|
|
82
|
+
if (isBlockedSpreadAttr(name))
|
|
83
|
+
continue
|
|
84
|
+
if (name === 'class')
|
|
98
85
|
setClass(el, v)
|
|
99
86
|
else if (name === 'style')
|
|
100
87
|
setStyle(el as HTMLElement, v)
|
|
@@ -131,17 +118,42 @@ function claimTextNode(claimed: Node | null, str: string): Text | undefined {
|
|
|
131
118
|
return undefined
|
|
132
119
|
}
|
|
133
120
|
|
|
134
|
-
export function insert(parent: Node, value: () => unknown, marker: Node | null = null): void {
|
|
121
|
+
export function insert(parent: Node, value: () => unknown, marker: Node | null = null, startMarker?: Node | null): void {
|
|
135
122
|
let current: Node | Node[] | null = null
|
|
136
123
|
let textNode: Text | undefined
|
|
124
|
+
let firstRun = true
|
|
137
125
|
|
|
138
126
|
effect(() => {
|
|
139
|
-
|
|
140
|
-
|
|
127
|
+
let res: { result: unknown, marker: Node | null, claimed: Node | null, nodes: Node[] | undefined }
|
|
128
|
+
if (firstRun) {
|
|
129
|
+
firstRun = false
|
|
130
|
+
let effMarker = marker
|
|
131
|
+
let effStart = startMarker
|
|
132
|
+
if (effStart === undefined && effMarker !== null && effMarker.nodeType === 8) {
|
|
133
|
+
const close = skipRange(effMarker)
|
|
134
|
+
if (close !== null) {
|
|
135
|
+
effStart = effMarker
|
|
136
|
+
effMarker = close
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
res = claimInsert(parent, effMarker, value, effStart)
|
|
140
|
+
marker = res.marker
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
res = { result: value(), marker, claimed: null, nodes: undefined }
|
|
144
|
+
}
|
|
141
145
|
const next = res.result
|
|
146
|
+
const ssrNodes = res.nodes
|
|
147
|
+
|
|
148
|
+
if (next == null && ssrNodes !== undefined) {
|
|
149
|
+
current = ssrNodes
|
|
150
|
+
return
|
|
151
|
+
}
|
|
142
152
|
|
|
143
153
|
if (next == null || typeof next === 'boolean') {
|
|
144
154
|
clearInserted(current)
|
|
155
|
+
if (ssrNodes !== undefined)
|
|
156
|
+
clearInserted(ssrNodes)
|
|
145
157
|
current = null
|
|
146
158
|
if (textNode !== undefined)
|
|
147
159
|
textNode.data = ''
|
|
@@ -158,8 +170,16 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
|
|
|
158
170
|
const claimed = claimTextNode(res.claimed, str)
|
|
159
171
|
if (claimed !== undefined) {
|
|
160
172
|
textNode = claimed
|
|
173
|
+
if (ssrNodes !== undefined && ssrNodes.length > 1) {
|
|
174
|
+
for (let i = 0; i < ssrNodes.length; i++) {
|
|
175
|
+
if (ssrNodes[i] !== claimed)
|
|
176
|
+
ssrNodes[i]!.parentNode?.removeChild(ssrNodes[i]!)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
161
179
|
}
|
|
162
180
|
else {
|
|
181
|
+
if (ssrNodes !== undefined)
|
|
182
|
+
clearInserted(ssrNodes)
|
|
163
183
|
textNode = document.createTextNode(str)
|
|
164
184
|
parent.insertBefore(textNode, marker)
|
|
165
185
|
}
|
|
@@ -179,10 +199,18 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
|
|
|
179
199
|
if (current === next)
|
|
180
200
|
return
|
|
181
201
|
if (current === null && next.parentNode === parent) {
|
|
202
|
+
if (ssrNodes !== undefined && ssrNodes.length > 1) {
|
|
203
|
+
for (let i = 0; i < ssrNodes.length; i++) {
|
|
204
|
+
if (ssrNodes[i] !== next)
|
|
205
|
+
ssrNodes[i]!.parentNode?.removeChild(ssrNodes[i]!)
|
|
206
|
+
}
|
|
207
|
+
}
|
|
182
208
|
current = next
|
|
183
209
|
return
|
|
184
210
|
}
|
|
185
211
|
clearInserted(current)
|
|
212
|
+
if (ssrNodes !== undefined)
|
|
213
|
+
clearInserted(ssrNodes)
|
|
186
214
|
if (next.nodeType === 11) {
|
|
187
215
|
const nodes = Array.from(next.childNodes)
|
|
188
216
|
parent.insertBefore(next, marker)
|
|
@@ -197,6 +225,18 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
|
|
|
197
225
|
|
|
198
226
|
if (Array.isArray(next)) {
|
|
199
227
|
clearInserted(current)
|
|
228
|
+
if (ssrNodes !== undefined) {
|
|
229
|
+
const kept = new Set<Node>()
|
|
230
|
+
for (let i = 0; i < next.length; i++) {
|
|
231
|
+
const item = next[i]
|
|
232
|
+
if (item instanceof Node && item.parentNode === parent)
|
|
233
|
+
kept.add(item)
|
|
234
|
+
}
|
|
235
|
+
for (let i = 0; i < ssrNodes.length; i++) {
|
|
236
|
+
if (!kept.has(ssrNodes[i]!))
|
|
237
|
+
ssrNodes[i]!.parentNode?.removeChild(ssrNodes[i]!)
|
|
238
|
+
}
|
|
239
|
+
}
|
|
200
240
|
const f = document.createDocumentFragment()
|
|
201
241
|
const nodes: Node[] = []
|
|
202
242
|
for (let i = 0; i < next.length; i++) {
|
|
@@ -259,8 +299,10 @@ export function show(
|
|
|
259
299
|
const res = claimInsert(parent, marker, () => untrack(() => runWithOwner(owner, fn)))
|
|
260
300
|
marker = res.marker
|
|
261
301
|
const rendered = res.result
|
|
262
|
-
if (rendered == null || typeof rendered === 'boolean')
|
|
302
|
+
if (rendered == null || typeof rendered === 'boolean') {
|
|
303
|
+
nodes = res.nodes ?? []
|
|
263
304
|
return
|
|
305
|
+
}
|
|
264
306
|
|
|
265
307
|
if (typeof rendered === 'string' || typeof rendered === 'number') {
|
|
266
308
|
const str = String(rendered)
|