@tylix/compiler 0.5.2 → 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.
- package/LICENSE +21 -0
- package/package.json +30 -2
- package/src/ast/nodes.js +219 -16
- package/src/ast/substituteCapabilityRefs.js +185 -61
- package/src/codegen/emitStatementLines.js +98 -54
- package/src/codegen/generateExpression.js +339 -36
- package/src/codegen/generateMethod.js +5 -3
- package/src/codegen/generatePage.js +74 -44
- package/src/codegen/generateStatement.js +169 -20
- package/src/codegen/generateTemplate.js +183 -101
- package/src/codegen/generateTemplateExpression.js +102 -59
- package/src/codegen/jsGlobals.js +211 -0
- package/src/compileComponent.js +39 -8
- package/src/imports/extractImports.js +112 -26
- package/src/imports/resolveImports.js +186 -0
- package/src/index.js +3 -2
- package/src/lexer/Lexer.js +430 -235
- package/src/lexer/tokenTypes.js +32 -7
- package/src/parser/Parser.js +2176 -325
- package/src/parser/languageOptions.js +16 -0
- package/src/parser/parseExpressionString.js +23 -7
- package/src/parser/parsePageFile.js +139 -58
- package/src/parser/parseTemplate.js +350 -62
- package/src/renderPageDocument.js +338 -56
- package/src/runtime/capability.js +39 -17
- package/src/runtime/loadingIndicator.js +91 -29
- package/src/runtime/reactive.js +362 -64
- package/src/runtime/useApi.js +74 -13
- package/src/runtime/useChannel.js +27 -6
- package/src/typecheck/buildVirtualTs.js +23 -12
- package/src/typecheck/tylix-globals.d.ts +23 -4
- package/src/typecheck/typedTemplateExpr.js +195 -53
- package/src/typecheckPage.js +28 -4
- package/src/codegen/generateExpression.array.test.js +0 -13
- package/src/codegen/generateExpression.callexpr.test.js +0 -19
- package/src/codegen/generateExpression.test.js +0 -59
- package/src/codegen/generateMethod.asyncawait.test.js +0 -37
- package/src/codegen/generateMethod.ifstatement.test.js +0 -20
- package/src/codegen/generateMethod.test.js +0 -81
- package/src/codegen/generatePage.onmount.test.js +0 -46
- package/src/codegen/generatePage.test.js +0 -138
- package/src/codegen/generateStatement.test.js +0 -31
- package/src/codegen/generateTemplate.ifeach.test.js +0 -138
- package/src/codegen/generateTemplate.test.js +0 -149
- package/src/codegen/generateTemplateExpression.test.js +0 -34
- package/src/compileComponent.test.js +0 -121
- package/src/imports/resolvePackageComponents.js +0 -41
- package/src/lexer/Lexer.test.js +0 -151
- package/src/parser/Parser.array.test.js +0 -37
- package/src/parser/Parser.asyncawait.test.js +0 -33
- package/src/parser/Parser.ifstatement.test.js +0 -20
- package/src/parser/Parser.onmount.test.js +0 -18
- package/src/parser/Parser.test.js +0 -315
- package/src/parser/parseComponent.test.js +0 -53
- package/src/parser/parsePageFile.test.js +0 -101
- package/src/parser/parseTemplate.ifeach.test.js +0 -33
- package/src/parser/parseTemplate.pre.test.js +0 -39
- package/src/parser/parseTemplate.test.js +0 -112
- package/src/renderPageDocument.test.js +0 -125
- package/src/runtime/reactive.test.js +0 -106
- package/test/dashboard-syntax.test.js +0 -116
|
@@ -1,40 +1,10 @@
|
|
|
1
|
-
import { generateExpression } from './generateExpression.js'
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
'true',
|
|
9
|
-
'false',
|
|
10
|
-
'undefined',
|
|
11
|
-
'NaN',
|
|
12
|
-
'Infinity',
|
|
13
|
-
'Math',
|
|
14
|
-
'JSON',
|
|
15
|
-
'Date',
|
|
16
|
-
'Number',
|
|
17
|
-
'String',
|
|
18
|
-
'Boolean',
|
|
19
|
-
'Array',
|
|
20
|
-
'Object',
|
|
21
|
-
'Set',
|
|
22
|
-
'Map',
|
|
23
|
-
'Intl',
|
|
24
|
-
'Promise',
|
|
25
|
-
'RegExp',
|
|
26
|
-
'Symbol',
|
|
27
|
-
'Error',
|
|
28
|
-
'URL',
|
|
29
|
-
'parseInt',
|
|
30
|
-
'parseFloat',
|
|
31
|
-
'isNaN',
|
|
32
|
-
'isFinite',
|
|
33
|
-
'encodeURIComponent',
|
|
34
|
-
'decodeURIComponent',
|
|
35
|
-
'console',
|
|
36
|
-
'window',
|
|
37
|
-
])
|
|
1
|
+
import { generateExpression, joinArrayElements, assignmentPatternSource } from './generateExpression.js'
|
|
2
|
+
import { JS_GLOBALS, paramNames } from './jsGlobals.js'
|
|
3
|
+
|
|
4
|
+
// JS_GLOBALS (see jsGlobals.js) lists the plain JS/browser globals that
|
|
5
|
+
// templates may use directly. Everything else that isn't a local (each
|
|
6
|
+
// variable, arrow param, $event) is treated as page state/capability
|
|
7
|
+
// and prefixed with "instance.".
|
|
38
8
|
|
|
39
9
|
function escapeTemplateLiteralText(text) {
|
|
40
10
|
return text
|
|
@@ -47,6 +17,14 @@ function unaryPrefix(operator) {
|
|
|
47
17
|
return /^[a-z]/i.test(operator) ? `${operator} ` : operator
|
|
48
18
|
}
|
|
49
19
|
|
|
20
|
+
// `5.toFixed(1)` is a syntax error; `(5).toFixed(1)` is not.
|
|
21
|
+
function memberObject(node, scope) {
|
|
22
|
+
const src = generateTemplateExpression(node, scope)
|
|
23
|
+
return node.type === 'Literal' && typeof node.value === 'number'
|
|
24
|
+
? `(${src})`
|
|
25
|
+
: src
|
|
26
|
+
}
|
|
27
|
+
|
|
50
28
|
export function generateTemplateExpression(node, scope = new Set()) {
|
|
51
29
|
if (node.type === 'Identifier') {
|
|
52
30
|
if (node.name === '$event' || scope.has(node.name)) {
|
|
@@ -63,9 +41,9 @@ export function generateTemplateExpression(node, scope = new Set()) {
|
|
|
63
41
|
|
|
64
42
|
if (node.type === 'MemberExpression') {
|
|
65
43
|
if (node.computed) {
|
|
66
|
-
return `${
|
|
44
|
+
return `${memberObject(node.object, scope)}${node.optional ? '?.' : ''}[${generateTemplateExpression(node.property, scope)}]`
|
|
67
45
|
}
|
|
68
|
-
return `${
|
|
46
|
+
return `${memberObject(node.object, scope)}${node.optional ? '?.' : '.'}${node.property}`
|
|
69
47
|
}
|
|
70
48
|
|
|
71
49
|
if (node.type === 'BinaryExpression') {
|
|
@@ -84,15 +62,39 @@ export function generateTemplateExpression(node, scope = new Set()) {
|
|
|
84
62
|
return `(${unaryPrefix(node.operator)}${generateTemplateExpression(node.argument, scope)})`
|
|
85
63
|
}
|
|
86
64
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
65
|
+
if (node.type === 'UpdateExpression') {
|
|
66
|
+
const arg = generateTemplateExpression(node.argument, scope)
|
|
67
|
+
return node.prefix ? `(${node.operator}${arg})` : `(${arg}${node.operator})`
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// `(a, b)` -- the comma operator.
|
|
71
|
+
if (node.type === 'SequenceExpression') {
|
|
72
|
+
return `(${node.expressions.map((e) => generateTemplateExpression(e, scope)).join(', ')})`
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// `x as T` and `x!` only matter to the typechecker; the real
|
|
76
|
+
// template code is just the inner expression.
|
|
77
|
+
if (node.type === 'AsExpression' || node.type === 'NonNullExpression') {
|
|
78
|
+
return generateTemplateExpression(node.expression, scope)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Only valid inside an `async` arrow (`{{ async () => await ... }}`)
|
|
82
|
+
// or an event handler (which is made async automatically when it
|
|
83
|
+
// contains `await`); a bare `{{ await x }}` in a text/attribute
|
|
84
|
+
// binding would land in a non-async render effect.
|
|
90
85
|
if (node.type === 'AwaitExpression') {
|
|
91
86
|
return `(await ${generateTemplateExpression(node.argument, scope)})`
|
|
92
87
|
}
|
|
93
88
|
|
|
94
|
-
|
|
95
|
-
|
|
89
|
+
// Parenthesized so `ok and count++` -> `(ok && (count = ...))` is
|
|
90
|
+
// valid JS rather than an assignment on the right of `&&`.
|
|
91
|
+
if (node.type === 'AssignmentExpression') {
|
|
92
|
+
const isPattern =
|
|
93
|
+
node.target.type === 'ObjectExpression' || node.target.type === 'ArrayExpression'
|
|
94
|
+
const target = isPattern
|
|
95
|
+
? assignmentPatternSource(node.target, (n) => generateTemplateExpression(n, scope))
|
|
96
|
+
: generateTemplateExpression(node.target, scope)
|
|
97
|
+
return `(${target} = ${generateTemplateExpression(node.value, scope)})`
|
|
96
98
|
}
|
|
97
99
|
|
|
98
100
|
if (node.type === 'CallExpression') {
|
|
@@ -109,34 +111,57 @@ export function generateTemplateExpression(node, scope = new Set()) {
|
|
|
109
111
|
return `new ${generateTemplateExpression(node.callee, scope)}(${args})`
|
|
110
112
|
}
|
|
111
113
|
|
|
112
|
-
// (a, b) => expr -- params become locals for the body, so they
|
|
113
|
-
// referenced bare instead of being prefixed with "instance.".
|
|
114
|
-
//
|
|
115
|
-
//
|
|
114
|
+
// (a, b = 1) => expr -- params become locals for the body, so they
|
|
115
|
+
// are referenced bare instead of being prefixed with "instance.".
|
|
116
|
+
// Params may be destructuring patterns ("[k, v]", "{ id }") or rest
|
|
117
|
+
// params ("...args"); paramNames() extracts the names they bind.
|
|
118
|
+
// Defaults are evaluated in the arrow's own scope. The whole
|
|
119
|
+
// function is parenthesized so it is safe both as a call argument
|
|
120
|
+
// and as an event handler that gets invoked immediately.
|
|
116
121
|
if (node.type === 'ArrowFunctionExpression') {
|
|
117
|
-
|
|
118
|
-
|
|
122
|
+
if (node.body.type === 'BlockStatement') {
|
|
123
|
+
throw new Error(
|
|
124
|
+
'Block-bodied arrow functions (x => { ... }) are not allowed in templates; use an expression body or move the code into an action',
|
|
125
|
+
)
|
|
126
|
+
}
|
|
127
|
+
const innerScope = new Set([...scope, ...paramNames(node.params)])
|
|
128
|
+
const defaults = node.paramDefaults ?? []
|
|
129
|
+
const params = node.params
|
|
130
|
+
.map((name, i) =>
|
|
131
|
+
defaults[i]
|
|
132
|
+
? `${name} = ${generateTemplateExpression(defaults[i], innerScope)}`
|
|
133
|
+
: name,
|
|
134
|
+
)
|
|
135
|
+
.join(', ')
|
|
119
136
|
const body = generateTemplateExpression(node.body, innerScope)
|
|
120
137
|
const asyncPrefix = node.isAsync ? 'async ' : ''
|
|
121
138
|
return `(${asyncPrefix}(${params}) => ${body})`
|
|
122
139
|
}
|
|
123
140
|
|
|
141
|
+
// Holes (`null` elements) become empty slots: [1, , 3]
|
|
124
142
|
if (node.type === 'ArrayExpression') {
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
return `[${
|
|
143
|
+
const parts = node.elements.map((e) =>
|
|
144
|
+
e === null ? '' : generateTemplateExpression(e, scope),
|
|
145
|
+
)
|
|
146
|
+
return `[${joinArrayElements(parts)}]`
|
|
129
147
|
}
|
|
130
148
|
|
|
131
149
|
// Parenthesized so an object literal is never mistaken for a block
|
|
132
150
|
// when it ends up as an arrow function body: x => ({ ... })
|
|
133
151
|
if (node.type === 'ObjectExpression') {
|
|
134
152
|
const properties = node.properties
|
|
135
|
-
.map((p) =>
|
|
136
|
-
p.spread
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
153
|
+
.map((p) => {
|
|
154
|
+
if (p.spread) return `...${generateTemplateExpression(p.value, scope)}`
|
|
155
|
+
if (p.method) {
|
|
156
|
+
throw new Error(
|
|
157
|
+
'Methods and getters/setters in object literals ({ fn() {} }, { get x() {} }) are only allowed in script code, not in template expressions',
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
const keySrc = p.keyExpr
|
|
161
|
+
? `[${generateTemplateExpression(p.keyExpr, scope)}]`
|
|
162
|
+
: JSON.stringify(p.key)
|
|
163
|
+
return `${keySrc}: ${generateTemplateExpression(p.value, scope)}`
|
|
164
|
+
})
|
|
140
165
|
.join(', ')
|
|
141
166
|
return `({ ${properties} })`
|
|
142
167
|
}
|
|
@@ -156,10 +181,28 @@ export function generateTemplateExpression(node, scope = new Set()) {
|
|
|
156
181
|
return `\`${body}\``
|
|
157
182
|
}
|
|
158
183
|
|
|
184
|
+
// tag`text ${x}` -- text parts are emitted as written (`raw`).
|
|
185
|
+
if (node.type === 'TaggedTemplateExpression') {
|
|
186
|
+
const body = node.quasi.parts
|
|
187
|
+
.map((part) =>
|
|
188
|
+
part.type === 'text'
|
|
189
|
+
? (part.raw ?? escapeTemplateLiteralText(part.value))
|
|
190
|
+
: `\${${generateTemplateExpression(part.expression, scope)}}`,
|
|
191
|
+
)
|
|
192
|
+
.join('')
|
|
193
|
+
return `${generateTemplateExpression(node.tag, scope)}\`${body}\``
|
|
194
|
+
}
|
|
195
|
+
|
|
159
196
|
if (node.type === 'Literal') {
|
|
160
197
|
return generateExpression(node)
|
|
161
198
|
}
|
|
162
199
|
|
|
200
|
+
if (node.type === 'ClassExpression') {
|
|
201
|
+
throw new Error(
|
|
202
|
+
'Classes are only allowed in script code, not in template expressions',
|
|
203
|
+
)
|
|
204
|
+
}
|
|
205
|
+
|
|
163
206
|
throw new Error(
|
|
164
207
|
`generateTemplateExpression: unsupported node type "${node.type}" in template expression`,
|
|
165
208
|
)
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
// Single source of truth for plain JS/browser globals that templates may
|
|
2
|
+
// use bare. Everything else (that isn't a local) is page state/props/
|
|
3
|
+
// capability and gets "instance." (or "this." in the virtual .ts).
|
|
4
|
+
//
|
|
5
|
+
// Intentionally NOT listed, because they are common field or capability
|
|
6
|
+
// names: status, name, location, history, event, open, close, print, top,
|
|
7
|
+
// length, parent, screen, Notification, Storage, Request, Response,
|
|
8
|
+
// Image, File, Event, Audio. Use window.location, window.history, etc.
|
|
9
|
+
|
|
10
|
+
export const JS_GLOBALS = new Set([
|
|
11
|
+
// values
|
|
12
|
+
'null',
|
|
13
|
+
'true',
|
|
14
|
+
'false',
|
|
15
|
+
'undefined',
|
|
16
|
+
'NaN',
|
|
17
|
+
'Infinity',
|
|
18
|
+
'globalThis',
|
|
19
|
+
|
|
20
|
+
// environment
|
|
21
|
+
'console',
|
|
22
|
+
'window',
|
|
23
|
+
'document',
|
|
24
|
+
'navigator',
|
|
25
|
+
'performance',
|
|
26
|
+
'crypto',
|
|
27
|
+
'localStorage',
|
|
28
|
+
'sessionStorage',
|
|
29
|
+
'indexedDB',
|
|
30
|
+
'matchMedia',
|
|
31
|
+
'getComputedStyle',
|
|
32
|
+
'getSelection',
|
|
33
|
+
'scrollTo',
|
|
34
|
+
'scrollBy',
|
|
35
|
+
|
|
36
|
+
// Tylix runtime helpers (declared in tylix-globals.d.ts). Without
|
|
37
|
+
// these, `{{ postApi(...) }}` or `onclick="{{ () => notFound() }}"`
|
|
38
|
+
// in a template became `instance.postApi` / `instance.notFound`.
|
|
39
|
+
'useApi',
|
|
40
|
+
'getApi',
|
|
41
|
+
'postApi',
|
|
42
|
+
'putApi',
|
|
43
|
+
'deleteApi',
|
|
44
|
+
'useChannel',
|
|
45
|
+
'notFound',
|
|
46
|
+
|
|
47
|
+
// dialogs
|
|
48
|
+
'alert',
|
|
49
|
+
'confirm',
|
|
50
|
+
'prompt',
|
|
51
|
+
|
|
52
|
+
// timers
|
|
53
|
+
'setTimeout',
|
|
54
|
+
'clearTimeout',
|
|
55
|
+
'setInterval',
|
|
56
|
+
'clearInterval',
|
|
57
|
+
'requestAnimationFrame',
|
|
58
|
+
'cancelAnimationFrame',
|
|
59
|
+
'requestIdleCallback',
|
|
60
|
+
'cancelIdleCallback',
|
|
61
|
+
'queueMicrotask',
|
|
62
|
+
|
|
63
|
+
// network
|
|
64
|
+
'fetch',
|
|
65
|
+
'FormData',
|
|
66
|
+
'URL',
|
|
67
|
+
'URLSearchParams',
|
|
68
|
+
'AbortController',
|
|
69
|
+
'AbortSignal',
|
|
70
|
+
'Headers',
|
|
71
|
+
'WebSocket',
|
|
72
|
+
'EventSource',
|
|
73
|
+
'XMLHttpRequest',
|
|
74
|
+
'BroadcastChannel',
|
|
75
|
+
'Worker',
|
|
76
|
+
'EventTarget',
|
|
77
|
+
|
|
78
|
+
// streams
|
|
79
|
+
'ReadableStream',
|
|
80
|
+
'WritableStream',
|
|
81
|
+
'TransformStream',
|
|
82
|
+
|
|
83
|
+
// core objects (Date and Intl cover toLocaleDateString,
|
|
84
|
+
// Intl.DateTimeFormat, Intl.NumberFormat, ...)
|
|
85
|
+
'Math',
|
|
86
|
+
'JSON',
|
|
87
|
+
'Date',
|
|
88
|
+
'Temporal',
|
|
89
|
+
'Number',
|
|
90
|
+
'String',
|
|
91
|
+
'Boolean',
|
|
92
|
+
'Array',
|
|
93
|
+
'Object',
|
|
94
|
+
'Function',
|
|
95
|
+
'Set',
|
|
96
|
+
'Map',
|
|
97
|
+
'WeakSet',
|
|
98
|
+
'WeakMap',
|
|
99
|
+
'WeakRef',
|
|
100
|
+
'FinalizationRegistry',
|
|
101
|
+
'Promise',
|
|
102
|
+
'RegExp',
|
|
103
|
+
'Symbol',
|
|
104
|
+
'BigInt',
|
|
105
|
+
'Reflect',
|
|
106
|
+
'Proxy',
|
|
107
|
+
'Intl',
|
|
108
|
+
'Atomics',
|
|
109
|
+
'Iterator',
|
|
110
|
+
'WebAssembly',
|
|
111
|
+
|
|
112
|
+
// errors
|
|
113
|
+
'Error',
|
|
114
|
+
'TypeError',
|
|
115
|
+
'RangeError',
|
|
116
|
+
'SyntaxError',
|
|
117
|
+
'ReferenceError',
|
|
118
|
+
'URIError',
|
|
119
|
+
'EvalError',
|
|
120
|
+
'AggregateError',
|
|
121
|
+
'DOMException',
|
|
122
|
+
|
|
123
|
+
// binary / files
|
|
124
|
+
'Blob',
|
|
125
|
+
'FileReader',
|
|
126
|
+
'ArrayBuffer',
|
|
127
|
+
'SharedArrayBuffer',
|
|
128
|
+
'DataView',
|
|
129
|
+
'TextEncoder',
|
|
130
|
+
'TextDecoder',
|
|
131
|
+
'Int8Array',
|
|
132
|
+
'Uint8Array',
|
|
133
|
+
'Uint8ClampedArray',
|
|
134
|
+
'Int16Array',
|
|
135
|
+
'Uint16Array',
|
|
136
|
+
'Int32Array',
|
|
137
|
+
'Uint32Array',
|
|
138
|
+
'Float32Array',
|
|
139
|
+
'Float64Array',
|
|
140
|
+
'BigInt64Array',
|
|
141
|
+
'BigUint64Array',
|
|
142
|
+
|
|
143
|
+
// DOM types
|
|
144
|
+
'HTMLElement',
|
|
145
|
+
'HTMLInputElement',
|
|
146
|
+
'HTMLTextAreaElement',
|
|
147
|
+
'HTMLSelectElement',
|
|
148
|
+
'HTMLOptionElement',
|
|
149
|
+
'HTMLButtonElement',
|
|
150
|
+
'HTMLFormElement',
|
|
151
|
+
'HTMLCanvasElement',
|
|
152
|
+
'HTMLImageElement',
|
|
153
|
+
'HTMLAnchorElement',
|
|
154
|
+
'HTMLDivElement',
|
|
155
|
+
'HTMLSpanElement',
|
|
156
|
+
'HTMLDialogElement',
|
|
157
|
+
'HTMLVideoElement',
|
|
158
|
+
'HTMLAudioElement',
|
|
159
|
+
'HTMLIFrameElement',
|
|
160
|
+
'HTMLTableElement',
|
|
161
|
+
'HTMLLabelElement',
|
|
162
|
+
'SVGElement',
|
|
163
|
+
'Element',
|
|
164
|
+
'Node',
|
|
165
|
+
'NodeList',
|
|
166
|
+
'DocumentFragment',
|
|
167
|
+
'DOMParser',
|
|
168
|
+
'CustomEvent',
|
|
169
|
+
'KeyboardEvent',
|
|
170
|
+
'MouseEvent',
|
|
171
|
+
'PointerEvent',
|
|
172
|
+
'FocusEvent',
|
|
173
|
+
'InputEvent',
|
|
174
|
+
'WheelEvent',
|
|
175
|
+
'DragEvent',
|
|
176
|
+
'TouchEvent',
|
|
177
|
+
'SubmitEvent',
|
|
178
|
+
'ClipboardEvent',
|
|
179
|
+
'MutationObserver',
|
|
180
|
+
'IntersectionObserver',
|
|
181
|
+
'ResizeObserver',
|
|
182
|
+
'CSS',
|
|
183
|
+
|
|
184
|
+
// functions
|
|
185
|
+
'parseInt',
|
|
186
|
+
'parseFloat',
|
|
187
|
+
'isNaN',
|
|
188
|
+
'isFinite',
|
|
189
|
+
'structuredClone',
|
|
190
|
+
'encodeURIComponent',
|
|
191
|
+
'decodeURIComponent',
|
|
192
|
+
'encodeURI',
|
|
193
|
+
'decodeURI',
|
|
194
|
+
'btoa',
|
|
195
|
+
'atob',
|
|
196
|
+
'reportError',
|
|
197
|
+
])
|
|
198
|
+
|
|
199
|
+
// Identifiers follow the same Unicode rules as the Lexer, so a param
|
|
200
|
+
// named `é` or `変数` is still recognised as a local.
|
|
201
|
+
const IDENTIFIER_RE = /^[\p{ID_Start}_$][\p{ID_Continue}$\u200c\u200d]*$/u
|
|
202
|
+
const IDENTIFIER_GLOBAL_RE = /[\p{ID_Start}_$][\p{ID_Continue}$\u200c\u200d]*/gu
|
|
203
|
+
|
|
204
|
+
// Arrow params are stored as source strings ("x", "[k, v]", "{ id }",
|
|
205
|
+
// "...args"). This returns the names those params actually bind, so
|
|
206
|
+
// they can be treated as locals inside the arrow body.
|
|
207
|
+
export function paramNames(params) {
|
|
208
|
+
return params.flatMap((p) =>
|
|
209
|
+
IDENTIFIER_RE.test(p) ? [p] : (p.match(IDENTIFIER_GLOBAL_RE) ?? []),
|
|
210
|
+
)
|
|
211
|
+
}
|
package/src/compileComponent.js
CHANGED
|
@@ -2,10 +2,15 @@ import { parseComponent } from './parser/parseComponent.js'
|
|
|
2
2
|
import { parseTemplate } from './parser/parseTemplate.js'
|
|
3
3
|
import { Lexer } from './lexer/Lexer.js'
|
|
4
4
|
import { Parser } from './parser/Parser.js'
|
|
5
|
+
import { normalizeLanguageOptions } from './parser/languageOptions.js'
|
|
5
6
|
import { generatePage } from './codegen/generatePage.js'
|
|
6
7
|
import { generateTemplate } from './codegen/generateTemplate.js'
|
|
8
|
+
import {
|
|
9
|
+
generateStatement,
|
|
10
|
+
declaredNames,
|
|
11
|
+
} from './codegen/generateStatement.js'
|
|
7
12
|
import { reactive, effect } from './runtime/reactive.js'
|
|
8
|
-
import { useApi } from '
|
|
13
|
+
import { useApi } from './runtime/useApi.js'
|
|
9
14
|
|
|
10
15
|
/**
|
|
11
16
|
* Compiles raw .tyx source into a mountable component descriptor.
|
|
@@ -17,29 +22,55 @@ import { useApi } from '../../core/src/runtime/useApi.js'
|
|
|
17
22
|
* The `components` map passed to mount() lets a template reference
|
|
18
23
|
* other compiled components by capitalized tag name (<Badge />);
|
|
19
24
|
* omit it for components that don't nest anything.
|
|
25
|
+
*
|
|
26
|
+
* `languageOption` takes the same compiler switches as
|
|
27
|
+
* renderPageDocument, e.g. { not: 'loose' }.
|
|
28
|
+
*
|
|
29
|
+
* Module-level declarations in the script (function, const, let,
|
|
30
|
+
* class, enum) are scoped to this component and attached to each
|
|
31
|
+
* instance so the template can call them.
|
|
20
32
|
*/
|
|
21
|
-
export function compileComponent(
|
|
33
|
+
export function compileComponent(
|
|
34
|
+
source,
|
|
35
|
+
className = 'Component',
|
|
36
|
+
languageOption = {},
|
|
37
|
+
) {
|
|
38
|
+
const language = normalizeLanguageOptions(languageOption ?? {})
|
|
22
39
|
const { script, template } = parseComponent(source)
|
|
23
40
|
|
|
24
41
|
const pageNode =
|
|
25
42
|
script.trim().length > 0
|
|
26
|
-
? new Parser(new Lexer(script).tokenize()).parse()
|
|
27
|
-
: { props: [], state: [], computed: [], actions: [] }
|
|
43
|
+
? new Parser(new Lexer(script).tokenize(), language).parse()
|
|
44
|
+
: { props: [], state: [], computed: [], actions: [], helpers: [] }
|
|
28
45
|
|
|
29
46
|
const classSource = generatePage(pageNode, className)
|
|
30
|
-
|
|
47
|
+
|
|
48
|
+
const helpers = pageNode.helpers ?? []
|
|
49
|
+
const helperSource = helpers
|
|
50
|
+
.map((h) => generateStatement(h, false))
|
|
51
|
+
.filter((s) => s.trim().length > 0)
|
|
52
|
+
.join('\n')
|
|
53
|
+
const exposed = helpers
|
|
54
|
+
.flatMap(declaredNames)
|
|
55
|
+
.map((n) => `${JSON.stringify(n)}: ${n}`)
|
|
56
|
+
.join(', ')
|
|
57
|
+
|
|
58
|
+
const { Class: ComponentClass, helperValues } = new Function(
|
|
31
59
|
'reactive',
|
|
32
60
|
'useApi',
|
|
33
|
-
|
|
61
|
+
`${helperSource}\nconst __Class = ${classSource};\nreturn { Class: __Class, helperValues: { ${exposed} } };`,
|
|
34
62
|
)(reactive, useApi)
|
|
35
63
|
|
|
36
|
-
const templateNodes = parseTemplate(template)
|
|
64
|
+
const templateNodes = parseTemplate(template, language)
|
|
37
65
|
const { code, rootVar } = generateTemplate(templateNodes)
|
|
38
66
|
|
|
39
67
|
return {
|
|
40
68
|
ComponentClass,
|
|
41
69
|
mount(document, components = {}) {
|
|
42
70
|
const instance = new ComponentClass()
|
|
71
|
+
for (const key of Object.keys(helperValues)) {
|
|
72
|
+
instance[key] = helperValues[key]
|
|
73
|
+
}
|
|
43
74
|
const renderFn = new Function(
|
|
44
75
|
'document',
|
|
45
76
|
'effect',
|
|
@@ -51,4 +82,4 @@ export function compileComponent(source, className = 'Component') {
|
|
|
51
82
|
return { node, instance }
|
|
52
83
|
},
|
|
53
84
|
}
|
|
54
|
-
}
|
|
85
|
+
}
|
|
@@ -1,29 +1,115 @@
|
|
|
1
|
+
import { findSectionBoundaries } from '../parser/parsePageFile.js'
|
|
2
|
+
// import { A, B as C } from "pkg" -> components from a package manifest
|
|
3
|
+
// import Card from "./a/Card" -> one local .tyx file, named by you
|
|
4
|
+
//
|
|
5
|
+
// `[ \t\r]*` at the ends (never `\s*`) so a match can't swallow
|
|
6
|
+
// neighbouring blank lines; `[^}]*` lets the braces span lines.
|
|
1
7
|
const IMPORT_LINE_RE =
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
8
|
+
/^[ \t]*import(?:\s*\{([^}]*)\}|\s+([A-Za-z_$][\w$]*))\s*from\s*["']([^"']+)["']\s*;?[ \t\r]*$/gm
|
|
9
|
+
|
|
10
|
+
const NAME_RE = /^[A-Z][A-Za-z0-9_$]*$/
|
|
11
|
+
const NAMED_ITEM_RE =
|
|
12
|
+
/^([A-Z][A-Za-z0-9_$]*)(?:\s+as\s+([A-Z][A-Za-z0-9_$]*))?$/
|
|
13
|
+
|
|
14
|
+
// Imports are only recognised BEFORE the template, so code samples
|
|
15
|
+
// inside <pre> blocks are never rewritten.
|
|
16
|
+
function headEnd(source) {
|
|
17
|
+
const sectionTemplate = findSectionBoundaries(source).find(
|
|
18
|
+
(b) => b.keyword === 'template',
|
|
19
|
+
)
|
|
20
|
+
const legacy = source.search(/<template[\s>]/)
|
|
21
|
+
const ends = [sectionTemplate ? sectionTemplate.start : -1, legacy].filter(
|
|
22
|
+
(n) => n >= 0,
|
|
23
|
+
)
|
|
24
|
+
return ends.length > 0 ? Math.min(...ends) : source.length
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Each removed import is replaced by the SAME number of newlines, so
|
|
28
|
+
// every line below it keeps its original line number (parse errors
|
|
29
|
+
// and typecheck diagnostics depend on that).
|
|
30
|
+
//
|
|
31
|
+
// Returns { imports, source } where each import is
|
|
32
|
+
// { kind: 'package' | 'local', specifier, line,
|
|
33
|
+
// names: [{ imported, local }] }
|
|
34
|
+
// `local` is the tag name the page uses; `imported` is the name in
|
|
35
|
+
// the package manifest (null for local files, which hold one
|
|
36
|
+
// component each).
|
|
15
37
|
export function extractImports(source) {
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
38
|
+
const end = headEnd(source)
|
|
39
|
+
const head = source.slice(0, end)
|
|
40
|
+
const packages = new Map() // specifier -> import entry
|
|
41
|
+
const locals = []
|
|
42
|
+
const taken = new Map() // local name -> specifier
|
|
43
|
+
|
|
44
|
+
const claim = (local, specifier, line) => {
|
|
45
|
+
if (taken.has(local) && taken.get(local) !== specifier) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
`"${local}" is imported twice (from "${taken.get(local)}" and "${specifier}", line ${line}); give one of them a different name`,
|
|
48
|
+
)
|
|
20
49
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
50
|
+
taken.set(local, specifier)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const cleaned = head.replace(
|
|
54
|
+
IMPORT_LINE_RE,
|
|
55
|
+
(match, braced, bare, specifier, offset) => {
|
|
56
|
+
const line = head.slice(0, offset).split('\n').length
|
|
57
|
+
|
|
58
|
+
if (specifier.startsWith('/')) {
|
|
59
|
+
throw new Error(
|
|
60
|
+
`Absolute import "${specifier}" at line ${line} is not supported; use a relative path`,
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (specifier.startsWith('.')) {
|
|
65
|
+
if (braced !== undefined) {
|
|
66
|
+
throw new Error(
|
|
67
|
+
`Line ${line}: a local file holds one component, so write: import Name from "${specifier}"`,
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
if (!NAME_RE.test(bare)) {
|
|
71
|
+
throw new Error(
|
|
72
|
+
`Line ${line}: component name "${bare}" must start with an uppercase letter`,
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
claim(bare, specifier, line)
|
|
76
|
+
locals.push({
|
|
77
|
+
kind: 'local',
|
|
78
|
+
specifier,
|
|
79
|
+
line,
|
|
80
|
+
names: [{ imported: null, local: bare }],
|
|
81
|
+
})
|
|
82
|
+
} else {
|
|
83
|
+
if (bare !== undefined) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`Line ${line}: packages export named components, so write: import { ${bare} } from "${specifier}"`,
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
let entry = packages.get(specifier)
|
|
89
|
+
if (!entry) {
|
|
90
|
+
entry = { kind: 'package', specifier, line, names: [] }
|
|
91
|
+
packages.set(specifier, entry)
|
|
92
|
+
}
|
|
93
|
+
for (const raw of braced.split(',').map((n) => n.trim()).filter(Boolean)) {
|
|
94
|
+
const m = NAMED_ITEM_RE.exec(raw)
|
|
95
|
+
if (!m) {
|
|
96
|
+
throw new Error(
|
|
97
|
+
`Line ${line}: cannot import "${raw}" from "${specifier}" (expected Name or Name as Other, PascalCase)`,
|
|
98
|
+
)
|
|
99
|
+
}
|
|
100
|
+
const imported = m[1]
|
|
101
|
+
const local = m[2] ?? m[1]
|
|
102
|
+
claim(local, specifier, line)
|
|
103
|
+
entry.names.push({ imported, local })
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return match.replace(/[^\n]/g, '') // keep the newlines only
|
|
108
|
+
},
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
imports: [...packages.values(), ...locals],
|
|
113
|
+
source: cleaned + source.slice(end),
|
|
114
|
+
}
|
|
115
|
+
}
|