@tylix/compiler 0.6.0 → 0.7.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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +30 -2
  3. package/src/ast/nodes.js +145 -23
  4. package/src/ast/substituteCapabilityRefs.js +52 -5
  5. package/src/codegen/emitStatementLines.js +60 -10
  6. package/src/codegen/generateExpression.js +294 -35
  7. package/src/codegen/generateStatement.js +125 -20
  8. package/src/codegen/generateTemplate.js +107 -96
  9. package/src/codegen/generateTemplateExpression.js +63 -10
  10. package/src/codegen/jsGlobals.js +62 -2
  11. package/src/compileComponent.js +37 -6
  12. package/src/lexer/Lexer.js +128 -28
  13. package/src/parser/Parser.js +1840 -500
  14. package/src/parser/parseExpressionString.js +5 -0
  15. package/src/parser/parseTemplate.js +153 -41
  16. package/src/renderPageDocument.js +71 -8
  17. package/src/runtime/capability.js +8 -1
  18. package/src/runtime/reactive.js +289 -61
  19. package/src/runtime/useApi.js +74 -13
  20. package/src/runtime/useChannel.js +27 -6
  21. package/src/typecheck/buildVirtualTs.js +11 -1
  22. package/src/typecheck/tylix-globals.d.ts +23 -4
  23. package/src/typecheck/typedTemplateExpr.js +90 -27
  24. package/src/codegen/generateExpression.array.test.js +0 -13
  25. package/src/codegen/generateExpression.callexpr.test.js +0 -19
  26. package/src/codegen/generateExpression.test.js +0 -59
  27. package/src/codegen/generateMethod.asyncawait.test.js +0 -37
  28. package/src/codegen/generateMethod.ifstatement.test.js +0 -20
  29. package/src/codegen/generateMethod.test.js +0 -81
  30. package/src/codegen/generatePage.onmount.test.js +0 -46
  31. package/src/codegen/generatePage.test.js +0 -138
  32. package/src/codegen/generateStatement.test.js +0 -31
  33. package/src/codegen/generateTemplate.ifeach.test.js +0 -138
  34. package/src/codegen/generateTemplate.test.js +0 -149
  35. package/src/codegen/generateTemplateExpression.test.js +0 -34
  36. package/src/compileComponent.test.js +0 -121
  37. package/src/lexer/Lexer.test.js +0 -151
  38. package/src/parser/Parser.array.test.js +0 -37
  39. package/src/parser/Parser.asyncawait.test.js +0 -33
  40. package/src/parser/Parser.ifstatement.test.js +0 -20
  41. package/src/parser/Parser.onmount.test.js +0 -18
  42. package/src/parser/Parser.test.js +0 -315
  43. package/src/parser/parseComponent.test.js +0 -53
  44. package/src/parser/parsePageFile.test.js +0 -101
  45. package/src/parser/parseTemplate.ifeach.test.js +0 -33
  46. package/src/parser/parseTemplate.pre.test.js +0 -39
  47. package/src/parser/parseTemplate.test.js +0 -112
  48. package/src/renderPageDocument.test.js +0 -125
  49. package/src/runtime/reactive.test.js +0 -106
  50. package/test/dashboard-syntax.test.js +0 -116
@@ -27,6 +27,18 @@ function nextVar(prefix) {
27
27
  return `${prefix}${nodeCounter++}`
28
28
  }
29
29
 
30
+ // Wraps a render-time expression so a throw (for example
31
+ // `post.createdAt.toLocaleDateString()` while `post` is still null)
32
+ // is logged with its template line and replaced by `fallback`, instead
33
+ // of aborting the whole mount. Reads made before the throw are still
34
+ // tracked, so the effect re-runs once the data arrives. Not used for
35
+ // event handlers, which already report errors through the browser.
36
+ function guard(exprSrc, fallback, what, line) {
37
+ const where = line ? ` at line ${line}` : ''
38
+ const label = JSON.stringify(`Tylix: error in ${what}${where}:`)
39
+ return `(() => { try { return ${exprSrc}; } catch (e) { console.error(${label}, e); return ${fallback}; } })()`
40
+ }
41
+
30
42
  /**
31
43
  * Compiles a template AST into the BODY of a render(instance,
32
44
  * document, components) function as a JS source string. No virtual
@@ -65,7 +77,9 @@ function compileNode(node, lines, scope, inSvg = false) {
65
77
  const varName = nextVar('text')
66
78
  const expr = generateTemplateExpression(node.expression, scope)
67
79
  lines.push(`const ${varName} = document.createTextNode("");`)
68
- lines.push(`effect(() => { ${varName}.nodeValue = ${expr}; });`)
80
+ lines.push(
81
+ `effect(() => { const v = ${guard(expr, '""', '{{ }} interpolation', node.line)}; ${varName}.nodeValue = v == null ? "" : v; });`,
82
+ )
69
83
  return varName
70
84
  }
71
85
 
@@ -85,9 +99,9 @@ function compileNode(node, lines, scope, inSvg = false) {
85
99
  }
86
100
 
87
101
  // Renders node.children into a local fragment and returns the lines
88
- // needed to build it plus the fragment's own variable name, without
89
- // touching the caller's `lines` array directly (used inside effect
90
- // callbacks below, which need their own nested block of statements).
102
+ // needed to build it, without touching the caller's `lines` array
103
+ // directly (used inside effect callbacks below, which need their own
104
+ // nested block of statements).
91
105
  function compileChildrenIntoFragment(children, scope, fragVar, inSvg = false) {
92
106
  const childLines = []
93
107
  const childVars = children.map((child) =>
@@ -103,30 +117,53 @@ function emitBranch(lines, children, scope, inSvg, indent) {
103
117
  )
104
118
  }
105
119
 
106
- // Conditional rendering with no VDOM: an anchor comment node marks
107
- // the block's position; on first run (before the anchor is even
108
- // attached to the real DOM by the caller) content builds into the
109
- // same fragment that holds the anchor. On every later run (state
110
- // changed), previous nodes are removed and new ones inserted right
111
- // after the anchor in the live DOM. `{{#else}}` / `{{#else if}}`
120
+ // Every {{#if}} / {{#each}} block owns the DOM range BETWEEN two
121
+ // comment markers (start, end). On every run the whole range is
122
+ // cleared and the new content is inserted before the end marker.
123
+ // Because nested blocks live inside the parent's range, a parent
124
+ // re-run also removes whatever its children inserted later -- the old
125
+ // "remember the nodes from the first run" approach leaked those.
126
+ function emitRangeOpen(lines, startVar, endVar, containerVar, label) {
127
+ lines.push(`const ${startVar} = document.createComment(${JSON.stringify(label)});`)
128
+ lines.push(`const ${endVar} = document.createComment(${JSON.stringify('/' + label)});`)
129
+ lines.push(`const ${containerVar} = document.createDocumentFragment();`)
130
+ lines.push(`${containerVar}.appendChild(${startVar});`)
131
+ lines.push(`${containerVar}.appendChild(${endVar});`)
132
+ lines.push(`effect(() => {`)
133
+ lines.push(
134
+ ` while (${startVar}.nextSibling && ${startVar}.nextSibling !== ${endVar}) ${startVar}.nextSibling.remove();`,
135
+ )
136
+ lines.push(` const frag = document.createDocumentFragment();`)
137
+ }
138
+
139
+ function emitRangeClose(lines, endVar) {
140
+ lines.push(
141
+ ` if (${endVar}.parentNode) { ${endVar}.parentNode.insertBefore(frag, ${endVar}); }`,
142
+ )
143
+ lines.push(`});`)
144
+ }
145
+
146
+ // Conditional rendering with no VDOM. `{{#else}}` / `{{#else if}}`
112
147
  // branches render into the same slot when the condition is false.
113
148
  function compileIf(node, lines, scope, inSvg = false) {
114
- const anchorVar = nextVar('ifAnchor')
149
+ const startVar = nextVar('ifStart')
150
+ const endVar = nextVar('ifEnd')
115
151
  const containerVar = nextVar('ifContainer')
116
- const nodesVar = nextVar('ifNodes')
117
- const initialVar = nextVar('ifInitial')
118
152
 
119
153
  // `{{#else if}}` chains (and an {{#else}} holding nothing but one
120
154
  // {{#if}}, which means the same thing) are flattened into a single
121
- // if / else if / else so the whole chain is ONE effect. Nesting
122
- // them would leave stale effects from replaced branches subscribed
123
- // to the same state.
155
+ // if / else if / else so the whole chain is ONE effect.
124
156
  const branches = []
125
157
  let current = node
126
158
  let finalElse = null
127
159
  while (true) {
128
160
  branches.push({
129
- cond: generateTemplateExpression(current.condition, scope),
161
+ cond: guard(
162
+ generateTemplateExpression(current.condition, scope),
163
+ 'false',
164
+ '{{#if}} condition',
165
+ current.line,
166
+ ),
130
167
  children: current.children,
131
168
  })
132
169
  const rest = current.elseChildren
@@ -138,15 +175,7 @@ function compileIf(node, lines, scope, inSvg = false) {
138
175
  break
139
176
  }
140
177
 
141
- lines.push(`const ${anchorVar} = document.createComment("if");`)
142
- lines.push(`const ${containerVar} = document.createDocumentFragment();`)
143
- lines.push(`${containerVar}.appendChild(${anchorVar});`)
144
- lines.push(`let ${nodesVar} = [];`)
145
- lines.push(`let ${initialVar} = true;`)
146
- lines.push(`effect(() => {`)
147
- lines.push(` for (const n of ${nodesVar}) n.remove();`)
148
- lines.push(` ${nodesVar} = [];`)
149
- lines.push(` const frag = document.createDocumentFragment();`)
178
+ emitRangeOpen(lines, startVar, endVar, containerVar, 'if')
150
179
  branches.forEach((b, i) => {
151
180
  lines.push(i === 0 ? ` if (${b.cond}) {` : ` } else if (${b.cond}) {`)
152
181
  emitBranch(lines, b.children, scope, inSvg, ' ')
@@ -156,71 +185,45 @@ function compileIf(node, lines, scope, inSvg = false) {
156
185
  emitBranch(lines, finalElse, scope, inSvg, ' ')
157
186
  }
158
187
  lines.push(` }`)
159
- lines.push(` ${nodesVar} = Array.from(frag.childNodes);`)
160
- lines.push(` if (${nodesVar}.length > 0) {`)
161
- lines.push(` if (${initialVar}) { ${containerVar}.appendChild(frag); }`)
162
- lines.push(
163
- ` else if (${anchorVar}.parentNode) { ${anchorVar}.parentNode.insertBefore(frag, ${anchorVar}.nextSibling); }`,
164
- )
165
- lines.push(` }`)
166
- lines.push(` ${initialVar} = false;`)
167
- lines.push(`});`)
188
+ emitRangeClose(lines, endVar)
168
189
 
169
190
  return containerVar
170
191
  }
171
192
 
172
193
  // {{#each item in items}}, {{#each item, i in items}},
173
194
  // {{#each [k, v] in Object.entries(o)}}, {{#each { id } in rows}}.
174
- // `{{#else}}` renders when the list is empty.
195
+ // `{{#else}}` renders when the list is empty. A null/undefined list
196
+ // (or one whose expression throws) renders as empty.
175
197
  function compileEach(node, lines, scope, inSvg = false) {
176
- const anchorVar = nextVar('eachAnchor')
198
+ const startVar = nextVar('eachStart')
199
+ const endVar = nextVar('eachEnd')
177
200
  const containerVar = nextVar('eachContainer')
178
- const nodesVar = nextVar('eachNodes')
179
- const initialVar = nextVar('eachInitial')
201
+ const listVar = nextVar('eachList')
202
+ const indexVar = nextVar('eachIndex')
180
203
  const iterableExpr = generateTemplateExpression(node.iterable, scope)
181
204
  const innerScope = new Set([
182
205
  ...scope,
183
206
  ...paramNames([node.itemName]),
184
207
  ...(node.indexName ? [node.indexName] : []),
185
208
  ])
186
- const hasElse = !!node.elseChildren
187
- const listVar = nextVar('eachList')
188
- const indexVar = nextVar('eachIndex')
189
209
 
190
- lines.push(`const ${anchorVar} = document.createComment("each");`)
191
- lines.push(`const ${containerVar} = document.createDocumentFragment();`)
192
- lines.push(`${containerVar}.appendChild(${anchorVar});`)
193
- lines.push(`let ${nodesVar} = [];`)
194
- lines.push(`let ${initialVar} = true;`)
195
- lines.push(`effect(() => {`)
196
- lines.push(` for (const n of ${nodesVar}) n.remove();`)
197
- lines.push(` const frag = document.createDocumentFragment();`)
198
- if (hasElse) {
199
- lines.push(` const ${listVar} = Array.from(${iterableExpr} ?? []);`)
200
- }
201
- if (node.indexName) lines.push(` let ${indexVar} = 0;`)
210
+ emitRangeOpen(lines, startVar, endVar, containerVar, 'each')
202
211
  lines.push(
203
- ` for (const ${node.itemName} of ${hasElse ? listVar : iterableExpr}) {`,
212
+ ` const ${listVar} = Array.from(${guard(iterableExpr, '[]', '{{#each}} list', node.line)} ?? []);`,
204
213
  )
214
+ if (node.indexName) lines.push(` let ${indexVar} = 0;`)
215
+ lines.push(` for (const ${node.itemName} of ${listVar}) {`)
205
216
  if (node.indexName) {
206
217
  lines.push(` const ${node.indexName} = ${indexVar}++;`)
207
218
  }
208
219
  emitBranch(lines, node.children, innerScope, inSvg, ' ')
209
220
  lines.push(` }`)
210
- if (hasElse) {
221
+ if (node.elseChildren) {
211
222
  lines.push(` if (${listVar}.length === 0) {`)
212
223
  emitBranch(lines, node.elseChildren, scope, inSvg, ' ')
213
224
  lines.push(` }`)
214
225
  }
215
- lines.push(` ${nodesVar} = Array.from(frag.childNodes);`)
216
- lines.push(` if (${nodesVar}.length > 0) {`)
217
- lines.push(` if (${initialVar}) { ${containerVar}.appendChild(frag); }`)
218
- lines.push(
219
- ` else if (${anchorVar}.parentNode) { ${anchorVar}.parentNode.insertBefore(frag, ${anchorVar}.nextSibling); }`,
220
- )
221
- lines.push(` }`)
222
- lines.push(` ${initialVar} = false;`)
223
- lines.push(`});`)
226
+ emitRangeClose(lines, endVar)
224
227
 
225
228
  return containerVar
226
229
  }
@@ -234,26 +237,26 @@ function compileElement(node, lines, scope, inSvg = false) {
234
237
  const varName = nextVar('component')
235
238
  const tagLiteral = JSON.stringify(node.tag)
236
239
 
237
- const propEntries = node.attributes.map((attr) => {
238
- const key = JSON.stringify(attr.name)
239
- if (!attr.dynamic) return `${key}: ${JSON.stringify(attr.value)}`
240
+ const propEntries = node.attributes.map((attr) => {
241
+ const key = JSON.stringify(attr.name)
242
+ if (!attr.dynamic) return `${key}: ${JSON.stringify(attr.value)}`
240
243
 
241
- let expr = generateTemplateExpression(attr.value, scope)
244
+ let expr = generateTemplateExpression(attr.value, scope)
242
245
 
243
- // Callback props (onXxx="{{ methodName }}") are plain values. A bare
244
- // instance-method reference loses its `this` the moment the child
245
- // calls it, so bind it here while `instance` is still in scope.
246
- if (/^on[A-Z]/.test(attr.name)) {
247
- if (attr.value.type === 'Identifier') expr = `(${expr}).bind(instance)`
248
- return `${key}: ${expr}`
249
- }
246
+ // Callback props (onXxx="{{ methodName }}") are plain values. A bare
247
+ // instance-method reference loses its `this` the moment the child
248
+ // calls it, so bind it here while `instance` is still in scope.
249
+ if (/^on[A-Z]/.test(attr.name)) {
250
+ if (attr.value.type === 'Identifier') expr = `(${expr}).bind(instance)`
251
+ return `${key}: ${expr}`
252
+ }
250
253
 
251
- // Everything else is a lazy getter: the child reads it inside its
252
- // own effects, so `<Child value="{{ count }}">` stays live instead
253
- // of being a snapshot taken at mount().
254
- return `get ${key}() { return ${expr}; }`
255
- })
256
- const propsExpr = `{ ${propEntries.join(', ')} }`
254
+ // Everything else is a lazy getter: the child reads it inside its
255
+ // own effects, so `<Child value="{{ count }}">` stays live instead
256
+ // of being a snapshot taken at mount().
257
+ return `get ${key}() { return ${guard(expr, 'undefined', `<${node.tag}> prop "${attr.name}"`, attr.line)}; }`
258
+ })
259
+ const propsExpr = `{ ${propEntries.join(', ')} }`
257
260
 
258
261
  lines.push(`let ${varName};`)
259
262
  lines.push(`if (components[${tagLiteral}]) {`)
@@ -274,8 +277,7 @@ const propsExpr = `{ ${propEntries.join(', ')} }`
274
277
  // Once we're inside an <svg>, every descendant (path, circle, g,
275
278
  // etc.) needs the SVG namespace too -- createElement() without a
276
279
  // namespace produces a non-rendering element that still LOOKS
277
- // correct in the DOM inspector (right tag name, right attributes),
278
- // which is exactly what made this bug so hard to spot.
280
+ // correct in the DOM inspector.
279
281
  const isSvgRoot = node.tag === 'svg'
280
282
  const nsForThisNode = inSvg || isSvgRoot
281
283
  const childInSvg = isSvgRoot ? true : inSvg
@@ -312,10 +314,8 @@ const LIVE_PROPERTY_ATTRS = new Set(['value', 'checked'])
312
314
  const LIVE_PROPERTY_TAGS = new Set(['input', 'textarea', 'select'])
313
315
 
314
316
  // Attributes where HTML only cares whether they're *present*, not
315
- // their string value -- setAttribute(name, "false") is still
316
- // truthy to the browser, same as "true" or "". These need
317
- // add/removeAttribute based on the JS value's truthiness, not a
318
- // literal setAttribute call with the stringified value.
317
+ // their string value. These need add/removeAttribute based on the JS
318
+ // value's truthiness, not a literal setAttribute call.
319
319
  const BOOLEAN_ATTRS = new Set([
320
320
  'disabled',
321
321
  'checked',
@@ -361,25 +361,36 @@ function compileAttribute(elVar, tag, attr, lines, scope) {
361
361
  }
362
362
 
363
363
  if (attr.dynamic) {
364
- const expr = generateTemplateExpression(attr.value, scope)
364
+ const raw = generateTemplateExpression(attr.value, scope)
365
+ const expr = guard(raw, 'undefined', `attribute "${attr.name}"`, attr.line)
366
+ const nameLit = JSON.stringify(attr.name)
365
367
  const useProperty =
366
368
  LIVE_PROPERTY_ATTRS.has(attr.name) && LIVE_PROPERTY_TAGS.has(tag)
367
369
  const useBoolean = BOOLEAN_ATTRS.has(attr.name) && !useProperty
370
+
368
371
  if (useProperty) {
369
372
  // Set the live DOM property, not the attribute, so re-renders
370
- // after the user has typed (e.g. clearing the form on submit)
371
- // actually update what's on screen.
372
- lines.push(`effect(() => { ${elVar}.${attr.name} = ${expr}; });`)
373
+ // after the user has typed actually update what's on screen.
374
+ // `value` shows null/undefined as empty, `checked` is coerced.
375
+ if (attr.name === 'value') {
376
+ lines.push(
377
+ `effect(() => { const v = ${expr}; ${elVar}.value = v == null ? "" : v; });`,
378
+ )
379
+ } else {
380
+ lines.push(`effect(() => { ${elVar}.${attr.name} = !!(${expr}); });`)
381
+ }
373
382
  } else if (useBoolean) {
374
383
  // Boolean attribute: presence, not string value, is what
375
- // matters to the browser. Add it (empty string) when truthy,
376
- // remove it entirely when falsy.
384
+ // matters to the browser.
377
385
  lines.push(
378
- `effect(() => { if (${expr}) { ${elVar}.setAttribute(${JSON.stringify(attr.name)}, ""); } else { ${elVar}.removeAttribute(${JSON.stringify(attr.name)}); } });`,
386
+ `effect(() => { if (${expr}) { ${elVar}.setAttribute(${nameLit}, ""); } else { ${elVar}.removeAttribute(${nameLit}); } });`,
379
387
  )
380
388
  } else {
389
+ // null/undefined remove the attribute instead of writing the
390
+ // string "undefined". false/0/"" are real values and are kept
391
+ // (aria-expanded="false" must stay).
381
392
  lines.push(
382
- `effect(() => { ${elVar}.setAttribute(${JSON.stringify(attr.name)}, ${expr}); });`,
393
+ `effect(() => { const v = ${expr}; if (v == null) { ${elVar}.removeAttribute(${nameLit}); } else { ${elVar}.setAttribute(${nameLit}, v); } });`,
383
394
  )
384
395
  }
385
396
  return
@@ -1,4 +1,4 @@
1
- import { generateExpression } from './generateExpression.js'
1
+ import { generateExpression, joinArrayElements, assignmentPatternSource } from './generateExpression.js'
2
2
  import { JS_GLOBALS, paramNames } from './jsGlobals.js'
3
3
 
4
4
  // JS_GLOBALS (see jsGlobals.js) lists the plain JS/browser globals that
@@ -17,6 +17,14 @@ function unaryPrefix(operator) {
17
17
  return /^[a-z]/i.test(operator) ? `${operator} ` : operator
18
18
  }
19
19
 
20
+ // `5.toFixed(1)` is a syntax error; `(5).toFixed(1)` is not.
21
+ function memberObject(node, scope) {
22
+ const src = generateTemplateExpression(node, scope)
23
+ return node.type === 'Literal' && typeof node.value === 'number'
24
+ ? `(${src})`
25
+ : src
26
+ }
27
+
20
28
  export function generateTemplateExpression(node, scope = new Set()) {
21
29
  if (node.type === 'Identifier') {
22
30
  if (node.name === '$event' || scope.has(node.name)) {
@@ -33,9 +41,9 @@ export function generateTemplateExpression(node, scope = new Set()) {
33
41
 
34
42
  if (node.type === 'MemberExpression') {
35
43
  if (node.computed) {
36
- return `${generateTemplateExpression(node.object, scope)}${node.optional ? '?.' : ''}[${generateTemplateExpression(node.property, scope)}]`
44
+ return `${memberObject(node.object, scope)}${node.optional ? '?.' : ''}[${generateTemplateExpression(node.property, scope)}]`
37
45
  }
38
- return `${generateTemplateExpression(node.object, scope)}${node.optional ? '?.' : '.'}${node.property}`
46
+ return `${memberObject(node.object, scope)}${node.optional ? '?.' : '.'}${node.property}`
39
47
  }
40
48
 
41
49
  if (node.type === 'BinaryExpression') {
@@ -54,6 +62,22 @@ export function generateTemplateExpression(node, scope = new Set()) {
54
62
  return `(${unaryPrefix(node.operator)}${generateTemplateExpression(node.argument, scope)})`
55
63
  }
56
64
 
65
+ if (node.type === 'UpdateExpression') {
66
+ const arg = generateTemplateExpression(node.argument, scope)
67
+ return node.prefix ? `(${node.operator}${arg})` : `(${arg}${node.operator})`
68
+ }
69
+
70
+ // `(a, b)` -- the comma operator.
71
+ if (node.type === 'SequenceExpression') {
72
+ return `(${node.expressions.map((e) => generateTemplateExpression(e, scope)).join(', ')})`
73
+ }
74
+
75
+ // `x as T` and `x!` only matter to the typechecker; the real
76
+ // template code is just the inner expression.
77
+ if (node.type === 'AsExpression' || node.type === 'NonNullExpression') {
78
+ return generateTemplateExpression(node.expression, scope)
79
+ }
80
+
57
81
  // Only valid inside an `async` arrow (`{{ async () => await ... }}`)
58
82
  // or an event handler (which is made async automatically when it
59
83
  // contains `await`); a bare `{{ await x }}` in a text/attribute
@@ -64,8 +88,13 @@ export function generateTemplateExpression(node, scope = new Set()) {
64
88
 
65
89
  // Parenthesized so `ok and count++` -> `(ok && (count = ...))` is
66
90
  // valid JS rather than an assignment on the right of `&&`.
67
- if (node.type === 'AssignmentExpression') {
68
- return `(${generateTemplateExpression(node.target, scope)} = ${generateTemplateExpression(node.value, scope)})`
91
+ if (node.type === 'AssignmentExpression') {
92
+ const isPattern =
93
+ node.target.type === 'ObjectExpression' || node.target.type === 'ArrayExpression'
94
+ const target = isPattern
95
+ ? assignmentPatternSource(node.target, (n) => generateTemplateExpression(n, scope))
96
+ : generateTemplateExpression(node.target, scope)
97
+ return `(${target} = ${generateTemplateExpression(node.value, scope)})`
69
98
  }
70
99
 
71
100
  if (node.type === 'CallExpression') {
@@ -90,6 +119,11 @@ export function generateTemplateExpression(node, scope = new Set()) {
90
119
  // function is parenthesized so it is safe both as a call argument
91
120
  // and as an event handler that gets invoked immediately.
92
121
  if (node.type === 'ArrowFunctionExpression') {
122
+ if (node.body.type === 'BlockStatement') {
123
+ throw new Error(
124
+ 'Block-bodied arrow functions (x => { ... }) are not allowed in templates; use an expression body or move the code into an action',
125
+ )
126
+ }
93
127
  const innerScope = new Set([...scope, ...paramNames(node.params)])
94
128
  const defaults = node.paramDefaults ?? []
95
129
  const params = node.params
@@ -104,11 +138,12 @@ export function generateTemplateExpression(node, scope = new Set()) {
104
138
  return `(${asyncPrefix}(${params}) => ${body})`
105
139
  }
106
140
 
141
+ // Holes (`null` elements) become empty slots: [1, , 3]
107
142
  if (node.type === 'ArrayExpression') {
108
- const elements = node.elements
109
- .map((e) => generateTemplateExpression(e, scope))
110
- .join(', ')
111
- return `[${elements}]`
143
+ const parts = node.elements.map((e) =>
144
+ e === null ? '' : generateTemplateExpression(e, scope),
145
+ )
146
+ return `[${joinArrayElements(parts)}]`
112
147
  }
113
148
 
114
149
  // Parenthesized so an object literal is never mistaken for a block
@@ -119,7 +154,7 @@ export function generateTemplateExpression(node, scope = new Set()) {
119
154
  if (p.spread) return `...${generateTemplateExpression(p.value, scope)}`
120
155
  if (p.method) {
121
156
  throw new Error(
122
- 'Method shorthand ({ fn() {} }) is only allowed in script code, not in template expressions',
157
+ 'Methods and getters/setters in object literals ({ fn() {} }, { get x() {} }) are only allowed in script code, not in template expressions',
123
158
  )
124
159
  }
125
160
  const keySrc = p.keyExpr
@@ -146,10 +181,28 @@ export function generateTemplateExpression(node, scope = new Set()) {
146
181
  return `\`${body}\``
147
182
  }
148
183
 
184
+ // tag`text ${x}` -- text parts are emitted as written (`raw`).
185
+ if (node.type === 'TaggedTemplateExpression') {
186
+ const body = node.quasi.parts
187
+ .map((part) =>
188
+ part.type === 'text'
189
+ ? (part.raw ?? escapeTemplateLiteralText(part.value))
190
+ : `\${${generateTemplateExpression(part.expression, scope)}}`,
191
+ )
192
+ .join('')
193
+ return `${generateTemplateExpression(node.tag, scope)}\`${body}\``
194
+ }
195
+
149
196
  if (node.type === 'Literal') {
150
197
  return generateExpression(node)
151
198
  }
152
199
 
200
+ if (node.type === 'ClassExpression') {
201
+ throw new Error(
202
+ 'Classes are only allowed in script code, not in template expressions',
203
+ )
204
+ }
205
+
153
206
  throw new Error(
154
207
  `generateTemplateExpression: unsupported node type "${node.type}" in template expression`,
155
208
  )
@@ -26,11 +26,24 @@ export const JS_GLOBALS = new Set([
26
26
  'crypto',
27
27
  'localStorage',
28
28
  'sessionStorage',
29
+ 'indexedDB',
29
30
  'matchMedia',
30
31
  'getComputedStyle',
32
+ 'getSelection',
31
33
  'scrollTo',
32
34
  'scrollBy',
33
35
 
36
+ // Tylix runtime helpers (declared in tylix-globals.d.ts). Without
37
+ // these, `{{ postApi(...) }}` or `onclick="{{ () => notFound() }}"`
38
+ // in a template became `instance.postApi` / `instance.notFound`.
39
+ 'useApi',
40
+ 'getApi',
41
+ 'postApi',
42
+ 'putApi',
43
+ 'deleteApi',
44
+ 'useChannel',
45
+ 'notFound',
46
+
34
47
  // dialogs
35
48
  'alert',
36
49
  'confirm',
@@ -60,21 +73,31 @@ export const JS_GLOBALS = new Set([
60
73
  'XMLHttpRequest',
61
74
  'BroadcastChannel',
62
75
  'Worker',
76
+ 'EventTarget',
77
+
78
+ // streams
79
+ 'ReadableStream',
80
+ 'WritableStream',
81
+ 'TransformStream',
63
82
 
64
- // core objects
83
+ // core objects (Date and Intl cover toLocaleDateString,
84
+ // Intl.DateTimeFormat, Intl.NumberFormat, ...)
65
85
  'Math',
66
86
  'JSON',
67
87
  'Date',
88
+ 'Temporal',
68
89
  'Number',
69
90
  'String',
70
91
  'Boolean',
71
92
  'Array',
72
93
  'Object',
94
+ 'Function',
73
95
  'Set',
74
96
  'Map',
75
97
  'WeakSet',
76
98
  'WeakMap',
77
99
  'WeakRef',
100
+ 'FinalizationRegistry',
78
101
  'Promise',
79
102
  'RegExp',
80
103
  'Symbol',
@@ -83,6 +106,8 @@ export const JS_GLOBALS = new Set([
83
106
  'Proxy',
84
107
  'Intl',
85
108
  'Atomics',
109
+ 'Iterator',
110
+ 'WebAssembly',
86
111
 
87
112
  // errors
88
113
  'Error',
@@ -93,11 +118,13 @@ export const JS_GLOBALS = new Set([
93
118
  'URIError',
94
119
  'EvalError',
95
120
  'AggregateError',
121
+ 'DOMException',
96
122
 
97
123
  // binary / files
98
124
  'Blob',
99
125
  'FileReader',
100
126
  'ArrayBuffer',
127
+ 'SharedArrayBuffer',
101
128
  'DataView',
102
129
  'TextEncoder',
103
130
  'TextDecoder',
@@ -111,16 +138,44 @@ export const JS_GLOBALS = new Set([
111
138
  'Float32Array',
112
139
  'Float64Array',
113
140
  'BigInt64Array',
141
+ 'BigUint64Array',
114
142
 
115
143
  // DOM types
116
144
  'HTMLElement',
145
+ 'HTMLInputElement',
146
+ 'HTMLTextAreaElement',
147
+ 'HTMLSelectElement',
148
+ 'HTMLOptionElement',
149
+ 'HTMLButtonElement',
150
+ 'HTMLFormElement',
151
+ 'HTMLCanvasElement',
152
+ 'HTMLImageElement',
153
+ 'HTMLAnchorElement',
154
+ 'HTMLDivElement',
155
+ 'HTMLSpanElement',
156
+ 'HTMLDialogElement',
157
+ 'HTMLVideoElement',
158
+ 'HTMLAudioElement',
159
+ 'HTMLIFrameElement',
160
+ 'HTMLTableElement',
161
+ 'HTMLLabelElement',
162
+ 'SVGElement',
117
163
  'Element',
118
164
  'Node',
119
165
  'NodeList',
166
+ 'DocumentFragment',
120
167
  'DOMParser',
121
168
  'CustomEvent',
122
169
  'KeyboardEvent',
123
170
  'MouseEvent',
171
+ 'PointerEvent',
172
+ 'FocusEvent',
173
+ 'InputEvent',
174
+ 'WheelEvent',
175
+ 'DragEvent',
176
+ 'TouchEvent',
177
+ 'SubmitEvent',
178
+ 'ClipboardEvent',
124
179
  'MutationObserver',
125
180
  'IntersectionObserver',
126
181
  'ResizeObserver',
@@ -141,11 +196,16 @@ export const JS_GLOBALS = new Set([
141
196
  'reportError',
142
197
  ])
143
198
 
199
+ // Identifiers follow the same Unicode rules as the Lexer, so a param
200
+ // named `é` or `変数` is still recognised as a local.
201
+ const IDENTIFIER_RE = /^[\p{ID_Start}_$][\p{ID_Continue}$\u200c\u200d]*$/u
202
+ const IDENTIFIER_GLOBAL_RE = /[\p{ID_Start}_$][\p{ID_Continue}$\u200c\u200d]*/gu
203
+
144
204
  // Arrow params are stored as source strings ("x", "[k, v]", "{ id }",
145
205
  // "...args"). This returns the names those params actually bind, so
146
206
  // they can be treated as locals inside the arrow body.
147
207
  export function paramNames(params) {
148
208
  return params.flatMap((p) =>
149
- /^[A-Za-z_$][\w$]*$/.test(p) ? [p] : (p.match(/[A-Za-z_$][\w$]*/g) ?? []),
209
+ IDENTIFIER_RE.test(p) ? [p] : (p.match(IDENTIFIER_GLOBAL_RE) ?? []),
150
210
  )
151
211
  }