@pairdraw/dom-css 0.21.1 → 0.22.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.
Files changed (37) hide show
  1. package/dist/chunks/behaviours/states/layers.js +78 -12
  2. package/dist/chunks/behaviours/states/layers.js.map +1 -1
  3. package/dist/chunks/browser.js +373 -37
  4. package/dist/chunks/browser.js.map +1 -1
  5. package/dist/chunks/import/html.js +66 -11
  6. package/dist/chunks/import/html.js.map +1 -1
  7. package/dist/chunks/import/jsx/source/ast.js +207 -0
  8. package/dist/chunks/import/jsx/source/ast.js.map +1 -0
  9. package/dist/chunks/import/jsx/source/candidates.js +74 -0
  10. package/dist/chunks/import/jsx/source/candidates.js.map +1 -0
  11. package/dist/chunks/import/jsx/source/evaluate.js +213 -0
  12. package/dist/chunks/import/jsx/source/evaluate.js.map +1 -0
  13. package/dist/chunks/import/jsx/source/index.js +448 -0
  14. package/dist/chunks/import/jsx/source/index.js.map +1 -0
  15. package/dist/export.d.ts +15 -2
  16. package/dist/export.js +2 -2
  17. package/dist/index.d.ts +66 -1
  18. package/dist/index.js +5 -2
  19. package/package.json +5 -3
  20. package/src/cssom/browser.ts +63 -0
  21. package/src/export/css.ts +28 -1
  22. package/src/export/index.ts +1 -0
  23. package/src/export/projection.ts +69 -10
  24. package/src/import/flow.ts +127 -6
  25. package/src/import/jsx/source/ast.ts +267 -0
  26. package/src/import/jsx/source/candidates.ts +72 -0
  27. package/src/import/jsx/source/evaluate.ts +300 -0
  28. package/src/import/jsx/source/index.ts +36 -0
  29. package/src/import/jsx/source/render.ts +543 -0
  30. package/src/import/jsx/source/report.ts +49 -0
  31. package/src/import/scene-graph.ts +19 -7
  32. package/src/index.ts +10 -0
  33. package/src/runtime/browser/runtime.ts +13 -5
  34. package/src/runtime/browser/sandbox.ts +176 -27
  35. package/src/runtime/css/scan.ts +45 -0
  36. package/src/runtime/css/url.ts +92 -0
  37. package/src/runtime/headless/styles.ts +71 -15
@@ -0,0 +1,267 @@
1
+ import { parse } from 'acorn'
2
+ import type {
3
+ ArrowFunctionExpression,
4
+ ArrayExpression,
5
+ AssignmentPattern,
6
+ AssignmentProperty,
7
+ BinaryExpression,
8
+ BlockStatement,
9
+ CallExpression,
10
+ ConditionalExpression,
11
+ ExportDefaultDeclaration,
12
+ ExportNamedDeclaration,
13
+ ExpressionStatement,
14
+ FunctionDeclaration,
15
+ FunctionExpression,
16
+ Identifier,
17
+ IfStatement,
18
+ LogicalExpression,
19
+ MemberExpression,
20
+ ModuleDeclaration,
21
+ Node,
22
+ ObjectExpression,
23
+ ObjectPattern,
24
+ Program,
25
+ Property,
26
+ RestElement,
27
+ ReturnStatement,
28
+ SpreadElement,
29
+ Statement,
30
+ TemplateLiteral,
31
+ UnaryExpression,
32
+ VariableDeclaration,
33
+ VariableDeclarator
34
+ } from 'acorn'
35
+ import { compact } from 'es-toolkit/array'
36
+ import { transform } from 'sucrase'
37
+
38
+ import { CodeSourceError } from './report'
39
+
40
+ /** A value the reader could work out without running anything. */
41
+ export type LiteralValue =
42
+ | string
43
+ | number
44
+ | boolean
45
+ | LiteralFunction
46
+ | LiteralValue[]
47
+ | LiteralObject
48
+
49
+ export interface LiteralObject {
50
+ [key: string]: LiteralValue
51
+ }
52
+
53
+ /** Whether a value is a function the paste defines, rather than an object it describes. */
54
+ export function isLiteralFunction(value: unknown): value is LiteralFunction {
55
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && 'kind' in value
56
+ }
57
+
58
+ export interface LiteralFunction {
59
+ kind: 'function'
60
+ node: FunctionDeclaration | FunctionExpression | ArrowFunctionExpression
61
+ env: Env
62
+ name?: string
63
+ }
64
+
65
+ /**
66
+ * A name a paste cannot know, such as a prop the caller passes or a hook's result. It shadows a
67
+ * module binding of the same name, the way a parameter shadows one in JavaScript.
68
+ */
69
+ export const UNKNOWN = Symbol('unknown')
70
+
71
+ export type Env = Map<string, LiteralValue | typeof UNKNOWN>
72
+
73
+ const TRANSFORM_OPTIONS = {
74
+ transforms: ['typescript', 'jsx'] as Array<'typescript' | 'jsx'>,
75
+ jsxPragma: '__h',
76
+ jsxFragmentPragma: '__fragment',
77
+ production: true
78
+ }
79
+
80
+ /** The program a pasted source stands for, after TypeScript and JSX turn into plain JavaScript. */
81
+ export function parseSource(source: string): Program {
82
+ const trimmed = source.trim()
83
+ if (!trimmed) throw new CodeSourceError('Nothing to paste')
84
+ let code: string
85
+ try {
86
+ code = transform(trimmed, TRANSFORM_OPTIONS).code
87
+ } catch (error) {
88
+ throw new CodeSourceError(`Not readable as JSX or HTML: ${errorMessage(error)}`)
89
+ }
90
+ try {
91
+ return parse(code, {
92
+ ecmaVersion: 'latest',
93
+ sourceType: 'module',
94
+ allowReturnOutsideFunction: true
95
+ })
96
+ } catch (error) {
97
+ throw new CodeSourceError(`Not readable as JSX or HTML: ${errorMessage(error)}`)
98
+ }
99
+ }
100
+
101
+ function errorMessage(error: unknown): string {
102
+ return error instanceof Error ? error.message : String(error)
103
+ }
104
+
105
+ /** Whether a call builds an element, which is what makes a function a component here. */
106
+ export function isElementCall(node: Node | null | undefined): boolean {
107
+ return node?.type === 'CallExpression' && calleeName(node as CallExpression) === '__h'
108
+ }
109
+
110
+ export function calleeName(node: CallExpression): string | undefined {
111
+ return node.callee.type === 'Identifier' ? node.callee.name : undefined
112
+ }
113
+
114
+ export function memberName(node: MemberExpression): string | undefined {
115
+ if (node.object.type !== 'Identifier') return undefined
116
+ const object = node.object.name
117
+ if (!node.computed && node.property.type === 'Identifier') {
118
+ return `${object}.${node.property.name}`
119
+ }
120
+ return object
121
+ }
122
+
123
+ export function propertyKey(property: Property | AssignmentProperty): string | null {
124
+ if (property.computed) return null
125
+ if (property.key.type === 'Identifier') return property.key.name
126
+ return typeof (property.key as { value?: unknown }).value === 'string'
127
+ ? String((property.key as { value?: unknown }).value)
128
+ : null
129
+ }
130
+
131
+ export function functionNode(
132
+ node: Node
133
+ ): FunctionDeclaration | FunctionExpression | ArrowFunctionExpression | null {
134
+ if (
135
+ node.type === 'FunctionDeclaration' ||
136
+ node.type === 'FunctionExpression' ||
137
+ node.type === 'ArrowFunctionExpression'
138
+ ) {
139
+ return node as FunctionDeclaration | FunctionExpression | ArrowFunctionExpression
140
+ }
141
+ return null
142
+ }
143
+
144
+ export function declarationOf(node: Statement | ModuleDeclaration): Node | null {
145
+ if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportDefaultDeclaration') {
146
+ return node.declaration ?? null
147
+ }
148
+ return node
149
+ }
150
+
151
+ /** `h1` reads as `H1` and `my-widget` as `MyWidget`, so a layer is named after its tag. */
152
+ export function pascalCase(value: string): string {
153
+ return compact(
154
+ value.split(/[^a-zA-Z0-9]+/).map((part) => (part ? part[0].toUpperCase() + part.slice(1) : ''))
155
+ ).join('')
156
+ }
157
+
158
+ /** Whether a function's body builds an element anywhere in its own statements. */
159
+ export function drawsElements(node: Node): boolean {
160
+ if (isElementCall(node)) return true
161
+ return childNodes(node).some((child) => drawsElements(child))
162
+ }
163
+
164
+ /** Children of each node kind, read through the fields acorn's own interfaces declare. */
165
+ const CHILD_READERS: Partial<Record<string, (node: Node) => Node[]>> = {
166
+ Program: (node) => (node as Program).body,
167
+ BlockStatement: (node) => (node as BlockStatement).body,
168
+ ExportNamedDeclaration: (node) => nodesIn((node as ExportNamedDeclaration).declaration),
169
+ ExportDefaultDeclaration: (node) => nodesIn((node as ExportDefaultDeclaration).declaration),
170
+ ExpressionStatement: (node) => [(node as ExpressionStatement).expression],
171
+ ReturnStatement: (node) => nodesIn((node as ReturnStatement).argument),
172
+ IfStatement: (node) => {
173
+ const statement = node as IfStatement
174
+ return [statement.test, statement.consequent, ...nodesIn(statement.alternate)]
175
+ },
176
+ VariableDeclaration: (node) => (node as VariableDeclaration).declarations,
177
+ VariableDeclarator: (node) => nodesIn((node as VariableDeclarator).init),
178
+ FunctionDeclaration: (node) => functionChildren(node as FunctionDeclaration),
179
+ FunctionExpression: (node) => functionChildren(node as FunctionExpression),
180
+ ArrowFunctionExpression: (node) => functionChildren(node as ArrowFunctionExpression),
181
+ CallExpression: (node) => {
182
+ const call = node as CallExpression
183
+ return [call.callee, ...call.arguments]
184
+ },
185
+ MemberExpression: (node) => {
186
+ const member = node as MemberExpression
187
+ return [member.object, member.property]
188
+ },
189
+ ObjectExpression: (node) => (node as ObjectExpression).properties,
190
+ Property: (node) => {
191
+ const property = node as Property
192
+ return [property.key, property.value]
193
+ },
194
+ ArrayExpression: (node) => nodesIn((node as ArrayExpression).elements),
195
+ SpreadElement: (node) => nodesIn((node as SpreadElement).argument),
196
+ TemplateLiteral: (node) => (node as TemplateLiteral).expressions,
197
+ UnaryExpression: (node) => [(node as UnaryExpression).argument],
198
+ BinaryExpression: (node) => {
199
+ const operation = node as BinaryExpression
200
+ return [operation.left, operation.right]
201
+ },
202
+ LogicalExpression: (node) => {
203
+ const operation = node as LogicalExpression
204
+ return [operation.left, operation.right]
205
+ },
206
+ ConditionalExpression: (node) => {
207
+ const conditional = node as ConditionalExpression
208
+ return [conditional.test, conditional.consequent, conditional.alternate]
209
+ },
210
+ AssignmentPattern: (node) => {
211
+ const pattern = node as AssignmentPattern
212
+ return [pattern.left, pattern.right]
213
+ },
214
+ ObjectPattern: (node) => (node as ObjectPattern).properties,
215
+ RestElement: (node) => nodesIn((node as RestElement).argument)
216
+ }
217
+
218
+ function functionChildren(
219
+ node: FunctionDeclaration | FunctionExpression | ArrowFunctionExpression
220
+ ): Node[] {
221
+ return [...node.params, node.body]
222
+ }
223
+
224
+ /** The nodes a node holds, so a walk reads children rather than every property of a node. */
225
+ export function childNodes(node: Node): Node[] {
226
+ return CHILD_READERS[node.type]?.(node) ?? []
227
+ }
228
+
229
+ function nodesIn(value: unknown): Node[] {
230
+ if (Array.isArray(value)) return value.filter(isNode)
231
+ return isNode(value) ? [value] : []
232
+ }
233
+
234
+ function isNode(value: unknown): value is Node {
235
+ return typeof value === 'object' && value !== null && 'type' in value && 'start' in value
236
+ }
237
+
238
+ /** The source an expression names, for the text a placeholder shows. */
239
+ export function expressionText(node: Node): string {
240
+ switch (node.type) {
241
+ case 'Identifier':
242
+ return (node as Identifier).name
243
+ case 'Literal': {
244
+ const value = (node as { value?: unknown }).value
245
+ return typeof value === 'string' ? JSON.stringify(value) : String(value)
246
+ }
247
+ case 'MemberExpression': {
248
+ const member = node as MemberExpression
249
+ const object = expressionText(member.object)
250
+ if (!member.computed && member.property.type === 'Identifier') {
251
+ return `${object}.${member.property.name}`
252
+ }
253
+ return `${object}[${expressionText(member.property)}]`
254
+ }
255
+ case 'CallExpression': {
256
+ const call = node as CallExpression
257
+ const argumentsText = call.arguments.map((argument) => expressionText(argument)).join(', ')
258
+ return `${expressionText(call.callee)}(${argumentsText})`
259
+ }
260
+ case 'ConditionalExpression':
261
+ return `${expressionText((node as ConditionalExpression).test)} ? …`
262
+ case 'TemplateLiteral':
263
+ return '`…`'
264
+ default:
265
+ return '…'
266
+ }
267
+ }
@@ -0,0 +1,72 @@
1
+ import type { DesignNode } from '#dom-css/types'
2
+
3
+ /** Variants whose utility draws nothing in a layer, so the whole class goes. */
4
+ const LAYERLESS_VARIANTS = new Set([
5
+ 'before',
6
+ 'after',
7
+ 'placeholder',
8
+ 'file',
9
+ 'marker',
10
+ 'selection'
11
+ ])
12
+
13
+ /** The utilities a class list names, with one base utility per class and its variant count. */
14
+ export function tailwindUtilities(classes: Iterable<string>): {
15
+ candidates: string[]
16
+ variantsStripped: number
17
+ } {
18
+ const candidates = new Set<string>()
19
+ let variantsStripped = 0
20
+ for (const token of classes) {
21
+ if (!token) continue
22
+ const base = baseUtility(token)
23
+ if (base === null) continue
24
+ if (base.variant) variantsStripped += 1
25
+ candidates.add(base.name)
26
+ }
27
+ return { candidates: [...candidates], variantsStripped }
28
+ }
29
+
30
+ /** `md:hover:bg-slate-50` → `bg-slate-50`; `before:content-['*']` → nothing. */
31
+ export function baseUtility(token: string): { name: string; variant: boolean } | null {
32
+ const variants: string[] = []
33
+ let depth = 0
34
+ let start = 0
35
+ for (let index = 0; index < token.length; index++) {
36
+ const character = token[index]
37
+ if (character === '[') depth++
38
+ else if (character === ']') depth = Math.max(0, depth - 1)
39
+ else if (character === ':' && depth === 0) {
40
+ variants.push(token.slice(start, index))
41
+ start = index + 1
42
+ }
43
+ }
44
+ const utility = token.slice(start)
45
+ if (variants.length === 0) return { name: token, variant: false }
46
+ if (variants.some((variant) => LAYERLESS_VARIANTS.has(variant))) return null
47
+ if (!utility || utility.startsWith('[')) return null
48
+ return { name: utility, variant: true }
49
+ }
50
+
51
+ /** The classes an element names; an element with no classes names none. */
52
+ function classText(attrs: Record<string, string | undefined>): string {
53
+ return attrs.class ?? ''
54
+ }
55
+
56
+ /**
57
+ * The Tailwind utilities pasted markup names, with the base utility kept from every variant
58
+ * (`md:flex-row` asks for `flex-row` here), so a paste styles the same at any canvas width.
59
+ */
60
+ export function tailwindCandidates(nodes: readonly DesignNode[]): {
61
+ candidates: string[]
62
+ variantsStripped: number
63
+ } {
64
+ const classes: string[] = []
65
+ const visit = (node: DesignNode): void => {
66
+ if (node.type !== 'element') return
67
+ classes.push(...classText(node.attrs).split(/\s+/))
68
+ for (const child of node.children) visit(child)
69
+ }
70
+ for (const node of nodes) visit(node)
71
+ return tailwindUtilities(classes)
72
+ }
@@ -0,0 +1,300 @@
1
+ import type {
2
+ ArrayExpression,
3
+ AssignmentPattern,
4
+ BinaryExpression,
5
+ CallExpression,
6
+ ConditionalExpression,
7
+ Identifier,
8
+ LogicalExpression,
9
+ MemberExpression,
10
+ Node,
11
+ ObjectExpression,
12
+ ObjectPattern,
13
+ TemplateLiteral,
14
+ UnaryExpression
15
+ } from 'acorn'
16
+
17
+ import {
18
+ calleeName,
19
+ functionNode,
20
+ isLiteralFunction,
21
+ propertyKey,
22
+ UNKNOWN,
23
+ type Env,
24
+ type LiteralFunction,
25
+ type LiteralObject,
26
+ type LiteralValue
27
+ } from './ast'
28
+
29
+ /** Class-merging helpers whose literal arguments read as one class list. */
30
+ export const CLASS_HELPERS = new Set(['cn', 'clsx', 'classnames', 'twMerge', 'cx'])
31
+
32
+ export function truthy(value: LiteralValue | null): boolean {
33
+ if (value === null) return false
34
+ if (Array.isArray(value)) return value.length > 0
35
+ if (typeof value === 'object') return 'kind' in value ? true : Object.keys(value).length > 0
36
+ return Boolean(value)
37
+ }
38
+
39
+ /** The value a node has without running anything, or `null` when only running could tell. */
40
+ export function evaluate(node: Node, env: Env): LiteralValue | null {
41
+ switch (node.type) {
42
+ case 'Literal':
43
+ return evaluateLiteral(node)
44
+ case 'Identifier':
45
+ return evaluateIdentifier(node as Identifier, env)
46
+ case 'TemplateLiteral':
47
+ return evaluateTemplate(node as TemplateLiteral, env)
48
+ case 'ArrayExpression':
49
+ return evaluateArray(node as ArrayExpression, env)
50
+ case 'ObjectExpression':
51
+ return evaluateObject(node as ObjectExpression, env)
52
+ case 'ArrowFunctionExpression':
53
+ case 'FunctionExpression': {
54
+ const fn = functionNode(node)
55
+ return fn ? { kind: 'function', node: fn, env } : null
56
+ }
57
+ case 'UnaryExpression':
58
+ return evaluateUnary(node as UnaryExpression, env)
59
+ case 'BinaryExpression':
60
+ return evaluateBinary(node as BinaryExpression, env)
61
+ case 'ConditionalExpression':
62
+ return evaluateConditional(node as ConditionalExpression, env)
63
+ case 'LogicalExpression':
64
+ return evaluateLogical(node as LogicalExpression, env)
65
+ case 'MemberExpression':
66
+ return evaluateMember(node as MemberExpression, env)
67
+ case 'CallExpression':
68
+ return evaluateCall(node as CallExpression, env)
69
+ default:
70
+ return null
71
+ }
72
+ }
73
+
74
+ function evaluateLiteral(node: Node): LiteralValue | null {
75
+ const value = (node as { value?: unknown }).value
76
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
77
+ return value
78
+ }
79
+ return null
80
+ }
81
+
82
+ function evaluateIdentifier(node: Identifier, env: Env): LiteralValue | null {
83
+ const value = env.get(node.name)
84
+ return value === undefined || value === UNKNOWN ? null : value
85
+ }
86
+
87
+ function evaluateTemplate(node: TemplateLiteral, env: Env): LiteralValue | null {
88
+ const values = node.expressions.map((expression) => evaluate(expression, env))
89
+ if (values.some((value) => value === null)) return null
90
+ let text = ''
91
+ node.quasis.forEach((quasi, index) => {
92
+ text += quasi.value.cooked ?? ''
93
+ const value = index < values.length ? values[index] : null
94
+ if (value !== null && typeof value !== 'object') text += String(value)
95
+ })
96
+ return text
97
+ }
98
+
99
+ function evaluateArray(node: ArrayExpression, env: Env): LiteralValue | null {
100
+ const values: LiteralValue[] = []
101
+ for (const element of node.elements) {
102
+ if (!element) continue
103
+ if (element.type === 'SpreadElement') {
104
+ const spread = evaluate(element.argument, env)
105
+ if (!Array.isArray(spread)) return null
106
+ values.push(...spread)
107
+ continue
108
+ }
109
+ const value = evaluate(element, env)
110
+ if (value === null) return null
111
+ values.push(value)
112
+ }
113
+ return values
114
+ }
115
+
116
+ function evaluateObject(node: ObjectExpression, env: Env): LiteralValue | null {
117
+ const result: LiteralObject = {}
118
+ for (const property of node.properties) {
119
+ if (property.type === 'SpreadElement') {
120
+ const spread = evaluate(property.argument, env)
121
+ if (
122
+ spread === null ||
123
+ typeof spread !== 'object' ||
124
+ Array.isArray(spread) ||
125
+ 'kind' in spread
126
+ ) {
127
+ return null
128
+ }
129
+ Object.assign(result, spread)
130
+ continue
131
+ }
132
+ const name = propertyKey(property)
133
+ if (!name) return null
134
+ const value = evaluate(property.value, env)
135
+ if (value === null) return null
136
+ result[name] = value
137
+ }
138
+ return result
139
+ }
140
+
141
+ function evaluateUnary(node: UnaryExpression, env: Env): LiteralValue | null {
142
+ const argument = evaluate(node.argument, env)
143
+ if (argument === null || typeof argument === 'object') return null
144
+ if (node.operator === '-') return typeof argument === 'number' ? -argument : null
145
+ if (node.operator === '!') return !truthy(argument)
146
+ return null
147
+ }
148
+
149
+ function evaluateConditional(node: ConditionalExpression, env: Env): LiteralValue | null {
150
+ const test = evaluate(node.test, env)
151
+ if (test === null) return null
152
+ return evaluate(truthy(test) ? node.consequent : node.alternate, env)
153
+ }
154
+
155
+ function evaluateLogical(node: LogicalExpression, env: Env): LiteralValue | null {
156
+ const left = evaluate(node.left, env)
157
+ if (node.operator === '??') return left ?? evaluate(node.right, env)
158
+ if (left === null) return null
159
+ if (node.operator === '||') return truthy(left) ? left : evaluate(node.right, env)
160
+ return truthy(left) ? evaluate(node.right, env) : left
161
+ }
162
+
163
+ function evaluateMember(node: MemberExpression, env: Env): LiteralValue | null {
164
+ const object = evaluate(node.object, env)
165
+ if (object === null || typeof object !== 'object' || Array.isArray(object) || 'kind' in object) {
166
+ return null
167
+ }
168
+ const property = memberKey(node, env)
169
+ if (!property) return null
170
+ return object[property] ?? null
171
+ }
172
+
173
+ /** A value as the key a computed property names; objects and functions name nothing. */
174
+ function primitiveText(value: LiteralValue | null): string {
175
+ if (value === null || typeof value === 'object') return ''
176
+ return String(value)
177
+ }
178
+
179
+ function memberKey(node: MemberExpression, env: Env): string | null {
180
+ if (node.computed) return primitiveText(evaluate(node.property, env))
181
+ if (node.property.type !== 'Identifier') return null
182
+ return node.property.name
183
+ }
184
+
185
+ function evaluateCall(node: CallExpression, env: Env): LiteralValue | null {
186
+ if (CLASS_HELPERS.has(calleeName(node) ?? '')) return mergeClasses(node, env)
187
+ if (node.callee.type !== 'Identifier') return null
188
+ const target = env.get(node.callee.name)
189
+ if (!isLiteralFunction(target)) return null
190
+ const args = node.arguments.map((argument) =>
191
+ argument.type === 'SpreadElement' ? null : evaluate(argument, env)
192
+ )
193
+ return callFunction(target, args)
194
+ }
195
+
196
+ /** `cn("flex", { "gap-2": active })`: the class names its literal arguments name. */
197
+ export function mergeClasses(node: CallExpression, env: Env): string {
198
+ const names = node.arguments
199
+ .flatMap((argument) => {
200
+ if (argument.type === 'SpreadElement') return []
201
+ const value = evaluate(argument, env)
202
+ return Array.isArray(value) ? value : [value]
203
+ })
204
+ .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
205
+ return names.join(' ')
206
+ }
207
+
208
+ function callFunction(
209
+ component: LiteralFunction,
210
+ args: (LiteralValue | null)[]
211
+ ): LiteralValue | null {
212
+ const env: Env = new Map(component.env)
213
+ bindParams(component.node, args, env)
214
+ if (component.node.body.type !== 'BlockStatement') {
215
+ return evaluate(component.node.body, env)
216
+ }
217
+ for (const statement of component.node.body.body) {
218
+ if (statement.type !== 'ReturnStatement') continue
219
+ const argument = statement.argument
220
+ return argument ? evaluate(argument, env) : null
221
+ }
222
+ return null
223
+ }
224
+
225
+ /** Binds a function's parameters to what a call passes, and to `UNKNOWN` for what it cannot. */
226
+ export function bindParams(
227
+ node: LiteralFunction['node'],
228
+ args: (LiteralValue | null)[],
229
+ env: Env
230
+ ): void {
231
+ node.params.forEach((param, index) => {
232
+ const argument = args[index] ?? null
233
+ if (param.type === 'Identifier') {
234
+ env.set(param.name, argument ?? UNKNOWN)
235
+ return
236
+ }
237
+ if (param.type === 'AssignmentPattern') {
238
+ bindDefault(param, argument, env)
239
+ return
240
+ }
241
+ if (param.type === 'ObjectPattern') bindPattern(param, argument, env)
242
+ })
243
+ }
244
+
245
+ function bindDefault(pattern: AssignmentPattern, argument: LiteralValue | null, env: Env): void {
246
+ if (pattern.left.type !== 'Identifier') return
247
+ env.set(pattern.left.name, argument ?? evaluate(pattern.right, env) ?? UNKNOWN)
248
+ }
249
+
250
+ function bindPattern(pattern: ObjectPattern, argument: LiteralValue | null, env: Env): void {
251
+ const source = literalObject(argument)
252
+ for (const property of pattern.properties) {
253
+ if (property.type !== 'Property') continue
254
+ const key = propertyKey(property)
255
+ if (!key || property.value.type !== 'Identifier') continue
256
+ env.set(property.value.name, source?.[key] ?? UNKNOWN)
257
+ }
258
+ }
259
+
260
+ function literalObject(value: LiteralValue | null): LiteralObject | null {
261
+ if (value === null || typeof value !== 'object' || Array.isArray(value) || 'kind' in value) {
262
+ return null
263
+ }
264
+ return value
265
+ }
266
+
267
+ function evaluateBinary(node: BinaryExpression, env: Env): LiteralValue | null {
268
+ const left = evaluate(node.left, env)
269
+ const right = evaluate(node.right, env)
270
+ if (left === null || right === null) return null
271
+ if (typeof left === 'object' || typeof right === 'object') return null
272
+ switch (node.operator) {
273
+ case '+':
274
+ return typeof left === 'string' || typeof right === 'string'
275
+ ? `${left}${right}`
276
+ : Number(left) + Number(right)
277
+ case '-':
278
+ return Number(left) - Number(right)
279
+ case '*':
280
+ return Number(left) * Number(right)
281
+ case '/':
282
+ return Number(left) / Number(right)
283
+ case '%':
284
+ return Number(left) % Number(right)
285
+ case '===':
286
+ return left === right
287
+ case '!==':
288
+ return left !== right
289
+ case '<':
290
+ return left < right
291
+ case '>':
292
+ return left > right
293
+ case '<=':
294
+ return left <= right
295
+ case '>=':
296
+ return left >= right
297
+ default:
298
+ return null
299
+ }
300
+ }
@@ -0,0 +1,36 @@
1
+ import type { DesignNode } from '#dom-css/types'
2
+
3
+ import type { Env } from './ast'
4
+ import { parseSource } from './ast'
5
+ import { collectBindings, collectComponents, renderRoots, type RenderState } from './render'
6
+ import { emptyReport, CodeSourceError, type CodeTree } from './report'
7
+
8
+ export { CodeSourceError, CodeTooLargeError, MAX_CODE_ELEMENTS } from './report'
9
+ export type { CodeReport, CodeTree } from './report'
10
+ export { tailwindCandidates, tailwindUtilities } from './candidates'
11
+
12
+ /**
13
+ * The element tree a pasted JSX or TSX source describes, and what it could not keep. Parsing and
14
+ * reading only: nothing in the source runs, and a construct the reader cannot classify becomes a
15
+ * placeholder rather than an error.
16
+ */
17
+ export function jsxSourceToTree(source: string): CodeTree {
18
+ const program = parseSource(source)
19
+ const report = emptyReport()
20
+ const moduleEnv: Env = new Map()
21
+ for (const statement of program.body) collectBindings(statement, moduleEnv)
22
+ const state: RenderState = {
23
+ report,
24
+ components: collectComponents(program, moduleEnv),
25
+ depth: 0,
26
+ elements: 0
27
+ }
28
+
29
+ const roots: DesignNode[] = renderRoots(program, moduleEnv, state)
30
+ if (roots.length === 0) {
31
+ throw new CodeSourceError(
32
+ 'No JSX element found: paste a React or JSX component, or HTML markup.'
33
+ )
34
+ }
35
+ return { children: roots, report }
36
+ }