@tylix/compiler 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # @tylix/compiler
2
+
3
+ Compiles `.tyx` page and component files into runnable JavaScript,
4
+ with full TypeScript support.
5
+
6
+ ## What's included
7
+
8
+ - **Lexer/Parser** — `Lexer`, `tokenTypes`, `Parser`, `parseComponent`,
9
+ `parseTemplate`, `parseExpressionString` turn `.tyx` source into an AST
10
+ (`ast/nodes.js`)
11
+ - **Codegen** — `generateExpression`, `generateStatement`, `generateMethod`,
12
+ `generatePage`, `generateTemplate` turn the AST into JS output
13
+ - **Typecheck** — `buildVirtualTs`, `typecheckVirtualFile`, `typecheckPage`,
14
+ and `transpileHelperSource` run `.tyx` scripts through the TypeScript
15
+ Compiler API for full type-annotation support
16
+ - **Imports** — `extractImports`, `resolvePackageComponents` resolve
17
+ component imports from external packages (e.g. `import { IconPlus }
18
+ from "tylix-icons"`) by reading a `tylix-components.json` manifest
19
+ from the package's `node_modules` folder — a plain JSON map of
20
+ exported name → `.tyx` file path — then reading that `.tyx` file's
21
+ source so it can be compiled inline alongside locally-defined
22
+ components. No bundler or special `package.json` exports map
23
+ required; any package that ships a manifest and some `.tyx` files
24
+ works.
25
+ - **Runtime** — `reactive` primitives
26
+ - `compileComponent` and `renderPageDocument` as the main entry points
27
+ tying parsing → typecheck → codegen together
28
+
29
+ ## Usage
30
+
31
+ Used internally by `@tylix/core` (dev server) and `@tylix/cli`
32
+ (`build`, `dev`) to turn `.tyx` files into runnable pages/components.
33
+ Not typically imported directly in application code.
34
+
35
+ ## License
36
+
37
+ MIT
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "@tylix/compiler",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "main": "./src/index.js",
6
6
  "scripts": {
7
7
  "test": "node --test src/*.test.js src/**/*.test.js"
8
8
  },
9
+ "dependencies": {
10
+ "typescript": "^5.9.3"
11
+ },
9
12
  "devDependencies": {
10
13
  "jsdom": "^24.0.0"
11
14
  }
package/src/ast/nodes.js CHANGED
@@ -13,16 +13,16 @@ export function PageNode({
13
13
  return { type: 'Page', props, state, computed, actions, onMount }
14
14
  }
15
15
 
16
- export function PropNode(name, propType) {
17
- return { type: 'Prop', name, propType }
16
+ export function PropNode(name, propType, optional = false) {
17
+ return { type: 'Prop', name, propType, optional }
18
18
  }
19
19
 
20
- export function StateNode(name, value) {
21
- return { type: 'State', name, value }
20
+ export function StateNode(name, value, typeAnnotation = null) {
21
+ return { type: 'State', name, value, typeAnnotation }
22
22
  }
23
23
 
24
- export function MethodNode(name, params, body) {
25
- return { type: 'Method', name, params, body }
24
+ export function MethodNode(name, params, body, returnType = null) {
25
+ return { type: 'Method', name, params, body, returnType }
26
26
  }
27
27
 
28
28
  export function AssignmentExpr(target, value) {
@@ -134,10 +134,14 @@ export function ContinueStatement() {
134
134
  return { type: 'ContinueStatement' }
135
135
  }
136
136
 
137
- export function ArrowFunctionExpr(params, body) {
138
- return { type: 'ArrowFunctionExpression', params, body }
137
+ export function ArrowFunctionExpr(params, body, paramTypes = null) {
138
+ return { type: 'ArrowFunctionExpression', params, body, paramTypes }
139
139
  }
140
140
 
141
141
  export function TemplateLiteralExpr(parts) {
142
142
  return { type: 'TemplateLiteralExpression', parts }
143
143
  }
144
+
145
+ export function SpreadElement(argument) {
146
+ return { type: 'SpreadElement', argument }
147
+ }
@@ -0,0 +1,86 @@
1
+ import { generateExpression } from './generateExpression.js'
2
+
3
+ // Structurally the same cases as generateStatement.js, but emits one
4
+ // line at a time through `sink.pushLine(text, originalLine)` instead
5
+ // of returning a single joined string -- needed so the virtual .ts
6
+ // builder can record a lineMap entry per generated line, not just
7
+ // per top-level declaration. Kept separate from generateStatement
8
+ // rather than instrumented in place, since the real JS codegen path
9
+ // has no use for per-line source positions.
10
+ //
11
+ // Every generateExpression() call here passes `true` for its typed
12
+ // param -- this file has exactly one consumer (buildVirtualPageTs,
13
+ // building the virtual .ts fed to the TypeScript compiler API), so
14
+ // unlike generateExpression itself (shared between real JS and
15
+ // virtual TS output), there's no "untyped" mode to preserve here.
16
+ export function emitStatementLines(node, sink, indent = ' ') {
17
+ const line = node.line
18
+ const push = (text) => sink.pushLine(`${indent}${text}`, line)
19
+
20
+ switch (node.type) {
21
+ case 'ReturnStatement':
22
+ push(
23
+ node.argument
24
+ ? `return ${generateExpression(node.argument, true)};`
25
+ : 'return;',
26
+ )
27
+ break
28
+
29
+ case 'ExpressionStatement':
30
+ push(`${generateExpression(node.expression, true)};`)
31
+ break
32
+
33
+ case 'VariableDeclaration':
34
+ push(
35
+ `${node.kind} ${node.name} = ${generateExpression(node.init, true)};`,
36
+ )
37
+ break
38
+
39
+ case 'IfStatement':
40
+ push(`if (${generateExpression(node.condition, true)}) {`)
41
+ for (const s of node.consequent)
42
+ emitStatementLines(s, sink, indent + ' ')
43
+ if (node.alternate) {
44
+ push('} else {')
45
+ for (const s of node.alternate)
46
+ emitStatementLines(s, sink, indent + ' ')
47
+ }
48
+ push('}')
49
+ break
50
+
51
+ case 'ForInStatement':
52
+ push(
53
+ `for (const ${node.varName} of ${generateExpression(node.iterable, true)}) {`,
54
+ )
55
+ for (const s of node.body) emitStatementLines(s, sink, indent + ' ')
56
+ push('}')
57
+ break
58
+
59
+ case 'ForRangeStatement':
60
+ push(
61
+ `for (let ${node.varName} = ${generateExpression(node.start, true)}; ${node.varName} < ${generateExpression(node.end, true)}; ${node.varName}++) {`,
62
+ )
63
+ for (const s of node.body) emitStatementLines(s, sink, indent + ' ')
64
+ push('}')
65
+ break
66
+
67
+ case 'RepeatStatement':
68
+ push(
69
+ `for (let __i = 0; __i < ${generateExpression(node.count, true)}; __i++) {`,
70
+ )
71
+ for (const s of node.body) emitStatementLines(s, sink, indent + ' ')
72
+ push('}')
73
+ break
74
+
75
+ case 'BreakStatement':
76
+ push('break;')
77
+ break
78
+
79
+ case 'ContinueStatement':
80
+ push('continue;')
81
+ break
82
+
83
+ default:
84
+ throw new Error(`emitStatementLines: unknown node type "${node.type}"`)
85
+ }
86
+ }
@@ -1,10 +1,15 @@
1
1
  /**
2
- * Compiles a single expression AST node into a JS source string.
3
- * Used both for method-body statements and template interpolations,
4
- * so every consumer (class codegen, template codegen) shares one
5
- * source of truth for expression -> JS translation.
2
+ * Compiles a single expression AST node into a JS (or, when
3
+ * typed=true, TypeScript) source string. Used both for method-body
4
+ * statements/template interpolations (typed=false, real JS output)
5
+ * and the virtual .ts file handed to the TypeScript compiler API
6
+ * (typed=true) -- one source of truth for expression -> source
7
+ * translation, so the two outputs can never structurally drift from
8
+ * each other. `typed` only changes ONE thing: whether an arrow
9
+ * function's params get a `: Type` annotation. Everything else emits
10
+ * identically either way.
6
11
  */
7
- export function generateExpression(node) {
12
+ export function generateExpression(node, typed = false) {
8
13
  switch (node.type) {
9
14
  case 'Literal':
10
15
  return typeof node.value === 'string'
@@ -16,26 +21,40 @@ export function generateExpression(node) {
16
21
 
17
22
  case 'MemberExpression':
18
23
  return node.computed
19
- ? `${generateExpression(node.object)}[${generateExpression(node.property)}]`
20
- : `${generateExpression(node.object)}.${node.property}`
24
+ ? `${generateExpression(node.object, typed)}[${generateExpression(node.property, typed)}]`
25
+ : `${generateExpression(node.object, typed)}.${node.property}`
21
26
 
22
27
  case 'NewExpression': {
23
- const args = node.args.map((a) => generateExpression(a)).join(', ')
24
- return `new ${generateExpression(node.callee)}(${args})`
28
+ const args = node.args.map((a) => generateExpression(a, typed)).join(', ')
29
+ return `new ${generateExpression(node.callee, typed)}(${args})`
25
30
  }
26
31
 
27
32
  case 'BinaryExpression':
28
- return `(${generateExpression(node.left)} ${node.operator} ${generateExpression(node.right)})`
33
+ return `(${generateExpression(node.left, typed)} ${node.operator} ${generateExpression(node.right, typed)})`
29
34
 
30
35
  case 'UnaryExpression':
31
- return `(${node.operator}${generateExpression(node.argument)})`
36
+ return `(${node.operator}${generateExpression(node.argument, typed)})`
32
37
 
33
38
  case 'TernaryExpression':
34
- return `(${generateExpression(node.condition)} ? ${generateExpression(node.consequent)} : ${generateExpression(node.alternate)})`
39
+ return `(${generateExpression(node.condition, typed)} ? ${generateExpression(node.consequent, typed)} : ${generateExpression(node.alternate, typed)})`
35
40
 
36
41
  case 'ArrowFunctionExpression': {
37
- const params = node.params.join(', ')
38
- return `(${params}) => (${generateExpression(node.body)})`
42
+ // paramTypes is a parallel array of type strings or null,
43
+ // populated by tryParseArrowFunction when a dev writes
44
+ // `f: Post => ...`; absent/null entries mean "no annotation
45
+ // was written" -- in typed mode those fall back to `any`
46
+ // rather than being left bare, since a bare untyped param in a
47
+ // .ts arrow function has no implicit-any exemption the way
48
+ // real JS does.
49
+ const paramTypes = node.paramTypes ?? node.params.map(() => null)
50
+ const params = node.params
51
+ .map((name, i) => {
52
+ if (!typed) return name
53
+ const paramType = paramTypes[i]
54
+ return `${name}: ${paramType ?? 'any'}`
55
+ })
56
+ .join(', ')
57
+ return `(${params}) => (${generateExpression(node.body, typed)})`
39
58
  }
40
59
 
41
60
  case 'TemplateLiteralExpression': {
@@ -43,33 +62,46 @@ export function generateExpression(node) {
43
62
  .map((p) =>
44
63
  p.type === 'text'
45
64
  ? escapeTemplateText(p.value)
46
- : `\${${generateExpression(p.expression)}}`,
65
+ : `\${${generateExpression(p.expression, typed)}}`,
47
66
  )
48
67
  .join('')
49
68
  return `\`${inner}\``
50
69
  }
51
70
 
52
71
  case 'AssignmentExpression':
53
- return `${generateExpression(node.target)} = ${generateExpression(node.value)}`
72
+ return `${generateExpression(node.target, typed)} = ${generateExpression(node.value, typed)}`
54
73
 
55
74
  case 'CallExpression': {
56
- const args = node.args.map((a) => generateExpression(a)).join(', ')
57
- return `${generateExpression(node.callee)}(${args})`
75
+ const args = node.args
76
+ .map((a) =>
77
+ a.type === 'SpreadElement'
78
+ ? `...${generateExpression(a.argument, typed)}`
79
+ : generateExpression(a, typed),
80
+ )
81
+ .join(', ')
82
+ return `${generateExpression(node.callee, typed)}(${args})`
58
83
  }
59
84
 
60
85
  case 'AwaitExpression':
61
- return `await ${generateExpression(node.argument)}`
86
+ return `await ${generateExpression(node.argument, typed)}`
62
87
 
63
88
  case 'ObjectExpression': {
64
89
  const props = node.properties
65
- .map((p) => `${JSON.stringify(p.key)}: ${generateExpression(p.value)}`)
90
+ .map(
91
+ (p) =>
92
+ `${JSON.stringify(p.key)}: ${generateExpression(p.value, typed)}`,
93
+ )
66
94
  .join(', ')
67
95
  return `{ ${props} }`
68
96
  }
69
97
 
70
98
  case 'ArrayExpression': {
71
99
  const elements = node.elements
72
- .map((e) => generateExpression(e))
100
+ .map((e) =>
101
+ e.type === 'SpreadElement'
102
+ ? `...${generateExpression(e.argument, typed)}`
103
+ : generateExpression(e, typed),
104
+ )
73
105
  .join(', ')
74
106
  return `[${elements}]`
75
107
  }
@@ -1,4 +1,4 @@
1
- import { generateStatement } from "./generateStatement.js";
1
+ import { generateStatement } from './generateStatement.js'
2
2
 
3
3
  /**
4
4
  * Compiles a MethodNode (used for both `computed` and `action` entries)
@@ -6,8 +6,10 @@ import { generateStatement } from "./generateStatement.js";
6
6
  * generated output.
7
7
  */
8
8
  export function generateMethod(node) {
9
- const params = node.params.join(", ");
10
- const body = node.body.map((stmt) => ` ${generateStatement(stmt)}`).join("\n");
11
- const asyncPrefix = node.isAsync ? "async " : "";
12
- return ` ${asyncPrefix}${node.name}(${params}) {\n${body}\n }`;
9
+ const params = node.params.map((p) => p.name).join(', ')
10
+ const body = node.body
11
+ .map((stmt) => ` ${generateStatement(stmt)}`)
12
+ .join('\n')
13
+ const asyncPrefix = node.isAsync ? 'async ' : ''
14
+ return ` ${asyncPrefix}${node.name}(${params}) {\n${body}\n }`
13
15
  }
@@ -3,6 +3,8 @@ import { generateTemplateExpression } from './generateTemplateExpression.js'
3
3
  const EVENT_ATTR_PREFIX = /^on(click|input|change|submit)$/i
4
4
  const COMPONENT_TAG_PATTERN = /^[A-Z]/
5
5
 
6
+ const SVG_NS = 'http://www.w3.org/2000/svg'
7
+
6
8
  let nodeCounter = 0
7
9
  function nextVar(prefix) {
8
10
  return `${prefix}${nodeCounter++}`
@@ -19,7 +21,9 @@ function nextVar(prefix) {
19
21
  export function generateTemplate(nodes) {
20
22
  nodeCounter = 0
21
23
  const lines = []
22
- const rootVars = nodes.map((node) => compileNode(node, lines, new Set()))
24
+ const rootVars = nodes.map((node) =>
25
+ compileNode(node, lines, new Set(), false),
26
+ )
23
27
 
24
28
  if (rootVars.length === 1) {
25
29
  return { code: lines.join('\n'), rootVar: rootVars[0] }
@@ -31,7 +35,7 @@ export function generateTemplate(nodes) {
31
35
  return { code: lines.join('\n'), rootVar: fragmentVar }
32
36
  }
33
37
 
34
- function compileNode(node, lines, scope) {
38
+ function compileNode(node, lines, scope, inSvg = false) {
35
39
  if (node.type === 'Text') {
36
40
  const varName = nextVar('text')
37
41
  lines.push(
@@ -49,28 +53,27 @@ function compileNode(node, lines, scope) {
49
53
  }
50
54
 
51
55
  if (node.type === 'If') {
52
- return compileIf(node, lines, scope)
56
+ return compileIf(node, lines, scope, inSvg)
53
57
  }
54
58
 
55
59
  if (node.type === 'Each') {
56
- return compileEach(node, lines, scope)
60
+ return compileEach(node, lines, scope, inSvg)
57
61
  }
58
62
 
59
63
  if (node.type === 'Element') {
60
- return compileElement(node, lines, scope)
64
+ return compileElement(node, lines, scope, inSvg)
61
65
  }
62
66
 
63
67
  throw new Error(`generateTemplate: unknown node type "${node.type}"`)
64
68
  }
65
-
66
69
  // Renders node.children into a local fragment and returns the lines
67
70
  // needed to build it plus the fragment's own variable name, without
68
71
  // touching the caller's `lines` array directly (used inside effect
69
72
  // callbacks below, which need their own nested block of statements).
70
- function compileChildrenIntoFragment(children, scope, fragVar) {
73
+ function compileChildrenIntoFragment(children, scope, fragVar, inSvg = false) {
71
74
  const childLines = []
72
75
  const childVars = children.map((child) =>
73
- compileNode(child, childLines, scope),
76
+ compileNode(child, childLines, scope, inSvg),
74
77
  )
75
78
  childLines.push(...childVars.map((v) => `${fragVar}.appendChild(${v});`))
76
79
  return childLines
@@ -82,7 +85,7 @@ function compileChildrenIntoFragment(children, scope, fragVar) {
82
85
  // same fragment that holds the anchor. On every later run (state
83
86
  // changed), previous nodes are removed and new ones inserted right
84
87
  // after the anchor in the live DOM.
85
- function compileIf(node, lines, scope) {
88
+ function compileIf(node, lines, scope, inSvg = false) {
86
89
  const anchorVar = nextVar('ifAnchor')
87
90
  const containerVar = nextVar('ifContainer')
88
91
  const nodesVar = nextVar('ifNodes')
@@ -99,7 +102,12 @@ function compileIf(node, lines, scope) {
99
102
  lines.push(` ${nodesVar} = [];`)
100
103
  lines.push(` if (${condExpr}) {`)
101
104
  lines.push(` const frag = document.createDocumentFragment();`)
102
- const childLines = compileChildrenIntoFragment(node.children, scope, 'frag')
105
+ const childLines = compileChildrenIntoFragment(
106
+ node.children,
107
+ scope,
108
+ 'frag',
109
+ inSvg,
110
+ )
103
111
  childLines.forEach((l) => lines.push(` ${l}`))
104
112
  lines.push(` ${nodesVar} = Array.from(frag.childNodes);`)
105
113
  lines.push(` if (${initialVar}) { ${containerVar}.appendChild(frag); }`)
@@ -113,11 +121,7 @@ function compileIf(node, lines, scope) {
113
121
  return containerVar
114
122
  }
115
123
 
116
- // List rendering, same anchor/rebuild strategy as compileIf, but
117
- // iterating a reactive array each time the effect runs. Not keyed
118
- // diffing -- every dependency change rebuilds the whole list, which
119
- // is the deliberate simplification for v1.
120
- function compileEach(node, lines, scope) {
124
+ function compileEach(node, lines, scope, inSvg = false) {
121
125
  const anchorVar = nextVar('eachAnchor')
122
126
  const containerVar = nextVar('eachContainer')
123
127
  const nodesVar = nextVar('eachNodes')
@@ -138,6 +142,7 @@ function compileEach(node, lines, scope) {
138
142
  node.children,
139
143
  innerScope,
140
144
  'frag',
145
+ inSvg,
141
146
  )
142
147
  childLines.forEach((l) => lines.push(` ${l}`))
143
148
  lines.push(` }`)
@@ -151,20 +156,31 @@ function compileEach(node, lines, scope) {
151
156
 
152
157
  return containerVar
153
158
  }
154
-
155
159
  function isComponentTag(tag) {
156
160
  return COMPONENT_TAG_PATTERN.test(tag)
157
161
  }
158
162
 
159
- function compileElement(node, lines, scope) {
163
+ function compileElement(node, lines, scope, inSvg = false) {
160
164
  if (isComponentTag(node.tag)) {
161
165
  const varName = nextVar('component')
162
166
  const tagLiteral = JSON.stringify(node.tag)
163
167
 
164
168
  const propEntries = node.attributes.map((attr) => {
165
- const expr = attr.dynamic
166
- ? generateTemplateExpression(attr.value, scope)
167
- : JSON.stringify(attr.value)
169
+ let expr
170
+ if (attr.dynamic) {
171
+ expr = generateTemplateExpression(attr.value, scope)
172
+ // Callback props (onXxx="{{ methodName }}") pass a bare
173
+ // instance-method reference. `generateTemplateExpression`
174
+ // turns `methodName` into `instance.methodName`, but handing
175
+ // that off as a plain value loses its `this` binding the
176
+ // moment the child calls it. Bind it here, while we still
177
+ // have `instance` in scope.
178
+ if (/^on[A-Z]/.test(attr.name) && attr.value.type === 'Identifier') {
179
+ expr = `(${expr}).bind(instance)`
180
+ }
181
+ } else {
182
+ expr = JSON.stringify(attr.value)
183
+ }
168
184
  return `${JSON.stringify(attr.name)}: ${expr}`
169
185
  })
170
186
  const propsExpr = `{ ${propEntries.join(', ')} }`
@@ -185,23 +201,37 @@ function compileElement(node, lines, scope) {
185
201
  return varName
186
202
  }
187
203
 
204
+ // Once we're inside an <svg>, every descendant (path, circle, g,
205
+ // etc.) needs the SVG namespace too -- createElement() without a
206
+ // namespace produces a non-rendering element that still LOOKS
207
+ // correct in the DOM inspector (right tag name, right attributes),
208
+ // which is exactly what made this bug so hard to spot.
209
+ const isSvgRoot = node.tag === 'svg'
210
+ const nsForThisNode = inSvg || isSvgRoot
211
+ const childInSvg = isSvgRoot ? true : inSvg
212
+
188
213
  const varName = nextVar('el')
189
- lines.push(
190
- `const ${varName} = document.createElement(${JSON.stringify(node.tag)});`,
191
- )
214
+ if (nsForThisNode) {
215
+ lines.push(
216
+ `const ${varName} = document.createElementNS(${JSON.stringify(SVG_NS)}, ${JSON.stringify(node.tag)});`,
217
+ )
218
+ } else {
219
+ lines.push(
220
+ `const ${varName} = document.createElement(${JSON.stringify(node.tag)});`,
221
+ )
222
+ }
192
223
 
193
224
  for (const attr of node.attributes) {
194
225
  compileAttribute(varName, node.tag, attr, lines, scope)
195
226
  }
196
227
 
197
228
  for (const child of node.children) {
198
- const childVar = compileNode(child, lines, scope)
229
+ const childVar = compileNode(child, lines, scope, childInSvg)
199
230
  lines.push(`${varName}.appendChild(${childVar});`)
200
231
  }
201
232
 
202
233
  return varName
203
234
  }
204
-
205
235
  // Attributes that reflect live user-editable DOM state -- setting
206
236
  // them via setAttribute() only seeds the *initial* value; once the
207
237
  // user interacts with the control, the live property diverges from
@@ -0,0 +1,29 @@
1
+ const IMPORT_LINE_RE =
2
+ /^\s*import\s*\{\s*([^}]+)\s*\}\s*from\s*["']([^"']+)["']\s*;?\s*$/gm
3
+
4
+ // Tylix pages/components can import named components from an
5
+ // installed package (e.g. `import { IconCheck, IconTrash } from
6
+ // "tylix-icons"`), the same way a local component under
7
+ // app/pages/components/ works -- this is a source-level rewrite
8
+ // step, not a grammar addition. Import lines never reach
9
+ // parsePageFile's script/template splitter or the Parser/Lexer at
10
+ // all; they're stripped out of the raw file text before any of that
11
+ // runs. Only package specifiers (no leading "." or "/") are handled
12
+ // here -- local components are already auto-discovered by
13
+ // loadComponents() scanning app/pages/components/, so a relative
14
+ // import isn't a case this needs to cover.
15
+ export function extractImports(source) {
16
+ const imports = []
17
+ const cleaned = source.replace(IMPORT_LINE_RE, (match, namesRaw, pkg) => {
18
+ if (pkg.startsWith('.') || pkg.startsWith('/')) {
19
+ return match // not a supported target -- leave as a normal parse error
20
+ }
21
+ const names = namesRaw
22
+ .split(',')
23
+ .map((n) => n.trim())
24
+ .filter(Boolean)
25
+ imports.push({ names, package: pkg })
26
+ return ''
27
+ })
28
+ return { imports, source: cleaned }
29
+ }
@@ -0,0 +1,41 @@
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
+ }
package/src/index.js CHANGED
@@ -1,15 +1,21 @@
1
- export * from "./parser/parseComponent.js";
2
- export * from "./parser/Parser.js";
3
- export * from "./parser/parseTemplate.js";
4
- export * from "./parser/parseExpressionString.js";
5
- export * from "./lexer/Lexer.js";
6
- export * from "./lexer/tokenTypes.js";
7
- export * from "./ast/nodes.js";
8
- export * from "./runtime/reactive.js";
9
- export * from "./codegen/generateExpression.js";
10
- export * from "./codegen/generateStatement.js";
11
- export * from "./codegen/generateMethod.js";
12
- export * from "./codegen/generatePage.js";
13
- export * from "./codegen/generateTemplate.js";
14
- export * from "./compileComponent.js";
15
- export * from "./renderPageDocument.js";
1
+ export * from './parser/parseComponent.js'
2
+ export * from './parser/Parser.js'
3
+ export * from './parser/parseTemplate.js'
4
+ export * from './parser/parseExpressionString.js'
5
+ export * from './lexer/Lexer.js'
6
+ export * from './lexer/tokenTypes.js'
7
+ export * from './ast/nodes.js'
8
+ export * from './runtime/reactive.js'
9
+ export * from './codegen/generateExpression.js'
10
+ export * from './codegen/generateStatement.js'
11
+ export * from './codegen/generateMethod.js'
12
+ export * from './codegen/generatePage.js'
13
+ export * from './codegen/generateTemplate.js'
14
+ export * from './compileComponent.js'
15
+ export * from './renderPageDocument.js'
16
+ export * from './typecheck/buildVirtualTs.js'
17
+ export * from './typecheck/typecheckVirtualFile.js'
18
+ export * from './typecheckPage.js'
19
+ export * from './typecheck/transpileHelperSource.js'
20
+ export * from './imports/extractImports.js'
21
+ export * from './imports/resolvePackageComponents.js'
@@ -9,6 +9,7 @@ const SINGLE_CHAR_TOKENS = {
9
9
  '.': TokenType.DOT,
10
10
  '[': TokenType.LBRACKET,
11
11
  ']': TokenType.RBRACKET,
12
+ '.': TokenType.DOT,
12
13
  }
13
14
 
14
15
  export class Lexer {
@@ -68,6 +69,12 @@ export class Lexer {
68
69
  continue
69
70
  }
70
71
 
72
+ if (char === '|') {
73
+ this.pushToken(TokenType.PIPE, '|')
74
+ this.pos++
75
+ continue
76
+ }
77
+
71
78
  // Compound assignment operators must be checked before their
72
79
  // single-char fallbacks below, same lookahead-before-fallback
73
80
  // pattern already used for '=>', '>=', '<=' above.
@@ -149,6 +156,16 @@ export class Lexer {
149
156
  continue
150
157
  }
151
158
 
159
+ if (
160
+ char === '.' &&
161
+ this.source[this.pos + 1] === '.' &&
162
+ this.source[this.pos + 2] === '.'
163
+ ) {
164
+ this.pushToken(TokenType.SPREAD, '...')
165
+ this.pos += 3
166
+ continue
167
+ }
168
+
152
169
  if (char in SINGLE_CHAR_TOKENS) {
153
170
  this.pushToken(SINGLE_CHAR_TOKENS[char], char)
154
171
  this.pos++