@tylix/compiler 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,133 @@
1
+ import { emitStatementLines } from '../codegen/emitStatementLines.js'
2
+ import { collectTemplateChecks } from './typedTemplateExpr.js'
3
+
4
+ function paramListWithTypes(params) {
5
+ return params
6
+ .map(
7
+ (p) => `${p.name}${p.typeAnnotation ? `: ${p.typeAnnotation}` : ': any'}`,
8
+ )
9
+ .join(', ')
10
+ }
11
+
12
+ // Recursively emits a check tree (see collectTemplateChecks) into
13
+ // the virtual __render() body. `each` entries open a real
14
+ // `for (const item of (iterable as any[]))` so the loop variable is
15
+ // an actual TS declaration, not a bare identifier the checker has
16
+ // never seen -- `as any[]` since state/props are typically `any`
17
+ // here anyway, and iterating `any` never fails strict mode regardless.
18
+ function emitChecks(checks, sink, indent) {
19
+ for (const c of checks) {
20
+ if (c.kind === 'each') {
21
+ sink.pushLine(
22
+ `${indent}for (const ${c.itemName} of (${c.iterableExpr} as any[])) {`,
23
+ c.line,
24
+ )
25
+ emitChecks(c.children, sink, indent + ' ')
26
+ sink.pushLine(`${indent}}`, null)
27
+ } else if (c.eventType) {
28
+ sink.pushLine(`${indent}{`, null)
29
+ sink.pushLine(
30
+ `${indent} const event: Event & { target: ${c.eventType} } = new Event("synthetic") as unknown as Event & { target: ${c.eventType} };`,
31
+ null,
32
+ )
33
+ sink.pushLine(`${indent} const $event = event;`, null)
34
+ sink.pushLine(`${indent} (${c.expr});`, c.line)
35
+ sink.pushLine(`${indent}}`, null)
36
+ } else {
37
+ sink.pushLine(`${indent}(${c.expr});`, c.line)
38
+ }
39
+ }
40
+ }
41
+
42
+ export function buildVirtualPageTs(pageNode, className, templateNodes = null) {
43
+ const lines = []
44
+ const lineMap = []
45
+ const sink = {
46
+ pushLine(text, originalLine) {
47
+ if (originalLine != null) {
48
+ lineMap.push({ virtualLine: lines.length + 1, originalLine })
49
+ }
50
+ lines.push(text)
51
+ },
52
+ }
53
+
54
+ if (pageNode.props.length > 0) {
55
+ sink.pushLine(`interface ${className}Props {`, null)
56
+ for (const p of pageNode.props) {
57
+ sink.pushLine(
58
+ ` ${p.name}${p.optional ? '?' : ''}: ${p.propType};`,
59
+ p.line,
60
+ )
61
+ }
62
+ sink.pushLine(`}`, null)
63
+ sink.pushLine(``, null)
64
+ }
65
+
66
+ sink.pushLine(`class ${className} {`, null)
67
+ sink.pushLine(` [key: string]: any;`, null)
68
+ if (pageNode.props.length > 0) {
69
+ sink.pushLine(` props!: ${className}Props;`, null)
70
+ }
71
+
72
+ for (const s of pageNode.state) {
73
+ sink.pushLine(` ${s.name}!: ${s.typeAnnotation ?? 'any'};`, s.line)
74
+ }
75
+
76
+ for (const c of pageNode.computed) {
77
+ sink.pushLine(``, null)
78
+ sink.pushLine(
79
+ ` get ${c.name}()${c.returnType ? `: ${c.returnType}` : ''} {`,
80
+ c.line,
81
+ )
82
+ for (const stmt of c.body) emitStatementLines(stmt, sink, ' ')
83
+ sink.pushLine(` }`, null)
84
+ }
85
+
86
+ for (const a of pageNode.actions) {
87
+ const returnType = a.returnType
88
+ ? a.isAsync
89
+ ? `Promise<${a.returnType}>`
90
+ : a.returnType
91
+ : ''
92
+ sink.pushLine(``, null)
93
+ sink.pushLine(
94
+ ` ${a.isAsync ? 'async ' : ''}${a.name}(${paramListWithTypes(a.params)})${returnType ? `: ${returnType}` : ''} {`,
95
+ a.line,
96
+ )
97
+ for (const stmt of a.body) emitStatementLines(stmt, sink, ' ')
98
+ sink.pushLine(` }`, null)
99
+ }
100
+
101
+ if (pageNode.onMount && pageNode.onMount.body.length > 0) {
102
+ sink.pushLine(``, null)
103
+ sink.pushLine(` async __onMount(): Promise<any> {`, pageNode.onMount.line)
104
+ for (const stmt of pageNode.onMount.body) {
105
+ emitStatementLines(stmt, sink, ' ')
106
+ }
107
+ sink.pushLine(` }`, null)
108
+ }
109
+
110
+ if (templateNodes) {
111
+ const checks = []
112
+ collectTemplateChecks(templateNodes, new Set(), checks)
113
+ if (checks.length > 0) {
114
+ sink.pushLine(``, null)
115
+ sink.pushLine(` __render() {`, null)
116
+ emitChecks(checks, sink, ' ')
117
+ sink.pushLine(` }`, null)
118
+ }
119
+ }
120
+
121
+ sink.pushLine(`}`, null)
122
+
123
+ return { source: lines.join('\n') + '\n', lineMap }
124
+ }
125
+
126
+ export function mapVirtualLineToSource(lineMap, virtualLine) {
127
+ let best = lineMap[0]?.originalLine ?? 1
128
+ for (const entry of lineMap) {
129
+ if (entry.virtualLine <= virtualLine) best = entry.originalLine
130
+ else break
131
+ }
132
+ return best
133
+ }
@@ -0,0 +1,24 @@
1
+ import ts from 'typescript'
2
+
3
+ // Transpiles a single .ts source file to plain, browser-runnable JS.
4
+ // Used for app/useApi/*.ts helpers, which get concatenated as raw
5
+ // text into the page's inline <script> and executed directly in the
6
+ // browser -- unlike pages themselves (which go through
7
+ // generatePage/generateTemplate), these files are handed to the
8
+ // browser close to verbatim, so any TypeScript syntax in them (type
9
+ // annotations, etc.) has to be stripped before they can run there.
10
+ //
11
+ // transpileModule (not the full typecheckSource/checker path) is
12
+ // deliberate here: these are simple, single-file helper functions
13
+ // with no cross-file type information to check against, and the
14
+ // project's own typecheckPage already covers .tyx pages -- this is
15
+ // purely a syntax-stripping step, not a second typechecking pass.
16
+ export function transpileTsToJs(source) {
17
+ const result = ts.transpileModule(source, {
18
+ compilerOptions: {
19
+ target: ts.ScriptTarget.ES2022,
20
+ module: ts.ModuleKind.ESNext,
21
+ },
22
+ })
23
+ return result.outputText
24
+ }
@@ -0,0 +1,40 @@
1
+ // packages/compiler/src/typecheck/tylix-globals.d.ts
2
+ declare function useApi(
3
+ path: string,
4
+ options?: {
5
+ method?: string
6
+ body?: unknown
7
+ headers?: Record<string, string>
8
+ },
9
+ ): Promise<{
10
+ ok: boolean
11
+ status: number
12
+ data: any
13
+ error?: string
14
+ }>
15
+
16
+ // getApi/postApi/putApi/deleteApi share useApi's response shape --
17
+ // convenience wrappers over the same underlying call.
18
+ declare function getApi(
19
+ path: string,
20
+ options?: { headers?: Record<string, string> },
21
+ ): Promise<{ ok: boolean; status: number; data: any; error?: string }>
22
+
23
+ declare function postApi(
24
+ path: string,
25
+ body?: unknown,
26
+ options?: { headers?: Record<string, string> },
27
+ ): Promise<{ ok: boolean; status: number; data: any; error?: string }>
28
+
29
+ declare function putApi(
30
+ path: string,
31
+ body?: unknown,
32
+ options?: { headers?: Record<string, string> },
33
+ ): Promise<{ ok: boolean; status: number; data: any; error?: string }>
34
+
35
+ declare function deleteApi(
36
+ path: string,
37
+ options?: { headers?: Record<string, string> },
38
+ ): Promise<{ ok: boolean; status: number; data: any; error?: string }>
39
+
40
+ declare function useChannel(name: string): any
@@ -0,0 +1,46 @@
1
+ import ts from 'typescript'
2
+ import { fileURLToPath } from 'node:url'
3
+
4
+ const VIRTUAL_FILE_NAME = '__tylix_virtual_page.ts'
5
+ const GLOBALS_FILE = fileURLToPath(
6
+ new URL('./tylix-globals.d.ts', import.meta.url),
7
+ )
8
+
9
+ export function typecheckSource(virtualSource, compilerOptions = {}) {
10
+ const options = {
11
+ strict: true,
12
+ target: ts.ScriptTarget.ES2022,
13
+ module: ts.ModuleKind.ESNext,
14
+ noEmit: true,
15
+ skipLibCheck: true,
16
+ ...compilerOptions,
17
+ }
18
+
19
+ const host = ts.createCompilerHost(options)
20
+ const originalGetSourceFile = host.getSourceFile
21
+ host.getSourceFile = (fileName, languageVersion, ...rest) => {
22
+ if (fileName === VIRTUAL_FILE_NAME) {
23
+ return ts.createSourceFile(fileName, virtualSource, languageVersion, true)
24
+ }
25
+ return originalGetSourceFile(fileName, languageVersion, ...rest)
26
+ }
27
+ host.fileExists = (fileName) =>
28
+ fileName === VIRTUAL_FILE_NAME || ts.sys.fileExists(fileName)
29
+ host.readFile = (fileName) =>
30
+ fileName === VIRTUAL_FILE_NAME ? virtualSource : ts.sys.readFile(fileName)
31
+
32
+ const program = ts.createProgram(
33
+ [VIRTUAL_FILE_NAME, GLOBALS_FILE],
34
+ options,
35
+ host,
36
+ )
37
+ const diagnostics = ts.getPreEmitDiagnostics(program)
38
+
39
+ return diagnostics
40
+ .filter((d) => d.file && d.file.fileName === VIRTUAL_FILE_NAME)
41
+ .map((d) => {
42
+ const message = ts.flattenDiagnosticMessageText(d.messageText, '\n')
43
+ const { line } = d.file.getLineAndCharacterOfPosition(d.start)
44
+ return { message, virtualLine: line + 1 }
45
+ })
46
+ }
@@ -0,0 +1,121 @@
1
+ // generateTemplateExpression's twin, for the virtual .ts class body
2
+ // built in buildVirtualPageTs. The REAL compiled template (see
3
+ // codegen/generateTemplateExpression.js) prefixes state reads with
4
+ // "instance." because the render function receives the page instance
5
+ // as a separate closed-over parameter. Inside the virtual class,
6
+ // there is no separate "instance" -- state/props are literal class
7
+ // members -- so the equivalent prefix is "this.".
8
+ export function typedTemplateExpr(node, scope) {
9
+ if (node.type === 'Identifier') {
10
+ if (node.name === '$event' || scope.has(node.name)) return node.name
11
+ return `this.${node.name}`
12
+ }
13
+ if (node.type === 'MemberExpression') {
14
+ return node.computed
15
+ ? `${typedTemplateExpr(node.object, scope)}[${typedTemplateExpr(node.property, scope)}]`
16
+ : `${typedTemplateExpr(node.object, scope)}.${node.property}`
17
+ }
18
+ if (node.type === 'BinaryExpression') {
19
+ return `(${typedTemplateExpr(node.left, scope)} ${node.operator} ${typedTemplateExpr(node.right, scope)})`
20
+ }
21
+ if (node.type === 'UnaryExpression') {
22
+ return `(${node.operator}${typedTemplateExpr(node.argument, scope)})`
23
+ }
24
+ if (node.type === 'AssignmentExpression') {
25
+ return `${typedTemplateExpr(node.target, scope)} = ${typedTemplateExpr(node.value, scope)}`
26
+ }
27
+ if (node.type === 'CallExpression') {
28
+ const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
29
+ return `${typedTemplateExpr(node.callee, scope)}(${args})`
30
+ }
31
+ if (node.type === 'NewExpression') {
32
+ const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
33
+ return `new ${typedTemplateExpr(node.callee, scope)}(${args})`
34
+ }
35
+ if (node.type === 'Literal') {
36
+ return typeof node.value === 'string'
37
+ ? JSON.stringify(node.value)
38
+ : String(node.value)
39
+ }
40
+ throw new Error(`typedTemplateExpr: unsupported node type "${node.type}"`)
41
+ }
42
+
43
+ const EVENT_ATTR_RE = /^on(click|input|change|submit)$/i
44
+
45
+ // Which DOM element type a synthetic $event's `target` should be
46
+ // typed as, keyed by the event name captured from EVENT_ATTR_RE
47
+ // (lowercased). Deliberately narrow -- these are the only event
48
+ // attributes the template grammar currently recognizes at all.
49
+ // Anything not listed falls back to the generic HTMLElement, same as
50
+ // a real framework would for an untyped/unknown handler.
51
+ const EVENT_TARGET_TYPES = {
52
+ input: 'HTMLInputElement',
53
+ change: 'HTMLInputElement',
54
+ submit: 'HTMLFormElement',
55
+ click: 'HTMLElement',
56
+ }
57
+
58
+ // Walks a parsed template AST (from parseTemplate) collecting every
59
+ // bindable expression as a tree of check entries, ready for
60
+ // buildVirtualPageTs to emit into a synthetic __render() method.
61
+ // Entries come in two kinds:
62
+ // { kind: 'check', expr, line, eventType } -- a single expression
63
+ // to typecheck (interpolation, #if condition, dynamic attribute)
64
+ // { kind: 'each', itemName, iterableExpr, line, children } -- an
65
+ // #each block; children is itself a list of these same entries
66
+ // The 'each' kind exists so the emitted TS can wrap its children in
67
+ // a real `for (const f of ...)` -- without an actual declaration for
68
+ // the loop variable, TS has no way to resolve identifiers like `f`
69
+ // inside the block, regardless of what our own scope-tracking says.
70
+ export function collectTemplateChecks(nodes, scope, out) {
71
+ for (const node of nodes) {
72
+ if (node.type === 'Interpolation') {
73
+ out.push({
74
+ kind: 'check',
75
+ expr: typedTemplateExpr(node.expression, scope),
76
+ line: node.line,
77
+ eventType: null,
78
+ })
79
+ } else if (node.type === 'If') {
80
+ out.push({
81
+ kind: 'check',
82
+ expr: typedTemplateExpr(node.condition, scope),
83
+ line: node.line,
84
+ eventType: null,
85
+ })
86
+ collectTemplateChecks(node.children, scope, out)
87
+ } else if (node.type === 'Each') {
88
+ const iterableExpr = typedTemplateExpr(node.iterable, scope)
89
+ const children = []
90
+ collectTemplateChecks(
91
+ node.children,
92
+ new Set([...scope, node.itemName]),
93
+ children,
94
+ )
95
+ out.push({
96
+ kind: 'each',
97
+ itemName: node.itemName,
98
+ iterableExpr,
99
+ line: node.line,
100
+ children,
101
+ })
102
+ } else if (node.type === 'Element') {
103
+ for (const attr of node.attributes) {
104
+ if (!attr.dynamic) continue
105
+ const eventMatch = EVENT_ATTR_RE.exec(attr.name)
106
+ const attrScope = eventMatch
107
+ ? new Set([...scope, '$event', 'event'])
108
+ : scope
109
+ out.push({
110
+ kind: 'check',
111
+ expr: typedTemplateExpr(attr.value, attrScope),
112
+ line: attr.line,
113
+ eventType: eventMatch
114
+ ? (EVENT_TARGET_TYPES[eventMatch[1].toLowerCase()] ?? 'HTMLElement')
115
+ : null,
116
+ })
117
+ }
118
+ collectTemplateChecks(node.children, scope, out)
119
+ }
120
+ }
121
+ }
@@ -0,0 +1,44 @@
1
+ import { parsePageFile } from './parser/parsePageFile.js'
2
+ import { parseTemplate } from './parser/parseTemplate.js'
3
+ import { Lexer } from './lexer/Lexer.js'
4
+ import { Parser } from './parser/Parser.js'
5
+ import {
6
+ buildVirtualPageTs,
7
+ mapVirtualLineToSource,
8
+ } from './typecheck/buildVirtualTs.js'
9
+ import { typecheckSource } from './typecheck/typecheckVirtualFile.js'
10
+
11
+ // Derives the virtual class/interface name from the page's own
12
+ // `page <Name>` declaration (via parsePageFile) -- the same source
13
+ // of truth generatePage already uses for the REAL compiled class --
14
+ // rather than the file's path/basename. File names and page names
15
+ // can legitimately differ (app/pages/post/post-detail.tyx declaring
16
+ // `page PostDetail`), and a kebab-case basename like "post-detail"
17
+ // isn't a valid TS class name -- using it verbatim produces
18
+ // `class post-detail { ... }`, which fails to parse as TypeScript
19
+ // at all and floods the diagnostics list with dozens of
20
+ // cascading-recovery errors, none of which point at anything wrong
21
+ // in the actual .tyx source.
22
+ export function typecheckPage(source) {
23
+ const { pageName, script, template, scriptStartLine } = parsePageFile(source)
24
+
25
+ const pageNode =
26
+ script.trim().length > 0
27
+ ? new Parser(new Lexer(script).tokenize()).parse()
28
+ : { props: [], state: [], computed: [], actions: [], onMount: null }
29
+
30
+ const templateNodes =
31
+ template.trim().length > 0 ? parseTemplate(template) : null
32
+
33
+ const { source: virtualSource, lineMap } = buildVirtualPageTs(
34
+ pageNode,
35
+ pageName,
36
+ templateNodes,
37
+ )
38
+ const diagnostics = typecheckSource(virtualSource)
39
+
40
+ return diagnostics.map((d) => {
41
+ const scriptLine = mapVirtualLineToSource(lineMap, d.virtualLine)
42
+ return { message: d.message, line: scriptLine + scriptStartLine - 1 }
43
+ })
44
+ }