@getcortexlabs/create-mavis 0.1.0-rc.12.1 → 0.1.0-rc.13

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 (34) hide show
  1. package/README.md +9 -5
  2. package/package.json +1 -1
  3. package/src/adapters.mjs +76 -0
  4. package/src/add-target.mjs +5 -0
  5. package/src/capabilities.mjs +626 -0
  6. package/src/cli.mjs +47 -12
  7. package/src/doctor.mjs +92 -25
  8. package/src/macos.mjs +276 -0
  9. package/src/package-manager.mjs +12 -4
  10. package/src/portability.mjs +6 -1
  11. package/src/presets.mjs +15 -81
  12. package/src/scaffold.mjs +15 -3
  13. package/src/ui.mjs +123 -61
  14. package/templates/macos/examples/tasks/shared/TaskDetail.lite.tsx +57 -0
  15. package/templates/macos/examples/tasks/shared/TaskRow.lite.tsx +33 -0
  16. package/templates/macos/examples/tasks/shared/Tasks.lite.tsx +251 -0
  17. package/templates/macos/examples/tasks/shared/types.ts +9 -0
  18. package/templates/macos/mobile/src/App.vue +12 -0
  19. package/templates/macos/mobile/src/app.ts +7 -0
  20. package/templates/macos/native/Package.swift +17 -0
  21. package/templates/macos/native/Sources/MavisDesktop/App.swift +20 -0
  22. package/templates/macos/root/tsconfig.json +14 -0
  23. package/templates/macos/scripts/generate.mjs +36 -0
  24. package/templates/macos/scripts/macos.mjs +56 -0
  25. package/templates/macos/scripts/portable/emit-swift.mjs +1287 -0
  26. package/templates/macos/scripts/portable/emit-vue.mjs +615 -0
  27. package/templates/macos/scripts/portable/index.mjs +95 -0
  28. package/templates/macos/scripts/portable/model.mjs +1441 -0
  29. package/templates/macos/scripts/portable/program.mjs +163 -0
  30. package/templates/macos/shared/Welcome.lite.tsx +42 -0
  31. package/templates/macos/web/index.html +12 -0
  32. package/templates/macos/web/src/main.js +39 -0
  33. package/templates/macos/web/src/style.css +13 -0
  34. package/templates/macos/web/vite.config.mjs +3 -0
@@ -0,0 +1,1441 @@
1
+ import ts from 'typescript'
2
+ import { preludePath, primitives } from './program.mjs'
3
+
4
+ // Swift keywords that cannot name a declaration, plus SwiftUI names a View member would shadow.
5
+ const swiftReserved = new Set(
6
+ 'associatedtype class deinit enum extension fileprivate func import init inout internal let operator private precedencegroup protocol public rethrows static struct subscript typealias var break case catch continue default defer do else fallthrough for guard if in repeat return throw switch where while Any as await false is nil self Self super throws true try body View State Binding Text Button Color Font Double String Bool Int Array Optional ForEach VStack HStack EmptyView'.split(
7
+ ' ',
8
+ ),
9
+ )
10
+ const jsReserved = new Set(['state', 'props', 'undefined', 'Math'])
11
+
12
+ export class PortableError extends Error {}
13
+
14
+ /** Types the generators understand. Numbers are JavaScript numbers, Double in Swift. */
15
+ export const T = {
16
+ string: { k: 'string' },
17
+ number: { k: 'number' },
18
+ boolean: { k: 'boolean' },
19
+ void: { k: 'void' },
20
+ record: (name) => ({ k: 'record', name }),
21
+ array: (of) => ({ k: 'array', of }),
22
+ optional: (of) => ({ k: 'optional', of }),
23
+ fn: (params) => ({ k: 'function', params }),
24
+ }
25
+ export const sameType = (a, b) => JSON.stringify(a) === JSON.stringify(b)
26
+ const primitive = (type) => ['string', 'number', 'boolean'].includes(type.k)
27
+ const describe = (type) =>
28
+ type.k === 'record'
29
+ ? type.name
30
+ : type.k === 'array'
31
+ ? `${describe(type.of)}[]`
32
+ : type.k === 'optional'
33
+ ? `${describe(type.of)} | undefined`
34
+ : type.k === 'function'
35
+ ? `(${type.params.map(describe).join(', ')}) => void`
36
+ : type.k
37
+
38
+ const stringMethods = {
39
+ trim: [[], T.string],
40
+ toLowerCase: [[], T.string],
41
+ toUpperCase: [[], T.string],
42
+ includes: [[T.string], T.boolean],
43
+ startsWith: [[T.string], T.boolean],
44
+ endsWith: [[T.string], T.boolean],
45
+ }
46
+ const mathFunctions = { min: 2, max: 2, floor: 1, ceil: 1, abs: 1, round: 1 }
47
+
48
+ /**
49
+ * Builds the portable model from type-checked shared sources. Every construct is
50
+ * checked here, before either generator writes a file.
51
+ */
52
+ export function buildModel({ checker, sourceFile, relative }, paths) {
53
+ const records = new Map()
54
+ const components = new Map()
55
+ const fail = (node, message) => {
56
+ const file = node.getSourceFile()
57
+ const { line, character } = file.getLineAndCharacterOfPosition(node.getStart(file))
58
+ throw new PortableError(`${relative(file.fileName)}:${line + 1}:${character + 1}: ${message}`)
59
+ }
60
+
61
+ function mapType(type, node, { allowFunction = false } = {}) {
62
+ if (type.flags & ts.TypeFlags.Union) {
63
+ const parts = type.types.filter((part) => !(part.flags & ts.TypeFlags.Undefined))
64
+ const optional = parts.length !== type.types.length
65
+ let inner
66
+ if (parts.every((part) => part.flags & ts.TypeFlags.StringLike)) inner = T.string
67
+ else if (parts.every((part) => part.flags & ts.TypeFlags.BooleanLike)) inner = T.boolean
68
+ else if (parts.every((part) => part.flags & ts.TypeFlags.NumberLike)) inner = T.number
69
+ else if (parts.length === 1) inner = mapType(parts[0], node, { allowFunction })
70
+ else fail(node, `Unsupported union type ${checker.typeToString(type)}.`)
71
+ return optional ? T.optional(inner) : inner
72
+ }
73
+ if (type.flags & ts.TypeFlags.StringLike) return T.string
74
+ if (type.flags & ts.TypeFlags.NumberLike) return T.number
75
+ if (type.flags & ts.TypeFlags.BooleanLike) return T.boolean
76
+ if (type.flags & ts.TypeFlags.Void) return T.void
77
+ if (checker.isArrayType(type)) return T.array(mapType(checker.getTypeArguments(type)[0], node))
78
+ if (type.flags & ts.TypeFlags.Object) {
79
+ const signatures = type.getCallSignatures()
80
+ if (signatures.length) {
81
+ if (!allowFunction) fail(node, 'Functions can only be component callback properties.')
82
+ if (signatures.length !== 1) fail(node, 'Callback properties need exactly one signature.')
83
+ const [signature] = signatures
84
+ if (!(signature.getReturnType().flags & ts.TypeFlags.Void))
85
+ fail(node, 'Callback properties must return void.')
86
+ return T.fn(
87
+ signature.parameters.map((parameter) =>
88
+ mapType(checker.getTypeOfSymbolAtLocation(parameter, node), node),
89
+ ),
90
+ )
91
+ }
92
+ const symbol = type.aliasSymbol ?? type.getSymbol()
93
+ const declaration = symbol?.declarations?.[0]
94
+ const named =
95
+ declaration &&
96
+ (ts.isTypeAliasDeclaration(declaration) ||
97
+ ts.isInterfaceDeclaration(declaration) ||
98
+ (ts.isTypeLiteralNode(declaration) && ts.isTypeAliasDeclaration(declaration.parent)))
99
+ if (!named || !relative(declaration.getSourceFile().fileName).startsWith('shared/'))
100
+ fail(
101
+ node,
102
+ `Declare a named record type for ${checker.typeToString(type)}, for example type Task = { id: string }.`,
103
+ )
104
+ const name = ts.isTypeLiteralNode(declaration) ? declaration.parent.name.text : symbol.name
105
+ registerRecord(name, type, declaration)
106
+ return T.record(name)
107
+ }
108
+ fail(node, `Unsupported type ${checker.typeToString(type)}.`)
109
+ }
110
+
111
+ function registerRecord(name, type, declaration) {
112
+ const builtIn = relative(declaration.getSourceFile().fileName) === preludePath
113
+ if (name === 'SelectOption' && !builtIn)
114
+ fail(declaration, 'SelectOption is the Mavis option type; give yours another name.')
115
+ if (records.has(name)) {
116
+ if (records.get(name).declaration !== declaration)
117
+ fail(declaration, `Record type ${name} is declared more than once.`)
118
+ return
119
+ }
120
+ checkName(declaration, name, 'Record type')
121
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name))
122
+ fail(declaration, `Record type ${name} must be PascalCase.`)
123
+ const record = { name, declaration, fields: [] }
124
+ records.set(name, record)
125
+ for (const property of checker.getPropertiesOfType(type)) {
126
+ const field = property.valueDeclaration ?? property.declarations?.[0]
127
+ checkName(field, property.name, 'Field')
128
+ const fieldType = mapType(checker.getTypeOfSymbolAtLocation(property, field), field)
129
+ if (fieldType.k === 'function' || fieldType.k === 'void')
130
+ fail(field, 'Record fields hold data, not functions.')
131
+ record.fields.push({ name: property.name, type: fieldType })
132
+ }
133
+ }
134
+
135
+ function selectOption() {
136
+ if (!records.has('SelectOption')) {
137
+ const declaration = sourceFile(preludePath).statements.find(
138
+ (statement) =>
139
+ ts.isTypeAliasDeclaration(statement) && statement.name.text === 'SelectOption',
140
+ )
141
+ registerRecord('SelectOption', checker.getTypeAtLocation(declaration.name), declaration)
142
+ }
143
+ return T.record('SelectOption')
144
+ }
145
+
146
+ function hasControl(node) {
147
+ if (node.v === 'component') return true
148
+ if (node.v === 'element') {
149
+ if (['MButton', 'MInput', 'MCheckbox', 'MSelect'].includes(node.tag)) return true
150
+ if (node.props.onClick || node.props.onKeyDown) return true
151
+ }
152
+ return [
153
+ ...(node.children ?? []),
154
+ ...(node.then ?? []),
155
+ ...(node.else ?? []),
156
+ ...(node.body ? [node.body] : []),
157
+ ].some(hasControl)
158
+ }
159
+
160
+ // A boolean attribute written as a literal: animate, animate={true} or animate={false}.
161
+ function flag(attribute) {
162
+ if (!attribute) return false
163
+ if (!attribute.initializer) return true
164
+ const value = attributeValue(attribute)
165
+ if (value.kind === ts.SyntaxKind.TrueKeyword) return true
166
+ if (value.kind === ts.SyntaxKind.FalseKeyword) return false
167
+ fail(attribute, 'animate is written as a literal: animate or animate={false}.')
168
+ }
169
+
170
+ function isLiteral(attribute) {
171
+ if (!attribute.initializer) return true
172
+ const value = attributeValue(attribute)
173
+ return (
174
+ ts.isStringLiteral(value) ||
175
+ value.kind === ts.SyntaxKind.TrueKeyword ||
176
+ value.kind === ts.SyntaxKind.FalseKeyword
177
+ )
178
+ }
179
+
180
+ function checkName(node, name, what) {
181
+ if (!/^[A-Za-z][A-Za-z0-9]*$/.test(name))
182
+ fail(node, `${what} ${name} needs a simple letters-and-digits name.`)
183
+ if (swiftReserved.has(name) || jsReserved.has(name) || /^mavis/i.test(name))
184
+ fail(node, `${what} ${name} collides with a reserved word in a generated target.`)
185
+ }
186
+
187
+ const typeOf = (node, options) => mapType(checker.getTypeAtLocation(node), node, options)
188
+
189
+ for (const path of paths) {
190
+ const file = sourceFile(path)
191
+ if (!file) throw new PortableError(`${path}: Not found.`)
192
+ if (path.endsWith('.lite.tsx')) components.set(path, readComponent(file, path))
193
+ else readTypesFile(file)
194
+ }
195
+
196
+ function readTypesFile(file) {
197
+ for (const statement of file.statements) {
198
+ if (
199
+ (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) &&
200
+ statement.modifiers?.every((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
201
+ )
202
+ continue
203
+ fail(statement, 'Type files contain only exported type declarations.')
204
+ }
205
+ }
206
+
207
+ function readComponent(file, path) {
208
+ const name = path.slice('shared/'.length, -'.lite.tsx'.length)
209
+ if (!/^[A-Z][A-Za-z0-9]*$/.test(name))
210
+ fail(
211
+ file,
212
+ `Component files are named after their component in PascalCase, e.g. TaskRow.lite.tsx.`,
213
+ )
214
+ let fn
215
+ const imports = new Map()
216
+ for (const statement of file.statements) {
217
+ if (ts.isImportDeclaration(statement)) {
218
+ const from = statement.moduleSpecifier.text
219
+ const clause = statement.importClause
220
+ if (from === '@builder.io/mitosis') {
221
+ const named = clause?.namedBindings
222
+ if (
223
+ !named ||
224
+ !ts.isNamedImports(named) ||
225
+ clause.name ||
226
+ named.elements.some(
227
+ (element) =>
228
+ element.propertyName ||
229
+ !['useStore', 'useRef', 'Show', 'For'].includes(element.name.text),
230
+ )
231
+ )
232
+ fail(statement, 'Import only { useStore, useRef, Show, For } from @builder.io/mitosis.')
233
+ continue
234
+ }
235
+ if (!from.startsWith('./')) fail(statement, 'Import other shared files with ./ paths only.')
236
+ if (clause?.isTypeOnly || (clause?.namedBindings && !clause.name)) continue
237
+ if (!clause?.name || clause.namedBindings)
238
+ fail(statement, 'Import one shared component as a default import.')
239
+ const target = from.replace(/^\.\//, '').replace(/\.lite$/, '')
240
+ if (clause.name.text !== target) fail(statement, `Import ${target} under its own name.`)
241
+ imports.set(clause.name.text, `shared/${target}.lite.tsx`)
242
+ continue
243
+ }
244
+ if (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) continue
245
+ if (ts.isFunctionDeclaration(statement)) {
246
+ const modifiers = statement.modifiers?.map((modifier) => modifier.kind) ?? []
247
+ if (
248
+ fn ||
249
+ modifiers.join() !== [ts.SyntaxKind.ExportKeyword, ts.SyntaxKind.DefaultKeyword].join()
250
+ )
251
+ fail(statement, 'A component file exports one default function component.')
252
+ fn = statement
253
+ continue
254
+ }
255
+ fail(statement, 'Only imports, type declarations and the component function are supported.')
256
+ }
257
+ if (!fn) fail(file, 'Export the component with export default function.')
258
+ if (fn.name?.text !== name) fail(fn, `The component in ${name}.lite.tsx must be named ${name}.`)
259
+ if (fn.asteriskToken || fn.typeParameters || fn.type || fn.parameters.length > 1)
260
+ fail(fn, 'Use function Name(props: { ... }) without generics or a return type.')
261
+
262
+ const component = {
263
+ name,
264
+ path,
265
+ imports,
266
+ props: [],
267
+ state: [],
268
+ getters: [],
269
+ actions: [],
270
+ view: null,
271
+ }
272
+ const members = new Map()
273
+ const declare = (node, memberName, kind) => {
274
+ checkName(node, memberName, kind)
275
+ if (members.has(memberName) || imports.has(memberName) || memberName === name)
276
+ fail(node, `${memberName} is already declared in ${name}.`)
277
+ members.set(memberName, kind)
278
+ }
279
+
280
+ if (fn.parameters.length) {
281
+ const parameter = fn.parameters[0]
282
+ if (
283
+ !ts.isIdentifier(parameter.name) ||
284
+ parameter.name.text !== 'props' ||
285
+ parameter.initializer
286
+ )
287
+ fail(parameter, 'Name the single parameter props.')
288
+ const propsType = checker.getTypeAtLocation(parameter)
289
+ for (const property of checker.getPropertiesOfType(propsType)) {
290
+ const declaration = property.valueDeclaration ?? property.declarations?.[0]
291
+ if (declaration && ts.isPropertySignature(declaration) && declaration.questionToken)
292
+ fail(declaration, 'Optional properties are not supported yet; pass every property.')
293
+ declare(declaration ?? parameter, property.name, 'Property')
294
+ component.props.push({
295
+ name: property.name,
296
+ type: mapType(
297
+ checker.getTypeOfSymbolAtLocation(property, parameter),
298
+ declaration ?? parameter,
299
+ { allowFunction: true },
300
+ ),
301
+ })
302
+ }
303
+ }
304
+
305
+ const body = fn.body.statements
306
+ let storeNode
307
+ component.refs = []
308
+ for (const statement of body.slice(0, -1)) {
309
+ const list = ts.isVariableStatement(statement) ? statement.declarationList : null
310
+ const declaration = list?.declarations[0]
311
+ const call = declaration?.initializer
312
+ if (
313
+ !list ||
314
+ list.flags !== ts.NodeFlags.Const ||
315
+ list.declarations.length !== 1 ||
316
+ !ts.isIdentifier(declaration.name) ||
317
+ declaration.type ||
318
+ !call ||
319
+ !ts.isCallExpression(call)
320
+ )
321
+ fail(
322
+ statement,
323
+ 'Before the returned JSX, declare only const state = useStore({ ... }) and const nameRef = useRef<MavisFieldRef>(null).',
324
+ )
325
+ const hook = call.expression.getText()
326
+ if (hook === 'useStore') {
327
+ if (
328
+ storeNode ||
329
+ declaration.name.text !== 'state' ||
330
+ call.arguments.length !== 1 ||
331
+ !ts.isObjectLiteralExpression(call.arguments[0])
332
+ )
333
+ fail(statement, 'Declare one const state = useStore({ ... }).')
334
+ storeNode = call.arguments[0]
335
+ } else if (hook === 'useRef') {
336
+ const [typeArgument] = call.typeArguments ?? []
337
+ if (
338
+ typeArgument?.getText() !== 'MavisFieldRef' ||
339
+ call.arguments.length > 1 ||
340
+ (call.arguments[0] && call.arguments[0].kind !== ts.SyntaxKind.NullKeyword)
341
+ )
342
+ fail(statement, 'Field references are const nameRef = useRef<MavisFieldRef>(null).')
343
+ declare(declaration, declaration.name.text, 'Ref')
344
+ component.refs.push({ name: declaration.name.text, node: declaration })
345
+ } else fail(call, 'Only useStore and useRef are supported here.')
346
+ }
347
+ const index = body.length - 1
348
+ if (!body.length || !ts.isReturnStatement(body[index]) || !body[index].expression)
349
+ fail(body[index] ?? fn, 'End the component by returning the screen as JSX.')
350
+
351
+ const pending = []
352
+ if (storeNode) {
353
+ for (const member of storeNode.properties) {
354
+ if (ts.isPropertyAssignment(member) && ts.isIdentifier(member.name)) {
355
+ declare(member, member.name.text, 'State')
356
+ pending.push(() =>
357
+ component.state.push({
358
+ name: member.name.text,
359
+ type: typeOf(member.name),
360
+ init: expr(
361
+ member.initializer,
362
+ scope(component, members, 'initializer'),
363
+ typeOf(member.name),
364
+ ),
365
+ }),
366
+ )
367
+ } else if (ts.isGetAccessor(member) && ts.isIdentifier(member.name)) {
368
+ declare(member, member.name.text, 'Getter')
369
+ if (!member.body) fail(member, 'Getters need a body.')
370
+ pending.push(() => {
371
+ const type = typeOf(member.name)
372
+ const ctx = scope(component, members, 'pure')
373
+ const locals = []
374
+ const statements = member.body.statements
375
+ statements.slice(0, -1).forEach((statement) => locals.push(constant(statement, ctx)))
376
+ const last = statements.at(-1)
377
+ if (!last || !ts.isReturnStatement(last) || !last.expression)
378
+ fail(
379
+ member,
380
+ 'A getter is optional const declarations followed by return <expression>.',
381
+ )
382
+ component.getters.push({
383
+ name: member.name.text,
384
+ type,
385
+ locals,
386
+ expr: expr(last.expression, ctx, type),
387
+ })
388
+ })
389
+ } else if (ts.isMethodDeclaration(member) && ts.isIdentifier(member.name)) {
390
+ declare(member, member.name.text, 'Action')
391
+ if (member.asteriskToken || member.typeParameters || member.questionToken)
392
+ fail(member, 'Actions are plain methods.')
393
+ if (member.modifiers?.length) fail(member, 'Actions cannot be async or have modifiers.')
394
+ if (member.type && member.type.kind !== ts.SyntaxKind.VoidKeyword)
395
+ fail(member.type, 'Actions return nothing.')
396
+ const params = member.parameters.map((parameter) => {
397
+ if (
398
+ !ts.isIdentifier(parameter.name) ||
399
+ parameter.initializer ||
400
+ parameter.questionToken ||
401
+ parameter.dotDotDotToken
402
+ )
403
+ fail(parameter, 'Action parameters are simple typed names.')
404
+ if (!parameter.type) fail(parameter, 'Give each action parameter a type.')
405
+ checkName(parameter, parameter.name.text, 'Parameter')
406
+ return { name: parameter.name.text, type: typeOf(parameter) }
407
+ })
408
+ pending.push(() => {
409
+ const ctx = scope(component, members, 'action')
410
+ params.forEach((param) => ctx.locals.set(param.name, param.type))
411
+ component.actions.push({
412
+ name: member.name.text,
413
+ params,
414
+ body: block(member.body, ctx),
415
+ })
416
+ })
417
+ } else
418
+ fail(member, 'useStore members are state values, getters (get x()) or action methods.')
419
+ }
420
+ }
421
+ component.members = members
422
+ component.pending = pending
423
+ component.render = body[index].expression
424
+ return component
425
+ }
426
+
427
+ for (const component of components.values()) {
428
+ for (const [importName, path] of component.imports)
429
+ if (!components.has(path))
430
+ fail(component.render, `${importName} is not a shared component file.`)
431
+ }
432
+ for (const component of components.values()) {
433
+ for (const task of component.pending) task()
434
+ component.view = view(component.render, scope(component, component.members, 'view'))
435
+ for (const reference of component.refs) {
436
+ if (!reference.field)
437
+ fail(
438
+ reference.node,
439
+ `${reference.name} is not attached to an MInput with ref={${reference.name}}.`,
440
+ )
441
+ delete reference.node
442
+ delete reference.field
443
+ }
444
+ delete component.pending
445
+ delete component.shortcuts
446
+ delete component.render
447
+ }
448
+ for (const record of records.values()) delete record.declaration
449
+ return { records: [...records.values()], components: [...components.values()] }
450
+
451
+ function scope(component, members, mode) {
452
+ return { component, members, mode, locals: new Map() }
453
+ }
454
+ function child(ctx, mode = ctx.mode) {
455
+ return { ...ctx, mode, locals: new Map(ctx.locals) }
456
+ }
457
+
458
+ function constant(statement, ctx) {
459
+ if (!ts.isVariableStatement(statement))
460
+ fail(statement, 'Only const declarations are supported here.')
461
+ const list = statement.declarationList
462
+ const [declaration] = list.declarations
463
+ if (
464
+ list.flags !== ts.NodeFlags.Const ||
465
+ list.declarations.length !== 1 ||
466
+ !ts.isIdentifier(declaration.name) ||
467
+ !declaration.initializer
468
+ )
469
+ fail(statement, 'Declare one const name = value at a time.')
470
+ const name = declaration.name.text
471
+ checkName(declaration, name, 'Local')
472
+ const type = typeOf(declaration.name)
473
+ const value = expr(declaration.initializer, ctx, type)
474
+ ctx.locals.set(name, type)
475
+ return { name, type, value }
476
+ }
477
+
478
+ function block(node, ctx) {
479
+ if (!ts.isBlock(node))
480
+ return ts.isExpressionStatement(node) ||
481
+ ts.isIfStatement(node) ||
482
+ ts.isReturnStatement(node) ||
483
+ ts.isVariableStatement(node)
484
+ ? stmt(node, ctx)
485
+ : [effect(node, ctx)]
486
+ const statements = node.statements
487
+ const out = []
488
+ for (const statement of statements) out.push(...stmt(statement, ctx))
489
+ return out
490
+ }
491
+
492
+ function stmt(node, ctx) {
493
+ if (ts.isVariableStatement(node)) return [{ s: 'const', ...constant(node, ctx) }]
494
+ if (ts.isReturnStatement(node)) {
495
+ if (node.expression) fail(node, 'Actions and handlers return without a value.')
496
+ return [{ s: 'return' }]
497
+ }
498
+ if (ts.isIfStatement(node)) {
499
+ // Narrow a local optional like TypeScript does: guard-style early return or a checked branch.
500
+ const narrow = narrowing(node.expression, ctx)
501
+ if (narrow?.op === '===' && !node.elseStatement && returnsOnly(node.thenStatement)) {
502
+ ctx.locals.set(narrow.name, narrow.inner)
503
+ return [{ s: 'guard', name: narrow.name }]
504
+ }
505
+ if (narrow?.op === '!==') {
506
+ const inner = child(ctx)
507
+ inner.locals.set(narrow.name, narrow.inner)
508
+ return [
509
+ {
510
+ s: 'iflet',
511
+ name: narrow.name,
512
+ then: block(node.thenStatement, inner),
513
+ else: node.elseStatement ? block(node.elseStatement, child(ctx)) : [],
514
+ },
515
+ ]
516
+ }
517
+ const test = expr(node.expression, ctx, T.boolean)
518
+ return [
519
+ {
520
+ s: 'if',
521
+ test,
522
+ then: block(node.thenStatement, child(ctx)),
523
+ else: node.elseStatement
524
+ ? ts.isIfStatement(node.elseStatement)
525
+ ? stmt(node.elseStatement, child(ctx))
526
+ : block(node.elseStatement, child(ctx))
527
+ : [],
528
+ },
529
+ ]
530
+ }
531
+ if (ts.isBlock(node)) return block(node, child(ctx))
532
+ if (ts.isExpressionStatement(node)) return [effect(node.expression, ctx)]
533
+ fail(node, 'Supported statements: const, if/else, return, state assignments and calls.')
534
+ }
535
+
536
+ function narrowing(test, ctx) {
537
+ if (!ts.isBinaryExpression(test)) return null
538
+ const kind = test.operatorToken.kind
539
+ const op =
540
+ kind === ts.SyntaxKind.EqualsEqualsEqualsToken
541
+ ? '==='
542
+ : kind === ts.SyntaxKind.ExclamationEqualsEqualsToken
543
+ ? '!=='
544
+ : null
545
+ const sides = [test.left, test.right]
546
+ const local = sides.find((side) => ts.isIdentifier(side) && side.text !== 'undefined')
547
+ const other = sides.find((side) => side !== local)
548
+ if (!op || !local || !ts.isIdentifier(other) || other.text !== 'undefined') return null
549
+ const type = ctx.locals.get(local.text)
550
+ if (type?.k !== 'optional') return null
551
+ return { op, name: local.text, inner: type.of }
552
+ }
553
+
554
+ function returnsOnly(node) {
555
+ if (ts.isReturnStatement(node)) return !node.expression
556
+ return ts.isBlock(node) && node.statements.length === 1 && returnsOnly(node.statements[0])
557
+ }
558
+
559
+ function statePath(node, ctx) {
560
+ const fields = []
561
+ let current = node
562
+ while (ts.isPropertyAccessExpression(current) && !current.questionDotToken) {
563
+ fields.unshift(current.name.text)
564
+ current = current.expression
565
+ }
566
+ if (!ts.isIdentifier(current) || current.text !== 'state' || !fields.length)
567
+ fail(node, 'Only state values and their record fields can be changed.')
568
+ const [name, ...rest] = fields
569
+ if (ctx.members.get(name) !== 'State') fail(node, `${name} is not a state value.`)
570
+ return { name, fields: rest, type: typeOf(node) }
571
+ }
572
+
573
+ function effect(node, ctx) {
574
+ if (ctx.mode !== 'action') fail(node, 'Changes are only allowed in actions and event handlers.')
575
+ if (ts.isParenthesizedExpression(node)) return effect(node.expression, ctx)
576
+ if (ts.isBinaryExpression(node)) {
577
+ const op = node.operatorToken.kind
578
+ const ops = {
579
+ [ts.SyntaxKind.EqualsToken]: '=',
580
+ [ts.SyntaxKind.PlusEqualsToken]: '+=',
581
+ [ts.SyntaxKind.MinusEqualsToken]: '-=',
582
+ }
583
+ if (!ops[op]) fail(node, 'Use =, += or -= to change state.')
584
+ const target = statePath(node.left, ctx)
585
+ if (ops[op] === '-=' && target.type.k !== 'number') fail(node, '-= needs a number.')
586
+ if (ops[op] === '+=' && !['number', 'string'].includes(target.type.k))
587
+ fail(node, '+= needs a number or a string.')
588
+ const value = expr(node.right, ctx, ops[op] === '=' ? target.type : undefined)
589
+ if (ops[op] === '+=' && target.type.k === 'number' && value.type.k !== 'number')
590
+ fail(node.right, 'Adding to a number needs a number.')
591
+ if (ops[op] === '+=' && target.type.k === 'string' && !primitive(value.type))
592
+ fail(node.right, 'Only strings, numbers and booleans can be appended to text.')
593
+ return { s: 'assign', target, op: ops[op], value }
594
+ }
595
+ if (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) {
596
+ const op =
597
+ node.operator === ts.SyntaxKind.PlusPlusToken
598
+ ? '+='
599
+ : node.operator === ts.SyntaxKind.MinusMinusToken
600
+ ? '-='
601
+ : null
602
+ if (!op) fail(node, 'Unsupported statement.')
603
+ const target = statePath(node.operand, ctx)
604
+ if (target.type.k !== 'number') fail(node, '++ and -- need a number.')
605
+ return { s: 'assign', target, op, value: { e: 'lit', value: 1, type: T.number } }
606
+ }
607
+ if (ts.isCallExpression(node)) {
608
+ const callee = node.expression
609
+ if (ts.isPropertyAccessExpression(callee) && !callee.questionDotToken) {
610
+ const owner = callee.expression
611
+ const method = callee.name.text
612
+ if (ts.isIdentifier(owner) && ctx.members.get(owner.text) === 'Ref') {
613
+ if (!['focus', 'blur'].includes(method) || node.arguments.length)
614
+ fail(callee, 'Field references support focus() and blur().')
615
+ return { s: method, ref: owner.text }
616
+ }
617
+ if (ts.isIdentifier(owner) && owner.text === 'state') {
618
+ if (ctx.members.get(method) !== 'Action') fail(callee, `${method} is not an action.`)
619
+ const action = actionSignature(ctx.component, method, callee)
620
+ return {
621
+ s: 'action',
622
+ name: method,
623
+ args: args(
624
+ node,
625
+ action.map((p) => p.type),
626
+ ctx,
627
+ ),
628
+ }
629
+ }
630
+ if (ts.isIdentifier(owner) && owner.text === 'props') {
631
+ const prop = ctx.component.props.find((p) => p.name === method)
632
+ if (prop?.type.k !== 'function') fail(callee, `${method} is not a callback property.`)
633
+ return { s: 'callback', name: method, args: args(node, prop.type.params, ctx) }
634
+ }
635
+ if (['push', 'unshift', 'splice'].includes(method)) {
636
+ const target = statePath(owner, ctx)
637
+ if (target.type.k !== 'array') fail(owner, `${method} needs a state array.`)
638
+ if (method === 'splice') {
639
+ if (node.arguments.length < 2 || node.arguments.length > 3)
640
+ fail(node, 'Use splice(start, deleteCount) or splice(start, 0, item).')
641
+ return {
642
+ s: 'splice',
643
+ target,
644
+ start: expr(node.arguments[0], ctx, T.number),
645
+ deleteCount: expr(node.arguments[1], ctx, T.number),
646
+ items: node.arguments.slice(2).map((arg) => expr(arg, ctx, target.type.of)),
647
+ }
648
+ }
649
+ if (node.arguments.length !== 1) fail(node, `${method} takes one item.`)
650
+ return { s: method, target, value: expr(node.arguments[0], ctx, target.type.of) }
651
+ }
652
+ }
653
+ fail(
654
+ node,
655
+ 'Call actions with state.name(...), callbacks with props.name(...), or change arrays with push, unshift or splice.',
656
+ )
657
+ }
658
+ fail(node, 'Supported statements: const, if/else, return, state assignments and calls.')
659
+ }
660
+
661
+ function actionSignature(component, name, node) {
662
+ const store = component.actions.find((action) => action.name === name)
663
+ if (store) return store.params
664
+ // Declared later in the same store: read the signature from the type checker.
665
+ const type = checker.getTypeAtLocation(node)
666
+ const [signature] = type.getCallSignatures()
667
+ return signature.parameters.map((parameter) => ({
668
+ type: mapType(checker.getTypeOfSymbolAtLocation(parameter, node), node),
669
+ }))
670
+ }
671
+
672
+ function args(node, types, ctx) {
673
+ if (node.arguments.length !== types.length) fail(node, `Expected ${types.length} argument(s).`)
674
+ return node.arguments.map((arg, i) => expr(arg, ctx, types[i]))
675
+ }
676
+
677
+ function expect(node, actual, expected) {
678
+ if (!expected) return
679
+ if (sameType(actual, expected)) return
680
+ if (expected.k === 'optional' && sameType(actual, expected.of)) return
681
+ fail(node, `Expected ${describe(expected)}, found ${describe(actual)}.`)
682
+ }
683
+
684
+ function expr(node, ctx, expected) {
685
+ const result = build(node, ctx, expected)
686
+ expect(node, result.type, expected)
687
+ return result
688
+ }
689
+
690
+ function build(node, ctx, expected) {
691
+ if (ts.isParenthesizedExpression(node)) return build(node.expression, ctx, expected)
692
+ if (ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
693
+ if (ctx.mode !== 'initializer')
694
+ fail(node, 'Type assertions are only allowed in initial state values.')
695
+ return build(node.expression, ctx, typeOf(node))
696
+ }
697
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
698
+ return { e: 'lit', value: node.text, type: T.string }
699
+ if (ts.isNumericLiteral(node)) {
700
+ const value = Number(node.text)
701
+ if (!Number.isFinite(value)) fail(node, 'Numbers must be finite.')
702
+ return { e: 'lit', value, type: T.number }
703
+ }
704
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return { e: 'lit', value: true, type: T.boolean }
705
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return { e: 'lit', value: false, type: T.boolean }
706
+ if (ts.isIdentifier(node)) {
707
+ if (node.text === 'undefined') {
708
+ if (expected?.k !== 'optional')
709
+ fail(node, 'undefined is only allowed where a value is optional.')
710
+ return { e: 'undefined', type: expected }
711
+ }
712
+ if (ctx.locals.has(node.text))
713
+ return { e: 'local', name: node.text, type: ctx.locals.get(node.text) }
714
+ fail(
715
+ node,
716
+ `${node.text} is not available here. Use state.name, props.name, locals or callback parameters.`,
717
+ )
718
+ }
719
+ if (ts.isTemplateExpression(node)) {
720
+ const parts = [node.head.text]
721
+ for (const span of node.templateSpans) {
722
+ const value = expr(span.expression, ctx)
723
+ if (!primitive(value.type))
724
+ fail(span.expression, 'Only strings, numbers and booleans can be placed in text.')
725
+ parts.push(value, span.literal.text)
726
+ }
727
+ return { e: 'template', parts: parts.filter((part) => part !== ''), type: T.string }
728
+ }
729
+ if (ts.isPropertyAccessExpression(node)) return access(node, ctx)
730
+ if (ts.isElementAccessExpression(node)) {
731
+ if (node.questionDotToken) fail(node, 'Use list[index] and check the result for undefined.')
732
+ const object = expr(node.expression, ctx)
733
+ if (object.type.k !== 'array') fail(node.expression, 'Index access works on arrays.')
734
+ const index = expr(node.argumentExpression, ctx, T.number)
735
+ return { e: 'index', object, index, type: T.optional(object.type.of) }
736
+ }
737
+ if (ts.isCallExpression(node)) return call(node, ctx)
738
+ if (ts.isPrefixUnaryExpression(node)) {
739
+ if (node.operator === ts.SyntaxKind.ExclamationToken)
740
+ return { e: 'unary', op: '!', arg: expr(node.operand, ctx, T.boolean), type: T.boolean }
741
+ if (node.operator === ts.SyntaxKind.MinusToken) {
742
+ const arg = expr(node.operand, ctx, T.number)
743
+ if (arg.e === 'lit') return { e: 'lit', value: -arg.value, type: T.number }
744
+ return { e: 'unary', op: '-', arg, type: T.number }
745
+ }
746
+ fail(node, 'Only ! and - are supported as prefix operators.')
747
+ }
748
+ if (ts.isBinaryExpression(node)) return binary(node, ctx, expected)
749
+ if (ts.isConditionalExpression(node)) {
750
+ const test = expr(node.condition, ctx, T.boolean)
751
+ const type = expected ?? typeOf(node)
752
+ // x === undefined ? a : b narrows x in b, and !== narrows it in a, like TypeScript.
753
+ const narrow = narrowing(node.condition, ctx)
754
+ const branch = (side, narrowed) => {
755
+ if (!narrowed) return expr(side, ctx, type)
756
+ const inner = child(ctx)
757
+ inner.locals.set(narrow.name, narrow.inner)
758
+ return expr(side, inner, type)
759
+ }
760
+ return {
761
+ e: 'cond',
762
+ test,
763
+ then: branch(node.whenTrue, narrow?.op === '!=='),
764
+ else: branch(node.whenFalse, narrow?.op === '==='),
765
+ type,
766
+ ...(narrow ? { narrow: { name: narrow.name, op: narrow.op } } : {}),
767
+ }
768
+ }
769
+ if (ts.isObjectLiteralExpression(node)) return record(node, ctx, expected)
770
+ if (ts.isArrayLiteralExpression(node)) {
771
+ const type = expected?.k === 'array' ? expected : typeOf(node)
772
+ if (type.k !== 'array') fail(node, 'Give this array an element type.')
773
+ return {
774
+ e: 'array',
775
+ items: node.elements.map((element) => {
776
+ if (ts.isSpreadElement(element)) fail(element, 'Array spread is not supported.')
777
+ return expr(element, ctx, type.of)
778
+ }),
779
+ type,
780
+ }
781
+ }
782
+ if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node))
783
+ fail(node, 'JSX is only allowed in the returned screen, Show and For.')
784
+ fail(node, 'This expression is not part of the portable subset yet.')
785
+ }
786
+
787
+ function access(node, ctx) {
788
+ const owner = node.expression
789
+ const name = node.name.text
790
+ if (ts.isIdentifier(owner) && owner.text === 'state' && !node.questionDotToken) {
791
+ const kind = ctx.members.get(name)
792
+ if (kind === 'State') return { e: 'state', name, type: typeOf(node) }
793
+ if (kind === 'Getter') {
794
+ if (ctx.mode === 'initializer') fail(node, 'Initial state cannot read getters.')
795
+ return { e: 'getter', name, type: typeOf(node) }
796
+ }
797
+ if (kind === 'Action')
798
+ fail(node, `Call ${name} as state.${name}(...) in an event handler or action.`)
799
+ fail(node, `state.${name} is not declared.`)
800
+ }
801
+ if (ts.isIdentifier(owner) && owner.text === 'props' && !node.questionDotToken) {
802
+ const prop = ctx.component.props.find((p) => p.name === name)
803
+ if (!prop) fail(node, `props.${name} is not declared.`)
804
+ if (prop.type.k === 'function')
805
+ fail(node, `Call ${name} as props.${name}(...) in an event handler.`)
806
+ return { e: 'prop', name, type: prop.type }
807
+ }
808
+ if (ctx.mode === 'initializer' && ts.isIdentifier(owner) && owner.text === 'state')
809
+ fail(node, 'Initial state cannot read other state values.')
810
+ const object = expr(owner, ctx)
811
+ const base = node.questionDotToken
812
+ ? object.type.k === 'optional'
813
+ ? object.type.of
814
+ : fail(node, '?. needs an optional value.')
815
+ : object.type
816
+ if (!node.questionDotToken && object.type.k === 'optional')
817
+ fail(node, `This value may be undefined; use ?. or check it first.`)
818
+ if (name === 'length' && (base.k === 'string' || base.k === 'array')) {
819
+ if (node.questionDotToken) fail(node, 'Use ?? with length, or check the value first.')
820
+ return { e: 'length', object, type: T.number }
821
+ }
822
+ if (base.k === 'record') {
823
+ const field = records.get(base.name).fields.find((f) => f.name === name)
824
+ if (!field) fail(node, `${base.name} has no field ${name}.`)
825
+ const type =
826
+ node.questionDotToken && field.type.k !== 'optional' ? T.optional(field.type) : field.type
827
+ return { e: 'field', object, name, optional: Boolean(node.questionDotToken), type }
828
+ }
829
+ fail(node, `${name} is not available on ${describe(base)}.`)
830
+ }
831
+
832
+ function call(node, ctx) {
833
+ const callee = node.expression
834
+ if (!ts.isPropertyAccessExpression(callee) || callee.questionDotToken)
835
+ fail(node, 'Only listed string, array and Math methods can be called in expressions.')
836
+ const method = callee.name.text
837
+ if (ts.isIdentifier(callee.expression) && callee.expression.text === 'Math') {
838
+ if (!(method in mathFunctions)) fail(callee, `Math.${method} is not supported.`)
839
+ if (node.arguments.length !== mathFunctions[method])
840
+ fail(node, `Math.${method} takes ${mathFunctions[method]} argument(s).`)
841
+ return {
842
+ e: 'math',
843
+ fn: method,
844
+ args: node.arguments.map((arg) => expr(arg, ctx, T.number)),
845
+ type: T.number,
846
+ }
847
+ }
848
+ if (ts.isIdentifier(callee.expression) && ['state', 'props'].includes(callee.expression.text))
849
+ fail(
850
+ node,
851
+ 'Actions and callbacks change things; call them from an event handler or action, not an expression.',
852
+ )
853
+ const object = expr(callee.expression, ctx)
854
+ if (object.type.k === 'optional') fail(callee, 'This value may be undefined; check it first.')
855
+ if (object.type.k === 'string') {
856
+ const signature = stringMethods[method]
857
+ if (!signature) fail(callee, `String method ${method} is not supported.`)
858
+ return { e: 'call', method, object, args: args(node, signature[0], ctx), type: signature[1] }
859
+ }
860
+ if (object.type.k === 'array') {
861
+ const element = object.type.of
862
+ const callback = (returns) => {
863
+ if (node.arguments.length !== 1) fail(node, `${method} takes one callback.`)
864
+ return arrow(node.arguments[0], [element], returns, ctx)
865
+ }
866
+ switch (method) {
867
+ case 'filter':
868
+ return { e: 'call', method, object, args: [callback(T.boolean)], type: object.type }
869
+ case 'some':
870
+ case 'every':
871
+ return { e: 'call', method, object, args: [callback(T.boolean)], type: T.boolean }
872
+ case 'find':
873
+ return {
874
+ e: 'call',
875
+ method,
876
+ object,
877
+ args: [callback(T.boolean)],
878
+ type: T.optional(element),
879
+ }
880
+ case 'findIndex':
881
+ return { e: 'call', method, object, args: [callback(T.boolean)], type: T.number }
882
+ case 'map': {
883
+ const fn = callback(undefined)
884
+ if (fn.body.type.k === 'optional' || fn.body.type.k === 'void')
885
+ fail(node.arguments[0], 'map must return a value.')
886
+ return { e: 'call', method, object, args: [fn], type: T.array(fn.body.type) }
887
+ }
888
+ case 'includes':
889
+ if (!primitive(element))
890
+ fail(callee, 'includes works on arrays of strings, numbers or booleans.')
891
+ return { e: 'call', method, object, args: args(node, [element], ctx), type: T.boolean }
892
+ case 'slice': {
893
+ if (node.arguments.length < 1 || node.arguments.length > 2)
894
+ fail(node, 'Use slice(start) or slice(start, end).')
895
+ return {
896
+ e: 'call',
897
+ method,
898
+ object,
899
+ args: node.arguments.map((arg) => expr(arg, ctx, T.number)),
900
+ type: object.type,
901
+ }
902
+ }
903
+ case 'toSorted': {
904
+ if (node.arguments.length !== 1) fail(node, 'toSorted takes a compare function.')
905
+ const compare = arrow(node.arguments[0], [element, element], T.number, ctx)
906
+ return { e: 'call', method, object, args: [compare], type: object.type }
907
+ }
908
+ case 'join':
909
+ if (element.k !== 'string') fail(callee, 'join works on arrays of strings.')
910
+ return { e: 'call', method, object, args: args(node, [T.string], ctx), type: T.string }
911
+ default:
912
+ fail(callee, `Array method ${method} is not supported in expressions.`)
913
+ }
914
+ }
915
+ fail(callee, `${method} is not available on ${describe(object.type)}.`)
916
+ }
917
+
918
+ function arrow(node, types, returns, ctx) {
919
+ if (
920
+ !ts.isArrowFunction(node) ||
921
+ node.parameters.length !== types.length ||
922
+ ts.isBlock(node.body)
923
+ )
924
+ fail(
925
+ node,
926
+ types.length === 1
927
+ ? 'Use a one-parameter arrow with an expression body, for example (task) => task.done.'
928
+ : 'Use a two-parameter arrow with an expression body, for example (a, b) => a.rank - b.rank.',
929
+ )
930
+ const inner = child(ctx)
931
+ const params = node.parameters.map((parameter, i) => {
932
+ if (!ts.isIdentifier(parameter.name) || parameter.initializer || parameter.dotDotDotToken)
933
+ fail(parameter, 'Use a simple parameter name.')
934
+ checkName(parameter, parameter.name.text, 'Parameter')
935
+ inner.locals.set(parameter.name.text, types[i])
936
+ return parameter.name.text
937
+ })
938
+ const body = expr(node.body, inner, returns)
939
+ return { e: 'arrow', params, types, body, type: types[0] }
940
+ }
941
+
942
+ function binary(node, ctx, expected) {
943
+ const kind = node.operatorToken.kind
944
+ const K = ts.SyntaxKind
945
+ if (kind === K.AmpersandAmpersandToken || kind === K.BarBarToken) {
946
+ const op = kind === K.AmpersandAmpersandToken ? '&&' : '||'
947
+ return {
948
+ e: 'logical',
949
+ op,
950
+ left: expr(node.left, ctx, T.boolean),
951
+ right: expr(node.right, ctx, T.boolean),
952
+ type: T.boolean,
953
+ }
954
+ }
955
+ if (kind === K.QuestionQuestionToken) {
956
+ const left = expr(node.left, ctx)
957
+ if (left.type.k !== 'optional') fail(node.left, '?? needs an optional value on the left.')
958
+ const right = expr(node.right, ctx, expected?.k === 'optional' ? expected : left.type.of)
959
+ return { e: 'logical', op: '??', left, right, type: right.type }
960
+ }
961
+ if (kind === K.EqualsEqualsToken || kind === K.ExclamationEqualsToken)
962
+ fail(node, 'Use === and !==.')
963
+ if (kind === K.EqualsEqualsEqualsToken || kind === K.ExclamationEqualsEqualsToken) {
964
+ const op = kind === K.EqualsEqualsEqualsToken ? '===' : '!=='
965
+ const leftUndefined = ts.isIdentifier(node.left) && node.left.text === 'undefined'
966
+ const rightUndefined = ts.isIdentifier(node.right) && node.right.text === 'undefined'
967
+ if (leftUndefined || rightUndefined) {
968
+ const value = expr(leftUndefined ? node.right : node.left, ctx)
969
+ if (value.type.k !== 'optional')
970
+ fail(node, 'Only optional values can be compared with undefined.')
971
+ return {
972
+ e: 'binary',
973
+ op,
974
+ left: value,
975
+ right: { e: 'undefined', type: value.type },
976
+ type: T.boolean,
977
+ }
978
+ }
979
+ const left = expr(node.left, ctx)
980
+ const right = expr(node.right, ctx)
981
+ const base = (type) => (type.k === 'optional' ? type.of : type)
982
+ if (!primitive(base(left.type)) || !sameType(base(left.type), base(right.type)))
983
+ fail(
984
+ node,
985
+ 'Compare strings, numbers or booleans of the same type. Records and arrays are compared by identity in JavaScript and by value in Swift.',
986
+ )
987
+ return { e: 'binary', op, left, right, type: T.boolean }
988
+ }
989
+ const arithmetic = {
990
+ [K.MinusToken]: '-',
991
+ [K.AsteriskToken]: '*',
992
+ [K.SlashToken]: '/',
993
+ [K.PercentToken]: '%',
994
+ }
995
+ const comparison = {
996
+ [K.LessThanToken]: '<',
997
+ [K.LessThanEqualsToken]: '<=',
998
+ [K.GreaterThanToken]: '>',
999
+ [K.GreaterThanEqualsToken]: '>=',
1000
+ }
1001
+ if (kind === K.PlusToken) {
1002
+ const left = expr(node.left, ctx)
1003
+ const right = expr(node.right, ctx)
1004
+ if (left.type.k === 'number' && right.type.k === 'number')
1005
+ return { e: 'binary', op: '+', left, right, type: T.number }
1006
+ if (
1007
+ (left.type.k === 'string' || right.type.k === 'string') &&
1008
+ primitive(left.type) &&
1009
+ primitive(right.type)
1010
+ )
1011
+ return { e: 'binary', op: 'concat', left, right, type: T.string }
1012
+ fail(node, '+ adds two numbers or joins text with strings, numbers or booleans.')
1013
+ }
1014
+ if (arithmetic[kind])
1015
+ return {
1016
+ e: 'binary',
1017
+ op: arithmetic[kind],
1018
+ left: expr(node.left, ctx, T.number),
1019
+ right: expr(node.right, ctx, T.number),
1020
+ type: T.number,
1021
+ }
1022
+ if (comparison[kind]) {
1023
+ const left = expr(node.left, ctx)
1024
+ const right = expr(node.right, ctx)
1025
+ if (left.type.k === 'string' && right.type.k === 'string')
1026
+ return { e: 'binary', op: comparison[kind], strings: true, left, right, type: T.boolean }
1027
+ if (left.type.k !== 'number' || right.type.k !== 'number')
1028
+ fail(node, `${comparison[kind]} compares two numbers or two strings.`)
1029
+ return { e: 'binary', op: comparison[kind], left, right, type: T.boolean }
1030
+ }
1031
+ fail(node, `Operator ${node.operatorToken.getText()} is not supported.`)
1032
+ }
1033
+
1034
+ function record(node, ctx, expected) {
1035
+ const [first] = node.properties
1036
+ // { ...task, done } copies task's record type.
1037
+ const copied =
1038
+ first && ts.isSpreadAssignment(first) ? expr(first.expression, ctx).type : undefined
1039
+ const type =
1040
+ expected?.k === 'record'
1041
+ ? expected
1042
+ : expected?.k === 'optional' && expected.of.k === 'record'
1043
+ ? expected.of
1044
+ : copied?.k === 'record'
1045
+ ? copied
1046
+ : typeOf(node)
1047
+ if (type.k !== 'record')
1048
+ fail(node, 'Object literals create records; give them a named record type.')
1049
+ const definition = records.get(type.name)
1050
+ let spread
1051
+ const fields = new Map()
1052
+ node.properties.forEach((property, index) => {
1053
+ if (ts.isSpreadAssignment(property)) {
1054
+ if (index !== 0) fail(property, 'Put ...spread first.')
1055
+ spread = expr(property.expression, ctx, type)
1056
+ return
1057
+ }
1058
+ let name, value
1059
+ if (ts.isPropertyAssignment(property) && ts.isIdentifier(property.name)) {
1060
+ name = property.name.text
1061
+ value = property.initializer
1062
+ } else if (ts.isShorthandPropertyAssignment(property)) {
1063
+ name = property.name.text
1064
+ value = property.name
1065
+ } else fail(property, 'Use name: value fields.')
1066
+ const field = definition.fields.find((f) => f.name === name)
1067
+ if (!field) fail(property, `${type.name} has no field ${name}.`)
1068
+ if (fields.has(name)) fail(property, `${name} is set twice.`)
1069
+ fields.set(name, expr(value, ctx, field.type))
1070
+ })
1071
+ if (!spread)
1072
+ for (const field of definition.fields)
1073
+ if (!fields.has(field.name)) {
1074
+ if (field.type.k !== 'optional') fail(node, `${type.name} needs ${field.name}.`)
1075
+ fields.set(field.name, { e: 'undefined', type: field.type })
1076
+ }
1077
+ return {
1078
+ e: 'record',
1079
+ name: type.name,
1080
+ spread,
1081
+ fields: [...fields].map(([name, value]) => ({ name, value })),
1082
+ type,
1083
+ }
1084
+ }
1085
+
1086
+ function handler(node, params, ctx) {
1087
+ if (!ts.isArrowFunction(node)) fail(node, 'Event handlers are arrow functions.')
1088
+ // Like JavaScript, a handler may ignore trailing arguments.
1089
+ if (node.parameters.length > params.length)
1090
+ fail(node, `This handler receives ${params.length} argument(s).`)
1091
+ const inner = child(ctx, 'action')
1092
+ const names = node.parameters.map((parameter, i) => {
1093
+ if (!ts.isIdentifier(parameter.name) || parameter.initializer || parameter.dotDotDotToken)
1094
+ fail(parameter, 'Use simple parameter names.')
1095
+ const name = parameter.name.text
1096
+ checkName(parameter, name, 'Parameter')
1097
+ inner.locals.set(name, params[i])
1098
+ return { name, type: params[i] }
1099
+ })
1100
+ for (const type of params.slice(names.length)) names.push({ name: '_', type, unused: true })
1101
+ return { params: names, body: block(node.body, inner) }
1102
+ }
1103
+
1104
+ function jsxName(node) {
1105
+ const tag = ts.isJsxElement(node) ? node.openingElement : node
1106
+ return { tag, name: tag.tagName.getText() }
1107
+ }
1108
+
1109
+ function children(nodes, ctx) {
1110
+ const out = []
1111
+ for (const node of nodes) {
1112
+ if (ts.isJsxText(node)) {
1113
+ if (node.text.trim()) fail(node, 'Put text inside MText.')
1114
+ continue
1115
+ }
1116
+ if (ts.isJsxExpression(node)) {
1117
+ if (!node.expression) continue
1118
+ fail(
1119
+ node,
1120
+ 'Use Show and For for conditional and repeated content; put values inside MText.',
1121
+ )
1122
+ }
1123
+ out.push(...viewNodes(node, ctx))
1124
+ }
1125
+ return out
1126
+ }
1127
+
1128
+ function viewNodes(node, ctx) {
1129
+ if (ts.isParenthesizedExpression(node)) return viewNodes(node.expression, ctx)
1130
+ if (ts.isJsxFragment(node)) return children(node.children, ctx)
1131
+ return [view(node, ctx)]
1132
+ }
1133
+
1134
+ function attributes(tag) {
1135
+ const result = new Map()
1136
+ for (const attribute of tag.attributes.properties) {
1137
+ if (!ts.isJsxAttribute(attribute) || !ts.isIdentifier(attribute.name))
1138
+ fail(attribute, 'Spread attributes are not supported.')
1139
+ if (result.has(attribute.name.text)) fail(attribute, `${attribute.name.text} is set twice.`)
1140
+ result.set(attribute.name.text, attribute)
1141
+ }
1142
+ return result
1143
+ }
1144
+
1145
+ function attributeValue(attribute) {
1146
+ const init = attribute.initializer
1147
+ if (!init) fail(attribute, `${attribute.name.text} needs a value.`)
1148
+ if (ts.isStringLiteral(init)) return init
1149
+ if (ts.isJsxExpression(init) && init.expression) return init.expression
1150
+ fail(attribute, `${attribute.name.text} needs a value.`)
1151
+ }
1152
+
1153
+ function view(node, ctx) {
1154
+ if (ts.isParenthesizedExpression(node)) return view(node.expression, ctx)
1155
+ if (ts.isJsxFragment(node)) fail(node, 'Return one root element.')
1156
+ if (!ts.isJsxElement(node) && !ts.isJsxSelfClosingElement(node))
1157
+ fail(node, 'Return JSX built from Mavis primitives, Show, For and shared components.')
1158
+ const { tag, name } = jsxName(node)
1159
+ const attrs = attributes(tag)
1160
+ const kids = ts.isJsxElement(node) ? node.children : []
1161
+ if (attrs.has('key') && !ctx.keyed)
1162
+ fail(attrs.get('key'), 'key belongs on the element returned by For.')
1163
+ if (name === 'Show') {
1164
+ for (const key of attrs.keys())
1165
+ if (!['when', 'else', 'animate'].includes(key))
1166
+ fail(attrs.get(key), `Show supports when, else and animate.`)
1167
+ if (!attrs.has('when')) fail(tag, 'Show needs when.')
1168
+ const animate = flag(attrs.get('animate'))
1169
+ // Revealed content keeps the column's spacing; a row would need another layout.
1170
+ if (animate && !['MColumn', 'MCard'].includes(ctx.parent?.tag))
1171
+ fail(attrs.get('animate'), 'An animated Show goes directly inside an MColumn or MCard.')
1172
+ const otherwise = attrs.has('else') ? attributeValue(attrs.get('else')) : null
1173
+ return {
1174
+ v: 'show',
1175
+ when: expr(attributeValue(attrs.get('when')), ctx, T.boolean),
1176
+ then: children(kids, { ...ctx, inShow: true }),
1177
+ else: otherwise ? viewNodes(otherwise, { ...ctx, inShow: true }) : [],
1178
+ ...(animate ? { animate: true, gap: ctx.parent.gap } : {}),
1179
+ }
1180
+ }
1181
+ if (name === 'For') {
1182
+ for (const key of attrs.keys())
1183
+ if (!['each', 'animate'].includes(key))
1184
+ fail(attrs.get(key), 'For supports each and animate.')
1185
+ const animate = flag(attrs.get('animate'))
1186
+ if (animate) {
1187
+ if (ctx.inFor) fail(attrs.get('animate'), 'Only a list outside other lists can animate.')
1188
+ if (!['MColumn', 'MRow'].includes(ctx.parent?.tag))
1189
+ fail(attrs.get('animate'), 'An animated For goes directly inside an MColumn or MRow.')
1190
+ if (ctx.parent.animated) fail(attrs.get('animate'), 'A stack can animate one list.')
1191
+ ctx.parent.animated = true
1192
+ }
1193
+ if (!attrs.has('each')) fail(tag, 'For needs each.')
1194
+ const each = expr(attributeValue(attrs.get('each')), ctx)
1195
+ if (each.type.k !== 'array') fail(attrs.get('each'), 'For needs an array.')
1196
+ const callbacks = kids.filter((kid) => !(ts.isJsxText(kid) && !kid.text.trim()))
1197
+ const callback =
1198
+ callbacks.length === 1 && ts.isJsxExpression(callbacks[0]) ? callbacks[0].expression : null
1199
+ if (
1200
+ !callback ||
1201
+ !ts.isArrowFunction(callback) ||
1202
+ ts.isBlock(callback.body) ||
1203
+ callback.parameters.length < 1 ||
1204
+ callback.parameters.length > 2
1205
+ )
1206
+ fail(
1207
+ tag,
1208
+ 'For takes one child: {(item) => <Element key={item.id} ... />} or {(item, index) => ...}.',
1209
+ )
1210
+ const inner = child(ctx)
1211
+ const [itemName, indexName] = callback.parameters.map((parameter) => {
1212
+ if (!ts.isIdentifier(parameter.name) || parameter.initializer)
1213
+ fail(parameter, 'Use simple parameter names.')
1214
+ checkName(parameter, parameter.name.text, 'Parameter')
1215
+ return parameter.name.text
1216
+ })
1217
+ inner.locals.set(itemName, each.type.of)
1218
+ if (indexName) inner.locals.set(indexName, T.number)
1219
+ const body = callback.body
1220
+ const element = ts.isParenthesizedExpression(body) ? body.expression : body
1221
+ if (!ts.isJsxElement(element) && !ts.isJsxSelfClosingElement(element))
1222
+ fail(body, 'For returns one element with a key.')
1223
+ const keyAttribute = attributes(jsxName(element).tag).get('key')
1224
+ if (!keyAttribute)
1225
+ fail(element, 'Give the repeated element a key, for example key={task.id}.')
1226
+ const keyNode = attributeValue(keyAttribute)
1227
+ let key
1228
+ if (ts.isIdentifier(keyNode) && keyNode.text === itemName && primitive(each.type.of))
1229
+ key = null
1230
+ else if (
1231
+ ts.isPropertyAccessExpression(keyNode) &&
1232
+ ts.isIdentifier(keyNode.expression) &&
1233
+ keyNode.expression.text === itemName &&
1234
+ each.type.of.k === 'record'
1235
+ ) {
1236
+ const field = records
1237
+ .get(each.type.of.name)
1238
+ .fields.find((f) => f.name === keyNode.name.text)
1239
+ if (!field || !['string', 'number'].includes(field.type.k))
1240
+ fail(keyNode, 'The key must be a string or number field of the item.')
1241
+ key = field.name
1242
+ } else
1243
+ fail(
1244
+ keyNode,
1245
+ `Use a field of ${itemName} as key, for example key={${itemName}.id}, or the item itself for a list of strings or numbers.`,
1246
+ )
1247
+ inner.keyed = true
1248
+ inner.inFor = true
1249
+ const rendered = view(element, inner)
1250
+ return {
1251
+ v: 'for',
1252
+ each,
1253
+ item: itemName,
1254
+ index: indexName ?? null,
1255
+ key,
1256
+ body: rendered,
1257
+ ...(animate ? { animate: true } : {}),
1258
+ }
1259
+ }
1260
+ const keyed = ctx.keyed
1261
+ ctx = { ...ctx, keyed: false }
1262
+ const spec = primitives[name]
1263
+ if (spec) {
1264
+ const props = {}
1265
+ for (const [key, attribute] of attrs) {
1266
+ if (key === 'key') continue
1267
+ const kind = spec[key]
1268
+ if (!kind) fail(attribute, `${name} supports ${Object.keys(spec).join(', ')}.`)
1269
+ if (!attribute.initializer && kind === 'boolean') {
1270
+ props[key] = { expr: { e: 'lit', value: true, type: T.boolean } }
1271
+ continue
1272
+ }
1273
+ const value = attributeValue(attribute)
1274
+ switch (kind) {
1275
+ case 'space':
1276
+ if (!ts.isStringLiteral(value))
1277
+ fail(attribute, `${key} takes a spacing token name, for example ${key}="md".`)
1278
+ props[key] = { lit: value.text }
1279
+ break
1280
+ case 'string':
1281
+ props[key] = ts.isStringLiteral(value)
1282
+ ? { lit: value.text }
1283
+ : { expr: expr(value, ctx, T.string) }
1284
+ break
1285
+ case 'boolean':
1286
+ props[key] = { expr: expr(value, ctx, T.boolean) }
1287
+ break
1288
+ case 'number':
1289
+ props[key] = { expr: expr(value, ctx, T.number) }
1290
+ break
1291
+ case 'optional-string':
1292
+ props[key] = { expr: expr(value, ctx, T.optional(T.string)) }
1293
+ break
1294
+ case 'options':
1295
+ props[key] = { expr: expr(value, ctx, T.array(selectOption())) }
1296
+ break
1297
+ case 'handler':
1298
+ props[key] = handler(value, [], ctx)
1299
+ break
1300
+ case 'shortcut': {
1301
+ if (!ts.isStringLiteral(value))
1302
+ fail(attribute, 'shortcut is written as a literal, for example shortcut="mod+k".')
1303
+ if (ctx.inFor) fail(attribute, 'Repeated rows cannot share one shortcut.')
1304
+ // The shortcut exists while its button does; a hidden button would differ by target.
1305
+ if (ctx.inShow)
1306
+ fail(attribute, 'A button with a shortcut stays on screen; use disabled, not Show.')
1307
+ const taken = (ctx.component.shortcuts ??= new Set())
1308
+ if (taken.has(value.text))
1309
+ fail(attribute, `${value.text} is already used in this file.`)
1310
+ taken.add(value.text)
1311
+ props[key] = { lit: value.text }
1312
+ break
1313
+ }
1314
+ case 'string-handler':
1315
+ case 'key':
1316
+ props[key] = handler(value, [T.string], ctx)
1317
+ break
1318
+ case 'boolean-handler':
1319
+ props[key] = handler(value, [T.boolean], ctx)
1320
+ break
1321
+ case 'ref': {
1322
+ if (!ts.isIdentifier(value) || ctx.members.get(value.text) !== 'Ref')
1323
+ fail(attribute, 'ref takes a field reference declared with useRef.')
1324
+ if (ctx.inFor) fail(attribute, 'Repeated rows cannot share one field reference.')
1325
+ const reference = ctx.component.refs.find((ref) => ref.name === value.text)
1326
+ if (reference.field) fail(attribute, `${value.text} already belongs to another field.`)
1327
+ reference.field = true
1328
+ props[key] = { ref: value.text }
1329
+ break
1330
+ }
1331
+ }
1332
+ }
1333
+ for (const required of {
1334
+ MButton: ['text', 'onClick'],
1335
+ MInput: ['label', 'value', 'onChange'],
1336
+ MCheckbox: ['label', 'checked', 'onChange'],
1337
+ MSelect: ['label', 'value', 'options', 'onChange'],
1338
+ }[name] ?? [])
1339
+ if (!props[required]) fail(tag, `${name} needs ${required}.`)
1340
+ if (name === 'MInput') {
1341
+ // These choose the platform control, so they are fixed in the source.
1342
+ for (const fixed of ['type', 'multiline'])
1343
+ if (props[fixed] && !('lit' in props[fixed]) && !isLiteral(attrs.get(fixed)))
1344
+ fail(attrs.get(fixed), `${fixed} must be written as a literal value.`)
1345
+ const multiline = props.multiline && props.multiline.expr.value === true
1346
+ if (multiline && props.type && props.type.lit !== 'text')
1347
+ fail(attrs.get('type'), 'A multiline MInput is always type="text".')
1348
+ if (multiline && props.onSubmit)
1349
+ fail(
1350
+ attrs.get('onSubmit'),
1351
+ 'Return adds a line in a multiline MInput; onSubmit needs a single-line field.',
1352
+ )
1353
+ if (props.rows && !multiline) fail(attrs.get('rows'), 'rows needs multiline.')
1354
+ }
1355
+ if ((name === 'MColumn' || name === 'MRow') && props.onKeyDown && !props.label)
1356
+ fail(tag, 'A stack that handles keys needs a label, so assistive technology can name it.')
1357
+ if (name === 'MCard' && props.onClick && !props.label)
1358
+ fail(tag, 'A card with onClick needs a label: it is announced as one button.')
1359
+ if (name === 'MText') {
1360
+ const parts = []
1361
+ for (const kid of kids) {
1362
+ if (ts.isJsxText(kid)) {
1363
+ const text = jsxText(kid.text)
1364
+ if (text) parts.push(text)
1365
+ } else if (ts.isJsxExpression(kid)) {
1366
+ if (!kid.expression) continue
1367
+ const value = expr(kid.expression, ctx)
1368
+ if (!primitive(value.type)) fail(kid, 'MText shows strings, numbers and booleans.')
1369
+ if (value.e === 'lit' && value.type.k === 'string') parts.push(value.value)
1370
+ else if (value.e === 'template') parts.push(...value.parts)
1371
+ else parts.push(value)
1372
+ } else fail(kid, 'MText contains text and values only.')
1373
+ }
1374
+ if (!parts.length) fail(tag, 'MText needs text.')
1375
+ return { v: 'text', props, parts, keyed }
1376
+ }
1377
+ if (
1378
+ !['MColumn', 'MRow', 'MGrid', 'MCard'].includes(name) &&
1379
+ kids.some((kid) => !(ts.isJsxText(kid) && !kid.text.trim()))
1380
+ )
1381
+ fail(node, `${name} takes no children; use its properties.`)
1382
+ const parent = { tag: name, gap: props.gap?.lit }
1383
+ const element = {
1384
+ v: 'element',
1385
+ tag: name,
1386
+ props,
1387
+ children: children(kids, { ...ctx, parent }),
1388
+ keyed,
1389
+ }
1390
+ // The whole card is one button; controls inside it could not be reached.
1391
+ if (name === 'MCard' && props.onClick && element.children.some(hasControl))
1392
+ fail(tag, 'A card with onClick shows text only; put buttons and fields outside it.')
1393
+ if (parent.animated) element.animatesList = true
1394
+ return element
1395
+ }
1396
+ const path = ctx.component.imports.get(name)
1397
+ if (!path) fail(tag, `${name} is not a Mavis primitive or an imported shared component.`)
1398
+ if (kids.some((kid) => !(ts.isJsxText(kid) && !kid.text.trim())))
1399
+ fail(node, 'Shared components do not take children yet.')
1400
+ const target = components.get(path)
1401
+ const props = []
1402
+ for (const prop of target.props) {
1403
+ const attribute = attrs.get(prop.name)
1404
+ if (!attribute) fail(tag, `${name} needs ${prop.name}.`)
1405
+ const value = attributeValue(attribute)
1406
+ props.push({
1407
+ name: prop.name,
1408
+ value:
1409
+ prop.type.k === 'function'
1410
+ ? { handler: handler(value, prop.type.params, ctx) }
1411
+ : { expr: expr(value, ctx, prop.type) },
1412
+ })
1413
+ }
1414
+ for (const key of attrs.keys())
1415
+ if (key !== 'key' && !target.props.some((prop) => prop.name === key))
1416
+ fail(attrs.get(key), `${name} has no property ${key}.`)
1417
+ return { v: 'component', name, props, keyed }
1418
+ }
1419
+ }
1420
+
1421
+ /** JSX whitespace rules: trim around line breaks and join lines with one space. */
1422
+ export function jsxText(raw) {
1423
+ const lines = raw.split(/\r\n|\n|\r/)
1424
+ let last = 0
1425
+ lines.forEach((line, i) => {
1426
+ if (/[^ \t]/.test(line)) last = i
1427
+ })
1428
+ let out = ''
1429
+ lines.forEach((line, i) => {
1430
+ const isFirst = i === 0
1431
+ const isLast = i === lines.length - 1
1432
+ let text = line.replace(/\t/g, ' ')
1433
+ if (!isFirst) text = text.replace(/^[ ]+/, '')
1434
+ if (!isLast) text = text.replace(/[ ]+$/, '')
1435
+ if (text) {
1436
+ if (i !== last) text += ' '
1437
+ out += text
1438
+ }
1439
+ })
1440
+ return out
1441
+ }