@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.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.
- package/package.json +1 -1
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +442 -0
- package/src/build/compile.ts +20 -11
- package/src/build/files.ts +136 -0
- package/src/build/graph.ts +158 -0
- package/src/build/index.ts +231 -1296
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +224 -0
- package/src/build/plugin-host.ts +184 -0
- package/src/build/prerender.ts +93 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +58 -0
- package/src/build/routes.ts +135 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +228 -114
- package/src/cli/index.ts +298 -79
- package/src/cli/new.ts +67 -35
- package/src/compiler/analyze.ts +666 -91
- package/src/compiler/dom.ts +822 -629
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +164 -21
- package/src/compiler/shared.ts +442 -0
- package/src/compiler/ssr.ts +390 -324
- package/src/context.ts +120 -0
- package/src/dev/index.ts +291 -76
- package/src/dom/action.ts +23 -13
- package/src/dom/extras.ts +157 -84
- package/src/dom/index.ts +154 -33
- package/src/dom/island.ts +117 -39
- package/src/dom/loop.ts +34 -21
- package/src/index.ts +2 -1
- package/src/jsx-runtime.ts +11 -0
- package/src/plugins/context.ts +57 -0
- package/src/plugins/index.ts +120 -17
- package/src/reactivity/index.ts +250 -157
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +37 -12
- package/src/server/action.ts +217 -74
- package/src/server/compress.ts +155 -56
- package/src/server/cookies.ts +59 -22
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +201 -33
- package/src/server/index.ts +964 -737
- package/src/server/loader.ts +120 -0
- package/src/server/router.ts +27 -8
- package/src/server/security.ts +87 -39
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +96 -10
- package/src/ssr/index.ts +225 -56
- package/src/style.ts +33 -0
- package/src/test/index.ts +5 -0
- package/src/unrenderable.ts +35 -0
package/src/ssr/context.ts
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
|
-
// Per-request SSR context for <Head> metadata
|
|
2
|
-
//
|
|
1
|
+
// Per-request SSR context for <Head> metadata, streaming <Suspense>, rendered island tracking,
|
|
2
|
+
// universal createContext/useContext, and deterministic hydration-safe useId().
|
|
3
3
|
|
|
4
4
|
import type { Html, KayChild } from '../jsx-runtime'
|
|
5
5
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
6
|
+
import { registerServerContextBridge } from '../context'
|
|
6
7
|
import { raw, ssrChild } from './index'
|
|
7
8
|
|
|
9
|
+
export interface SettledChunk {
|
|
10
|
+
html: string
|
|
11
|
+
error?: unknown
|
|
12
|
+
}
|
|
13
|
+
|
|
8
14
|
export interface PendingChunk {
|
|
9
15
|
id: number
|
|
10
|
-
|
|
16
|
+
// Settles to the boundary's HTML, or to its error template and the error: it never rejects.
|
|
17
|
+
settled: Promise<SettledChunk>
|
|
18
|
+
renderError: (error: unknown) => string
|
|
11
19
|
}
|
|
12
20
|
|
|
13
21
|
export interface RenderContext {
|
|
@@ -15,13 +23,73 @@ export interface RenderContext {
|
|
|
15
23
|
title: string | undefined
|
|
16
24
|
pending: PendingChunk[]
|
|
17
25
|
nextId: number
|
|
26
|
+
islandDepth: number
|
|
27
|
+
islandSeq: number
|
|
28
|
+
idPrefix: string
|
|
29
|
+
idSeq: number
|
|
30
|
+
contexts: Map<symbol, unknown>
|
|
31
|
+
/** Maps island chunk URL -> eager (true if hydrate is undefined/'load'). */
|
|
32
|
+
renderedIslands: Map<string, boolean>
|
|
33
|
+
hasIslands: boolean
|
|
34
|
+
htmlAttrs: Record<string, string>
|
|
18
35
|
}
|
|
19
36
|
|
|
20
37
|
const STORAGE_KEY = Symbol.for('kay.render.storage')
|
|
21
38
|
const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
|
|
22
39
|
|
|
40
|
+
registerServerContextBridge({
|
|
41
|
+
getContext(key: symbol) {
|
|
42
|
+
const ctx = renderStorage.getStore()
|
|
43
|
+
if (ctx !== undefined && ctx.contexts.has(key))
|
|
44
|
+
return { found: true, value: ctx.contexts.get(key) }
|
|
45
|
+
return undefined
|
|
46
|
+
},
|
|
47
|
+
runWithContext<T>(key: symbol, value: unknown, fn: () => T): T {
|
|
48
|
+
const ctx = renderStorage.getStore()
|
|
49
|
+
if (ctx === undefined)
|
|
50
|
+
return fn()
|
|
51
|
+
const had = ctx.contexts.has(key)
|
|
52
|
+
const prev = ctx.contexts.get(key)
|
|
53
|
+
ctx.contexts.set(key, value)
|
|
54
|
+
try {
|
|
55
|
+
return fn()
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
if (had)
|
|
59
|
+
ctx.contexts.set(key, prev)
|
|
60
|
+
else
|
|
61
|
+
ctx.contexts.delete(key)
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
nextId() {
|
|
65
|
+
const ctx = renderStorage.getStore()
|
|
66
|
+
if (ctx === undefined)
|
|
67
|
+
return undefined
|
|
68
|
+
return `${ctx.idPrefix}${ctx.idSeq++}`
|
|
69
|
+
},
|
|
70
|
+
head(props) {
|
|
71
|
+
return Head(props)
|
|
72
|
+
},
|
|
73
|
+
suspense(props) {
|
|
74
|
+
return Suspense(props)
|
|
75
|
+
},
|
|
76
|
+
})
|
|
77
|
+
|
|
23
78
|
export function createRenderContext(): RenderContext {
|
|
24
|
-
return {
|
|
79
|
+
return {
|
|
80
|
+
headParts: [],
|
|
81
|
+
title: undefined,
|
|
82
|
+
pending: [],
|
|
83
|
+
nextId: 0,
|
|
84
|
+
islandDepth: 0,
|
|
85
|
+
islandSeq: 0,
|
|
86
|
+
idPrefix: '',
|
|
87
|
+
idSeq: 0,
|
|
88
|
+
contexts: new Map(),
|
|
89
|
+
renderedIslands: new Map(),
|
|
90
|
+
hasIslands: false,
|
|
91
|
+
htmlAttrs: {},
|
|
92
|
+
}
|
|
25
93
|
}
|
|
26
94
|
|
|
27
95
|
export function runWithRenderContext<T>(ctx: RenderContext, fn: () => T): T {
|
|
@@ -32,7 +100,7 @@ export function currentRenderContext(): RenderContext | undefined {
|
|
|
32
100
|
return renderStorage.getStore()
|
|
33
101
|
}
|
|
34
102
|
|
|
35
|
-
const TITLE_RE = /<title
|
|
103
|
+
const TITLE_RE = /<title\b[^>]*>([\s\S]*?)<\/title>/gi
|
|
36
104
|
|
|
37
105
|
/** Collects document <head> tags during SSR; innermost <title> wins. */
|
|
38
106
|
export function Head(props: { children?: KayChild }): Html {
|
|
@@ -41,10 +109,12 @@ export function Head(props: { children?: KayChild }): Html {
|
|
|
41
109
|
return raw('')
|
|
42
110
|
|
|
43
111
|
let html = ssrChild(props.children)
|
|
112
|
+
TITLE_RE.lastIndex = 0
|
|
44
113
|
const titleMatch = TITLE_RE.exec(html)
|
|
45
114
|
if (titleMatch !== null) {
|
|
46
115
|
// Inner page renders before outer layouts, so the first (innermost) <title> wins.
|
|
47
116
|
ctx.title ??= titleMatch[0]
|
|
117
|
+
TITLE_RE.lastIndex = 0
|
|
48
118
|
html = html.replace(TITLE_RE, '')
|
|
49
119
|
}
|
|
50
120
|
if (html !== '')
|
|
@@ -64,7 +134,7 @@ export function renderCollectedHead(ctx: RenderContext): string {
|
|
|
64
134
|
* Streaming SSR boundary: flushes `fallback` immediately and streams resolved async children
|
|
65
135
|
* with a zero-dependency inline swap script. Islands inside streamed chunks hydrate automatically!
|
|
66
136
|
*/
|
|
67
|
-
export function Suspense(props: { fallback?: KayChild, children?: KayChild | Promise<KayChild> }): Html {
|
|
137
|
+
export function Suspense(props: { fallback?: KayChild, error?: KayChild | ((error: unknown) => KayChild), children?: KayChild | Promise<KayChild> }): Html {
|
|
68
138
|
const ctx = renderStorage.getStore()
|
|
69
139
|
const child = props.children
|
|
70
140
|
|
|
@@ -75,15 +145,31 @@ export function Suspense(props: { fallback?: KayChild, children?: KayChild | Pro
|
|
|
75
145
|
return raw(ssrChild(props.fallback))
|
|
76
146
|
|
|
77
147
|
const id = ctx.nextId++
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
148
|
+
// Capture RenderContext so timeout / error fallback renders still run inside the request context.
|
|
149
|
+
const renderError = (error: unknown): string => {
|
|
150
|
+
try {
|
|
151
|
+
return runWithRenderContext(ctx, () => ssrChild(typeof props.error === 'function' ? props.error(error) : props.error))
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return ''
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
ctx.pending.push({ id, settled: settle(ctx, child, renderError), renderError })
|
|
82
158
|
|
|
83
159
|
const fallbackHtml = ssrChild(props.fallback)
|
|
84
160
|
return raw(`<kay-s id="k-s-${id}">${fallbackHtml}</kay-s>`)
|
|
85
161
|
}
|
|
86
162
|
|
|
163
|
+
async function settle(ctx: RenderContext, child: Promise<KayChild>, renderError: (error: unknown) => string): Promise<SettledChunk> {
|
|
164
|
+
try {
|
|
165
|
+
const resolved = await child
|
|
166
|
+
return { html: runWithRenderContext(ctx, () => ssrChild(resolved)) }
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
return { html: renderError(error), error }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
87
173
|
/** Fixed streaming swap bootstrap (constant content -> deterministic SHA-256 CSP hash, zero per-chunk inline scripts). */
|
|
88
174
|
export const KAY_STREAM_SCRIPT = `(()=>{const w=n=>{if(n.nodeType===1&&n.tagName==='TEMPLATE'&&n.dataset.ks){const s=document.getElementById('k-s-'+n.dataset.ks);if(s){s.replaceWith(n.content);n.remove()}}};const o=new MutationObserver(ms=>{for(const m of ms)for(const n of m.addedNodes)w(n)});o.observe(document.documentElement,{childList:true,subtree:true});document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('template[data-ks]').forEach(w);o.disconnect()},{once:true})})()`
|
|
89
175
|
|
package/src/ssr/index.ts
CHANGED
|
@@ -1,55 +1,68 @@
|
|
|
1
1
|
// Kay v2 SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
|
|
2
2
|
|
|
3
3
|
import type { Html, HydrateStrategy, KayChild } from '../jsx-runtime'
|
|
4
|
-
import {
|
|
4
|
+
import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
|
|
5
|
+
import { styleText } from '../style'
|
|
6
|
+
import { assertRenderable } from '../unrenderable'
|
|
7
|
+
import { currentRenderContext, KAY_STREAM_SCRIPT } from './context'
|
|
5
8
|
|
|
6
9
|
export const KAY_ISLAND_STYLE = 'kay-island,kay-slot{display:contents}'
|
|
7
10
|
export const KAY_SUSPENSE_STYLE = 'kay-s{display:contents}'
|
|
8
11
|
|
|
12
|
+
export const RAW_HTML = Symbol.for('kay.html')
|
|
13
|
+
|
|
14
|
+
function isRawHtml(value: unknown): value is Html {
|
|
15
|
+
return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[RAW_HTML] === true && '__html' in value
|
|
16
|
+
}
|
|
17
|
+
|
|
9
18
|
const ESC_TEXT = /[&<>]/
|
|
10
19
|
const ESC_ATTR = /[&"<>]/
|
|
11
20
|
const bunEscape = typeof Bun !== 'undefined' && typeof Bun.escapeHTML === 'function' ? Bun.escapeHTML : undefined
|
|
12
21
|
|
|
22
|
+
function escText(str: string): string {
|
|
23
|
+
if (bunEscape !== undefined)
|
|
24
|
+
return bunEscape(str)
|
|
25
|
+
if (!ESC_TEXT.test(str))
|
|
26
|
+
return str
|
|
27
|
+
return str.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
28
|
+
}
|
|
29
|
+
|
|
13
30
|
export function esc(value: unknown): string {
|
|
14
|
-
if (typeof value === 'string')
|
|
15
|
-
|
|
16
|
-
return bunEscape(value)
|
|
17
|
-
if (!ESC_TEXT.test(value))
|
|
18
|
-
return value
|
|
19
|
-
return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
20
|
-
}
|
|
31
|
+
if (typeof value === 'string')
|
|
32
|
+
return escText(value)
|
|
21
33
|
if (typeof value === 'number')
|
|
22
34
|
return String(value)
|
|
23
35
|
if (value == null || typeof value === 'boolean')
|
|
24
36
|
return ''
|
|
25
|
-
if (
|
|
26
|
-
return
|
|
37
|
+
if (isRawHtml(value))
|
|
38
|
+
return value.__html
|
|
27
39
|
if (Array.isArray(value)) {
|
|
28
40
|
let out = ''
|
|
29
41
|
for (let i = 0; i < value.length; i++)
|
|
30
42
|
out += esc(value[i])
|
|
31
43
|
return out
|
|
32
44
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
return bunEscape(str)
|
|
36
|
-
if (!ESC_TEXT.test(str))
|
|
37
|
-
return str
|
|
38
|
-
return str.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
45
|
+
assertRenderable(value, 'text')
|
|
46
|
+
return escText(String(value))
|
|
39
47
|
}
|
|
40
48
|
|
|
41
49
|
export function ssrRaw(value: unknown): string {
|
|
42
50
|
if (value == null || value === false)
|
|
43
51
|
return ''
|
|
52
|
+
if (isRawHtml(value))
|
|
53
|
+
return String(value.__html)
|
|
44
54
|
if (typeof value === 'object' && '__html' in value)
|
|
45
|
-
|
|
55
|
+
throw new TypeError(UNBRANDED_INNER_HTML)
|
|
46
56
|
return String(value)
|
|
47
57
|
}
|
|
48
58
|
|
|
59
|
+
/** React's `{ __html }` shape reaching innerHTML unbranded: kay would print `[object Object]`. */
|
|
60
|
+
const UNBRANDED_INNER_HTML = 'kay: innerHTML takes the HTML string, got a { __html } object; pass the string, or raw(html) for a value typed Html.'
|
|
61
|
+
|
|
49
62
|
const CLOSE_STYLE_RE = /<\/(style)/gi
|
|
50
|
-
const
|
|
63
|
+
const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
|
|
51
64
|
|
|
52
|
-
/** Emits raw text inside `<style>` or `<script>` without HTML entity escaping, neutralizing
|
|
65
|
+
/** Emits raw text inside `<style>` or `<script>` without HTML entity escaping, neutralizing dangerous script/style sequences. */
|
|
53
66
|
export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
|
|
54
67
|
if (value == null || typeof value === 'boolean')
|
|
55
68
|
return ''
|
|
@@ -59,12 +72,12 @@ export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
|
|
|
59
72
|
out += ssrRawText(tag, value[i])
|
|
60
73
|
return out
|
|
61
74
|
}
|
|
62
|
-
const str =
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
?
|
|
66
|
-
|
|
67
|
-
return str.replace(
|
|
75
|
+
const str = isRawHtml(value) ? String(value.__html) : String(value)
|
|
76
|
+
if (tag === 'script') {
|
|
77
|
+
return str.replace(SCRIPT_UNSAFE_RE, (_, body: string) =>
|
|
78
|
+
body.charCodeAt(0) === 47 ? `<\\${body}` : `\\u003c${body}`)
|
|
79
|
+
}
|
|
80
|
+
return str.replace(CLOSE_STYLE_RE, '<\\/$1')
|
|
68
81
|
}
|
|
69
82
|
|
|
70
83
|
export function escAttr(value: unknown): string {
|
|
@@ -81,14 +94,20 @@ export function escAttr(value: unknown): string {
|
|
|
81
94
|
}
|
|
82
95
|
|
|
83
96
|
export function raw(html: string): Html {
|
|
84
|
-
return { __html: html }
|
|
97
|
+
return { __html: html, [RAW_HTML]: true } as unknown as Html
|
|
85
98
|
}
|
|
86
99
|
|
|
87
100
|
export function ssrAttr(name: string, value: unknown): string {
|
|
88
|
-
if (value == null ||
|
|
101
|
+
if (value == null || isBlockedAttr(name))
|
|
89
102
|
return ''
|
|
90
|
-
if (value ===
|
|
91
|
-
|
|
103
|
+
if (typeof value === 'boolean') {
|
|
104
|
+
if (isStringBoolAttr(name))
|
|
105
|
+
return ` ${name}="${value ? 'true' : 'false'}"`
|
|
106
|
+
return value ? ` ${name}` : ''
|
|
107
|
+
}
|
|
108
|
+
if (isUnsafeUrlAttr(name, value))
|
|
109
|
+
return ''
|
|
110
|
+
assertRenderable(value, name)
|
|
92
111
|
return ` ${name}="${escAttr(value)}"`
|
|
93
112
|
}
|
|
94
113
|
|
|
@@ -98,43 +117,38 @@ export function ssrStyle(value: unknown): string {
|
|
|
98
117
|
if (typeof value === 'string')
|
|
99
118
|
return ` style="${escAttr(value)}"`
|
|
100
119
|
if (typeof value === 'object') {
|
|
101
|
-
|
|
102
|
-
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
103
|
-
if (v != null && v !== '')
|
|
104
|
-
out += `${k}:${v};`
|
|
105
|
-
}
|
|
120
|
+
const out = styleText(value as Record<string, unknown>)
|
|
106
121
|
return out === '' ? '' : ` style="${escAttr(out)}"`
|
|
107
122
|
}
|
|
108
123
|
return ''
|
|
109
124
|
}
|
|
110
125
|
|
|
111
|
-
const
|
|
126
|
+
const SPREAD_DANGEROUS_HTML = 'kay: dangerouslySetInnerHTML in a spread: write innerHTML={html} on the element.'
|
|
112
127
|
|
|
113
128
|
export function ssrSpread(props: Record<string, unknown> | null | undefined): string {
|
|
114
129
|
if (props == null || typeof props !== 'object')
|
|
115
130
|
return ''
|
|
116
131
|
let out = ''
|
|
117
132
|
for (const [rawKey, value] of Object.entries(props)) {
|
|
118
|
-
if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children'
|
|
133
|
+
if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
|
|
119
134
|
continue
|
|
135
|
+
if (rawKey === 'dangerouslySetInnerHTML')
|
|
136
|
+
throw new TypeError(SPREAD_DANGEROUS_HTML)
|
|
120
137
|
const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
|
|
138
|
+
if (isBlockedAttr(name))
|
|
139
|
+
continue
|
|
121
140
|
out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value)
|
|
122
141
|
}
|
|
123
142
|
return out
|
|
124
143
|
}
|
|
125
144
|
|
|
126
|
-
export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render: (item: T, index: number) => string): string {
|
|
145
|
+
export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render: (item: T, index: number, array: readonly T[]) => string): string {
|
|
127
146
|
if (!items)
|
|
128
147
|
return ''
|
|
148
|
+
const list: readonly T[] = Array.isArray(items) ? items : [...items]
|
|
129
149
|
let out = ''
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
out += render(items[i] as T, i)
|
|
133
|
-
return out
|
|
134
|
-
}
|
|
135
|
-
let i = 0
|
|
136
|
-
for (const item of items)
|
|
137
|
-
out += render(item, i++)
|
|
150
|
+
for (let i = 0; i < list.length; i++)
|
|
151
|
+
out += render(list[i] as T, i, list)
|
|
138
152
|
return out
|
|
139
153
|
}
|
|
140
154
|
|
|
@@ -145,14 +159,15 @@ export function ssrChild(value: KayChild): string {
|
|
|
145
159
|
return String(value)
|
|
146
160
|
if (value == null || typeof value === 'boolean')
|
|
147
161
|
return ''
|
|
148
|
-
if (
|
|
149
|
-
return
|
|
162
|
+
if (isRawHtml(value))
|
|
163
|
+
return value.__html
|
|
150
164
|
if (Array.isArray(value)) {
|
|
151
165
|
let out = ''
|
|
152
166
|
for (let i = 0; i < value.length; i++)
|
|
153
167
|
out += ssrChild(value[i])
|
|
154
168
|
return out
|
|
155
169
|
}
|
|
170
|
+
assertRenderable(value, 'text')
|
|
156
171
|
return esc(String(value))
|
|
157
172
|
}
|
|
158
173
|
|
|
@@ -160,7 +175,7 @@ function serializeIslandProps(props: Record<string, unknown>): string {
|
|
|
160
175
|
return JSON.stringify(props, function (this: Record<string, unknown>, key: string, value: unknown) {
|
|
161
176
|
const orig = key !== '' && this != null && typeof this === 'object' ? this[key] : value
|
|
162
177
|
if (orig instanceof Date)
|
|
163
|
-
return { __k: 'D', v: orig.toISOString() }
|
|
178
|
+
return { __k: 'D', v: Number.isNaN(orig.getTime()) ? 'NaN' : orig.toISOString() }
|
|
164
179
|
if (orig instanceof Set)
|
|
165
180
|
return { __k: 'S', v: [...orig] }
|
|
166
181
|
if (orig instanceof Map)
|
|
@@ -171,26 +186,169 @@ function serializeIslandProps(props: Record<string, unknown>): string {
|
|
|
171
186
|
return { __k: 'R', v: [orig.source, orig.flags] }
|
|
172
187
|
if (typeof orig === 'bigint')
|
|
173
188
|
return { __k: 'B', v: orig.toString() }
|
|
189
|
+
if (typeof orig === 'function')
|
|
190
|
+
throw new TypeError(`kay: island prop "${key}" is a function, which cannot reach the browser; define it inside the island, or import it there.`)
|
|
191
|
+
if (typeof orig === 'object' && orig !== null && 'peek' in orig && 'value' in orig)
|
|
192
|
+
throw new TypeError(`kay: island prop "${key}" is a signal; pass ${key}.value, or import the signal in the island from a shared module.`)
|
|
174
193
|
return value
|
|
175
194
|
})
|
|
176
195
|
}
|
|
177
196
|
|
|
197
|
+
let fallbackIslandDepth = 0
|
|
198
|
+
|
|
199
|
+
function getIslandDepth(): number {
|
|
200
|
+
const ctx = currentRenderContext()
|
|
201
|
+
return ctx !== undefined ? ctx.islandDepth : fallbackIslandDepth
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function recordRenderedIsland(chunk: string, hydrate?: HydrateStrategy): void {
|
|
205
|
+
const ctx = currentRenderContext()
|
|
206
|
+
if (ctx === undefined)
|
|
207
|
+
return
|
|
208
|
+
ctx.hasIslands = true
|
|
209
|
+
const eager = hydrate === undefined || hydrate === 'load'
|
|
210
|
+
if (eager)
|
|
211
|
+
ctx.renderedIslands.set(chunk, true)
|
|
212
|
+
else if (!ctx.renderedIslands.has(chunk))
|
|
213
|
+
ctx.renderedIslands.set(chunk, false)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function ssrInIsland(render: () => string, chunk?: string, hydrate?: HydrateStrategy): string {
|
|
217
|
+
const ctx = currentRenderContext()
|
|
218
|
+
if (ctx !== undefined) {
|
|
219
|
+
if (chunk !== undefined && ctx.islandDepth === 0)
|
|
220
|
+
recordRenderedIsland(chunk, hydrate)
|
|
221
|
+
ctx.islandDepth++
|
|
222
|
+
try {
|
|
223
|
+
return render()
|
|
224
|
+
}
|
|
225
|
+
finally {
|
|
226
|
+
ctx.islandDepth--
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
fallbackIslandDepth++
|
|
230
|
+
try {
|
|
231
|
+
return render()
|
|
232
|
+
}
|
|
233
|
+
finally {
|
|
234
|
+
fallbackIslandDepth--
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Lazily evaluates non-async component children on first read inside the component's dynamic context, memoizing the result. */
|
|
239
|
+
export function ssrChildProp<P extends Record<string, unknown>>(props: P, fn: () => Html): P {
|
|
240
|
+
let cached: Html | undefined
|
|
241
|
+
let evaluated = false
|
|
242
|
+
return Object.defineProperty(props, 'children', {
|
|
243
|
+
enumerable: true,
|
|
244
|
+
configurable: true,
|
|
245
|
+
get() {
|
|
246
|
+
if (!evaluated) {
|
|
247
|
+
evaluated = true
|
|
248
|
+
cached = fn()
|
|
249
|
+
}
|
|
250
|
+
return cached
|
|
251
|
+
},
|
|
252
|
+
})
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function ssrIslandStatic(
|
|
256
|
+
chunk: string,
|
|
257
|
+
openTag: string,
|
|
258
|
+
render: (() => string) | undefined,
|
|
259
|
+
hydrate?: HydrateStrategy,
|
|
260
|
+
): string {
|
|
261
|
+
if (getIslandDepth() > 0)
|
|
262
|
+
return render !== undefined ? render() : ''
|
|
263
|
+
|
|
264
|
+
const ctx = currentRenderContext()
|
|
265
|
+
if (ctx !== undefined)
|
|
266
|
+
recordRenderedIsland(chunk, hydrate)
|
|
267
|
+
|
|
268
|
+
let idAttr = ''
|
|
269
|
+
let inner = ''
|
|
270
|
+
if (render !== undefined && hydrate !== 'client') {
|
|
271
|
+
if (ctx !== undefined) {
|
|
272
|
+
const prevPrefix = ctx.idPrefix
|
|
273
|
+
const prevSeq = ctx.idSeq
|
|
274
|
+
const islandPrefix = `i${ctx.islandSeq++}-`
|
|
275
|
+
ctx.idPrefix = islandPrefix
|
|
276
|
+
ctx.idSeq = 0
|
|
277
|
+
try {
|
|
278
|
+
inner = ssrInIsland(render)
|
|
279
|
+
if (ctx.idSeq > 0)
|
|
280
|
+
idAttr = ` i="${islandPrefix}"`
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
ctx.idPrefix = prevPrefix
|
|
284
|
+
ctx.idSeq = prevSeq
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
inner = ssrInIsland(render)
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const tag = idAttr === '' ? openTag : `${openTag.slice(0, -1)}${idAttr}>`
|
|
293
|
+
return `${tag}${inner}</kay-island>`
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function safeJsonScript(json: string): string {
|
|
297
|
+
return json.replace(/</g, '\\u003c')
|
|
298
|
+
}
|
|
299
|
+
|
|
178
300
|
export function ssrIsland(
|
|
179
|
-
_id: string,
|
|
180
301
|
chunk: string,
|
|
181
302
|
render: () => string,
|
|
182
303
|
props: Record<string, unknown>,
|
|
183
304
|
hydrate?: HydrateStrategy,
|
|
305
|
+
scriptProps = false,
|
|
184
306
|
): string {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
307
|
+
if (getIslandDepth() > 0)
|
|
308
|
+
return render()
|
|
309
|
+
|
|
310
|
+
const ctx = currentRenderContext()
|
|
311
|
+
if (ctx !== undefined)
|
|
312
|
+
recordRenderedIsland(chunk, hydrate)
|
|
313
|
+
|
|
314
|
+
let propsAttr = ''
|
|
315
|
+
let propsScript = ''
|
|
316
|
+
if (Object.keys(props).length > 0) {
|
|
317
|
+
const json = serializeIslandProps(props)
|
|
318
|
+
if (scriptProps)
|
|
319
|
+
propsScript = `<script type="application/json">${safeJsonScript(json)}</script>`
|
|
320
|
+
else
|
|
321
|
+
propsAttr = ` p="${escAttr(json)}"`
|
|
322
|
+
}
|
|
188
323
|
const hydrateAttr = hydrate !== undefined && hydrate !== 'load'
|
|
189
324
|
? ` h="${escAttr(hydrate)}"`
|
|
190
325
|
: ''
|
|
191
|
-
const inner = hydrate === 'client' ? '' : render()
|
|
192
326
|
|
|
193
|
-
|
|
327
|
+
let idAttr = ''
|
|
328
|
+
let inner = ''
|
|
329
|
+
if (hydrate !== 'client') {
|
|
330
|
+
if (ctx !== undefined) {
|
|
331
|
+
const prevPrefix = ctx.idPrefix
|
|
332
|
+
const prevSeq = ctx.idSeq
|
|
333
|
+
const islandPrefix = `i${ctx.islandSeq++}-`
|
|
334
|
+
ctx.idPrefix = islandPrefix
|
|
335
|
+
ctx.idSeq = 0
|
|
336
|
+
try {
|
|
337
|
+
inner = ssrInIsland(render)
|
|
338
|
+
if (ctx.idSeq > 0)
|
|
339
|
+
idAttr = ` i="${islandPrefix}"`
|
|
340
|
+
}
|
|
341
|
+
finally {
|
|
342
|
+
ctx.idPrefix = prevPrefix
|
|
343
|
+
ctx.idSeq = prevSeq
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
else {
|
|
347
|
+
inner = ssrInIsland(render)
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return `<kay-island c="${escAttr(chunk)}"${propsAttr}${hydrateAttr}${idAttr}>${inner}${propsScript}</kay-island>`
|
|
194
352
|
}
|
|
195
353
|
|
|
196
354
|
export interface DocumentOptions {
|
|
@@ -198,6 +356,7 @@ export interface DocumentOptions {
|
|
|
198
356
|
head?: string | undefined
|
|
199
357
|
headTags?: Iterable<string> | undefined
|
|
200
358
|
lang?: string | undefined
|
|
359
|
+
htmlAttrs?: Record<string, string> | undefined
|
|
201
360
|
runtimeScript?: string | undefined
|
|
202
361
|
alwaysLoadRuntime?: boolean | undefined
|
|
203
362
|
preloadChunks?: Iterable<string> | undefined
|
|
@@ -207,7 +366,7 @@ export interface DocumentOptions {
|
|
|
207
366
|
}
|
|
208
367
|
|
|
209
368
|
export function renderDocument(options: DocumentOptions): string {
|
|
210
|
-
const { body, head = '', headTags, lang = 'en', runtimeScript, alwaysLoadRuntime, preloadChunks, styles, hasIslands, hasSuspense } = options
|
|
369
|
+
const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, preloadChunks, styles, hasIslands, hasSuspense } = options
|
|
211
370
|
let headExtra = head
|
|
212
371
|
|
|
213
372
|
if (headTags !== undefined) {
|
|
@@ -234,5 +393,15 @@ export function renderDocument(options: DocumentOptions): string {
|
|
|
234
393
|
if (runtimeScript !== undefined && (hasIslands || alwaysLoadRuntime))
|
|
235
394
|
headExtra += `<script type="module" src="${escAttr(runtimeScript)}"></script>`
|
|
236
395
|
|
|
237
|
-
|
|
396
|
+
let attrStr = ''
|
|
397
|
+
const effectiveLang = htmlAttrs?.lang ?? lang
|
|
398
|
+
attrStr += ` lang="${escAttr(effectiveLang)}"`
|
|
399
|
+
if (htmlAttrs !== undefined) {
|
|
400
|
+
for (const [k, v] of Object.entries(htmlAttrs)) {
|
|
401
|
+
if (k !== 'lang' && !isBlockedAttr(k))
|
|
402
|
+
attrStr += ` ${k}="${escAttr(v)}"`
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
return `<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>${body}</body></html>`
|
|
238
407
|
}
|
package/src/style.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The CSS text of a style object, shared by the server and the browser so both render the same declarations.
|
|
2
|
+
|
|
3
|
+
// Properties that take a bare number; any other number gets `px`.
|
|
4
|
+
const UNITLESS = new Set([
|
|
5
|
+
'animation-iteration-count', 'aspect-ratio', 'border-image-outset', 'border-image-slice', 'border-image-width',
|
|
6
|
+
'column-count', 'columns', 'fill-opacity', 'flex', 'flex-grow', 'flex-shrink', 'flood-opacity', 'font-weight',
|
|
7
|
+
'grid-area', 'grid-column', 'grid-column-end', 'grid-column-start', 'grid-row', 'grid-row-end', 'grid-row-start',
|
|
8
|
+
'line-clamp', '-webkit-line-clamp', 'line-height', 'opacity', 'order', 'orphans', 'scale', 'stop-opacity',
|
|
9
|
+
'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'tab-size',
|
|
10
|
+
'widows', 'z-index', 'zoom',
|
|
11
|
+
])
|
|
12
|
+
const UPPER = /[A-Z]/g
|
|
13
|
+
const MS_PREFIX = /^ms[A-Z]/
|
|
14
|
+
|
|
15
|
+
// `backgroundColor` becomes `background-color` and `msTransform` `-ms-transform`; a custom property keeps its case.
|
|
16
|
+
function cssName(key: string): string {
|
|
17
|
+
if (key.startsWith('--'))
|
|
18
|
+
return key
|
|
19
|
+
const name = key.replace(UPPER, c => `-${c.toLowerCase()}`)
|
|
20
|
+
return MS_PREFIX.test(key) ? `-${name}` : name
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function styleText(style: Record<string, unknown>): string {
|
|
24
|
+
let out = ''
|
|
25
|
+
for (const [key, value] of Object.entries(style)) {
|
|
26
|
+
if (value == null || value === '' || value === false)
|
|
27
|
+
continue
|
|
28
|
+
const name = cssName(key)
|
|
29
|
+
const px = typeof value === 'number' && !name.startsWith('--') && !UNITLESS.has(name)
|
|
30
|
+
out += `${name}:${value}${px ? 'px' : ''};`
|
|
31
|
+
}
|
|
32
|
+
return out
|
|
33
|
+
}
|
package/src/test/index.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import type { BuildManifest, BuildOptions } from '../build/index'
|
|
4
4
|
import type { KayApp, ServerOptions } from '../server/index'
|
|
5
|
+
import type { TrustProxy } from '../server/security'
|
|
5
6
|
import { build } from '../build/index'
|
|
6
7
|
import { createServer } from '../server/index'
|
|
7
8
|
|
|
@@ -10,6 +11,8 @@ export interface TestAppOptions extends Omit<BuildOptions, 'compile' | 'static'>
|
|
|
10
11
|
lang?: string | undefined
|
|
11
12
|
security?: ServerOptions['security']
|
|
12
13
|
trustedOrigins?: string[] | undefined
|
|
14
|
+
trustProxy?: TrustProxy | undefined
|
|
15
|
+
maxRequestBodySize?: number | undefined
|
|
13
16
|
}
|
|
14
17
|
|
|
15
18
|
export interface TestApp {
|
|
@@ -40,6 +43,8 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
40
43
|
lang: options.lang,
|
|
41
44
|
security: options.security,
|
|
42
45
|
trustedOrigins: options.trustedOrigins,
|
|
46
|
+
trustProxy: options.trustProxy,
|
|
47
|
+
maxRequestBodySize: options.maxRequestBodySize,
|
|
43
48
|
plugins: options.plugins,
|
|
44
49
|
})
|
|
45
50
|
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Values whose String() is never what the author meant, shared by the SSR and DOM renderers so both refuse them alike.
|
|
2
|
+
|
|
3
|
+
// A value with its own toString, such as a server action printing its URL, renders as that string on purpose.
|
|
4
|
+
function hasOwnToString(value: object): boolean {
|
|
5
|
+
const { toString } = value
|
|
6
|
+
return typeof toString === 'function' && toString !== Function.prototype.toString && toString !== Object.prototype.toString && toString !== Array.prototype.toString
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function describe(value: unknown, asClass: boolean): [string, string] | undefined {
|
|
10
|
+
if (typeof value === 'function')
|
|
11
|
+
return hasOwnToString(value) ? undefined : ['a function', 'call it, or pass it to an event prop']
|
|
12
|
+
if (typeof value !== 'object' || value === null)
|
|
13
|
+
return undefined
|
|
14
|
+
if (typeof (value as { then?: unknown }).then === 'function')
|
|
15
|
+
return ['a Promise', 'await it in an async component, or make that component the only child of <Suspense>']
|
|
16
|
+
if ('peek' in value && 'value' in value)
|
|
17
|
+
return ['a signal', 'read its .value']
|
|
18
|
+
if ('__html' in value)
|
|
19
|
+
return ['a { __html } object', 'pass the string to innerHTML, or wrap trusted HTML in raw()']
|
|
20
|
+
if (asClass && Array.isArray(value))
|
|
21
|
+
return ['an array', 'join the names into one string']
|
|
22
|
+
if (hasOwnToString(value))
|
|
23
|
+
return undefined
|
|
24
|
+
const proto = Object.getPrototypeOf(value)
|
|
25
|
+
if (proto === Object.prototype || proto === null)
|
|
26
|
+
return ['a plain object', 'render one of its fields']
|
|
27
|
+
return undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Throws when `value` would print as `[object Object]`, `[object Promise]` or a function's source; `place` is `text` or an attribute name. */
|
|
31
|
+
export function assertRenderable(value: unknown, place: string): void {
|
|
32
|
+
const found = describe(value, place === 'class')
|
|
33
|
+
if (found !== undefined)
|
|
34
|
+
throw new TypeError(`kay: cannot render ${found[0]} as ${place === 'text' ? 'text' : `the ${place} attribute`}; ${found[1]}.`)
|
|
35
|
+
}
|