@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
@@ -1,5 +1,5 @@
1
1
  import { JS_GLOBALS, paramNames } from '../codegen/jsGlobals.js'
2
-
2
+ import { joinArrayElements, assignmentPatternSource } from '../codegen/generateExpression.js'
3
3
  // generateTemplateExpression's twin, for the virtual .ts class body
4
4
  // built in buildVirtualPageTs. The REAL compiled template (see
5
5
  // codegen/generateTemplateExpression.js) prefixes state reads with
@@ -19,6 +19,14 @@ function unaryPrefix(operator) {
19
19
  return /^[a-z]/i.test(operator) ? `${operator} ` : operator
20
20
  }
21
21
 
22
+ // `5.toFixed(1)` is a syntax error; `(5).toFixed(1)` is not.
23
+ function memberObject(node, scope) {
24
+ const src = typedTemplateExpr(node, scope)
25
+ return node.type === 'Literal' && typeof node.value === 'number'
26
+ ? `(${src})`
27
+ : src
28
+ }
29
+
22
30
  export function typedTemplateExpr(node, scope) {
23
31
  if (node.type === 'Identifier') {
24
32
  if (node.name === '$event' || scope.has(node.name)) return node.name
@@ -28,9 +36,9 @@ export function typedTemplateExpr(node, scope) {
28
36
  }
29
37
  if (node.type === 'MemberExpression') {
30
38
  if (node.computed) {
31
- return `${typedTemplateExpr(node.object, scope)}${node.optional ? '?.' : ''}[${typedTemplateExpr(node.property, scope)}]`
39
+ return `${memberObject(node.object, scope)}${node.optional ? '?.' : ''}[${typedTemplateExpr(node.property, scope)}]`
32
40
  }
33
- return `${typedTemplateExpr(node.object, scope)}${node.optional ? '?.' : '.'}${node.property}`
41
+ return `${memberObject(node.object, scope)}${node.optional ? '?.' : '.'}${node.property}`
34
42
  }
35
43
  if (node.type === 'BinaryExpression') {
36
44
  return `(${typedTemplateExpr(node.left, scope)} ${node.operator} ${typedTemplateExpr(node.right, scope)})`
@@ -38,6 +46,23 @@ export function typedTemplateExpr(node, scope) {
38
46
  if (node.type === 'UnaryExpression') {
39
47
  return `(${unaryPrefix(node.operator)}${typedTemplateExpr(node.argument, scope)})`
40
48
  }
49
+ if (node.type === 'UpdateExpression') {
50
+ const arg = typedTemplateExpr(node.argument, scope)
51
+ return node.prefix ? `(${node.operator}${arg})` : `(${arg}${node.operator})`
52
+ }
53
+
54
+ // `(a, b)` -- the comma operator.
55
+ if (node.type === 'SequenceExpression') {
56
+ return `(${node.expressions.map((e) => typedTemplateExpr(e, scope)).join(', ')})`
57
+ }
58
+
59
+ // The casts are the whole point of the virtual file: keep them.
60
+ if (node.type === 'AsExpression') {
61
+ return `(${typedTemplateExpr(node.expression, scope)} ${node.keyword ?? 'as'} ${node.typeAnnotation})`
62
+ }
63
+ if (node.type === 'NonNullExpression') {
64
+ return `${typedTemplateExpr(node.expression, scope)}!`
65
+ }
41
66
 
42
67
  if (node.type === 'AwaitExpression') {
43
68
  return `(await ${typedTemplateExpr(node.argument, scope)})`
@@ -51,44 +76,61 @@ export function typedTemplateExpr(node, scope) {
51
76
  return `(${typedTemplateExpr(node.left, scope)} ?? ${typedTemplateExpr(node.right, scope)})`
52
77
  }
53
78
 
54
- if (node.type === 'AssignmentExpression') {
55
- return `(${typedTemplateExpr(node.target, scope)} = ${typedTemplateExpr(node.value, scope)})`
56
- }
57
- if (node.type === 'CallExpression') {
58
- const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
59
- return `${typedTemplateExpr(node.callee, scope)}${node.optional ? '?.' : ''}(${args})`
60
- }
61
- if (node.type === 'NewExpression') {
62
- const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
63
- return `new ${typedTemplateExpr(node.callee, scope)}(${args})`
64
- }
79
+ if (node.type === 'AssignmentExpression') {
80
+ const isPattern =
81
+ node.target.type === 'ObjectExpression' || node.target.type === 'ArrayExpression'
82
+ const target = isPattern
83
+ ? assignmentPatternSource(node.target, (n) => typedTemplateExpr(n, scope))
84
+ : typedTemplateExpr(node.target, scope)
85
+ return `(${target} = ${typedTemplateExpr(node.value, scope)})`
86
+ }
87
+ if (node.type === 'CallExpression') {
88
+ const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
89
+ const typeArgs = node.typeArgs ? `<${node.typeArgs}>` : ''
90
+ return `${typedTemplateExpr(node.callee, scope)}${node.optional ? '?.' : ''}${typeArgs}(${args})`
91
+ }
92
+ if (node.type === 'NewExpression') {
93
+ const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
94
+ const typeArgs = node.typeArgs ? `<${node.typeArgs}>` : ''
95
+ return `new ${typedTemplateExpr(node.callee, scope)}${typeArgs}(${args})`
96
+ }
65
97
 
66
- // Arrow params are typed `any` unless annotated, matching what
67
- // generateExpression does in typed mode. Params become locals, so
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.
98
+ // Arrow params are typed `any` (`any[]` for rest) unless annotated,
99
+ // matching what generateExpression does in typed mode. Params become
100
+ // locals, so they are referenced bare in the body. Destructured/rest
101
+ // params are stored as source strings; paramNames() extracts the
102
+ // names they bind. Defaults are checked in the arrow's own scope.
71
103
  if (node.type === 'ArrowFunctionExpression') {
104
+ if (node.body.type === 'BlockStatement') {
105
+ throw new Error(
106
+ 'Block-bodied arrow functions (x => { ... }) are not allowed in templates; use an expression body or move the code into an action',
107
+ )
108
+ }
72
109
  const innerScope = new Set([...scope, ...paramNames(node.params)])
73
110
  const types = node.paramTypes ?? node.params.map(() => null)
74
111
  const defaults = node.paramDefaults ?? []
112
+ const optionals = node.paramOptional ?? []
75
113
  const params = node.params
76
114
  .map((name, i) => {
77
- const base = `${name}: ${types[i] ?? 'any'}`
115
+ const fallback = name.startsWith('...') ? 'any[]' : 'any'
116
+ const optional = optionals[i] && !defaults[i] ? '?' : ''
117
+ const base = `${name}${optional}: ${types[i] ?? fallback}`
78
118
  return defaults[i]
79
119
  ? `${base} = ${typedTemplateExpr(defaults[i], innerScope)}`
80
120
  : base
81
121
  })
82
122
  .join(', ')
83
123
  const asyncPrefix = node.isAsync ? 'async ' : ''
84
- return `(${asyncPrefix}(${params}) => (${typedTemplateExpr(node.body, innerScope)}))`
124
+ const returnType = node.returnType ? `: ${node.returnType}` : ''
125
+ return `(${asyncPrefix}${node.typeParams ?? ''}(${params})${returnType} => (${typedTemplateExpr(node.body, innerScope)}))`
85
126
  }
86
127
 
128
+ // Holes (`null` elements) become empty slots: [1, , 3]
87
129
  if (node.type === 'ArrayExpression') {
88
- const elements = node.elements
89
- .map((e) => typedTemplateExpr(e, scope))
90
- .join(', ')
91
- return `[${elements}]`
130
+ const parts = node.elements.map((e) =>
131
+ e === null ? '' : typedTemplateExpr(e, scope),
132
+ )
133
+ return `[${joinArrayElements(parts)}]`
92
134
  }
93
135
 
94
136
  if (node.type === 'ObjectExpression') {
@@ -97,7 +139,7 @@ export function typedTemplateExpr(node, scope) {
97
139
  if (p.spread) return `...${typedTemplateExpr(p.value, scope)}`
98
140
  if (p.method) {
99
141
  throw new Error(
100
- 'Method shorthand ({ fn() {} }) is only allowed in script code, not in template expressions',
142
+ 'Methods and getters/setters in object literals ({ fn() {} }, { get x() {} }) are only allowed in script code, not in template expressions',
101
143
  )
102
144
  }
103
145
  const keySrc = p.keyExpr
@@ -124,11 +166,30 @@ export function typedTemplateExpr(node, scope) {
124
166
  return `\`${body}\``
125
167
  }
126
168
 
169
+ // tag`text ${x}` -- text parts are emitted as written (`raw`).
170
+ if (node.type === 'TaggedTemplateExpression') {
171
+ const body = node.quasi.parts
172
+ .map((part) =>
173
+ part.type === 'text'
174
+ ? (part.raw ?? escapeTemplateText(part.value))
175
+ : `\${${typedTemplateExpr(part.expression, scope)}}`,
176
+ )
177
+ .join('')
178
+ return `${typedTemplateExpr(node.tag, scope)}\`${body}\``
179
+ }
180
+
127
181
  if (node.type === 'Literal') {
128
182
  return typeof node.value === 'string'
129
183
  ? JSON.stringify(node.value)
130
184
  : String(node.value)
131
185
  }
186
+
187
+ if (node.type === 'ClassExpression') {
188
+ throw new Error(
189
+ 'Classes are only allowed in script code, not in template expressions',
190
+ )
191
+ }
192
+
132
193
  throw new Error(`typedTemplateExpr: unsupported node type "${node.type}"`)
133
194
  }
134
195
 
@@ -189,7 +250,9 @@ const EVENT_TYPES = {
189
250
  }
190
251
 
191
252
  function eventTypesFor(eventName) {
192
- return EVENT_TYPES[eventName.toLowerCase()] ?? ['Event', 'HTMLElement']
253
+ return Object.hasOwn(EVENT_TYPES, eventName.toLowerCase())
254
+ ? EVENT_TYPES[eventName.toLowerCase()]
255
+ : ['Event', 'HTMLElement']
193
256
  }
194
257
 
195
258
  // Walks a parsed template AST (from parseTemplate) collecting every
@@ -1,13 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateExpression } from "./generateExpression.js";
4
- import { ArrayExpr, Literal } from "../ast/nodes.js";
5
-
6
- test("generates an empty array literal", () => {
7
- assert.equal(generateExpression(ArrayExpr([])), "[]");
8
- });
9
-
10
- test("generates an array literal with literal elements", () => {
11
- const node = ArrayExpr([Literal(1), Literal(2), Literal("x")]);
12
- assert.equal(generateExpression(node), '[1, 2, "x"]');
13
- });
@@ -1,19 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateExpression } from "./generateExpression.js";
4
- import { CallExpr, MemberExpr, Identifier, Literal } from "../ast/nodes.js";
5
-
6
- test("generates a call with no arguments", () => {
7
- const node = CallExpr(MemberExpr(Identifier("this"), "load"), []);
8
- assert.equal(generateExpression(node), "this.load()");
9
- });
10
-
11
- test("generates a call with multiple arguments", () => {
12
- const node = CallExpr(Identifier("remove"), [Literal(1), Literal("x")]);
13
- assert.equal(generateExpression(node), 'remove(1, "x")');
14
- });
15
-
16
- test("generates a call with a member-expression argument", () => {
17
- const node = CallExpr(Identifier("remove"), [MemberExpr(Identifier("post"), "id")]);
18
- assert.equal(generateExpression(node), "remove(post.id)");
19
- });
@@ -1,59 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateExpression } from "./generateExpression.js";
4
- import {
5
- Literal,
6
- Identifier,
7
- MemberExpr,
8
- BinaryExpr,
9
- AssignmentExpr,
10
- } from "../ast/nodes.js";
11
-
12
- test("generates a number literal", () => {
13
- assert.equal(generateExpression(Literal(42)), "42");
14
- });
15
-
16
- test("generates a string literal as a properly quoted JS string", () => {
17
- assert.equal(generateExpression(Literal("hello")), '"hello"');
18
- });
19
-
20
- test("generates an identifier", () => {
21
- assert.equal(generateExpression(Identifier("count")), "count");
22
- });
23
-
24
- test("generates a member expression", () => {
25
- const node = MemberExpr(Identifier("this"), "count");
26
- assert.equal(generateExpression(node), "this.count");
27
- });
28
-
29
- test("generates a chained member expression", () => {
30
- const node = MemberExpr(MemberExpr(Identifier("this"), "state"), "count");
31
- assert.equal(generateExpression(node), "this.state.count");
32
- });
33
-
34
- test("generates a binary expression wrapped in parens", () => {
35
- const node = BinaryExpr("+", Identifier("count"), Literal(1));
36
- assert.equal(generateExpression(node), "(count + 1)");
37
- });
38
-
39
- test("generates a nested binary expression", () => {
40
- const node = BinaryExpr("*", BinaryExpr("+", Identifier("a"), Identifier("b")), Literal(2));
41
- assert.equal(generateExpression(node), "((a + b) * 2)");
42
- });
43
-
44
- test("generates an assignment expression", () => {
45
- const node = AssignmentExpr(MemberExpr(Identifier("this"), "count"), Literal(0));
46
- assert.equal(generateExpression(node), "this.count = 0");
47
- });
48
-
49
- test("generates an assignment with a binary expression value", () => {
50
- const node = AssignmentExpr(
51
- MemberExpr(Identifier("this"), "count"),
52
- BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
53
- );
54
- assert.equal(generateExpression(node), "this.count = (this.count + 1)");
55
- });
56
-
57
- test("throws on an unknown node type", () => {
58
- assert.throws(() => generateExpression({ type: "Bogus" }), /unknown node type "Bogus"/);
59
- });
@@ -1,37 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateMethod } from "./generateMethod.js";
4
- import { Parser } from "../parser/Parser.js";
5
- import { Lexer } from "../lexer/Lexer.js";
6
-
7
- test("generates a real async method that awaits a resolved promise", async () => {
8
- const source = `
9
- action
10
- async load() {
11
- const value = await this.fetchValue()
12
- this.result = value
13
- }`;
14
- const page = new Parser(new Lexer(source).tokenize()).parse();
15
- const methodSource = generateMethod(page.actions[0]);
16
-
17
- const classSource = `class Test {
18
- constructor() { this.result = null; }
19
- async fetchValue() { return 42; }
20
- ${methodSource}
21
- }`;
22
- const TestClass = new Function(`return ${classSource}`)();
23
- const instance = new TestClass();
24
- await instance.load();
25
- assert.equal(instance.result, 42);
26
- });
27
-
28
- test("generates an object literal argument correctly", () => {
29
- const source = `
30
- action
31
- async save() {
32
- await this.post({ method: "POST", id: 5 })
33
- }`;
34
- const page = new Parser(new Lexer(source).tokenize()).parse();
35
- const methodSource = generateMethod(page.actions[0]);
36
- assert.match(methodSource, /this\.post\(\{ "method": "POST", "id": 5 \}\)/);
37
- });
@@ -1,20 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateMethod } from "./generateMethod.js";
4
- import { Parser } from "../parser/Parser.js";
5
- import { Lexer } from "../lexer/Lexer.js";
6
-
7
- test("generates a real if/else branch that executes correctly", () => {
8
- const source = `action\ncheck(ok) {\n if (ok) {\n this.result = "yes"\n } else {\n this.result = "no"\n }\n}`;
9
- const page = new Parser(new Lexer(source).tokenize()).parse();
10
- const methodSource = generateMethod(page.actions[0]);
11
-
12
- const classSource = `class Test { constructor() { this.result = null; } ${methodSource} }`;
13
- const TestClass = new Function(`return ${classSource}`)();
14
- const instance = new TestClass();
15
-
16
- instance.check(true);
17
- assert.equal(instance.result, "yes");
18
- instance.check(false);
19
- assert.equal(instance.result, "no");
20
- });
@@ -1,81 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateMethod } from "./generateMethod.js";
4
- import {
5
- MethodNode,
6
- ReturnStatement,
7
- ExpressionStatement,
8
- AssignmentExpr,
9
- BinaryExpr,
10
- MemberExpr,
11
- Identifier,
12
- Literal,
13
- } from "../ast/nodes.js";
14
-
15
- test("generates a zero-parameter method with a single return statement", () => {
16
- const node = MethodNode(
17
- "doubled",
18
- [],
19
- [ReturnStatement(BinaryExpr("*", MemberExpr(Identifier("this"), "count"), Literal(2)))]
20
- );
21
-
22
- const code = generateMethod(node);
23
- assert.equal(code, " doubled() {\n return (this.count * 2);\n }");
24
- });
25
-
26
- test("generates a method with parameters", () => {
27
- // Params are { name, typeAnnotation } objects, the same shape the
28
- // parser produces.
29
- const node = MethodNode("setCount", [{ name: "value", typeAnnotation: null }], [
30
- ExpressionStatement(AssignmentExpr(MemberExpr(Identifier("this"), "count"), Identifier("value"))),
31
- ]);
32
-
33
- const code = generateMethod(node);
34
- assert.equal(code, " setCount(value) {\n this.count = value;\n }");
35
- });
36
-
37
- test("generates a method with multiple statements", () => {
38
- const node = MethodNode(
39
- "increment",
40
- [],
41
- [
42
- ExpressionStatement(
43
- AssignmentExpr(
44
- MemberExpr(Identifier("this"), "count"),
45
- BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
46
- )
47
- ),
48
- ReturnStatement(MemberExpr(Identifier("this"), "count")),
49
- ]
50
- );
51
-
52
- const code = generateMethod(node);
53
- assert.equal(
54
- code,
55
- " increment() {\n this.count = (this.count + 1);\n return this.count;\n }"
56
- );
57
- });
58
-
59
- test("the generated method source is valid, executable JavaScript", () => {
60
- const node = MethodNode(
61
- "increment",
62
- [],
63
- [
64
- ExpressionStatement(
65
- AssignmentExpr(
66
- MemberExpr(Identifier("this"), "count"),
67
- BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
68
- )
69
- ),
70
- ]
71
- );
72
-
73
- const methodSource = generateMethod(node);
74
- const classSource = `class Test { ${methodSource} }`;
75
- const TestClass = new Function(`return ${classSource}`)();
76
-
77
- const instance = new TestClass();
78
- instance.count = 5;
79
- instance.increment();
80
- assert.equal(instance.count, 6);
81
- });
@@ -1,46 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generatePage } from "./generatePage.js";
4
- import { reactive } from "../runtime/reactive.js";
5
- import { Parser } from "../parser/Parser.js";
6
- import { Lexer } from "../lexer/Lexer.js";
7
-
8
- function buildPageClass(source) {
9
- const page = new Parser(new Lexer(source).tokenize()).parse();
10
- const classSource = generatePage(page, "Page");
11
- return new Function("reactive", `return ${classSource}`)(reactive);
12
- }
13
-
14
- // onMount is not invoked from the constructor: the host awaits
15
- // __ready() (so capabilities are loaded) and then calls __onMount().
16
- test("onMount does not run on construction", () => {
17
- const Page = buildPageClass(`state\ncount: 0\nonMount\nthis.count = 99`);
18
-
19
- const instance = new Page();
20
- assert.equal(instance.count, 0);
21
- });
22
-
23
- test("onMount runs when the host calls __onMount()", () => {
24
- const Page = buildPageClass(`state\ncount: 0\nonMount\nthis.count = 99`);
25
-
26
- const instance = new Page();
27
- instance.__onMount();
28
- assert.equal(instance.count, 99);
29
- });
30
-
31
- test("async onMount can await before setting state", async () => {
32
- const source = `state\ndata: 0\nonMount\nasync {\n const value = await this.fetchIt()\n this.data = value\n}`;
33
- const page = new Parser(new Lexer(source).tokenize()).parse();
34
- const classSource = generatePage(page, "Page");
35
-
36
- const PageClass = new Function(
37
- "reactive",
38
- `const Page = ${classSource};
39
- Page.prototype.fetchIt = async function () { return 123; };
40
- return Page;`
41
- )(reactive);
42
-
43
- const instance = new PageClass();
44
- await instance.__onMount();
45
- assert.equal(instance.data, 123);
46
- });
@@ -1,138 +0,0 @@
1
- import { test } from 'node:test'
2
- import assert from 'node:assert/strict'
3
- import { generatePage } from './generatePage.js'
4
- import { reactive, effect } from '../runtime/reactive.js'
5
- import { Parser } from '../parser/Parser.js'
6
- import { Lexer } from '../lexer/Lexer.js'
7
-
8
- function compileAndLoad(source, className = 'Page') {
9
- const tokens = new Lexer(source).tokenize()
10
- const page = new Parser(tokens).parse()
11
- const classSource = generatePage(page, className)
12
- // reactive must be in scope for the generated class body to run
13
- return new Function('reactive', `return ${classSource}`)(reactive)
14
- }
15
-
16
- test('generates working state initializers for array, object, and null values, not just numbers/strings', () => {
17
- const source = `
18
- state
19
- items: []
20
- config: { enabled: true }
21
- selectedId: null
22
- `
23
- const Page = compileAndLoad(source, 'TestPage')
24
- const instance = new Page()
25
-
26
- assert.deepEqual(instance.items, [])
27
- assert.deepEqual(instance.config, { enabled: true })
28
- assert.equal(instance.selectedId, null)
29
- })
30
-
31
- test('generates a class with reactive state accessible via this.<name>', () => {
32
- const Page = compileAndLoad(`state { count: 0 }`)
33
- const instance = new Page()
34
- assert.equal(instance.count, 0)
35
- instance.count = 5
36
- assert.equal(instance.count, 5)
37
- })
38
-
39
- test('state writes trigger reactive effects (proves no manual re-render wiring needed)', () => {
40
- const Page = compileAndLoad(`state { count: 0 }`)
41
- const instance = new Page()
42
- let seen = null
43
-
44
- effect(() => {
45
- seen = instance.count
46
- })
47
-
48
- assert.equal(seen, 0)
49
- instance.count = 42
50
- assert.equal(seen, 42)
51
- })
52
-
53
- test('generates working action methods that mutate state', () => {
54
- const source = `
55
- state { count: 0 }
56
- action {
57
- increment() {
58
- this.count = this.count + 1;
59
- }
60
- }`
61
- const Page = compileAndLoad(source)
62
- const instance = new Page()
63
-
64
- instance.increment()
65
- assert.equal(instance.count, 1)
66
- instance.increment()
67
- assert.equal(instance.count, 2)
68
- })
69
-
70
- test('generates working computed getters derived from state', () => {
71
- const source = `
72
- state { count: 3 }
73
- computed {
74
- doubled() {
75
- return this.count * 2;
76
- }
77
- }`
78
- const Page = compileAndLoad(source)
79
- const instance = new Page()
80
-
81
- assert.equal(instance.doubled, 6)
82
- instance.count = 10
83
- assert.equal(instance.doubled, 20)
84
- })
85
-
86
- test('computed getters are reactive when read inside an effect', () => {
87
- const source = `
88
- state { count: 3 }
89
- computed {
90
- doubled() {
91
- return this.count * 2;
92
- }
93
- }`
94
- const Page = compileAndLoad(source)
95
- const instance = new Page()
96
- let seenDoubled = null
97
-
98
- effect(() => {
99
- seenDoubled = instance.doubled
100
- })
101
-
102
- assert.equal(seenDoubled, 6)
103
- instance.count = 5
104
- assert.equal(seenDoubled, 10)
105
- })
106
-
107
- test('generates a full realistic counter page end to end', () => {
108
- const source = `
109
- state { count: 0 }
110
- computed {
111
- doubled() {
112
- return this.count * 2;
113
- }
114
- }
115
- action {
116
- increment() {
117
- this.count = this.count + 1;
118
- }
119
- reset() {
120
- this.count = 0;
121
- }
122
- }`
123
- const Page = compileAndLoad(source, 'Counter')
124
- const instance = new Page()
125
-
126
- assert.equal(instance.count, 0)
127
- assert.equal(instance.doubled, 0)
128
-
129
- instance.increment()
130
- instance.increment()
131
- instance.increment()
132
-
133
- assert.equal(instance.count, 3)
134
- assert.equal(instance.doubled, 6)
135
-
136
- instance.reset()
137
- assert.equal(instance.count, 0)
138
- })
@@ -1,31 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateStatement } from "./generateStatement.js";
4
- import {
5
- ReturnStatement,
6
- ExpressionStatement,
7
- AssignmentExpr,
8
- BinaryExpr,
9
- MemberExpr,
10
- Identifier,
11
- Literal,
12
- } from "../ast/nodes.js";
13
-
14
- test("generates a return statement", () => {
15
- const node = ReturnStatement(BinaryExpr("*", MemberExpr(Identifier("this"), "count"), Literal(2)));
16
- assert.equal(generateStatement(node), "return (this.count * 2);");
17
- });
18
-
19
- test("generates an expression statement wrapping an assignment", () => {
20
- const node = ExpressionStatement(
21
- AssignmentExpr(
22
- MemberExpr(Identifier("this"), "count"),
23
- BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
24
- )
25
- );
26
- assert.equal(generateStatement(node), "this.count = (this.count + 1);");
27
- });
28
-
29
- test("throws on an unknown statement type", () => {
30
- assert.throws(() => generateStatement({ type: "Bogus" }), /unknown node type "Bogus"/);
31
- });