@tylix/compiler 0.3.5 → 0.3.6
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/package.json +1 -1
- package/src/ast/nodes.js +34 -1
- package/src/ast/substituteCapabilityRefs.js +162 -0
- package/src/codegen/generateCapability.js +49 -0
- package/src/codegen/generatePage.js +73 -7
- package/src/index.js +2 -0
- package/src/lexer/Lexer.js +12 -0
- package/src/lexer/tokenTypes.js +21 -0
- package/src/parser/Parser.js +200 -8
- package/src/parser/parsePageFile.js +1 -1
- package/src/renderPageDocument.js +90 -10
- package/src/runtime/capability.js +61 -0
- package/src/typecheckPage.js +4 -2
- package/test/dashboard-syntax.test.js +116 -0
package/package.json
CHANGED
package/src/ast/nodes.js
CHANGED
|
@@ -4,13 +4,46 @@
|
|
|
4
4
|
* later, the Analyzer) can switch on it without instanceof checks.
|
|
5
5
|
*/
|
|
6
6
|
export function PageNode({
|
|
7
|
+
title = null,
|
|
8
|
+
layout = null,
|
|
9
|
+
needs = [],
|
|
7
10
|
props = [],
|
|
8
11
|
state = [],
|
|
12
|
+
uses = [],
|
|
13
|
+
prefetch = [],
|
|
14
|
+
background = [],
|
|
15
|
+
permissions = [],
|
|
16
|
+
meta = [],
|
|
9
17
|
computed = [],
|
|
10
18
|
actions = [],
|
|
11
19
|
onMount = null,
|
|
12
20
|
}) {
|
|
13
|
-
return {
|
|
21
|
+
return {
|
|
22
|
+
type: 'Page',
|
|
23
|
+
title,
|
|
24
|
+
layout,
|
|
25
|
+
needs,
|
|
26
|
+
props,
|
|
27
|
+
state,
|
|
28
|
+
uses,
|
|
29
|
+
prefetch,
|
|
30
|
+
background,
|
|
31
|
+
permissions,
|
|
32
|
+
meta,
|
|
33
|
+
computed,
|
|
34
|
+
actions,
|
|
35
|
+
onMount,
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function CapabilityRefNode(capability, member, args = null) {
|
|
40
|
+
// args === null means it's a bare reference (needs/uses entries: `Auth`)
|
|
41
|
+
// args !== null (possibly []) means it's a call (prefetch/background: `Posts.latest`, `Posts.search("x")`)
|
|
42
|
+
return { type: 'CapabilityRef', capability, member, args }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function MetaEntryNode(key, value) {
|
|
46
|
+
return { type: 'MetaEntry', key, value }
|
|
14
47
|
}
|
|
15
48
|
|
|
16
49
|
export function PropNode(name, propType, optional = false) {
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { Identifier, MemberExpr } from './nodes.js'
|
|
2
|
+
|
|
3
|
+
function rewriteExpr(node, capabilityNames) {
|
|
4
|
+
if (node == null) return node
|
|
5
|
+
switch (node.type) {
|
|
6
|
+
case 'Identifier':
|
|
7
|
+
return capabilityNames.has(node.name)
|
|
8
|
+
? MemberExpr(Identifier('this'), node.name)
|
|
9
|
+
: node
|
|
10
|
+
case 'MemberExpression':
|
|
11
|
+
return {
|
|
12
|
+
...node,
|
|
13
|
+
object: rewriteExpr(node.object, capabilityNames),
|
|
14
|
+
property: node.computed
|
|
15
|
+
? rewriteExpr(node.property, capabilityNames)
|
|
16
|
+
: node.property,
|
|
17
|
+
}
|
|
18
|
+
case 'CallExpression':
|
|
19
|
+
return {
|
|
20
|
+
...node,
|
|
21
|
+
callee: rewriteExpr(node.callee, capabilityNames),
|
|
22
|
+
args: node.args.map((a) => rewriteExpr(a, capabilityNames)),
|
|
23
|
+
}
|
|
24
|
+
case 'AssignmentExpression':
|
|
25
|
+
return {
|
|
26
|
+
...node,
|
|
27
|
+
target: rewriteExpr(node.target, capabilityNames),
|
|
28
|
+
value: rewriteExpr(node.value, capabilityNames),
|
|
29
|
+
}
|
|
30
|
+
case 'BinaryExpression':
|
|
31
|
+
return {
|
|
32
|
+
...node,
|
|
33
|
+
left: rewriteExpr(node.left, capabilityNames),
|
|
34
|
+
right: rewriteExpr(node.right, capabilityNames),
|
|
35
|
+
}
|
|
36
|
+
case 'UnaryExpression':
|
|
37
|
+
return { ...node, argument: rewriteExpr(node.argument, capabilityNames) }
|
|
38
|
+
case 'AwaitExpression':
|
|
39
|
+
return { ...node, argument: rewriteExpr(node.argument, capabilityNames) }
|
|
40
|
+
case 'TernaryExpression':
|
|
41
|
+
return {
|
|
42
|
+
...node,
|
|
43
|
+
condition: rewriteExpr(node.condition, capabilityNames),
|
|
44
|
+
consequent: rewriteExpr(node.consequent, capabilityNames),
|
|
45
|
+
alternate: rewriteExpr(node.alternate, capabilityNames),
|
|
46
|
+
}
|
|
47
|
+
case 'NullishCoalescingExpression':
|
|
48
|
+
return {
|
|
49
|
+
...node,
|
|
50
|
+
left: rewriteExpr(node.left, capabilityNames),
|
|
51
|
+
right: rewriteExpr(node.right, capabilityNames),
|
|
52
|
+
}
|
|
53
|
+
case 'ArrowFunctionExpression':
|
|
54
|
+
return { ...node, body: rewriteExpr(node.body, capabilityNames) }
|
|
55
|
+
case 'ArrayExpression':
|
|
56
|
+
return {
|
|
57
|
+
...node,
|
|
58
|
+
elements: node.elements.map((e) => rewriteExpr(e, capabilityNames)),
|
|
59
|
+
}
|
|
60
|
+
case 'ObjectExpression':
|
|
61
|
+
return {
|
|
62
|
+
...node,
|
|
63
|
+
properties: node.properties.map((p) => ({
|
|
64
|
+
...p,
|
|
65
|
+
value: rewriteExpr(p.value, capabilityNames),
|
|
66
|
+
})),
|
|
67
|
+
}
|
|
68
|
+
default:
|
|
69
|
+
return node
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function rewriteStatement(stmt, capabilityNames) {
|
|
74
|
+
switch (stmt.type) {
|
|
75
|
+
case 'ExpressionStatement':
|
|
76
|
+
return {
|
|
77
|
+
...stmt,
|
|
78
|
+
expression: rewriteExpr(stmt.expression, capabilityNames),
|
|
79
|
+
}
|
|
80
|
+
case 'ReturnStatement':
|
|
81
|
+
return { ...stmt, argument: rewriteExpr(stmt.argument, capabilityNames) }
|
|
82
|
+
case 'VariableDeclaration':
|
|
83
|
+
return { ...stmt, init: rewriteExpr(stmt.init, capabilityNames) }
|
|
84
|
+
case 'IfStatement':
|
|
85
|
+
return {
|
|
86
|
+
...stmt,
|
|
87
|
+
condition: rewriteExpr(stmt.condition, capabilityNames),
|
|
88
|
+
consequent: stmt.consequent.map((s) =>
|
|
89
|
+
rewriteStatement(s, capabilityNames),
|
|
90
|
+
),
|
|
91
|
+
alternate: stmt.alternate
|
|
92
|
+
? stmt.alternate.map((s) => rewriteStatement(s, capabilityNames))
|
|
93
|
+
: null,
|
|
94
|
+
}
|
|
95
|
+
case 'ForInStatement':
|
|
96
|
+
return {
|
|
97
|
+
...stmt,
|
|
98
|
+
iterable: rewriteExpr(stmt.iterable, capabilityNames),
|
|
99
|
+
body: stmt.body.map((s) => rewriteStatement(s, capabilityNames)),
|
|
100
|
+
}
|
|
101
|
+
case 'ForRangeStatement':
|
|
102
|
+
return {
|
|
103
|
+
...stmt,
|
|
104
|
+
start: rewriteExpr(stmt.start, capabilityNames),
|
|
105
|
+
end: rewriteExpr(stmt.end, capabilityNames),
|
|
106
|
+
body: stmt.body.map((s) => rewriteStatement(s, capabilityNames)),
|
|
107
|
+
}
|
|
108
|
+
case 'RepeatStatement':
|
|
109
|
+
return {
|
|
110
|
+
...stmt,
|
|
111
|
+
count: rewriteExpr(stmt.count, capabilityNames),
|
|
112
|
+
body: stmt.body.map((s) => rewriteStatement(s, capabilityNames)),
|
|
113
|
+
}
|
|
114
|
+
case 'TryStatement':
|
|
115
|
+
return {
|
|
116
|
+
...stmt,
|
|
117
|
+
tryBlock: stmt.tryBlock.map((s) =>
|
|
118
|
+
rewriteStatement(s, capabilityNames),
|
|
119
|
+
),
|
|
120
|
+
catchBlock: stmt.catchBlock
|
|
121
|
+
? stmt.catchBlock.map((s) => rewriteStatement(s, capabilityNames))
|
|
122
|
+
: null,
|
|
123
|
+
finallyBlock: stmt.finallyBlock
|
|
124
|
+
? stmt.finallyBlock.map((s) => rewriteStatement(s, capabilityNames))
|
|
125
|
+
: null,
|
|
126
|
+
}
|
|
127
|
+
case 'BreakStatement':
|
|
128
|
+
case 'ContinueStatement':
|
|
129
|
+
return stmt
|
|
130
|
+
default:
|
|
131
|
+
return stmt
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function substituteCapabilityRefs(pageNode) {
|
|
136
|
+
const capabilityNames = new Set([
|
|
137
|
+
...(pageNode.uses ?? []).map((u) => u.name),
|
|
138
|
+
...(pageNode.needs ?? []).map((n) => n.name),
|
|
139
|
+
...(pageNode.background ?? []).map((b) => b.name),
|
|
140
|
+
])
|
|
141
|
+
if (capabilityNames.size === 0) return pageNode
|
|
142
|
+
|
|
143
|
+
return {
|
|
144
|
+
...pageNode,
|
|
145
|
+
computed: (pageNode.computed ?? []).map((c) => ({
|
|
146
|
+
...c,
|
|
147
|
+
body: c.body.map((s) => rewriteStatement(s, capabilityNames)),
|
|
148
|
+
})),
|
|
149
|
+
actions: (pageNode.actions ?? []).map((a) => ({
|
|
150
|
+
...a,
|
|
151
|
+
body: a.body.map((s) => rewriteStatement(s, capabilityNames)),
|
|
152
|
+
})),
|
|
153
|
+
onMount: pageNode.onMount
|
|
154
|
+
? {
|
|
155
|
+
...pageNode.onMount,
|
|
156
|
+
body: pageNode.onMount.body.map((s) =>
|
|
157
|
+
rewriteStatement(s, capabilityNames),
|
|
158
|
+
),
|
|
159
|
+
}
|
|
160
|
+
: null,
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { generateExpression } from './generateExpression.js'
|
|
2
|
+
import { generateStatement } from './generateStatement.js'
|
|
3
|
+
import { generateMethod } from './generateMethod.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Compiles a capability AST (see Parser.parseCapability) into a
|
|
7
|
+
* defineCapability(name, def) call.
|
|
8
|
+
*
|
|
9
|
+
* Unlike generatePage's class output, there's no reactive() wrapping
|
|
10
|
+
* here and no accessor pairs -- resolveCapability (runtime/capability.js)
|
|
11
|
+
* handles wrapping entry.def.state in reactive() itself on first
|
|
12
|
+
* resolution, so state is emitted as a plain object literal, and
|
|
13
|
+
* actions/init are emitted as plain (unbound) methods that
|
|
14
|
+
* resolveCapability binds to the reactive instance at resolve time.
|
|
15
|
+
*
|
|
16
|
+
* action entries reuse generateMethod as-is -- its `name(params) {
|
|
17
|
+
* body }` output is valid both as a class method (generatePage's use)
|
|
18
|
+
* and as ES6 object-method shorthand (this file's use), so there's no
|
|
19
|
+
* need for a second, parallel method-body codegen path here.
|
|
20
|
+
*/
|
|
21
|
+
export function generateCapability(capabilityNode) {
|
|
22
|
+
const stateProps = capabilityNode.state
|
|
23
|
+
.map((s) => ` ${s.name}: ${generateExpression(s.value)},`)
|
|
24
|
+
.join('\n')
|
|
25
|
+
|
|
26
|
+
const actionMethods = capabilityNode.actions
|
|
27
|
+
.map((a) => ` ${generateMethod(a)},`)
|
|
28
|
+
.join('\n')
|
|
29
|
+
|
|
30
|
+
const initMethod = capabilityNode.init
|
|
31
|
+
? (() => {
|
|
32
|
+
const body = capabilityNode.init.body
|
|
33
|
+
.map((stmt) => ` ${generateStatement(stmt)}`)
|
|
34
|
+
.join('\n')
|
|
35
|
+
const asyncPrefix = capabilityNode.init.isAsync ? 'async ' : ''
|
|
36
|
+
return ` ${asyncPrefix}init() {\n${body}\n },`
|
|
37
|
+
})()
|
|
38
|
+
: ''
|
|
39
|
+
|
|
40
|
+
return `defineCapability(${JSON.stringify(capabilityNode.name)}, {
|
|
41
|
+
state: {
|
|
42
|
+
${stateProps}
|
|
43
|
+
},
|
|
44
|
+
actions: {
|
|
45
|
+
${actionMethods}
|
|
46
|
+
},
|
|
47
|
+
${initMethod}
|
|
48
|
+
});`
|
|
49
|
+
}
|
|
@@ -7,12 +7,17 @@ import { generateExpression } from './generateExpression.js'
|
|
|
7
7
|
* `this.count` reads/writes go through the reactive() proxy and
|
|
8
8
|
* correctly trigger dependent effects (template re-renders, computed
|
|
9
9
|
* re-evaluation) without any special-casing in the method codegen.
|
|
10
|
+
* - uses entries become read-only getters that resolve a named
|
|
11
|
+
* capability from the shared runtime registry -- unlike state,
|
|
12
|
+
* there's no matching setter, since capabilities are singletons
|
|
13
|
+
* owned by the registry, not per-page instance data.
|
|
10
14
|
* - computed entries become plain getters (their body already contains
|
|
11
15
|
* a `return` statement from the parser).
|
|
12
16
|
* - action entries become plain instance methods.
|
|
13
17
|
*
|
|
14
|
-
* The generated class expects `reactive` to be
|
|
15
|
-
* module is evaluated (imported from
|
|
18
|
+
* The generated class expects `reactive` and `resolveCapability` to be
|
|
19
|
+
* in scope where the module is evaluated (imported from
|
|
20
|
+
* @tylix/compiler's runtime).
|
|
16
21
|
*/
|
|
17
22
|
export function generatePage(pageNode, className = 'Page', target = 'client') {
|
|
18
23
|
const propAssignments = pageNode.props
|
|
@@ -34,6 +39,36 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
|
|
|
34
39
|
)
|
|
35
40
|
.join('\n\n')
|
|
36
41
|
|
|
42
|
+
// pageNode.uses may be absent on older/pre-capability ASTs (e.g.
|
|
43
|
+
// anything compiled before this field existed), so default to []
|
|
44
|
+
// rather than assuming every caller has been updated.
|
|
45
|
+
// pageNode.uses/needs/background may each name capabilities the page
|
|
46
|
+
// reads from directly (Auth.user, Theme.mode, etc.) -- substituteCapabilityRefs
|
|
47
|
+
// already treats all three as the same "capability name" pool when
|
|
48
|
+
// rewriting bare references to `this.<Name>`, so the getters generated
|
|
49
|
+
// here must cover the same pool, not just `uses` alone, or a
|
|
50
|
+
// needs-only or background-only capability resolves to undefined at
|
|
51
|
+
// runtime with no compile-time signal that anything's wrong.
|
|
52
|
+
const capabilityRefs = [
|
|
53
|
+
...(pageNode.uses ?? []),
|
|
54
|
+
...(pageNode.needs ?? []),
|
|
55
|
+
...(pageNode.background ?? []),
|
|
56
|
+
]
|
|
57
|
+
const seenCapabilities = new Set()
|
|
58
|
+
const uniqueCapabilityRefs = capabilityRefs.filter((c) => {
|
|
59
|
+
if (seenCapabilities.has(c.name)) return false
|
|
60
|
+
seenCapabilities.add(c.name)
|
|
61
|
+
return true
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
const usesAccessors = uniqueCapabilityRefs
|
|
65
|
+
.map(
|
|
66
|
+
(u) => ` get ${u.name}() {
|
|
67
|
+
return resolveCapability(${JSON.stringify(u.name)});
|
|
68
|
+
}`,
|
|
69
|
+
)
|
|
70
|
+
.join('\n\n')
|
|
71
|
+
|
|
37
72
|
const computedGetters = pageNode.computed
|
|
38
73
|
.map((c) => {
|
|
39
74
|
const body = c.body
|
|
@@ -47,13 +82,44 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
|
|
|
47
82
|
.map((a) => generateMethod(a))
|
|
48
83
|
.join('\n\n')
|
|
49
84
|
|
|
85
|
+
const needsResolution = (pageNode.needs ?? [])
|
|
86
|
+
.map(
|
|
87
|
+
(n) => ` await resolveCapability(${JSON.stringify(n.name)}).ready();`,
|
|
88
|
+
)
|
|
89
|
+
.join('\n')
|
|
90
|
+
|
|
91
|
+
const prefetchResolution = (pageNode.prefetch ?? [])
|
|
92
|
+
.map((p) => {
|
|
93
|
+
const argsSrc = p.args
|
|
94
|
+
? p.args.map((a) => generateExpression(a)).join(', ')
|
|
95
|
+
: ''
|
|
96
|
+
return ` await resolveCapability(${JSON.stringify(p.capability)}).${p.member}(${argsSrc});`
|
|
97
|
+
})
|
|
98
|
+
.join('\n')
|
|
99
|
+
|
|
100
|
+
const backgroundResolution = (pageNode.background ?? [])
|
|
101
|
+
.map((b) => ` resolveCapability(${JSON.stringify(b.name)});`) // fire-and-forget, no await
|
|
102
|
+
.join('\n')
|
|
103
|
+
|
|
104
|
+
const readyBody = [needsResolution, prefetchResolution]
|
|
105
|
+
.filter(Boolean)
|
|
106
|
+
.join('\n')
|
|
107
|
+
|
|
108
|
+
const readyMethod = readyBody ? ` async __ready() {\n${readyBody}\n }` : ''
|
|
109
|
+
|
|
50
110
|
// onMount is only ever emitted into the class at all when
|
|
51
111
|
// generating for the client bundle. Server-side (SSR) output never
|
|
52
112
|
// contains the onMount call OR its method body -- there's no
|
|
53
113
|
// runtime guard to rely on, because the code simply isn't there.
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
114
|
+
//
|
|
115
|
+
// IMPORTANT: onMount is no longer invoked from inside the
|
|
116
|
+
// constructor. Pages that declare `needs` capabilities must have
|
|
117
|
+
// those capabilities' async init() fully resolved (via __ready())
|
|
118
|
+
// before onMount runs, or onMount's own logic (e.g. redirecting
|
|
119
|
+
// based on Auth.user) races against that resolution and reads
|
|
120
|
+
// stale/uninitialized capability state. The caller (renderPageDocument.js)
|
|
121
|
+
// is responsible for awaiting __ready() and then calling __onMount()
|
|
122
|
+
// explicitly, in that order.
|
|
57
123
|
const onMountMethod =
|
|
58
124
|
pageNode.onMount && target === 'client'
|
|
59
125
|
? (() => {
|
|
@@ -70,9 +136,9 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
|
|
|
70
136
|
${propAssignments ? propAssignments + '\n' : ''} this.__state = reactive({
|
|
71
137
|
${stateInit}
|
|
72
138
|
});
|
|
73
|
-
${
|
|
139
|
+
${backgroundResolution ? backgroundResolution + '\n' : ''} }
|
|
74
140
|
|
|
75
|
-
${[stateAccessors, computedGetters, actionMethods, onMountMethod].filter(Boolean).join('\n\n')}
|
|
141
|
+
${[stateAccessors, usesAccessors, computedGetters, actionMethods, readyMethod, onMountMethod].filter(Boolean).join('\n\n')}
|
|
76
142
|
}`
|
|
77
143
|
}
|
|
78
144
|
|
package/src/index.js
CHANGED
|
@@ -19,3 +19,5 @@ export * from './typecheckPage.js'
|
|
|
19
19
|
export * from './typecheck/transpileHelperSource.js'
|
|
20
20
|
export * from './imports/extractImports.js'
|
|
21
21
|
export * from './imports/resolvePackageComponents.js'
|
|
22
|
+
export * from './runtime/capability.js'
|
|
23
|
+
export * from './codegen/generateCapability.js'
|
package/src/lexer/Lexer.js
CHANGED
|
@@ -356,6 +356,18 @@ export class Lexer {
|
|
|
356
356
|
this.pos++
|
|
357
357
|
}
|
|
358
358
|
const text = this.source.slice(start, this.pos)
|
|
359
|
+
|
|
360
|
+
const unitMatch = /^(ms|s|m|h|d)/.exec(this.source.slice(this.pos))
|
|
361
|
+
if (
|
|
362
|
+
unitMatch &&
|
|
363
|
+
!/[A-Za-z0-9_$]/.test(this.source[this.pos + unitMatch[0].length] ?? '')
|
|
364
|
+
) {
|
|
365
|
+
const unit = unitMatch[0]
|
|
366
|
+
this.pos += unit.length
|
|
367
|
+
this.pushToken(TokenType.DURATION, `${text}${unit}`)
|
|
368
|
+
return
|
|
369
|
+
}
|
|
370
|
+
|
|
359
371
|
this.pushToken(TokenType.NUMBER, Number(text))
|
|
360
372
|
}
|
|
361
373
|
|
package/src/lexer/tokenTypes.js
CHANGED
|
@@ -8,7 +8,17 @@ export const TokenType = {
|
|
|
8
8
|
ACTION: 'ACTION',
|
|
9
9
|
TEMPLATE: 'TEMPLATE',
|
|
10
10
|
PROPS: 'PROPS',
|
|
11
|
+
USES: 'USES',
|
|
12
|
+
CAPABILITY: 'CAPABILITY',
|
|
13
|
+
INIT: 'INIT',
|
|
11
14
|
ONMOUNT: 'ONMOUNT',
|
|
15
|
+
NEEDS: 'NEEDS',
|
|
16
|
+
PREFETCH: 'PREFETCH',
|
|
17
|
+
BACKGROUND: 'BACKGROUND',
|
|
18
|
+
PERMISSIONS: 'PERMISSIONS',
|
|
19
|
+
META: 'META',
|
|
20
|
+
TITLE: 'TITLE',
|
|
21
|
+
DURATION: 'DURATION',
|
|
12
22
|
NEW: 'NEW',
|
|
13
23
|
TRY: 'TRY',
|
|
14
24
|
CATCH: 'CATCH',
|
|
@@ -96,6 +106,17 @@ export const KEYWORDS = {
|
|
|
96
106
|
action: TokenType.ACTION,
|
|
97
107
|
template: TokenType.TEMPLATE,
|
|
98
108
|
props: TokenType.PROPS,
|
|
109
|
+
uses: TokenType.USES,
|
|
110
|
+
capability: TokenType.CAPABILITY,
|
|
111
|
+
init: TokenType.INIT,
|
|
112
|
+
title: TokenType.TITLE,
|
|
113
|
+
layout: TokenType.LAYOUT,
|
|
114
|
+
needs: TokenType.NEEDS,
|
|
115
|
+
prefetch: TokenType.PREFETCH,
|
|
116
|
+
background: TokenType.BACKGROUND,
|
|
117
|
+
permissions: TokenType.PERMISSIONS,
|
|
118
|
+
meta: TokenType.META,
|
|
119
|
+
actions: TokenType.ACTION,
|
|
99
120
|
onMount: TokenType.ONMOUNT,
|
|
100
121
|
new: TokenType.NEW,
|
|
101
122
|
return: TokenType.RETURN,
|
package/src/parser/Parser.js
CHANGED
|
@@ -32,6 +32,8 @@ import {
|
|
|
32
32
|
RepeatStatement,
|
|
33
33
|
BreakStatement,
|
|
34
34
|
ContinueStatement,
|
|
35
|
+
CapabilityRefNode,
|
|
36
|
+
MetaEntryNode,
|
|
35
37
|
} from '../ast/nodes.js'
|
|
36
38
|
import { parseExpressionString } from './parseExpressionString.js'
|
|
37
39
|
|
|
@@ -101,6 +103,7 @@ export class Parser {
|
|
|
101
103
|
state: [],
|
|
102
104
|
computed: [],
|
|
103
105
|
actions: [],
|
|
106
|
+
uses: [],
|
|
104
107
|
onMount: null,
|
|
105
108
|
}
|
|
106
109
|
|
|
@@ -111,12 +114,38 @@ export class Parser {
|
|
|
111
114
|
page.state = this.parseSectionBlock(this.parseStateEntry.bind(this))
|
|
112
115
|
} else if (this.match(TokenType.COMPUTED)) {
|
|
113
116
|
page.computed = this.parseSectionBlock(this.parseMethod.bind(this))
|
|
117
|
+
} else if (this.match(TokenType.USES)) {
|
|
118
|
+
page.uses = this.parseSectionBlock(this.parseUsesEntry.bind(this))
|
|
114
119
|
} else if (this.match(TokenType.ACTION)) {
|
|
115
120
|
page.actions = this.parseSectionBlock(this.parseMethod.bind(this))
|
|
116
121
|
} else if (this.check(TokenType.ONMOUNT)) {
|
|
117
122
|
const startLine = this.peek().line
|
|
118
123
|
this.advance()
|
|
119
124
|
page.onMount = { ...this.parseOnMountBody(), line: startLine }
|
|
125
|
+
} else if (this.match(TokenType.TITLE)) {
|
|
126
|
+
page.title = this.expect(
|
|
127
|
+
TokenType.STRING,
|
|
128
|
+
"Expected a string after 'title'",
|
|
129
|
+
).value
|
|
130
|
+
} else if (this.match(TokenType.LAYOUT)) {
|
|
131
|
+
page.layout = this.expect(
|
|
132
|
+
TokenType.IDENTIFIER,
|
|
133
|
+
'Expected a layout component name',
|
|
134
|
+
).value
|
|
135
|
+
} else if (this.match(TokenType.NEEDS)) {
|
|
136
|
+
page.needs = this.parseSectionBlock(this.parseUsesEntry.bind(this))
|
|
137
|
+
} else if (this.match(TokenType.PREFETCH)) {
|
|
138
|
+
page.prefetch = this.parseSectionBlock(
|
|
139
|
+
this.parseCapabilityRefEntry.bind(this),
|
|
140
|
+
)
|
|
141
|
+
} else if (this.match(TokenType.BACKGROUND)) {
|
|
142
|
+
page.background = this.parseSectionBlock(this.parseUsesEntry.bind(this))
|
|
143
|
+
} else if (this.match(TokenType.PERMISSIONS)) {
|
|
144
|
+
page.permissions = this.parseSectionBlock(
|
|
145
|
+
this.parsePermissionEntry.bind(this),
|
|
146
|
+
)
|
|
147
|
+
} else if (this.match(TokenType.META)) {
|
|
148
|
+
page.meta = this.parseSectionBlock(this.parseMetaEntry.bind(this))
|
|
120
149
|
} else {
|
|
121
150
|
throw new Error(
|
|
122
151
|
`Unexpected token ${this.peek().type} at line ${this.peek().line}`,
|
|
@@ -139,7 +168,7 @@ export class Parser {
|
|
|
139
168
|
return { body, isAsync }
|
|
140
169
|
}
|
|
141
170
|
const body = []
|
|
142
|
-
while (!this.
|
|
171
|
+
while (!this.isAtSectionBoundary()) {
|
|
143
172
|
body.push(this.parseStatement())
|
|
144
173
|
}
|
|
145
174
|
return { body, isAsync }
|
|
@@ -166,23 +195,73 @@ export class Parser {
|
|
|
166
195
|
isSectionKeyword(type) {
|
|
167
196
|
return (
|
|
168
197
|
type === TokenType.PROPS ||
|
|
198
|
+
type === TokenType.USES ||
|
|
169
199
|
type === TokenType.STATE ||
|
|
170
200
|
type === TokenType.COMPUTED ||
|
|
171
201
|
type === TokenType.ACTION ||
|
|
172
202
|
type === TokenType.ONMOUNT ||
|
|
203
|
+
type === TokenType.INIT ||
|
|
173
204
|
type === TokenType.EOF
|
|
174
205
|
)
|
|
175
206
|
}
|
|
176
207
|
|
|
208
|
+
// These five double as ordinary field names in practice (title
|
|
209
|
+
// especially), so unlike the keywords above they can't be trusted as
|
|
210
|
+
// section boundaries on token type alone -- isAtSectionBoundary below
|
|
211
|
+
// checks the following token to disambiguate.
|
|
212
|
+
isAmbiguousSectionKeyword(type) {
|
|
213
|
+
return (
|
|
214
|
+
type === TokenType.TITLE ||
|
|
215
|
+
type === TokenType.LAYOUT ||
|
|
216
|
+
type === TokenType.NEEDS ||
|
|
217
|
+
type === TokenType.PREFETCH ||
|
|
218
|
+
type === TokenType.BACKGROUND ||
|
|
219
|
+
type === TokenType.PERMISSIONS ||
|
|
220
|
+
type === TokenType.META
|
|
221
|
+
)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
isAtSectionBoundary() {
|
|
225
|
+
const type = this.peek().type
|
|
226
|
+
if (this.isSectionKeyword(type)) return true
|
|
227
|
+
if (this.isAmbiguousSectionKeyword(type)) {
|
|
228
|
+
const next = this.tokens[this.pos + 1]
|
|
229
|
+
// Followed by ':' or '(' means it's a field/prop/method name in
|
|
230
|
+
// the CURRENT block (e.g. `title: ""`, `title(Type): ""`), not
|
|
231
|
+
// the start of a new section.
|
|
232
|
+
return !(
|
|
233
|
+
next &&
|
|
234
|
+
(next.type === TokenType.COLON || next.type === TokenType.LPAREN)
|
|
235
|
+
)
|
|
236
|
+
}
|
|
237
|
+
return false
|
|
238
|
+
}
|
|
239
|
+
|
|
177
240
|
parseBareBlock(parseEntry) {
|
|
178
241
|
const entries = []
|
|
179
|
-
while (!this.
|
|
242
|
+
while (!this.isAtSectionBoundary()) {
|
|
180
243
|
entries.push(parseEntry())
|
|
181
244
|
this.match(TokenType.COMMA)
|
|
182
245
|
}
|
|
183
246
|
return entries
|
|
184
247
|
}
|
|
185
248
|
|
|
249
|
+
// Shared by parseStateEntry/parsePropEntry/parseMethod: a keyword
|
|
250
|
+
// token (title, layout, needs, etc.) is a perfectly valid field/prop/
|
|
251
|
+
// method name once we're past the section-boundary check above --
|
|
252
|
+
// same allowance parsePropertyName already makes for `.title` access.
|
|
253
|
+
parseNameToken(message) {
|
|
254
|
+
const token = this.peek()
|
|
255
|
+
if (
|
|
256
|
+
token.type === TokenType.IDENTIFIER ||
|
|
257
|
+
KEYWORD_TOKEN_TYPES.has(token.type)
|
|
258
|
+
) {
|
|
259
|
+
this.advance()
|
|
260
|
+
return token.value
|
|
261
|
+
}
|
|
262
|
+
throw new Error(`${message} at line ${token.line}, got ${token.type}`)
|
|
263
|
+
}
|
|
264
|
+
|
|
186
265
|
parsePropEntry() {
|
|
187
266
|
const startLine = this.peek().line
|
|
188
267
|
const name = this.expect(TokenType.IDENTIFIER, 'Expected prop name').value
|
|
@@ -191,9 +270,72 @@ export class Parser {
|
|
|
191
270
|
const propType = this.parseTypeExpression()
|
|
192
271
|
return { ...PropNode(name, propType, optional), line: startLine }
|
|
193
272
|
}
|
|
273
|
+
|
|
274
|
+
parseUsesEntry() {
|
|
275
|
+
const startLine = this.peek().line
|
|
276
|
+
const token = this.expect(TokenType.IDENTIFIER, 'Expected capability name')
|
|
277
|
+
const name = token.value
|
|
278
|
+
if (!/^[A-Z]/.test(name)) {
|
|
279
|
+
throw new Error(
|
|
280
|
+
`Capability name "${name}" must start with an uppercase letter (line ${startLine})`,
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
return { name, line: startLine }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
parseCapabilityRefEntry() {
|
|
287
|
+
const startLine = this.peek().line
|
|
288
|
+
const capability = this.expect(
|
|
289
|
+
TokenType.IDENTIFIER,
|
|
290
|
+
'Expected a capability name',
|
|
291
|
+
).value
|
|
292
|
+
this.expect(
|
|
293
|
+
TokenType.DOT,
|
|
294
|
+
"Expected '.' after capability name in prefetch entry",
|
|
295
|
+
)
|
|
296
|
+
const member = this.parsePropertyName("after '.'")
|
|
297
|
+
let args = null
|
|
298
|
+
if (this.check(TokenType.LPAREN)) {
|
|
299
|
+
args = this.parseCallArguments()
|
|
300
|
+
}
|
|
301
|
+
return { ...CapabilityRefNode(capability, member, args), line: startLine }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
parsePermissionEntry() {
|
|
305
|
+
const startLine = this.peek().line
|
|
306
|
+
let name = this.expect(
|
|
307
|
+
TokenType.IDENTIFIER,
|
|
308
|
+
'Expected a permission name',
|
|
309
|
+
).value
|
|
310
|
+
while (this.match(TokenType.DOT)) {
|
|
311
|
+
name += '.' + this.parsePropertyName("after '.'")
|
|
312
|
+
}
|
|
313
|
+
return { name, line: startLine }
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
parseMetaEntry() {
|
|
317
|
+
const startLine = this.peek().line
|
|
318
|
+
const key = this.expect(TokenType.IDENTIFIER, 'Expected a meta key').value
|
|
319
|
+
let value
|
|
320
|
+
if (
|
|
321
|
+
this.check(TokenType.STRING) ||
|
|
322
|
+
this.check(TokenType.NUMBER) ||
|
|
323
|
+
this.check(TokenType.DURATION)
|
|
324
|
+
) {
|
|
325
|
+
value = this.advance().value
|
|
326
|
+
} else if (this.check(TokenType.IDENTIFIER)) {
|
|
327
|
+
// true / false, lexed as identifiers per parsePrimary's convention
|
|
328
|
+
const raw = this.advance().value
|
|
329
|
+
value = raw === 'true' ? true : raw === 'false' ? false : raw
|
|
330
|
+
} else {
|
|
331
|
+
throw new Error(`Expected a meta value at line ${this.peek().line}`)
|
|
332
|
+
}
|
|
333
|
+
return { ...MetaEntryNode(key, value), line: startLine }
|
|
334
|
+
}
|
|
335
|
+
|
|
194
336
|
parseStateEntry() {
|
|
195
337
|
const startLine = this.peek().line
|
|
196
|
-
const name = this.
|
|
338
|
+
const name = this.parseNameToken('Expected state name')
|
|
197
339
|
|
|
198
340
|
let typeAnnotation = null
|
|
199
341
|
if (this.match(TokenType.LPAREN)) {
|
|
@@ -218,10 +360,11 @@ export class Parser {
|
|
|
218
360
|
const value = this.parsePrimary()
|
|
219
361
|
return { ...StateNode(name, value, typeAnnotation), line: startLine }
|
|
220
362
|
}
|
|
363
|
+
|
|
221
364
|
parseMethod() {
|
|
222
365
|
const startLine = this.peek().line
|
|
223
366
|
const isAsync = this.match(TokenType.ASYNC)
|
|
224
|
-
const name = this.
|
|
367
|
+
const name = this.parseNameToken('Expected method name')
|
|
225
368
|
this.expect(TokenType.LPAREN, "Expected '(' after method name")
|
|
226
369
|
|
|
227
370
|
const params = []
|
|
@@ -362,6 +505,42 @@ export class Parser {
|
|
|
362
505
|
return node
|
|
363
506
|
}
|
|
364
507
|
|
|
508
|
+
// Parses a capability.tyx file: `capability Name` header, then
|
|
509
|
+
// state/action/init sections. Structurally similar to parse(), but
|
|
510
|
+
// deliberately separate rather than unified -- a capability has no
|
|
511
|
+
// props, no template, and `init` (not `onMount`) is its only
|
|
512
|
+
// lifecycle hook, so sharing parse()'s isSectionKeyword/loop would
|
|
513
|
+
// mean threading capability-only exceptions through page-only logic.
|
|
514
|
+
parseCapability() {
|
|
515
|
+
this.expect(TokenType.CAPABILITY, "Expected 'capability'")
|
|
516
|
+
const name = this.expect(
|
|
517
|
+
TokenType.IDENTIFIER,
|
|
518
|
+
'Expected capability name',
|
|
519
|
+
).value
|
|
520
|
+
|
|
521
|
+
const capability = { name, state: [], actions: [], init: null }
|
|
522
|
+
|
|
523
|
+
while (!this.check(TokenType.EOF)) {
|
|
524
|
+
if (this.match(TokenType.STATE)) {
|
|
525
|
+
capability.state = this.parseSectionBlock(
|
|
526
|
+
this.parseStateEntry.bind(this),
|
|
527
|
+
)
|
|
528
|
+
} else if (this.match(TokenType.ACTION)) {
|
|
529
|
+
capability.actions = this.parseSectionBlock(this.parseMethod.bind(this))
|
|
530
|
+
} else if (this.check(TokenType.INIT)) {
|
|
531
|
+
const startLine = this.peek().line
|
|
532
|
+
this.advance()
|
|
533
|
+
capability.init = { ...this.parseOnMountBody(), line: startLine }
|
|
534
|
+
} else {
|
|
535
|
+
throw new Error(
|
|
536
|
+
`Unexpected token ${this.peek().type} at line ${this.peek().line}`,
|
|
537
|
+
)
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
return capability
|
|
542
|
+
}
|
|
543
|
+
|
|
365
544
|
parseStatementInner() {
|
|
366
545
|
if (this.match(TokenType.RETURN)) {
|
|
367
546
|
const hasValue =
|
|
@@ -568,7 +747,10 @@ export class Parser {
|
|
|
568
747
|
// position.
|
|
569
748
|
tryParseArrowFunction() {
|
|
570
749
|
// single-param form: x => expr or x: Type => expr
|
|
571
|
-
if (
|
|
750
|
+
if (
|
|
751
|
+
this.check(TokenType.IDENTIFIER) ||
|
|
752
|
+
KEYWORD_TOKEN_TYPES.has(this.peek().type)
|
|
753
|
+
) {
|
|
572
754
|
const next = this.tokens[this.pos + 1]
|
|
573
755
|
if (next && next.type === TokenType.ARROW) {
|
|
574
756
|
const param = this.advance().value
|
|
@@ -603,7 +785,10 @@ export class Parser {
|
|
|
603
785
|
|
|
604
786
|
if (!this.check(TokenType.RPAREN)) {
|
|
605
787
|
while (true) {
|
|
606
|
-
if (
|
|
788
|
+
if (
|
|
789
|
+
!this.check(TokenType.IDENTIFIER) &&
|
|
790
|
+
!KEYWORD_TOKEN_TYPES.has(this.peek().type)
|
|
791
|
+
) {
|
|
607
792
|
isValidParamList = false
|
|
608
793
|
break
|
|
609
794
|
}
|
|
@@ -828,7 +1013,10 @@ export class Parser {
|
|
|
828
1013
|
return TemplateLiteralExpr(parts)
|
|
829
1014
|
}
|
|
830
1015
|
|
|
831
|
-
if (
|
|
1016
|
+
if (
|
|
1017
|
+
this.check(TokenType.IDENTIFIER) ||
|
|
1018
|
+
KEYWORD_TOKEN_TYPES.has(this.peek().type)
|
|
1019
|
+
) {
|
|
832
1020
|
const name = this.advance().value
|
|
833
1021
|
// "null"/"true"/"false"/"undefined" are lexed as plain identifier
|
|
834
1022
|
// tokens (there's no separate keyword TokenType for them), but
|
|
@@ -958,9 +1146,13 @@ export class Parser {
|
|
|
958
1146
|
const properties = []
|
|
959
1147
|
while (!this.check(TokenType.RBRACE)) {
|
|
960
1148
|
const isString = this.check(TokenType.STRING)
|
|
1149
|
+
const isKeywordKey =
|
|
1150
|
+
!isString && KEYWORD_TOKEN_TYPES.has(this.peek().type)
|
|
961
1151
|
const key = isString
|
|
962
1152
|
? this.advance().value
|
|
963
|
-
:
|
|
1153
|
+
: isKeywordKey
|
|
1154
|
+
? this.advance().value
|
|
1155
|
+
: this.expect(TokenType.IDENTIFIER, 'Expected an object key').value
|
|
964
1156
|
|
|
965
1157
|
if (!isString && !this.check(TokenType.COLON)) {
|
|
966
1158
|
// Shorthand: { name } means { name: name }
|
|
@@ -79,7 +79,7 @@ export function parsePageFile(source) {
|
|
|
79
79
|
export function findSectionBoundaries(source) {
|
|
80
80
|
const boundaries = []
|
|
81
81
|
const lineStartPattern =
|
|
82
|
-
/(^|\n)[ \t]*(state|computed|action|template|style)\b/g
|
|
82
|
+
/(^|\n)[ \t]*(uses|state|computed|action|template|style)\b/g
|
|
83
83
|
let match
|
|
84
84
|
while ((match = lineStartPattern.exec(source)) !== null) {
|
|
85
85
|
const keyword = match[2]
|
|
@@ -9,12 +9,18 @@ import { Lexer } from './lexer/Lexer.js'
|
|
|
9
9
|
import { Parser } from './parser/Parser.js'
|
|
10
10
|
import { generatePage } from './codegen/generatePage.js'
|
|
11
11
|
import { generateTemplate } from './codegen/generateTemplate.js'
|
|
12
|
+
import { generateCapability } from './codegen/generateCapability.js'
|
|
13
|
+
import { substituteCapabilityRefs } from './ast/substituteCapabilityRefs.js'
|
|
12
14
|
|
|
13
15
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
14
16
|
const RUNTIME_SOURCE = fs
|
|
15
17
|
.readFileSync(path.join(__dirname, 'runtime', 'reactive.js'), 'utf-8')
|
|
16
18
|
.replace(/export\s+/g, '')
|
|
17
19
|
|
|
20
|
+
const CAPABILITY_SOURCE = fs
|
|
21
|
+
.readFileSync(path.join(__dirname, 'runtime', 'capability.js'), 'utf-8')
|
|
22
|
+
.replace(/export\s+/g, '')
|
|
23
|
+
|
|
18
24
|
const LOADING_INDICATOR_SOURCE = fs
|
|
19
25
|
.readFileSync(path.join(__dirname, 'runtime', 'loadingIndicator.js'), 'utf-8')
|
|
20
26
|
.replace(/export\s+/g, '')
|
|
@@ -27,15 +33,67 @@ const USE_CHANNEL_SOURCE = fs
|
|
|
27
33
|
.readFileSync(path.join(__dirname, 'runtime', 'useChannel.js'), 'utf-8')
|
|
28
34
|
.replace(/export\s+/g, '')
|
|
29
35
|
|
|
36
|
+
const capabilityCache = new Map() // capabilitiesDir -> { signature, code }
|
|
37
|
+
|
|
38
|
+
async function loadCapabilityDefinitions(capabilitiesDir) {
|
|
39
|
+
const exists = await fs.promises
|
|
40
|
+
.access(capabilitiesDir)
|
|
41
|
+
.then(() => true)
|
|
42
|
+
.catch(() => false)
|
|
43
|
+
if (!exists) return ''
|
|
44
|
+
|
|
45
|
+
const files = (await fs.promises.readdir(capabilitiesDir)).filter((f) =>
|
|
46
|
+
f.endsWith('.tyx'),
|
|
47
|
+
)
|
|
48
|
+
if (files.length === 0) return ''
|
|
49
|
+
|
|
50
|
+
const stats = await Promise.all(
|
|
51
|
+
files.map((f) => fs.promises.stat(path.join(capabilitiesDir, f))),
|
|
52
|
+
)
|
|
53
|
+
const signature = files
|
|
54
|
+
.map((f, i) => `${f}:${stats[i].mtimeMs}`)
|
|
55
|
+
.sort()
|
|
56
|
+
.join('|')
|
|
57
|
+
|
|
58
|
+
const cached = capabilityCache.get(capabilitiesDir)
|
|
59
|
+
if (cached && cached.signature === signature) {
|
|
60
|
+
return cached.code
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const definitions = (
|
|
64
|
+
await Promise.all(
|
|
65
|
+
files.map(async (file) => {
|
|
66
|
+
const source = await fs.promises.readFile(
|
|
67
|
+
path.join(capabilitiesDir, file),
|
|
68
|
+
'utf-8',
|
|
69
|
+
)
|
|
70
|
+
try {
|
|
71
|
+
const capabilityNode = new Parser(
|
|
72
|
+
new Lexer(source).tokenize(),
|
|
73
|
+
).parseCapability()
|
|
74
|
+
return generateCapability(capabilityNode)
|
|
75
|
+
} catch (err) {
|
|
76
|
+
err.message = `In app/capabilities/${file}: ${err.message}`
|
|
77
|
+
throw err
|
|
78
|
+
}
|
|
79
|
+
}),
|
|
80
|
+
)
|
|
81
|
+
).join('\n\n')
|
|
82
|
+
|
|
83
|
+
capabilityCache.set(capabilitiesDir, { signature, code: definitions })
|
|
84
|
+
return definitions
|
|
85
|
+
}
|
|
86
|
+
|
|
30
87
|
function compileComponentSource(source, fallbackClassName) {
|
|
31
88
|
const isNativeComponent = /^\s*component\s+\w+/.test(source)
|
|
32
89
|
|
|
33
90
|
if (isNativeComponent) {
|
|
34
91
|
const { componentName, script, template } = parseComponentFile(source)
|
|
35
|
-
const pageNode =
|
|
92
|
+
const pageNode = substituteCapabilityRefs(
|
|
36
93
|
script.trim().length > 0
|
|
37
94
|
? new Parser(new Lexer(script).tokenize()).parse()
|
|
38
|
-
: { props: [], state: [], computed: [], actions: [] }
|
|
95
|
+
: { props: [], state: [], computed: [], actions: [], uses: [] },
|
|
96
|
+
)
|
|
39
97
|
|
|
40
98
|
const classSource = generatePage(pageNode, componentName)
|
|
41
99
|
const templateNodes = parseTemplate(template)
|
|
@@ -46,10 +104,11 @@ function compileComponentSource(source, fallbackClassName) {
|
|
|
46
104
|
|
|
47
105
|
const { script, template } = parseComponent(source)
|
|
48
106
|
|
|
49
|
-
const pageNode =
|
|
107
|
+
const pageNode = substituteCapabilityRefs(
|
|
50
108
|
script.trim().length > 0
|
|
51
109
|
? new Parser(new Lexer(script).tokenize()).parse()
|
|
52
|
-
: { props: [], state: [], computed: [], actions: [] }
|
|
110
|
+
: { props: [], state: [], computed: [], actions: [], uses: [] },
|
|
111
|
+
)
|
|
53
112
|
|
|
54
113
|
const classSource = generatePage(pageNode, fallbackClassName)
|
|
55
114
|
const templateNodes = parseTemplate(template)
|
|
@@ -88,10 +147,16 @@ function parseTemplateWithLineOffset(template, offset) {
|
|
|
88
147
|
}
|
|
89
148
|
}
|
|
90
149
|
|
|
91
|
-
export function renderPageDocument(
|
|
150
|
+
export async function renderPageDocument(
|
|
92
151
|
source,
|
|
93
152
|
childComponents = {},
|
|
94
|
-
{
|
|
153
|
+
{
|
|
154
|
+
layout = null,
|
|
155
|
+
props = {},
|
|
156
|
+
apiHelpers = '',
|
|
157
|
+
channelsPort = null,
|
|
158
|
+
capabilitiesDir = path.join(process.cwd(), 'app', 'capabilities'),
|
|
159
|
+
} = {},
|
|
95
160
|
) {
|
|
96
161
|
const {
|
|
97
162
|
pageName,
|
|
@@ -102,16 +167,19 @@ export function renderPageDocument(
|
|
|
102
167
|
templateStartLine,
|
|
103
168
|
} = parsePageFile(source)
|
|
104
169
|
|
|
105
|
-
const pageNode =
|
|
170
|
+
const pageNode = substituteCapabilityRefs(
|
|
106
171
|
script.trim().length > 0
|
|
107
172
|
? parseScriptWithLineOffset(script, scriptStartLine)
|
|
108
|
-
: { props: [], state: [], computed: [], actions: [] }
|
|
173
|
+
: { props: [], state: [], computed: [], actions: [], uses: [] },
|
|
174
|
+
)
|
|
109
175
|
|
|
110
176
|
const classSource = generatePage(pageNode, pageName)
|
|
111
177
|
|
|
112
178
|
const templateNodes = parseTemplateWithLineOffset(template, templateStartLine)
|
|
113
179
|
const { code, rootVar } = generateTemplate(templateNodes)
|
|
114
180
|
|
|
181
|
+
const capabilityDefinitions = await loadCapabilityDefinitions(capabilitiesDir)
|
|
182
|
+
|
|
115
183
|
const childNames = Object.keys(childComponents)
|
|
116
184
|
const childClassSources = childNames
|
|
117
185
|
.map(
|
|
@@ -163,6 +231,10 @@ ${layoutCompiled.code}
|
|
|
163
231
|
const inlineScript = `
|
|
164
232
|
${RUNTIME_SOURCE}
|
|
165
233
|
|
|
234
|
+
${CAPABILITY_SOURCE}
|
|
235
|
+
|
|
236
|
+
${capabilityDefinitions}
|
|
237
|
+
|
|
166
238
|
${LOADING_INDICATOR_SOURCE}
|
|
167
239
|
|
|
168
240
|
${USE_API_SOURCE}
|
|
@@ -181,7 +253,13 @@ document.addEventListener("DOMContentLoaded", () => {
|
|
|
181
253
|
const instance = new ${pageName}(${JSON.stringify(props)});
|
|
182
254
|
const components = {};
|
|
183
255
|
${childRegistrations}
|
|
184
|
-
(function (document, instance, components) {
|
|
256
|
+
(async function (document, instance, components) {
|
|
257
|
+
if (typeof instance.__ready === "function") {
|
|
258
|
+
await instance.__ready();
|
|
259
|
+
}
|
|
260
|
+
if (typeof instance.__onMount === "function") {
|
|
261
|
+
await instance.__onMount();
|
|
262
|
+
}
|
|
185
263
|
${code}
|
|
186
264
|
${layoutMountCode}
|
|
187
265
|
})(document, instance, components);
|
|
@@ -192,6 +270,8 @@ ${layoutMountCode}
|
|
|
192
270
|
|
|
193
271
|
const scriptSegments = [
|
|
194
272
|
{ name: 'runtime (reactive.js)', code: RUNTIME_SOURCE },
|
|
273
|
+
{ name: 'runtime (capability.js)', code: CAPABILITY_SOURCE },
|
|
274
|
+
{ name: 'capability definitions', code: capabilityDefinitions },
|
|
195
275
|
{ name: 'loading indicator', code: LOADING_INDICATOR_SOURCE },
|
|
196
276
|
{ name: 'useApi', code: USE_API_SOURCE },
|
|
197
277
|
{ name: 'useChannel', code: USE_CHANNEL_SOURCE },
|
|
@@ -238,7 +318,7 @@ ${layoutMountCode}
|
|
|
238
318
|
}
|
|
239
319
|
})();
|
|
240
320
|
</script>
|
|
241
|
-
<title>${pageName}</title>
|
|
321
|
+
<title>${pageNode.title ?? pageName}</title>
|
|
242
322
|
<link rel="stylesheet" href="/tailwind.css">
|
|
243
323
|
${styleTag}
|
|
244
324
|
</head>
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Capability registry: singleton, framework-managed state/action
|
|
2
|
+
// bundles that pages access via `uses` (see generatePage.js's
|
|
3
|
+
// usesAccessors, which call resolveCapability(name) as a getter).
|
|
4
|
+
// One instance per capability name, shared across every page in the
|
|
5
|
+
// app -- resolveCapability memoizes on first resolution rather than
|
|
6
|
+
// re-running the def, the same "resolve once, reuse forever" shape
|
|
7
|
+
// createResource's .load() gives resources, just app-scoped instead
|
|
8
|
+
// of per-page.
|
|
9
|
+
//
|
|
10
|
+
// A capability def has the shape:
|
|
11
|
+
// {
|
|
12
|
+
// state: { ... }, // plain object, becomes reactive()
|
|
13
|
+
// actions: { name(...) {} }, // methods; `this` bound to the
|
|
14
|
+
// // reactive instance so they can
|
|
15
|
+
// // read/write state like a page
|
|
16
|
+
// // action can
|
|
17
|
+
// async init() { ... }, // optional, runs once; `this`
|
|
18
|
+
// // bound the same way
|
|
19
|
+
// }
|
|
20
|
+
|
|
21
|
+
const registry = new Map()
|
|
22
|
+
|
|
23
|
+
export function defineCapability(name, def) {
|
|
24
|
+
registry.set(name, { def, instance: null, initPromise: null })
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function bindActions(actions, instance) {
|
|
28
|
+
const bound = {}
|
|
29
|
+
for (const key of Object.keys(actions ?? {})) {
|
|
30
|
+
bound[key] = actions[key].bind(instance)
|
|
31
|
+
}
|
|
32
|
+
return bound
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function resolveCapability(name) {
|
|
36
|
+
const entry = registry.get(name)
|
|
37
|
+
if (!entry) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
`Unknown capability "${name}". Did you forget to register it with defineCapability()?`,
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (!entry.instance) {
|
|
44
|
+
entry.instance = reactive({ ...entry.def.state })
|
|
45
|
+
Object.assign(
|
|
46
|
+
entry.instance,
|
|
47
|
+
bindActions(entry.def.actions, entry.instance),
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (!entry.initPromise && entry.def.init) {
|
|
52
|
+
entry.initPromise = entry.def.init.call(entry.instance)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Exposed so pages can `await Auth.ready()` before making a
|
|
56
|
+
// redirect decision, instead of racing the reactive `loading` flag
|
|
57
|
+
// with their own onMount timing.
|
|
58
|
+
entry.instance.ready = () => entry.initPromise ?? Promise.resolve()
|
|
59
|
+
|
|
60
|
+
return entry.instance
|
|
61
|
+
}
|
package/src/typecheckPage.js
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
mapVirtualLineToSource,
|
|
8
8
|
} from './typecheck/buildVirtualTs.js'
|
|
9
9
|
import { typecheckSource } from './typecheck/typecheckVirtualFile.js'
|
|
10
|
+
import { substituteCapabilityRefs } from './ast/substituteCapabilityRefs.js'
|
|
10
11
|
|
|
11
12
|
// Derives the virtual class/interface name from the page's own
|
|
12
13
|
// `page <Name>` declaration (via parsePageFile) -- the same source
|
|
@@ -22,10 +23,11 @@ import { typecheckSource } from './typecheck/typecheckVirtualFile.js'
|
|
|
22
23
|
export function typecheckPage(source, apiHelpersSource = '') {
|
|
23
24
|
const { pageName, script, template, scriptStartLine } = parsePageFile(source)
|
|
24
25
|
|
|
25
|
-
const pageNode =
|
|
26
|
+
const pageNode = substituteCapabilityRefs(
|
|
26
27
|
script.trim().length > 0
|
|
27
28
|
? new Parser(new Lexer(script).tokenize()).parse()
|
|
28
|
-
: { props: [], state: [], computed: [], actions: [], onMount: null }
|
|
29
|
+
: { props: [], state: [], computed: [], actions: [], onMount: null },
|
|
30
|
+
)
|
|
29
31
|
|
|
30
32
|
const templateNodes =
|
|
31
33
|
template.trim().length > 0 ? parseTemplate(template) : null
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { test } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { parsePageFile } from '../src/parser/parsePageFile.js'
|
|
7
|
+
import { Lexer } from '../src/lexer/Lexer.js'
|
|
8
|
+
import { Parser } from '../src/parser/Parser.js'
|
|
9
|
+
import { generatePage } from '../src/codegen/generatePage.js'
|
|
10
|
+
import { renderPageDocument } from '../src/renderPageDocument.js'
|
|
11
|
+
|
|
12
|
+
const SOURCE = `page Dashboard
|
|
13
|
+
title "Dashboard"
|
|
14
|
+
layout DashboardLayout
|
|
15
|
+
needs
|
|
16
|
+
Auth
|
|
17
|
+
uses
|
|
18
|
+
Theme
|
|
19
|
+
Posts
|
|
20
|
+
prefetch
|
|
21
|
+
Posts.latest
|
|
22
|
+
background
|
|
23
|
+
Analytics
|
|
24
|
+
permissions
|
|
25
|
+
posts.view
|
|
26
|
+
meta
|
|
27
|
+
transition "fade"
|
|
28
|
+
keepAlive true
|
|
29
|
+
cache 10m
|
|
30
|
+
state
|
|
31
|
+
search: ""
|
|
32
|
+
computed
|
|
33
|
+
filteredPosts() {
|
|
34
|
+
return Posts.where(post => post.title.contains(this.search))
|
|
35
|
+
}
|
|
36
|
+
actions
|
|
37
|
+
async publishPost(post) {
|
|
38
|
+
await Posts.publish(post)
|
|
39
|
+
}
|
|
40
|
+
template
|
|
41
|
+
<div>{{ search }}</div>
|
|
42
|
+
`
|
|
43
|
+
|
|
44
|
+
function parseScript() {
|
|
45
|
+
const { script } = parsePageFile(SOURCE)
|
|
46
|
+
const tokens = new Lexer(script).tokenize()
|
|
47
|
+
return new Parser(tokens).parse()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
test('parses all six page-level sections without throwing', () => {
|
|
51
|
+
const page = parseScript()
|
|
52
|
+
|
|
53
|
+
assert.equal(page.title, 'Dashboard')
|
|
54
|
+
assert.equal(page.layout, 'DashboardLayout')
|
|
55
|
+
assert.deepEqual(
|
|
56
|
+
page.needs.map((n) => n.name),
|
|
57
|
+
['Auth'],
|
|
58
|
+
)
|
|
59
|
+
assert.deepEqual(
|
|
60
|
+
page.uses.map((u) => u.name),
|
|
61
|
+
['Theme', 'Posts'],
|
|
62
|
+
)
|
|
63
|
+
assert.equal(page.prefetch[0].capability, 'Posts')
|
|
64
|
+
assert.equal(page.prefetch[0].member, 'latest')
|
|
65
|
+
assert.deepEqual(
|
|
66
|
+
page.background.map((b) => b.name),
|
|
67
|
+
['Analytics'],
|
|
68
|
+
)
|
|
69
|
+
assert.deepEqual(
|
|
70
|
+
page.permissions.map((p) => p.name),
|
|
71
|
+
['posts.view'],
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
const meta = Object.fromEntries(page.meta.map((m) => [m.key, m.value]))
|
|
75
|
+
assert.equal(meta.transition, 'fade')
|
|
76
|
+
assert.equal(meta.keepAlive, true)
|
|
77
|
+
assert.equal(meta.cache, '10m')
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
test('generated page class is syntactically valid JS', () => {
|
|
81
|
+
const page = parseScript()
|
|
82
|
+
const classSource = generatePage(page, 'Dashboard')
|
|
83
|
+
|
|
84
|
+
assert.doesNotThrow(() => new Function(classSource), classSource)
|
|
85
|
+
assert.match(classSource, /async __ready\(\)/)
|
|
86
|
+
assert.match(classSource, /resolveCapability\("Auth"\)\.ready\(\)/)
|
|
87
|
+
assert.match(classSource, /resolveCapability\("Posts"\)\.latest\(\)/)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
test('renderPageDocument compiles the full Dashboard against stub capabilities', async () => {
|
|
91
|
+
const dir = await mkdtemp(path.join(tmpdir(), 'tylix-test-'))
|
|
92
|
+
const capabilitiesDir = path.join(dir, 'capabilities')
|
|
93
|
+
await mkdir(capabilitiesDir, { recursive: true })
|
|
94
|
+
|
|
95
|
+
await writeFile(
|
|
96
|
+
path.join(capabilitiesDir, 'Auth.tyx'),
|
|
97
|
+
`capability Auth\nstate\n user: null\naction\n noop() {}\n`,
|
|
98
|
+
)
|
|
99
|
+
await writeFile(
|
|
100
|
+
path.join(capabilitiesDir, 'Theme.tyx'),
|
|
101
|
+
`capability Theme\nstate\n mode: "dark"\naction\n noop() {}\n`,
|
|
102
|
+
)
|
|
103
|
+
await writeFile(
|
|
104
|
+
path.join(capabilitiesDir, 'Posts.tyx'),
|
|
105
|
+
`capability Posts\nstate\n data: []\naction\n async latest() {}\n where(fn) { return this.data.filter(fn) }\n`,
|
|
106
|
+
)
|
|
107
|
+
await writeFile(
|
|
108
|
+
path.join(capabilitiesDir, 'Analytics.tyx'),
|
|
109
|
+
`capability Analytics\nstate\n visitorsToday: 0\naction\n noop() {}\n`,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
const html = await renderPageDocument(SOURCE, {}, { capabilitiesDir })
|
|
113
|
+
assert.match(html, /<title>Dashboard<\/title>/)
|
|
114
|
+
|
|
115
|
+
await rm(dir, { recursive: true, force: true })
|
|
116
|
+
})
|