@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.2

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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +615 -0
  4. package/src/build/compile.ts +32 -19
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +255 -1461
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +227 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +94 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +300 -129
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +58 -38
  19. package/src/compiler/analyze.ts +723 -93
  20. package/src/compiler/dom.ts +848 -762
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +172 -23
  24. package/src/compiler/shared.ts +485 -0
  25. package/src/compiler/ssr.ts +331 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +358 -76
  28. package/src/dom/action.ts +114 -14
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +122 -80
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +5 -1
  34. package/src/jsx-runtime.ts +432 -93
  35. package/src/plugins/context.ts +83 -0
  36. package/src/plugins/index.ts +285 -23
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +157 -79
  41. package/src/server/compress.ts +197 -104
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +189 -77
  45. package/src/server/index.ts +1024 -878
  46. package/src/server/loader.ts +138 -0
  47. package/src/server/router.ts +69 -26
  48. package/src/server/security.ts +50 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -15
  55. package/src/unrenderable.ts +35 -0
@@ -0,0 +1,354 @@
1
+ // Refuses JSX that compiles but does the wrong thing, mostly habits from React, Solid and Astro, with an error naming the fix.
2
+
3
+ import type { JSXAttribute, JSXAttributeItem, JSXElement, Node, Program } from 'oxc-parser'
4
+ import { walk } from './analyze'
5
+ import { EVENT_ATTR, filterMeaningfulChildren, isComponentTag, jsxTagName, unwrapParens, VOID_ELEMENTS } from './shared'
6
+
7
+ // The kay prop for each DOM event, keyed by the event name kay binds (`onKeyDown` binds `keydown`).
8
+ const EVENT_PROPS = new Map(Object.entries({
9
+ abort: 'onAbort', animationcancel: 'onAnimationCancel', animationend: 'onAnimationEnd', animationiteration: 'onAnimationIteration', animationstart: 'onAnimationStart',
10
+ auxclick: 'onAuxClick', beforeinput: 'onBeforeInput', beforetoggle: 'onBeforeToggle', blur: 'onBlur', cancel: 'onCancel',
11
+ canplay: 'onCanPlay', canplaythrough: 'onCanPlayThrough', change: 'onChange', click: 'onClick', close: 'onClose',
12
+ compositionend: 'onCompositionEnd', compositionstart: 'onCompositionStart', compositionupdate: 'onCompositionUpdate',
13
+ contextmenu: 'onContextMenu', copy: 'onCopy', cut: 'onCut', dblclick: 'onDblClick', drag: 'onDrag', dragend: 'onDragEnd',
14
+ dragenter: 'onDragEnter', dragleave: 'onDragLeave', dragover: 'onDragOver', dragstart: 'onDragStart', drop: 'onDrop',
15
+ durationchange: 'onDurationChange', emptied: 'onEmptied', ended: 'onEnded', error: 'onError', focus: 'onFocus',
16
+ focusin: 'onFocusIn', focusout: 'onFocusOut', formdata: 'onFormData', gotpointercapture: 'onGotPointerCapture',
17
+ input: 'onInput', invalid: 'onInvalid', keydown: 'onKeyDown', keypress: 'onKeyPress', keyup: 'onKeyUp', load: 'onLoad',
18
+ loadeddata: 'onLoadedData', loadedmetadata: 'onLoadedMetadata', loadstart: 'onLoadStart',
19
+ lostpointercapture: 'onLostPointerCapture', mousedown: 'onMouseDown', mouseenter: 'onMouseEnter', mouseleave: 'onMouseLeave',
20
+ mousemove: 'onMouseMove', mouseout: 'onMouseOut', mouseover: 'onMouseOver', mouseup: 'onMouseUp', paste: 'onPaste',
21
+ pause: 'onPause', play: 'onPlay', playing: 'onPlaying', pointercancel: 'onPointerCancel', pointerdown: 'onPointerDown',
22
+ pointerenter: 'onPointerEnter', pointerleave: 'onPointerLeave', pointermove: 'onPointerMove', pointerout: 'onPointerOut',
23
+ pointerover: 'onPointerOver', pointerup: 'onPointerUp', progress: 'onProgress', ratechange: 'onRateChange', reset: 'onReset',
24
+ resize: 'onResize', scroll: 'onScroll', scrollend: 'onScrollEnd', securitypolicyviolation: 'onSecurityPolicyViolation',
25
+ seeked: 'onSeeked', seeking: 'onSeeking', select: 'onSelect', selectionchange: 'onSelectionChange',
26
+ selectstart: 'onSelectStart', slotchange: 'onSlotChange', stalled: 'onStalled', submit: 'onSubmit', suspend: 'onSuspend',
27
+ timeupdate: 'onTimeUpdate', toggle: 'onToggle', touchcancel: 'onTouchCancel', touchend: 'onTouchEnd',
28
+ touchmove: 'onTouchMove', touchstart: 'onTouchStart', transitioncancel: 'onTransitionCancel',
29
+ transitionend: 'onTransitionEnd', transitionrun: 'onTransitionRun', transitionstart: 'onTransitionStart',
30
+ volumechange: 'onVolumeChange', waiting: 'onWaiting', wheel: 'onWheel',
31
+ afterprint: 'onAfterPrint', beforeprint: 'onBeforePrint', beforeunload: 'onBeforeUnload', hashchange: 'onHashChange',
32
+ message: 'onMessage', offline: 'onOffline', online: 'onOnline', pagehide: 'onPageHide', pageshow: 'onPageShow',
33
+ popstate: 'onPopState', storage: 'onStorage', unload: 'onUnload', fullscreenchange: 'onFullscreenChange',
34
+ fullscreenerror: 'onFullscreenError', loadend: 'onLoadEnd', search: 'onSearch', beforematch: 'onBeforeMatch',
35
+ command: 'onCommand', cuechange: 'onCueChange', encrypted: 'onEncrypted', waitingforkey: 'onWaitingForKey',
36
+ pointerrawupdate: 'onPointerRawUpdate', contextlost: 'onContextLost', contextrestored: 'onContextRestored',
37
+ contentvisibilityautostatechange: 'onContentVisibilityAutoStateChange',
38
+ }))
39
+
40
+ // React names whose DOM event is spelled differently.
41
+ const RENAMED_EVENTS = new Map([['doubleclick', 'dblclick']])
42
+ const CAPTURE_SUFFIX = 'capture'
43
+ const LOWERCASE_EVENT = /^on[a-z]/
44
+
45
+ function eventProp(event: string): string {
46
+ return EVENT_PROPS.get(event) ?? `on${event.charAt(0).toUpperCase()}${event.slice(1)}`
47
+ }
48
+
49
+ export function mistake(what: string, filename: string, fix: string): Error {
50
+ return new Error(`kay compiler: ${what} in ${filename}: ${fix}.`)
51
+ }
52
+
53
+ const HYDRATE_MODES = new Set(['load', 'visible', 'idle', 'interaction', 'client'])
54
+ const MEDIA_MODE = /^media\(.+\)$/
55
+
56
+ /** Throws on a hydrate mode the browser runtime would silently treat as `load`; `*` stands for a mode picked at runtime. */
57
+ export function checkHydrateMode(mode: string, what: string, filename: string): void {
58
+ if (mode !== '*' && !HYDRATE_MODES.has(mode) && !MEDIA_MODE.test(mode))
59
+ throw mistake(what, filename, 'use load, visible, idle, interaction, client or media(<query>)')
60
+ }
61
+
62
+ function checkHandler(name: string, value: JSXAttribute['value'], filename: string, code: string): void {
63
+ if (value === null)
64
+ throw mistake(name, filename, `pass a function, ${name}={() => ...}`)
65
+ if (value.type === 'Literal')
66
+ throw mistake(`${name}="..."`, filename, `pass a function, ${name}={() => ...}`)
67
+ if (value.type !== 'JSXExpressionContainer')
68
+ return
69
+ const expr = unwrapParens(value.expression)
70
+ if ((expr.type === 'Literal' && typeof expr.value === 'string') || expr.type === 'TemplateLiteral')
71
+ throw mistake(`${name}="..."`, filename, `pass a function, ${name}={() => ...}`)
72
+ if (expr.type === 'UpdateExpression' || expr.type === 'AssignmentExpression') {
73
+ const source = code.slice(expr.start, expr.end)
74
+ throw mistake(`${name} runs ${source} at render`, filename, `write ${name}={() => ${source}}`)
75
+ }
76
+ }
77
+
78
+ // SVG presentation attributes React spells in camelCase; SVG is case-sensitive, so the camelCase name sets nothing.
79
+ const KEBAB_SVG_ATTRS = new Set([
80
+ 'alignment-baseline', 'baseline-shift', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters',
81
+ 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family',
82
+ 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'image-rendering',
83
+ 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'paint-order', 'pointer-events',
84
+ 'shape-rendering', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',
85
+ 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration',
86
+ 'text-rendering', 'transform-origin', 'unicode-bidi', 'vector-effect', 'word-spacing', 'writing-mode',
87
+ ])
88
+ const CAMEL_HUMP = /[A-Z]/g
89
+ // React's uncontrolled-input props and the attribute each one stands for.
90
+ const REACT_DEFAULTS = new Map([['defaultValue', 'value'], ['defaultChecked', 'checked']])
91
+ const BOOLEAN_ATTRS = new Set([
92
+ 'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default', 'defer', 'disabled',
93
+ 'formnovalidate', 'hidden', 'inert', 'ismap', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open',
94
+ 'playsinline', 'readonly', 'required', 'reversed', 'selected',
95
+ ])
96
+
97
+ function checkRef(value: JSXAttribute['value'], filename: string): void {
98
+ if (value === null)
99
+ throw mistake('ref', filename, 'pass a function, ref={el => ...}')
100
+ if (value.type === 'Literal')
101
+ throw mistake('ref="..."', filename, 'pass a function, ref={el => ...}')
102
+ if (value.type === 'JSXExpressionContainer' && unwrapParens(value.expression).type === 'ObjectExpression')
103
+ throw mistake('ref={{ ... }}', filename, 'pass a function, ref={el => ...}, kay has no ref objects')
104
+ }
105
+
106
+ function checkSpelling(name: string, value: JSXAttribute['value'], filename: string): void {
107
+ const kebab = name.replace(CAMEL_HUMP, hump => `-${hump.toLowerCase()}`)
108
+ if (kebab !== name && KEBAB_SVG_ATTRS.has(kebab))
109
+ throw mistake(name, filename, `write ${kebab}={...}, SVG attributes are case-sensitive`)
110
+ if (name === 'xlinkHref')
111
+ throw mistake(name, filename, 'write xlink:href={...}, or href={...}')
112
+ const attribute = REACT_DEFAULTS.get(name)
113
+ if (attribute !== undefined)
114
+ throw mistake(name, filename, `write ${attribute}={...}`)
115
+ if (value?.type === 'Literal' && value.value === 'false' && BOOLEAN_ATTRS.has(name.toLowerCase()))
116
+ throw mistake(`${name}="false"`, filename, `write ${name}={false}, any string turns it on`)
117
+ }
118
+
119
+ // Astro's client: directives and the $hydrate mode each one means.
120
+ const CLIENT_DIRECTIVES = new Map([['load', 'load'], ['visible', 'visible'], ['idle', 'idle'], ['only', 'client'], ['media', 'media(<query>)']])
121
+ // XML namespaces SVG and MathML really use; every other prefix is a directive from another framework.
122
+ const XML_NAMESPACES = new Set(['xlink', 'xml', 'xmlns'])
123
+
124
+ function checkNamespacedAttribute(namespace: string, name: string, filename: string): void {
125
+ if (XML_NAMESPACES.has(namespace))
126
+ return
127
+ const what = `${namespace}:${name}`
128
+ if (namespace === 'on')
129
+ throw mistake(what, filename, `write ${eventProp(name.toLowerCase())}={...}`)
130
+ if (namespace === 'client')
131
+ throw mistake(what, filename, `write $hydrate="${CLIENT_DIRECTIVES.get(name) ?? 'load'}"`)
132
+ if (what === 'class:list')
133
+ throw mistake(what, filename, 'pass one string to class, joining the names yourself')
134
+ if (what === 'set:html')
135
+ throw mistake(what, filename, 'write innerHTML={...}')
136
+ if (what === 'set:text')
137
+ throw mistake(what, filename, 'write the text as children')
138
+ if (namespace === 'use')
139
+ throw mistake(what, filename, `call ${name} in a ref`)
140
+ if (namespace === 'prop' || namespace === 'attr' || namespace === 'bool')
141
+ throw mistake(what, filename, `write ${name}={...}`)
142
+ throw mistake(what, filename, `kay has no ${namespace}: directives`)
143
+ }
144
+
145
+ // The source of `x` in React's `{{ __html: x }}`, or undefined when the attribute holds something else.
146
+ function reactHtmlSource(value: JSXAttribute['value'], code: string): string | undefined {
147
+ if (value?.type !== 'JSXExpressionContainer')
148
+ return undefined
149
+ const expr = unwrapParens(value.expression)
150
+ if (expr.type !== 'ObjectExpression')
151
+ return undefined
152
+ for (const p of expr.properties) {
153
+ if (p.type !== 'Property')
154
+ continue
155
+ const keyName = p.key.type === 'Identifier' ? p.key.name : p.key.type === 'Literal' ? String(p.key.value) : undefined
156
+ if (keyName === '__html')
157
+ return code.slice(p.value.start, p.value.end)
158
+ }
159
+ return undefined
160
+ }
161
+
162
+ function checkInnerHtml(element: JSXElement, tag: string, attr: JSXAttribute, filename: string, code: string): void {
163
+ const html = reactHtmlSource(attr.value, code)
164
+ if (html !== undefined)
165
+ throw mistake('innerHTML={{ __html }}', filename, `write innerHTML={${html}}, kay takes the HTML string itself`)
166
+ if (VOID_ELEMENTS.has(tag))
167
+ throw mistake(`innerHTML on <${tag}>`, filename, 'a void element has no content, drop innerHTML')
168
+ if (filterMeaningfulChildren(element.children).length > 0)
169
+ throw mistake('innerHTML with children', filename, 'keep one, the children or innerHTML')
170
+ }
171
+
172
+ function checkElementAttribute(attr: JSXAttribute, isCustomElement: boolean, filename: string, code: string): void {
173
+ if (attr.name.type !== 'JSXIdentifier')
174
+ return
175
+ const name = attr.name.name
176
+ if (name === 'dangerouslySetInnerHTML')
177
+ throw mistake(name, filename, `write innerHTML={${reactHtmlSource(attr.value, code) ?? '...'}}`)
178
+ if (name === 'classList')
179
+ throw mistake(name, filename, 'pass one string to class, joining the names yourself')
180
+ if (name === 'ref')
181
+ return checkRef(attr.value, filename)
182
+ checkSpelling(name, attr.value, filename)
183
+ if (LOWERCASE_EVENT.test(name) && EVENT_PROPS.has(name.slice(2)))
184
+ throw mistake(name, filename, `write ${eventProp(name.slice(2))}={...}, kay binds camelCase event props only`)
185
+ if (!EVENT_ATTR.test(name))
186
+ return
187
+ checkHandler(name, attr.value, filename, code)
188
+ if (!isCustomElement)
189
+ checkEventName(name, filename)
190
+ }
191
+
192
+ function checkEventName(name: string, filename: string): void {
193
+ const event = name.slice(2).toLowerCase()
194
+ if (EVENT_PROPS.has(event))
195
+ return
196
+ const renamed = RENAMED_EVENTS.get(event)
197
+ if (renamed !== undefined)
198
+ throw mistake(name, filename, `write ${eventProp(renamed)}={...}`)
199
+ if (event.endsWith(CAPTURE_SUFFIX) && EVENT_PROPS.has(event.slice(0, -CAPTURE_SUFFIX.length)))
200
+ throw mistake(name, filename, `kay has no capture props, call addEventListener('${event.slice(0, -CAPTURE_SUFFIX.length)}', fn, { capture: true }) in a ref`)
201
+ throw mistake(name, filename, `no DOM event is named "${event}"; for a custom event, call addEventListener in a ref`)
202
+ }
203
+
204
+ // Plain containers that never take focus unless given a tabIndex, so their onFocus/onBlur never fire.
205
+ const UNFOCUSABLE_TAGS = new Set([
206
+ 'article', 'aside', 'div', 'fieldset', 'footer', 'form', 'header', 'label', 'li', 'main', 'nav', 'ol', 'p', 'section',
207
+ 'span', 'table', 'tbody', 'td', 'th', 'thead', 'tr', 'ul',
208
+ ])
209
+ const FOCUS_EVENTS = new Map([['onFocus', 'onFocusIn'], ['onBlur', 'onFocusOut']])
210
+ // Input types whose change event waits for the field to lose focus.
211
+ const TEXT_INPUT_TYPES = new Set(['text', 'search', 'email', 'url', 'tel', 'password', 'number'])
212
+
213
+ function staticAttr(attributes: readonly JSXAttributeItem[], name: string): JSXAttribute | undefined {
214
+ for (const a of attributes) {
215
+ if (a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier' && a.name.name === name)
216
+ return a
217
+ }
218
+ return undefined
219
+ }
220
+
221
+ function checkFocusAndChange(tag: string, attributes: readonly JSXAttributeItem[], filename: string, warnings: string[]): void {
222
+ const canFocus = !UNFOCUSABLE_TAGS.has(tag) || attributes.some(a =>
223
+ a.type === 'JSXSpreadAttribute'
224
+ || (a.name.type === 'JSXIdentifier' && ['tabIndex', 'tabindex', 'contentEditable', 'contenteditable'].includes(a.name.name)),
225
+ )
226
+ for (const [prop, bubbling] of FOCUS_EVENTS) {
227
+ if (!canFocus && staticAttr(attributes, prop) !== undefined)
228
+ throw mistake(`${prop} on <${tag}>`, filename, `focus does not bubble, write ${bubbling}={...}, or give the <${tag}> a tabIndex`)
229
+ }
230
+ if (staticAttr(attributes, 'onChange') === undefined)
231
+ return
232
+ const type = staticAttr(attributes, 'type')?.value
233
+ const isTextField = tag === 'textarea' || (tag === 'input' && (type === undefined || (type?.type === 'Literal' && typeof type.value === 'string' && TEXT_INPUT_TYPES.has(type.value))))
234
+ if (isTextField)
235
+ warnings.push(`kay compiler: onChange on <${tag}> in ${filename} fires when the field loses focus, not per keystroke; write onInput={...} for every keystroke.`)
236
+ }
237
+
238
+ /** Throws when a JSX element would compile into something other than what its author meant, and adds to `warnings` what may be meant but usually is not. */
239
+ export function checkMistakes(element: JSXElement, filename: string, code: string, warnings: string[]): void {
240
+ const tag = jsxTagName(element.openingElement.name)
241
+ const isElement = tag !== '' && !isComponentTag(tag)
242
+ const isCustomElement = tag.includes('-')
243
+ if (tag === 'Suspense') {
244
+ const children = filterMeaningfulChildren(element.children).length
245
+ if (children > 1)
246
+ throw mistake(`<Suspense> with ${children} children`, filename, 'give it one child, and one <Suspense> per async component')
247
+ }
248
+ const attributes = element.openingElement.attributes
249
+ if (isElement && staticAttr(attributes, 'class') !== undefined && staticAttr(attributes, 'className') !== undefined)
250
+ throw mistake('class and className', filename, 'keep one, they set the same attribute')
251
+ if (isElement)
252
+ checkFocusAndChange(tag, attributes, filename, warnings)
253
+ for (const attr of attributes) {
254
+ if (attr.type !== 'JSXAttribute')
255
+ continue
256
+ if (attr.name.type === 'JSXNamespacedName')
257
+ checkNamespacedAttribute(attr.name.namespace.name, attr.name.name.name, filename)
258
+ else if (isElement && attr.name.name === 'innerHTML')
259
+ checkInnerHtml(element, tag, attr, filename, code)
260
+ else if (isElement)
261
+ checkElementAttribute(attr, isCustomElement, filename, code)
262
+ }
263
+ }
264
+
265
+ function calleeName(callee: Node): string {
266
+ if (callee.type === 'Identifier')
267
+ return callee.name
268
+ if (callee.type === 'MemberExpression' && !callee.computed && callee.object.type === 'Identifier' && callee.property.type === 'Identifier')
269
+ return `${callee.object.name}.${callee.property.name}`
270
+ return ''
271
+ }
272
+
273
+ // Names bound once in the file to a signal() or computed() call; a name bound twice may be shadowed, so it is left out.
274
+ function signalNames(program: Program, signalCallees: ReadonlySet<string>): Set<string> {
275
+ const bindings = new Map<string, number>()
276
+ const signals = new Set<string>()
277
+ const bind = (id: Node | null | undefined): void => {
278
+ if (id?.type === 'Identifier')
279
+ bindings.set(id.name, (bindings.get(id.name) ?? 0) + 1)
280
+ }
281
+ walk(program, (node) => {
282
+ if (node.type === 'VariableDeclarator') {
283
+ bind(node.id)
284
+ if (node.id.type === 'Identifier' && node.init?.type === 'CallExpression' && signalCallees.has(calleeName(node.init.callee)))
285
+ signals.add(node.id.name)
286
+ }
287
+ else if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
288
+ if (node.type !== 'ArrowFunctionExpression')
289
+ bind(node.id)
290
+ for (const param of node.params)
291
+ walk(param, (p) => { if (p.type === 'Identifier') bind(p) })
292
+ }
293
+ })
294
+ for (const name of signals) {
295
+ if (bindings.get(name) !== 1)
296
+ signals.delete(name)
297
+ }
298
+ return signals
299
+ }
300
+
301
+ // The signal an expression reads without `.value` where JSX would print or test it.
302
+ function bareSignal(expr: Node, signals: ReadonlySet<string>): string | undefined {
303
+ const node = unwrapParens(expr)
304
+ if (node.type === 'Identifier')
305
+ return signals.has(node.name) ? node.name : undefined
306
+ if (node.type === 'LogicalExpression' || node.type === 'BinaryExpression')
307
+ return bareSignal(node.left, signals) ?? bareSignal(node.right, signals)
308
+ if (node.type === 'ConditionalExpression')
309
+ return bareSignal(node.test, signals)
310
+ if (node.type === 'UnaryExpression')
311
+ return bareSignal(node.argument, signals)
312
+ if (node.type === 'TemplateLiteral') {
313
+ for (const part of node.expressions) {
314
+ const found = bareSignal(part, signals)
315
+ if (found !== undefined)
316
+ return found
317
+ }
318
+ }
319
+ return undefined
320
+ }
321
+
322
+ /** Throws when JSX prints or tests a local signal or computed without `.value`, on an element's children or attributes. */
323
+ export function checkBareSignals(program: Program, signalCallees: ReadonlySet<string>, filename: string): void {
324
+ if (signalCallees.size === 0)
325
+ return
326
+ const signals = signalNames(program, signalCallees)
327
+ if (signals.size === 0)
328
+ return
329
+ const refuse = (expr: Node): void => {
330
+ const name = bareSignal(expr, signals)
331
+ if (name !== undefined)
332
+ throw mistake(`${name} without .value`, filename, `write ${name}.value`)
333
+ }
334
+ walk(program, (node) => {
335
+ if (node.type !== 'JSXElement' && node.type !== 'JSXFragment')
336
+ return
337
+ const tag = node.type === 'JSXElement' ? jsxTagName(node.openingElement.name) : ''
338
+ if (isComponentTag(tag))
339
+ return
340
+ for (const child of node.children) {
341
+ if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
342
+ refuse(child.expression)
343
+ }
344
+ if (node.type !== 'JSXElement')
345
+ return
346
+ for (const attr of node.openingElement.attributes) {
347
+ if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier')
348
+ continue
349
+ const name = attr.name.name
350
+ if (name !== '' && name !== 'ref' && name !== 'key' && !EVENT_ATTR.test(name) && attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
351
+ refuse(attr.value.expression)
352
+ }
353
+ })
354
+ }
@@ -40,7 +40,7 @@ export class SourceEditor {
40
40
  for (let i = 0; i < patches.length; i++) {
41
41
  const p = patches[i]!
42
42
  if (p.start < cursor)
43
- continue
43
+ throw new Error(`kay compiler: overlapping source patch [${p.start}, ${p.end}] overlaps previous end ${cursor}`)
44
44
  out += this.#source.slice(cursor, p.start)
45
45
  out += p.text
46
46
  cursor = p.end
@@ -1,17 +1,30 @@
1
1
  // What must never reach a browser bundle, shared by `kay build` and `kay check`.
2
2
 
3
- import type { AstNode } from './analyze'
4
- import { walk } from './analyze'
3
+ import type { MemberExpression, Node, Program } from 'oxc-parser'
4
+ import { loadDeclarations } from './analyze'
5
+ import { collectPatternNames } from './shared'
5
6
 
6
7
  export const SERVER_ONLY_MODULES = new Set([
7
8
  'kay/server',
8
9
  '@kayjs/kay/server',
10
+ 'bun',
9
11
  'bun:sqlite',
12
+ 'bun:sql',
10
13
  'bun:ffi',
11
14
  'bun:dns',
15
+ 'bun:test',
16
+ 'bun:jsc',
12
17
  'node:fs',
13
18
  'node:fs/promises',
14
19
  'node:child_process',
20
+ 'node:crypto',
21
+ 'node:dns',
22
+ 'node:async_hooks',
23
+ 'node:module',
24
+ 'node:vm',
25
+ 'node:inspector',
26
+ 'node:process',
27
+ 'node:sqlite',
15
28
  'node:net',
16
29
  'node:http',
17
30
  'node:https',
@@ -25,6 +38,18 @@ export const SERVER_ONLY_MODULES = new Set([
25
38
  'fs',
26
39
  'fs/promises',
27
40
  'child_process',
41
+ 'crypto',
42
+ 'dns',
43
+ 'async_hooks',
44
+ 'module',
45
+ 'vm',
46
+ 'os',
47
+ 'http2',
48
+ 'worker_threads',
49
+ 'cluster',
50
+ 'dgram',
51
+ 'tls',
52
+ 'readline',
28
53
  'net',
29
54
  'http',
30
55
  'https',
@@ -35,28 +60,152 @@ export const SERVER_ONLY_FILTER = new RegExp(`^(?:${[...SERVER_ONLY_MODULES].map
35
60
  // The client build inlines PUBLIC_* (from its own environment) and NODE_ENV; any other read ships a server variable name and crashes in the browser.
36
61
  const CLIENT_ENV_KEY = /^(?:PUBLIC_\w*|NODE_ENV)$/
37
62
 
38
- function isProcessEnv(node: AstNode | null | undefined): boolean {
39
- return node?.type === 'MemberExpression' && !node.computed && node.object?.type === 'Identifier' && node.object.name === 'process' && node.property?.name === 'env'
63
+ function propKeyName(member: MemberExpression): string | undefined {
64
+ if (!member.computed && member.property.type === 'Identifier')
65
+ return member.property.name
66
+ if (member.computed && member.property.type === 'Literal' && typeof member.property.value === 'string')
67
+ return member.property.value
68
+ return undefined
40
69
  }
41
70
 
42
- /** True when the module reads `process.env` outside its `load()` (stripped from client code) for a key the client build does not inline. */
43
- export function readsPrivateEnv(program: AstNode, isInlined: (key: string) => boolean = key => CLIENT_ENV_KEY.test(key)): boolean {
44
- let found = false
45
- walk(program, (node) => {
46
- if (found)
47
- return false
48
- if (node.type === 'ExportNamedDeclaration' && node.declaration?.type === 'FunctionDeclaration' && node.declaration.id?.name === 'load')
49
- return false
50
- if (node.type === 'MemberExpression' && isProcessEnv(node.object)) {
51
- const key = node.computed ? node.property?.value : node.property?.name
52
- found = typeof key !== 'string' || !isInlined(key)
53
- return false
54
- }
55
- if (isProcessEnv(node)) {
56
- found = true
57
- return false
58
- }
71
+ function isEnvRoot(node: Node, shadowed: ReadonlySet<string>): 'process' | 'bun' | undefined {
72
+ if (node.type !== 'MemberExpression')
73
+ return undefined
74
+ if (propKeyName(node) !== 'env')
59
75
  return undefined
60
- })
61
- return found
76
+ const obj = node.object
77
+ if (obj.type === 'Identifier') {
78
+ if (obj.name === 'process' && !shadowed.has('process'))
79
+ return 'process'
80
+ if (obj.name === 'Bun' && !shadowed.has('Bun'))
81
+ return 'bun'
82
+ }
83
+ if (obj.type === 'MemberExpression' && obj.object.type === 'Identifier' && obj.object.name === 'globalThis' && !shadowed.has('globalThis')) {
84
+ const key = propKeyName(obj)
85
+ if (key === 'process')
86
+ return 'process'
87
+ if (key === 'Bun')
88
+ return 'bun'
89
+ }
90
+ return undefined
91
+ }
92
+
93
+ /** Byte offset of the first `process.env` or `Bun.env` read outside `load()` for a key the client build does not inline, or `undefined`. */
94
+ export function findPrivateEnvOffset(program: Program, isInlined: (key: string) => boolean = key => CLIENT_ENV_KEY.test(key)): number | undefined {
95
+ let foundOffset: number | undefined
96
+ const loadCode = new Set<Node>(loadDeclarations(program))
97
+
98
+ function visit(node: unknown, shadowed: Set<string>): void {
99
+ if (foundOffset !== undefined || node === null || typeof node !== 'object')
100
+ return
101
+ if (Array.isArray(node)) {
102
+ for (let i = 0; i < node.length; i++)
103
+ visit(node[i], shadowed)
104
+ return
105
+ }
106
+ const n = node as Node
107
+ if (typeof n.type !== 'string' || loadCode.has(n))
108
+ return
109
+
110
+ if (n.type === 'MemberExpression') {
111
+ const rootKind = isEnvRoot(n.object, shadowed)
112
+ if (rootKind !== undefined) {
113
+ // Bun.env is never statically inlined in browser bundles.
114
+ if (rootKind === 'bun') {
115
+ foundOffset = n.start
116
+ return
117
+ }
118
+ const key = propKeyName(n)
119
+ if (key === undefined || !isInlined(key))
120
+ foundOffset = n.start
121
+ return
122
+ }
123
+ if (isEnvRoot(n, shadowed) !== undefined) {
124
+ foundOffset = n.start
125
+ return
126
+ }
127
+ }
128
+
129
+ if (n.type === 'ArrowFunctionExpression' || n.type === 'FunctionExpression' || n.type === 'FunctionDeclaration') {
130
+ const next = new Set(shadowed)
131
+ if (n.type !== 'ArrowFunctionExpression' && n.id !== null)
132
+ next.add(n.id.name)
133
+ for (const p of n.params)
134
+ collectPatternNames(p, next)
135
+ visit(n.body, next)
136
+ return
137
+ }
138
+ if (n.type === 'BlockStatement') {
139
+ const next = new Set(shadowed)
140
+ for (const stmt of n.body) {
141
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
142
+ next.add(stmt.id.name)
143
+ else if (stmt.type === 'ClassDeclaration' && stmt.id !== null)
144
+ next.add(stmt.id.name)
145
+ }
146
+ for (const stmt of n.body) {
147
+ if (stmt.type === 'VariableDeclaration') {
148
+ for (const d of stmt.declarations) {
149
+ visit(d.init, next)
150
+ collectPatternNames(d.id, next)
151
+ }
152
+ }
153
+ else {
154
+ visit(stmt, next)
155
+ }
156
+ }
157
+ return
158
+ }
159
+ if (n.type === 'CatchClause') {
160
+ const next = new Set(shadowed)
161
+ collectPatternNames(n.param, next)
162
+ visit(n.body, next)
163
+ return
164
+ }
165
+ if (n.type === 'ForInStatement' || n.type === 'ForOfStatement') {
166
+ visit(n.right, shadowed)
167
+ const next = new Set(shadowed)
168
+ if (n.left.type === 'VariableDeclaration') {
169
+ for (const d of n.left.declarations)
170
+ collectPatternNames(d.id, next)
171
+ }
172
+ visit(n.body, next)
173
+ return
174
+ }
175
+ if (n.type === 'ForStatement') {
176
+ const next = new Set(shadowed)
177
+ if (n.init !== null) {
178
+ if (n.init.type === 'VariableDeclaration') {
179
+ for (const d of n.init.declarations) {
180
+ visit(d.init, next)
181
+ collectPatternNames(d.id, next)
182
+ }
183
+ }
184
+ else {
185
+ visit(n.init, next)
186
+ }
187
+ }
188
+ visit(n.test, next)
189
+ visit(n.update, next)
190
+ visit(n.body, next)
191
+ return
192
+ }
193
+
194
+ if (n.type.startsWith('TS'))
195
+ return
196
+ for (const [key, val] of Object.entries(n)) {
197
+ if (key === 'start' || key === 'end' || key === 'type')
198
+ continue
199
+ if (val !== null && typeof val === 'object')
200
+ visit(val, shadowed)
201
+ }
202
+ }
203
+
204
+ visit(program, new Set())
205
+ return foundOffset
206
+ }
207
+
208
+ /** True when the module reads `process.env` or `Bun.env` outside its `load()` (stripped from client code) for a key the client build does not inline. */
209
+ export function readsPrivateEnv(program: Program, isInlined: (key: string) => boolean = key => CLIENT_ENV_KEY.test(key)): boolean {
210
+ return findPrivateEnvOffset(program, isInlined) !== undefined
62
211
  }