@tylix/compiler 0.5.1 → 0.6.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.
@@ -1,3 +1,5 @@
1
+ import { JS_GLOBALS, paramNames } from '../codegen/jsGlobals.js'
2
+
1
3
  // generateTemplateExpression's twin, for the virtual .ts class body
2
4
  // built in buildVirtualPageTs. The REAL compiled template (see
3
5
  // codegen/generateTemplateExpression.js) prefixes state reads with
@@ -20,6 +22,8 @@ function unaryPrefix(operator) {
20
22
  export function typedTemplateExpr(node, scope) {
21
23
  if (node.type === 'Identifier') {
22
24
  if (node.name === '$event' || scope.has(node.name)) return node.name
25
+ if (node.name === 'this') return 'this'
26
+ if (JS_GLOBALS.has(node.name)) return node.name
23
27
  return `this.${node.name}`
24
28
  }
25
29
  if (node.type === 'MemberExpression') {
@@ -47,9 +51,9 @@ export function typedTemplateExpr(node, scope) {
47
51
  return `(${typedTemplateExpr(node.left, scope)} ?? ${typedTemplateExpr(node.right, scope)})`
48
52
  }
49
53
 
50
- if (node.type === 'AssignmentExpression') {
51
- return `${typedTemplateExpr(node.target, scope)} = ${typedTemplateExpr(node.value, scope)}`
52
- }
54
+ if (node.type === 'AssignmentExpression') {
55
+ return `(${typedTemplateExpr(node.target, scope)} = ${typedTemplateExpr(node.value, scope)})`
56
+ }
53
57
  if (node.type === 'CallExpression') {
54
58
  const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
55
59
  return `${typedTemplateExpr(node.callee, scope)}${node.optional ? '?.' : ''}(${args})`
@@ -61,12 +65,20 @@ export function typedTemplateExpr(node, scope) {
61
65
 
62
66
  // Arrow params are typed `any` unless annotated, matching what
63
67
  // generateExpression does in typed mode. Params become locals, so
64
- // they are referenced bare in the body.
68
+ // they are referenced bare in the body. Destructured/rest params are
69
+ // stored as source strings; paramNames() extracts the names they
70
+ // bind. Defaults are checked in the arrow's own scope.
65
71
  if (node.type === 'ArrowFunctionExpression') {
66
- const innerScope = new Set([...scope, ...node.params])
72
+ const innerScope = new Set([...scope, ...paramNames(node.params)])
67
73
  const types = node.paramTypes ?? node.params.map(() => null)
74
+ const defaults = node.paramDefaults ?? []
68
75
  const params = node.params
69
- .map((name, i) => `${name}: ${types[i] ?? 'any'}`)
76
+ .map((name, i) => {
77
+ const base = `${name}: ${types[i] ?? 'any'}`
78
+ return defaults[i]
79
+ ? `${base} = ${typedTemplateExpr(defaults[i], innerScope)}`
80
+ : base
81
+ })
70
82
  .join(', ')
71
83
  const asyncPrefix = node.isAsync ? 'async ' : ''
72
84
  return `(${asyncPrefix}(${params}) => (${typedTemplateExpr(node.body, innerScope)}))`
@@ -81,11 +93,18 @@ export function typedTemplateExpr(node, scope) {
81
93
 
82
94
  if (node.type === 'ObjectExpression') {
83
95
  const properties = node.properties
84
- .map((p) =>
85
- p.spread
86
- ? `...${typedTemplateExpr(p.value, scope)}`
87
- : `${JSON.stringify(p.key)}: ${typedTemplateExpr(p.value, scope)}`,
88
- )
96
+ .map((p) => {
97
+ if (p.spread) return `...${typedTemplateExpr(p.value, scope)}`
98
+ if (p.method) {
99
+ throw new Error(
100
+ 'Method shorthand ({ fn() {} }) is only allowed in script code, not in template expressions',
101
+ )
102
+ }
103
+ const keySrc = p.keyExpr
104
+ ? `[${typedTemplateExpr(p.keyExpr, scope)}]`
105
+ : JSON.stringify(p.key)
106
+ return `${keySrc}: ${typedTemplateExpr(p.value, scope)}`
107
+ })
89
108
  .join(', ')
90
109
  return `({ ${properties} })`
91
110
  }
@@ -113,33 +132,81 @@ export function typedTemplateExpr(node, scope) {
113
132
  throw new Error(`typedTemplateExpr: unsupported node type "${node.type}"`)
114
133
  }
115
134
 
116
- const EVENT_ATTR_RE = /^on(click|input|change|submit)$/i
117
-
118
- // Which DOM element type a synthetic $event's `target` should be
119
- // typed as, keyed by the event name captured from EVENT_ATTR_RE
120
- // (lowercased). Deliberately narrow -- these are the only event
121
- // attributes the template grammar currently recognizes at all.
122
- // Anything not listed falls back to the generic HTMLElement, same as
123
- // a real framework would for an untyped/unknown handler.
124
- const EVENT_TARGET_TYPES = {
125
- input: 'HTMLInputElement',
126
- change: 'HTMLInputElement',
127
- submit: 'HTMLFormElement',
128
- click: 'HTMLElement',
135
+ // Any on<event> attribute is an event listener (see generateTemplate).
136
+ const EVENT_ATTR_RE = /^on([a-z]+)$/i
137
+
138
+ // [event interface, element type of `event.target`] per DOM event
139
+ // name. Anything not listed falls back to a plain Event on a generic
140
+ // HTMLElement, same as a real framework would for an unknown handler.
141
+ const MOUSE = ['MouseEvent', 'HTMLElement']
142
+ const KEY = ['KeyboardEvent', 'HTMLInputElement']
143
+ const FOCUS = ['FocusEvent', 'HTMLInputElement']
144
+ const POINTER = ['PointerEvent', 'HTMLElement']
145
+ const DRAG = ['DragEvent', 'HTMLElement']
146
+ const TOUCH = ['TouchEvent', 'HTMLElement']
147
+ const EVENT_TYPES = {
148
+ click: MOUSE,
149
+ dblclick: MOUSE,
150
+ auxclick: MOUSE,
151
+ contextmenu: MOUSE,
152
+ mousedown: MOUSE,
153
+ mouseup: MOUSE,
154
+ mousemove: MOUSE,
155
+ mouseenter: MOUSE,
156
+ mouseleave: MOUSE,
157
+ mouseover: MOUSE,
158
+ mouseout: MOUSE,
159
+ keydown: KEY,
160
+ keyup: KEY,
161
+ keypress: KEY,
162
+ input: ['InputEvent', 'HTMLInputElement'],
163
+ change: ['Event', 'HTMLInputElement'],
164
+ submit: ['SubmitEvent', 'HTMLFormElement'],
165
+ reset: ['Event', 'HTMLFormElement'],
166
+ focus: FOCUS,
167
+ blur: FOCUS,
168
+ focusin: FOCUS,
169
+ focusout: FOCUS,
170
+ scroll: ['Event', 'HTMLElement'],
171
+ wheel: ['WheelEvent', 'HTMLElement'],
172
+ pointerdown: POINTER,
173
+ pointerup: POINTER,
174
+ pointermove: POINTER,
175
+ pointerenter: POINTER,
176
+ pointerleave: POINTER,
177
+ pointercancel: POINTER,
178
+ drag: DRAG,
179
+ dragstart: DRAG,
180
+ dragend: DRAG,
181
+ dragenter: DRAG,
182
+ dragleave: DRAG,
183
+ dragover: DRAG,
184
+ drop: DRAG,
185
+ touchstart: TOUCH,
186
+ touchmove: TOUCH,
187
+ touchend: TOUCH,
188
+ touchcancel: TOUCH,
189
+ }
190
+
191
+ function eventTypesFor(eventName) {
192
+ return EVENT_TYPES[eventName.toLowerCase()] ?? ['Event', 'HTMLElement']
129
193
  }
130
194
 
131
195
  // Walks a parsed template AST (from parseTemplate) collecting every
132
196
  // bindable expression as a tree of check entries, ready for
133
197
  // buildVirtualPageTs to emit into a synthetic __render() method.
134
198
  // Entries come in two kinds:
135
- // { kind: 'check', expr, line, eventType } -- a single expression
136
- // to typecheck (interpolation, #if condition, dynamic attribute)
137
- // { kind: 'each', itemName, iterableExpr, line, children } -- an
138
- // #each block; children is itself a list of these same entries
199
+ // { kind: 'check', expr, line, eventType, eventBase } -- a single
200
+ // expression to typecheck (interpolation, #if condition, dynamic
201
+ // attribute). eventType/eventBase are set for event handlers.
202
+ // { kind: 'each', itemName, indexName, iterableExpr, line, children }
203
+ // -- an #each block; children is itself a list of these same entries
139
204
  // The 'each' kind exists so the emitted TS can wrap its children in
140
205
  // a real `for (const f of ...)` -- without an actual declaration for
141
206
  // the loop variable, TS has no way to resolve identifiers like `f`
142
207
  // inside the block, regardless of what our own scope-tracking says.
208
+ // {{#else}} branches are collected as ordinary entries after their
209
+ // block, in the OUTER scope (an each-else has no loop variable).
143
210
  export function collectTemplateChecks(nodes, scope, out) {
144
211
  for (const node of nodes) {
145
212
  if (node.type === 'Interpolation') {
@@ -148,6 +215,7 @@ export function collectTemplateChecks(nodes, scope, out) {
148
215
  expr: typedTemplateExpr(node.expression, scope),
149
216
  line: node.line,
150
217
  eventType: null,
218
+ eventBase: null,
151
219
  })
152
220
  } else if (node.type === 'If') {
153
221
  out.push({
@@ -155,23 +223,32 @@ export function collectTemplateChecks(nodes, scope, out) {
155
223
  expr: typedTemplateExpr(node.condition, scope),
156
224
  line: node.line,
157
225
  eventType: null,
226
+ eventBase: null,
158
227
  })
159
228
  collectTemplateChecks(node.children, scope, out)
229
+ if (node.elseChildren) {
230
+ collectTemplateChecks(node.elseChildren, scope, out)
231
+ }
160
232
  } else if (node.type === 'Each') {
161
233
  const iterableExpr = typedTemplateExpr(node.iterable, scope)
162
234
  const children = []
163
- collectTemplateChecks(
164
- node.children,
165
- new Set([...scope, node.itemName]),
166
- children,
167
- )
235
+ const innerScope = new Set([
236
+ ...scope,
237
+ ...paramNames([node.itemName]),
238
+ ...(node.indexName ? [node.indexName] : []),
239
+ ])
240
+ collectTemplateChecks(node.children, innerScope, children)
168
241
  out.push({
169
242
  kind: 'each',
170
243
  itemName: node.itemName,
244
+ indexName: node.indexName ?? null,
171
245
  iterableExpr,
172
246
  line: node.line,
173
247
  children,
174
248
  })
249
+ if (node.elseChildren) {
250
+ collectTemplateChecks(node.elseChildren, scope, out)
251
+ }
175
252
  } else if (node.type === 'Element') {
176
253
  for (const attr of node.attributes) {
177
254
  if (!attr.dynamic) continue
@@ -179,13 +256,15 @@ export function collectTemplateChecks(nodes, scope, out) {
179
256
  const attrScope = eventMatch
180
257
  ? new Set([...scope, '$event', 'event'])
181
258
  : scope
259
+ const [eventBase, eventType] = eventMatch
260
+ ? eventTypesFor(eventMatch[1])
261
+ : [null, null]
182
262
  out.push({
183
263
  kind: 'check',
184
264
  expr: typedTemplateExpr(attr.value, attrScope),
185
265
  line: attr.line,
186
- eventType: eventMatch
187
- ? (EVENT_TARGET_TYPES[eventMatch[1].toLowerCase()] ?? 'HTMLElement')
188
- : null,
266
+ eventType,
267
+ eventBase,
189
268
  })
190
269
  }
191
270
  collectTemplateChecks(node.children, scope, out)
@@ -2,6 +2,7 @@ import { parsePageFile } from './parser/parsePageFile.js'
2
2
  import { parseTemplate } from './parser/parseTemplate.js'
3
3
  import { Lexer } from './lexer/Lexer.js'
4
4
  import { Parser } from './parser/Parser.js'
5
+ import { normalizeLanguageOptions } from './parser/languageOptions.js'
5
6
  import {
6
7
  buildVirtualPageTs,
7
8
  mapVirtualLineToSource,
@@ -20,17 +21,40 @@ import { substituteCapabilityRefs } from './ast/substituteCapabilityRefs.js'
20
21
  // at all and floods the diagnostics list with dozens of
21
22
  // cascading-recovery errors, none of which point at anything wrong
22
23
  // in the actual .tyx source.
23
- export function typecheckPage(source, apiHelpersSource = '') {
24
+ //
25
+ // `source` must already have its import lines blanked out by
26
+ // extractImports() (which keeps line numbers intact), or any page with
27
+ // an `import` line fails to parse here.
28
+ //
29
+ // `languageOption` must be the same object passed to
30
+ // renderPageDocument ({ not: 'loose' } etc.): the typechecker has to
31
+ // parse the page the same way the real build does, or it would report
32
+ // on a different program than the one that runs.
33
+ export function typecheckPage(
34
+ source,
35
+ apiHelpersSource = '',
36
+ languageOption = {},
37
+ ) {
38
+ // createApp has a variable named `language` that holds
39
+ // 'typescript' | 'javascript'. Passing that here by mistake would
40
+ // silently fall back to defaults, so refuse it loudly.
41
+ if (languageOption !== null && typeof languageOption !== 'object') {
42
+ throw new Error(
43
+ `typecheckPage: the language options must be an object like { not: 'loose' }, got ${typeof languageOption} "${languageOption}"`,
44
+ )
45
+ }
46
+ const language = normalizeLanguageOptions(languageOption ?? {})
47
+
24
48
  const { pageName, script, template, scriptStartLine } = parsePageFile(source)
25
49
 
26
50
  const pageNode = substituteCapabilityRefs(
27
51
  script.trim().length > 0
28
- ? new Parser(new Lexer(script).tokenize()).parse()
52
+ ? new Parser(new Lexer(script).tokenize(), language).parse()
29
53
  : { props: [], state: [], computed: [], actions: [], onMount: null },
30
54
  )
31
55
 
32
56
  const templateNodes =
33
- template.trim().length > 0 ? parseTemplate(template) : null
57
+ template.trim().length > 0 ? parseTemplate(template, language) : null
34
58
 
35
59
  const { source: virtualSource, lineMap } = buildVirtualPageTs(
36
60
  pageNode,
@@ -43,4 +67,4 @@ export function typecheckPage(source, apiHelpersSource = '') {
43
67
  const scriptLine = mapVirtualLineToSource(lineMap, d.virtualLine)
44
68
  return { message: d.message, line: scriptLine + scriptStartLine - 1 }
45
69
  })
46
- }
70
+ }
@@ -1,41 +0,0 @@
1
- import fs from 'node:fs/promises'
2
- import path from 'node:path'
3
-
4
- // A component package (like tylix-icons) ships a manifest at its
5
- // root mapping exported names to the .tyx file that defines them:
6
- // { "IconCheck": "icons/IconCheck.tyx", "IconTrash": "icons/IconTrash.tyx" }
7
- // This keeps resolution to "read one JSON file, then read the .tyx
8
- // files it points at" -- no bundler, no special package.json export
9
- // map, just a plain manifest a package author (or a scaffolding tool)
10
- // can hand-write.
11
- const MANIFEST_FILE = 'tylix-components.json'
12
-
13
- export async function resolvePackageComponents(imports, baseDir) {
14
- const components = {}
15
-
16
- for (const { names, package: pkgName } of imports) {
17
- const pkgDir = path.join(baseDir, 'node_modules', pkgName)
18
- const manifestPath = path.join(pkgDir, MANIFEST_FILE)
19
-
20
- let manifest
21
- try {
22
- manifest = JSON.parse(await fs.readFile(manifestPath, 'utf-8'))
23
- } catch {
24
- throw new Error(
25
- `Cannot resolve components from "${pkgName}": missing or invalid ${MANIFEST_FILE} in node_modules/${pkgName}. Is the package installed?`,
26
- )
27
- }
28
-
29
- for (const name of names) {
30
- const relPath = manifest[name]
31
- if (!relPath) {
32
- throw new Error(
33
- `"${pkgName}" does not export a component named "${name}" (checked ${MANIFEST_FILE})`,
34
- )
35
- }
36
- components[name] = await fs.readFile(path.join(pkgDir, relPath), 'utf-8')
37
- }
38
- }
39
-
40
- return components
41
- }