goaljs 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/package.json +7 -4
- package/recipes/README.md +100 -0
- package/recipes/drizzle.js +59 -0
- package/recipes/eslint.js +38 -0
- package/recipes/playwright.js +48 -0
- package/recipes/postcss.js +32 -0
- package/recipes/prettier.js +19 -0
- package/recipes/prisma.js +67 -0
- package/recipes/sentry.js +57 -0
- package/recipes/tailwindcss.js +60 -0
- package/recipes/vitest.js +43 -0
- package/src/add.js +179 -0
- package/src/app.js +18 -3
- package/src/build.js +60 -17
- package/src/cli.js +33 -5
- package/src/compiler.js +10 -4
- package/src/css.js +30 -0
- package/src/eslint.js +106 -0
- package/src/rt.js +32 -2
- package/src/syntax.js +139 -9
- package/src/types.js +464 -0
- package/src/vite.js +25 -4
package/src/types.js
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
// Types, in a file that starts with #strict (see syntax.js, which reads them out of the code).
|
|
2
|
+
//
|
|
3
|
+
// check() runs on the file's AST before it is compiled. A #strict file gives a type to what has no
|
|
4
|
+
// other way to get one: a component's props, a server function's parameters, and a var whose initial
|
|
5
|
+
// value doesn't say (an empty list, null), or that comes from a .js module, which has no types. The
|
|
6
|
+
// rest is inferred. It reports a prop of the wrong type, a required prop left out or one the component
|
|
7
|
+
// doesn't take; state, an argument or a returned value of the wrong type; markup that can't render;
|
|
8
|
+
// and a .goal import without #strict. What can't be inferred is unknown, and unknown is never an error.
|
|
9
|
+
//
|
|
10
|
+
// A type is { k: 'string' | 'number' | 'boolean' | 'null' | 'undefined' | 'void' | 'unknown' |
|
|
11
|
+
// 'Markup' | 'never' } or { k: 'lit', v }, { k: 'array', of }, { k: 'object', fields: { name:
|
|
12
|
+
// { type, optional } } }, { k: 'fn', params: [{ type, optional }], returns }, { k: 'union', of }, or
|
|
13
|
+
// { k: 'ref', name }, a declared type.
|
|
14
|
+
|
|
15
|
+
import { parse } from '@babel/parser';
|
|
16
|
+
import traverse from '@babel/traverse';
|
|
17
|
+
import * as t from '@babel/types';
|
|
18
|
+
import { desugar } from './syntax.js';
|
|
19
|
+
|
|
20
|
+
const T = (k) => ({ k });
|
|
21
|
+
const UNKNOWN = T('unknown');
|
|
22
|
+
const BOOLEAN_ATTRS = new Set(['disabled', 'checked', 'hidden', 'required', 'readonly', 'multiple', 'selected', 'open', 'autofocus']);
|
|
23
|
+
const ARRAY_SAME = new Set(['filter', 'slice', 'concat', 'reverse', 'sort', 'toSorted', 'toReversed']);
|
|
24
|
+
const ARRAY_BOOL = new Set(['some', 'every', 'includes']);
|
|
25
|
+
const STRING_SAME = new Set(['trim', 'slice', 'toUpperCase', 'toLowerCase', 'replace', 'replaceAll', 'padStart', 'padEnd', 'repeat', 'at']);
|
|
26
|
+
const STRING_BOOL = new Set(['includes', 'startsWith', 'endsWith']);
|
|
27
|
+
|
|
28
|
+
/** The words a type is written in, for errors. */
|
|
29
|
+
export function show(x) {
|
|
30
|
+
switch (x.k) {
|
|
31
|
+
case 'lit':
|
|
32
|
+
return JSON.stringify(x.v);
|
|
33
|
+
case 'array':
|
|
34
|
+
return `${x.of.k === 'union' || x.of.k === 'fn' ? `(${show(x.of)})` : show(x.of)}[]`;
|
|
35
|
+
case 'object':
|
|
36
|
+
return `{ ${Object.entries(x.fields).map(([n, f]) => `${n}${f.optional ? '?' : ''}: ${show(f.type)}`).join(', ')} }`;
|
|
37
|
+
case 'fn':
|
|
38
|
+
return `(${x.params.map((p, i) => `${String.fromCharCode(97 + i)}${p.optional ? '?' : ''}: ${show(p.type)}`).join(', ')}) => ${show(x.returns)}`;
|
|
39
|
+
case 'union':
|
|
40
|
+
return x.of.map(show).join(' | ');
|
|
41
|
+
case 'ref':
|
|
42
|
+
return x.name;
|
|
43
|
+
default:
|
|
44
|
+
return x.k;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const union = (of) => {
|
|
49
|
+
const flat = [];
|
|
50
|
+
for (const x of of) for (const y of x.k === 'union' ? x.of : [x]) if (!flat.some((z) => show(z) === show(y))) flat.push(y);
|
|
51
|
+
return flat.length === 1 ? flat[0] : { k: 'union', of: flat };
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** A literal's own type: what a var it starts takes (var n = 0 is a number, not just 0). */
|
|
55
|
+
const widen = (x) => (x.k === 'lit' ? T(typeof x.v) : x.k === 'union' ? union(x.of.map(widen)) : x);
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Checks a #strict file. `d` is what desugar() read (its types), `other(spec)` what another .goal file
|
|
59
|
+
* exports (see exportsOf), and `fail(message, node)` reports at a node of `ast`, whose positions are
|
|
60
|
+
* the source's.
|
|
61
|
+
*/
|
|
62
|
+
export function check(ast, d, other, fail) {
|
|
63
|
+
const decls = new Map([...d.types.decls].map(([n, x]) => [n, x.type]));
|
|
64
|
+
const pos = (node) => node.loc.start.index; // in the source (see relocate in compiler.js)
|
|
65
|
+
const at = (node) => d.types.at.get(pos(node));
|
|
66
|
+
const result = (fn) => d.types.at.get(-pos(fn) - 1); // a function's written result: see syntax.js
|
|
67
|
+
const here = (index) => ({ loc: { start: { index } } });
|
|
68
|
+
const resolve = (x) => {
|
|
69
|
+
while (x.k === 'ref') x = decls.get(x.name);
|
|
70
|
+
return x;
|
|
71
|
+
};
|
|
72
|
+
const known = (x, node) => {
|
|
73
|
+
if (x.k === 'ref' && !decls.has(x.name)) fail(`no type is named ${x.name}`, node);
|
|
74
|
+
for (const y of [...(x.of ? [x.of].flat() : []), ...Object.values(x.fields ?? {}).map((f) => f.type), ...(x.params ?? []).map((p) => p.type), ...(x.returns ? [x.returns] : [])])
|
|
75
|
+
known(y, node);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// Imports: .goal files that are #strict too (their types, components and server functions), and
|
|
79
|
+
// .js modules, whose values are unknown until given a type.
|
|
80
|
+
const imported = new Map(); // local name -> its type
|
|
81
|
+
for (const s of ast.program.body) {
|
|
82
|
+
if (!t.isImportDeclaration(s)) continue;
|
|
83
|
+
const spec = s.source.value;
|
|
84
|
+
if (!spec.endsWith('.goal')) {
|
|
85
|
+
for (const x of s.specifiers) imported.set(x.local.name, { k: 'unknown', js: spec });
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const info = other?.(spec);
|
|
89
|
+
if (!info?.strict) fail(`${spec} isn't #strict: a #strict file can import only #strict .goal files`, s);
|
|
90
|
+
s.specifiers = s.specifiers.filter((x) => {
|
|
91
|
+
const name = t.isImportSpecifier(x) ? x.imported.name : 'default';
|
|
92
|
+
if (info.types.has(name)) {
|
|
93
|
+
decls.set(x.local.name, info.types.get(name)); // a type: it exists only here
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
imported.set(x.local.name, info.values.get(name) ?? UNKNOWN);
|
|
97
|
+
return true;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
for (const x of d.types.decls.values()) known(x.type, here(x.at));
|
|
101
|
+
for (const [i, x] of d.types.at) known(x, here(i < 0 ? -i - 1 : i));
|
|
102
|
+
|
|
103
|
+
const server = new Set(d.serverFns.map((f) => f.name));
|
|
104
|
+
const fns = new Map(); // function node -> its type
|
|
105
|
+
const comps = new Map(); // component name -> its props type, or null for one without props
|
|
106
|
+
const types = new Map(); // binding -> its type, once worked out
|
|
107
|
+
|
|
108
|
+
traverse(ast, {
|
|
109
|
+
Program(p) {
|
|
110
|
+
for (const s of p.get('body')) {
|
|
111
|
+
const fn = s.isExportNamedDeclaration() || s.isExportDefaultDeclaration() ? s.get('declaration') : s;
|
|
112
|
+
if (!fn.isFunctionDeclaration() || !fn.node.id) continue;
|
|
113
|
+
const name = fn.node.id.name;
|
|
114
|
+
const param = fn.node.params[0];
|
|
115
|
+
if (/^[A-Z]/.test(name)) {
|
|
116
|
+
if (param && !at(param)) fail(`give ${name}'s props a type: function ${name}(props: { ... })`, param);
|
|
117
|
+
comps.set(name, param ? resolve(at(param)) : null);
|
|
118
|
+
} else if (server.has(name))
|
|
119
|
+
for (const x of fn.node.params) if (!at(x)) fail(`${name}'s arguments come from the network: give ${t.isIdentifier(x) ? x.name : 'each one'} a type`, x);
|
|
120
|
+
const returns = result(fn.node);
|
|
121
|
+
if (server.has(name) && returns && !json(resolve(returns))) fail(`${name}'s result travels as JSON: ${show(returns)} can't`, fn.node);
|
|
122
|
+
}
|
|
123
|
+
p.stop();
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
/** Can a value of this type travel as JSON? */
|
|
128
|
+
function json(x) {
|
|
129
|
+
x = resolve(x);
|
|
130
|
+
if (x.k === 'fn' || x.k === 'Markup') return false;
|
|
131
|
+
if (x.k === 'array') return json(x.of);
|
|
132
|
+
if (x.k === 'union') return x.of.every(json);
|
|
133
|
+
if (x.k === 'object') return Object.values(x.fields).every((f) => json(f.type));
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Does a value of type s fit where type to is expected? Unknown fits anywhere, and takes anything. */
|
|
138
|
+
function fits(s, to) {
|
|
139
|
+
s = resolve(s);
|
|
140
|
+
to = resolve(to);
|
|
141
|
+
if (s.k === 'unknown' || to.k === 'unknown' || s.k === 'never' || to.k === 'void') return true;
|
|
142
|
+
if (s.k === 'union') return s.of.every((x) => fits(x, to));
|
|
143
|
+
if (to.k === 'union') return to.of.some((x) => fits(s, x));
|
|
144
|
+
if (s.k === 'lit') return to.k === 'lit' ? to.v === s.v : to.k === typeof s.v;
|
|
145
|
+
if (s.k !== to.k) return s.k === 'void' && to.k === 'undefined';
|
|
146
|
+
if (s.k === 'array') return fits(s.of, to.of);
|
|
147
|
+
if (s.k === 'object')
|
|
148
|
+
return Object.entries(to.fields).every(([n, f]) => (s.fields[n] ? fits(s.fields[n].type, f.optional ? union([f.type, T('undefined')]) : f.type) : f.optional));
|
|
149
|
+
if (s.k === 'fn') return to.params.every((p, i) => !s.params[i] || fits(p.type, s.params[i].type)) && fits(s.returns, to.returns);
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The type of what a binding holds. */
|
|
154
|
+
function bindingType(b) {
|
|
155
|
+
if (types.has(b)) return types.get(b);
|
|
156
|
+
types.set(b, UNKNOWN); // while working it out: a binding that reads itself is unknown
|
|
157
|
+
const x = workOut(b);
|
|
158
|
+
types.set(b, x);
|
|
159
|
+
return x;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function workOut(b) {
|
|
163
|
+
const p = b.path;
|
|
164
|
+
if (imported.has(b.identifier.name) && (p.isImportSpecifier() || p.isImportDefaultSpecifier() || p.isImportNamespaceSpecifier())) return imported.get(b.identifier.name);
|
|
165
|
+
if (p.isVariableDeclarator()) {
|
|
166
|
+
if (!t.isIdentifier(p.node.id)) return UNKNOWN;
|
|
167
|
+
const written = at(p.node.id);
|
|
168
|
+
if (written) return written;
|
|
169
|
+
const init = p.get('init');
|
|
170
|
+
const x = init.node ? typeOf(init) : T('undefined');
|
|
171
|
+
const name = p.node.id.name;
|
|
172
|
+
if (x.js) fail(`${name} comes from ${x.js}, which has no types: give it one, like ${p.parent.kind} ${name}: Type = ...`, p.node);
|
|
173
|
+
if (b.kind === 'var' && (!init.node || x.k === 'null' || x.k === 'undefined' || (x.k === 'array' && x.of.k === 'never')))
|
|
174
|
+
fail(`give ${name} a type: its initial value doesn't say, so write var ${name}: Type = ...`, p.node);
|
|
175
|
+
return widen(x);
|
|
176
|
+
}
|
|
177
|
+
if (p.isFunctionDeclaration()) return fnType(p);
|
|
178
|
+
if (b.kind === 'param') return paramType(b);
|
|
179
|
+
return UNKNOWN;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** A parameter's type: written, a component's prop, or what a list method gives its callback. */
|
|
183
|
+
function paramType(b) {
|
|
184
|
+
const fn = b.scope.path;
|
|
185
|
+
const i = fn.node.params.findIndex((x) => Object.values(t.getBindingIdentifiers(x)).includes(b.identifier));
|
|
186
|
+
const param = fn.node.params[i];
|
|
187
|
+
const whole = t.isAssignmentPattern(param) ? param.left : param;
|
|
188
|
+
const written = at(whole);
|
|
189
|
+
let x = written ? resolve(written) : null;
|
|
190
|
+
if (!x && fn.parentPath.isCallExpression() && fn.listKey === 'arguments' && fn.key === 0) {
|
|
191
|
+
const callee = fn.parentPath.get('callee');
|
|
192
|
+
if (callee.isMemberExpression() && !callee.node.computed) {
|
|
193
|
+
const list = resolve(typeOf(callee.get('object')));
|
|
194
|
+
if (list.k === 'array') x = i === 0 ? list.of : i === 1 ? T('number') : null;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (!x) return UNKNOWN;
|
|
198
|
+
if (whole === b.identifier) return x;
|
|
199
|
+
// Destructured: { a, b } takes the fields of the object type.
|
|
200
|
+
const field = x.k === 'object' ? x.fields[b.identifier.name] : null;
|
|
201
|
+
return field ? (field.optional ? union([field.type, T('undefined')]) : field.type) : UNKNOWN;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function fnType(p) {
|
|
205
|
+
if (fns.has(p.node)) return fns.get(p.node);
|
|
206
|
+
const written = result(p.node);
|
|
207
|
+
fns.set(p.node, { k: 'fn', params: [], returns: UNKNOWN });
|
|
208
|
+
const params = p.node.params.map((x) => ({ type: at(t.isAssignmentPattern(x) ? x.left : x) ?? UNKNOWN, optional: t.isAssignmentPattern(x) }));
|
|
209
|
+
let returns = written;
|
|
210
|
+
if (!returns) {
|
|
211
|
+
const body = p.get('body');
|
|
212
|
+
if (!body.isBlockStatement()) returns = typeOf(body);
|
|
213
|
+
else {
|
|
214
|
+
const found = [];
|
|
215
|
+
body.traverse({
|
|
216
|
+
ReturnStatement(r) {
|
|
217
|
+
found.push(r.node.argument ? typeOf(r.get('argument')) : T('undefined')); // its own: nested functions are skipped
|
|
218
|
+
},
|
|
219
|
+
Function(f) {
|
|
220
|
+
f.skip();
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
returns = found.length ? union(found) : T('void');
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const x = { k: 'fn', params, returns };
|
|
227
|
+
fns.set(p.node, x);
|
|
228
|
+
return x;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** The type of an expression, as far as it can be worked out: unknown otherwise. */
|
|
232
|
+
function typeOf(p) {
|
|
233
|
+
const n = p.node;
|
|
234
|
+
if (p.isNumericLiteral() || p.isStringLiteral() || p.isBooleanLiteral()) return { k: 'lit', v: n.value };
|
|
235
|
+
if (p.isNullLiteral()) return T('null');
|
|
236
|
+
if (p.isTemplateLiteral()) return T('string');
|
|
237
|
+
if (p.isJSXElement() || p.isJSXFragment()) return T('Markup');
|
|
238
|
+
if (p.isIdentifier()) {
|
|
239
|
+
if (n.name === 'undefined') return T('undefined');
|
|
240
|
+
const b = p.scope.getBinding(n.name);
|
|
241
|
+
return b ? bindingType(b) : UNKNOWN;
|
|
242
|
+
}
|
|
243
|
+
if (p.isArrayExpression()) return { k: 'array', of: n.elements.length ? widen(union(p.get('elements').map(typeOf))) : T('never') };
|
|
244
|
+
if (p.isObjectExpression()) {
|
|
245
|
+
const fields = {};
|
|
246
|
+
for (const f of p.get('properties')) {
|
|
247
|
+
if (!f.isObjectProperty() || f.node.computed) return UNKNOWN;
|
|
248
|
+
fields[t.isIdentifier(f.node.key) ? f.node.key.name : f.node.key.value] = { type: widen(typeOf(f.get('value'))), optional: false };
|
|
249
|
+
}
|
|
250
|
+
return { k: 'object', fields };
|
|
251
|
+
}
|
|
252
|
+
if (p.isMemberExpression()) return member(p);
|
|
253
|
+
if (p.isCallExpression()) return call(p);
|
|
254
|
+
if (p.isBinaryExpression()) {
|
|
255
|
+
if (n.operator === '+') {
|
|
256
|
+
const [a, b] = [resolve(typeOf(p.get('left'))), resolve(typeOf(p.get('right')))];
|
|
257
|
+
const str = (x) => x.k === 'string' || (x.k === 'lit' && typeof x.v === 'string');
|
|
258
|
+
const num = (x) => x.k === 'number' || (x.k === 'lit' && typeof x.v === 'number');
|
|
259
|
+
return str(a) || str(b) ? T('string') : num(a) && num(b) ? T('number') : UNKNOWN;
|
|
260
|
+
}
|
|
261
|
+
return ['-', '*', '/', '%', '**', '|', '&', '^', '<<', '>>', '>>>'].includes(n.operator) ? T('number') : T('boolean');
|
|
262
|
+
}
|
|
263
|
+
if (p.isLogicalExpression()) return union([typeOf(p.get('left')), typeOf(p.get('right'))]);
|
|
264
|
+
if (p.isUnaryExpression()) return n.operator === '!' || n.operator === 'delete' ? T('boolean') : n.operator === 'typeof' ? T('string') : n.operator === 'void' ? T('undefined') : T('number');
|
|
265
|
+
if (p.isUpdateExpression()) return T('number');
|
|
266
|
+
if (p.isConditionalExpression()) return union([typeOf(p.get('consequent')), typeOf(p.get('alternate'))]);
|
|
267
|
+
if (p.isAssignmentExpression()) return typeOf(p.get('right'));
|
|
268
|
+
if (p.isArrowFunctionExpression() || p.isFunctionExpression()) return fnType(p);
|
|
269
|
+
if (p.isAwaitExpression()) return typeOf(p.get('argument'));
|
|
270
|
+
return UNKNOWN;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function member(p) {
|
|
274
|
+
const obj = resolve(typeOf(p.get('object')));
|
|
275
|
+
if (obj.k === 'unknown') return obj;
|
|
276
|
+
if (p.node.computed) return obj.k === 'array' ? obj.of : UNKNOWN;
|
|
277
|
+
const name = p.node.property.name;
|
|
278
|
+
if (name === 'length' && (obj.k === 'array' || obj.k === 'string')) return T('number');
|
|
279
|
+
const f = obj.k === 'object' ? obj.fields[name] : null;
|
|
280
|
+
return f ? (f.optional ? union([f.type, T('undefined')]) : f.type) : UNKNOWN;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function call(p) {
|
|
284
|
+
const callee = p.get('callee');
|
|
285
|
+
const args = p.get('arguments');
|
|
286
|
+
if (callee.isIdentifier()) {
|
|
287
|
+
const conv = { Number: 'number', String: 'string', Boolean: 'boolean' }[callee.node.name];
|
|
288
|
+
if (conv && !p.scope.getBinding(callee.node.name)) return T(conv);
|
|
289
|
+
}
|
|
290
|
+
if (callee.isMemberExpression() && !callee.node.computed) {
|
|
291
|
+
const obj = resolve(typeOf(callee.get('object')));
|
|
292
|
+
const name = callee.node.property.name;
|
|
293
|
+
if (obj.k === 'array') {
|
|
294
|
+
if (name === 'map') {
|
|
295
|
+
const fn = args[0] && resolve(typeOf(args[0]));
|
|
296
|
+
return { k: 'array', of: fn?.k === 'fn' ? widen(fn.returns) : UNKNOWN };
|
|
297
|
+
}
|
|
298
|
+
if (ARRAY_SAME.has(name)) return obj;
|
|
299
|
+
if (name === 'find') return union([obj.of, T('undefined')]);
|
|
300
|
+
if (ARRAY_BOOL.has(name)) return T('boolean');
|
|
301
|
+
if (name === 'join') return T('string');
|
|
302
|
+
if (name === 'indexOf' || name === 'findIndex') return T('number');
|
|
303
|
+
}
|
|
304
|
+
if (obj.k === 'string' || (obj.k === 'lit' && typeof obj.v === 'string')) {
|
|
305
|
+
if (STRING_SAME.has(name)) return T('string');
|
|
306
|
+
if (STRING_BOOL.has(name)) return T('boolean');
|
|
307
|
+
if (name === 'indexOf') return T('number');
|
|
308
|
+
if (name === 'split') return { k: 'array', of: T('string') };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const fn = resolve(typeOf(callee));
|
|
312
|
+
return fn.k === 'fn' ? fn.returns : fn.js ? fn : UNKNOWN;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const sure = (s, to, message, node) => {
|
|
316
|
+
if (!fits(s, to)) fail(message, node);
|
|
317
|
+
};
|
|
318
|
+
const near = (word, words) => words.find((w) => w !== word && w.length > 2 && distance(word, w) <= 2);
|
|
319
|
+
|
|
320
|
+
// What each part of the file does with these types.
|
|
321
|
+
traverse(ast, {
|
|
322
|
+
VariableDeclarator(p) {
|
|
323
|
+
if (!t.isIdentifier(p.node.id)) return;
|
|
324
|
+
const b = p.scope.getBinding(p.node.id.name);
|
|
325
|
+
const x = bindingType(b);
|
|
326
|
+
if (at(p.node.id) && p.node.init) sure(typeOf(p.get('init')), x, `${p.node.id.name} is ${show(x)}, not ${show(widen(typeOf(p.get('init'))))}`, p.node.init);
|
|
327
|
+
},
|
|
328
|
+
AssignmentExpression(p) {
|
|
329
|
+
const left = p.get('left');
|
|
330
|
+
if (!left.isIdentifier() || p.node.operator !== '=') return;
|
|
331
|
+
const b = p.scope.getBinding(left.node.name);
|
|
332
|
+
if (!b) return;
|
|
333
|
+
const x = bindingType(b);
|
|
334
|
+
const v = typeOf(p.get('right'));
|
|
335
|
+
sure(v, x, `${left.node.name} is ${show(x)}, not ${show(widen(v))}`, p.node);
|
|
336
|
+
},
|
|
337
|
+
ReturnStatement(p) {
|
|
338
|
+
const fn = p.getFunctionParent();
|
|
339
|
+
const written = fn && result(fn.node);
|
|
340
|
+
if (!written || !p.node.argument) return;
|
|
341
|
+
const name = fn.node.id?.name ?? 'the function';
|
|
342
|
+
sure(typeOf(p.get('argument')), written, `${name} returns ${show(written)}, not ${show(widen(typeOf(p.get('argument'))))}`, p.node);
|
|
343
|
+
},
|
|
344
|
+
CallExpression(p) {
|
|
345
|
+
const fn = resolve(typeOf(p.get('callee')));
|
|
346
|
+
if (fn.k !== 'fn') return;
|
|
347
|
+
const name = p.get('callee').isIdentifier() ? p.node.callee.name : 'the function';
|
|
348
|
+
const args = p.get('arguments');
|
|
349
|
+
const need = fn.params.filter((x) => !x.optional).length;
|
|
350
|
+
if (args.length < need || args.length > fn.params.length) fail(`${name} takes ${need === fn.params.length ? need : `${need} to ${fn.params.length}`} argument${fn.params.length === 1 ? '' : 's'}, not ${args.length}`, p.node);
|
|
351
|
+
args.forEach((a, i) => sure(typeOf(a), fn.params.at(i).type, `${name} takes ${show(fn.params.at(i).type)}, not ${show(widen(typeOf(a)))}`, a.node));
|
|
352
|
+
},
|
|
353
|
+
JSXExpressionContainer(p) {
|
|
354
|
+
if (!p.parentPath.isJSXElement() && !p.parentPath.isJSXFragment()) return;
|
|
355
|
+
const e = p.get('expression');
|
|
356
|
+
if (e.isJSXEmptyExpression()) return;
|
|
357
|
+
const bad = unrenderable(typeOf(e));
|
|
358
|
+
if (bad) fail(bad === 'fn' ? "a function can't be rendered: call it, or render what it gives" : `${show(bad)} can't be rendered: render a field of it, like {${e.isIdentifier() ? e.node.name : 'it'}.${Object.keys(resolve(bad).fields)[0] ?? 'name'}}`, e.node);
|
|
359
|
+
},
|
|
360
|
+
JSXAttribute(p) {
|
|
361
|
+
const v = p.get('value');
|
|
362
|
+
const name = p.node.name.name;
|
|
363
|
+
if (!v.isJSXExpressionContainer() || /^[A-Z]/.test(p.parent.name.name)) return; // a component's prop: see JSXOpeningElement
|
|
364
|
+
if (BOOLEAN_ATTRS.has(name)) {
|
|
365
|
+
const x = typeOf(v.get('expression'));
|
|
366
|
+
sure(x, T('boolean'), `${name} takes true or false, not ${show(widen(x))}`, v.node);
|
|
367
|
+
}
|
|
368
|
+
},
|
|
369
|
+
JSXOpeningElement(p) {
|
|
370
|
+
const name = p.node.name.name;
|
|
371
|
+
if (typeof name !== 'string' || !/^[A-Z]/.test(name)) return;
|
|
372
|
+
const props = comps.has(name) ? comps.get(name) : resolve(imported.get(name) ?? UNKNOWN).props;
|
|
373
|
+
if (props === undefined) return; // a component whose props aren't known
|
|
374
|
+
const fields = props?.fields ?? {};
|
|
375
|
+
const given = new Set();
|
|
376
|
+
for (const a of p.get('attributes')) {
|
|
377
|
+
if (!a.isJSXAttribute()) return; // a spread: the compiler says it isn't supported
|
|
378
|
+
const prop = a.node.name.name;
|
|
379
|
+
given.add(prop);
|
|
380
|
+
if (!fields[prop]) fail(`${name} has no prop ${prop}${near(prop, Object.keys(fields)) ? `; did you mean ${near(prop, Object.keys(fields))}?` : ''}`, a.node);
|
|
381
|
+
const v = a.get('value');
|
|
382
|
+
const x = !v.node ? { k: 'lit', v: true } : v.isStringLiteral() ? { k: 'lit', v: v.node.value } : typeOf(v.get('expression'));
|
|
383
|
+
sure(x, fields[prop].type, `${name}'s ${prop} is ${show(fields[prop].type)}, not ${show(widen(x))}`, a.node);
|
|
384
|
+
}
|
|
385
|
+
const kids = p.parent.children.some((c) => !t.isJSXText(c) || c.value.trim());
|
|
386
|
+
if (kids) {
|
|
387
|
+
if (!fields.children) fail(`${name} takes no children`, p.parent);
|
|
388
|
+
given.add('children');
|
|
389
|
+
}
|
|
390
|
+
for (const [n, f] of Object.entries(fields)) if (!f.optional && !given.has(n)) fail(`${name} needs ${n}`, p.node);
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
// What the server checks at runtime: each server function's parameters, declared names written out.
|
|
395
|
+
const out = (x, seen = new Set()) => {
|
|
396
|
+
if (x.k === 'ref') return seen.has(x.name) ? UNKNOWN : out(decls.get(x.name), new Set([...seen, x.name]));
|
|
397
|
+
if (x.k === 'array') return { k: 'array', of: out(x.of, seen) };
|
|
398
|
+
if (x.k === 'union') return { k: 'union', of: x.of.map((y) => out(y, seen)) };
|
|
399
|
+
if (x.k === 'object') return { k: 'object', fields: Object.fromEntries(Object.entries(x.fields).map(([n, f]) => [n, { type: out(f.type, seen), optional: f.optional }])) };
|
|
400
|
+
return x;
|
|
401
|
+
};
|
|
402
|
+
const params = new Map();
|
|
403
|
+
for (const s of ast.program.body) {
|
|
404
|
+
const fn = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
405
|
+
if (t.isFunctionDeclaration(fn) && server.has(fn.id.name))
|
|
406
|
+
params.set(fn.id.name, fn.params.map((x) => ({ type: out(at(t.isAssignmentPattern(x) ? x.left : x)), optional: t.isAssignmentPattern(x) })));
|
|
407
|
+
}
|
|
408
|
+
return { params };
|
|
409
|
+
|
|
410
|
+
/** What in a type can't be rendered as markup: an object, or 'fn' for a function. */
|
|
411
|
+
function unrenderable(x) {
|
|
412
|
+
x = resolve(x);
|
|
413
|
+
if (x.k === 'fn') return 'fn';
|
|
414
|
+
if (x.k === 'object') return x;
|
|
415
|
+
if (x.k === 'array') return unrenderable(x.of);
|
|
416
|
+
if (x.k === 'union') return x.of.map(unrenderable).find(Boolean);
|
|
417
|
+
return null;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** How far apart two words are: edits to turn one into the other. */
|
|
422
|
+
function distance(a, b) {
|
|
423
|
+
let row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
424
|
+
for (let i = 1; i <= a.length; i++) {
|
|
425
|
+
const next = [i];
|
|
426
|
+
for (let j = 1; j <= b.length; j++) next.push(Math.min(row.at(j) + 1, next.at(j - 1) + 1, row.at(j - 1) + (a[i - 1] === b[j - 1] ? 0 : 1)));
|
|
427
|
+
row = next;
|
|
428
|
+
}
|
|
429
|
+
return row.at(-1);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* What a .goal file gives a #strict file that imports it: whether it is #strict, its exported types
|
|
434
|
+
* (with the names they use resolved), and the type of each exported value: a component carries its
|
|
435
|
+
* props as `props`, a server function its parameters and result.
|
|
436
|
+
*/
|
|
437
|
+
export function exportsOf(source, file) {
|
|
438
|
+
const d = desugar(source, file);
|
|
439
|
+
const info = { strict: d.strict, types: new Map(), values: new Map() };
|
|
440
|
+
if (!d.strict) return info;
|
|
441
|
+
const decls = new Map([...d.types.decls].map(([n, x]) => [n, x.type]));
|
|
442
|
+
const inline = (x, seen = new Set()) => {
|
|
443
|
+
if (x.k === 'ref') return decls.has(x.name) && !seen.has(x.name) ? inline(decls.get(x.name), new Set([...seen, x.name])) : UNKNOWN;
|
|
444
|
+
if (x.k === 'array') return { k: 'array', of: inline(x.of, seen) };
|
|
445
|
+
if (x.k === 'union') return { k: 'union', of: x.of.map((y) => inline(y, seen)) };
|
|
446
|
+
if (x.k === 'object') return { k: 'object', fields: Object.fromEntries(Object.entries(x.fields).map(([n, f]) => [n, { ...f, type: inline(f.type, seen) }])) };
|
|
447
|
+
if (x.k === 'fn') return { k: 'fn', params: x.params.map((p) => ({ ...p, type: inline(p.type, seen) })), returns: inline(x.returns, seen) };
|
|
448
|
+
return x;
|
|
449
|
+
};
|
|
450
|
+
for (const [n, x] of d.types.decls) if (x.exported) info.types.set(n, inline(x.type));
|
|
451
|
+
const at = (pos) => d.types.at.get(d.map(pos));
|
|
452
|
+
const server = new Set(d.serverFns.map((f) => f.name));
|
|
453
|
+
for (const s of parse(d.code, { sourceType: 'module', plugins: ['jsx'] }).program.body) {
|
|
454
|
+
const fn = s.declaration;
|
|
455
|
+
if (!t.isExportNamedDeclaration(s) || !t.isFunctionDeclaration(fn)) continue;
|
|
456
|
+
const name = fn.id.name;
|
|
457
|
+
if (/^[A-Z]/.test(name)) info.values.set(name, { k: 'unknown', props: fn.params[0] ? inline(at(fn.params[0].start) ?? UNKNOWN) : null });
|
|
458
|
+
else if (server.has(name)) {
|
|
459
|
+
const params = fn.params.map((x) => ({ type: inline(at(x.start) ?? UNKNOWN), optional: false }));
|
|
460
|
+
info.values.set(name, { k: 'fn', params, returns: inline(d.types.at.get(-d.map(fn.start) - 1) ?? UNKNOWN) });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return info;
|
|
464
|
+
}
|
package/src/vite.js
CHANGED
|
@@ -11,13 +11,17 @@
|
|
|
11
11
|
// (/ui/Panel.goal.render.js), which the browser renders components from. The .goal files themselves
|
|
12
12
|
// are never served. When a file changes, the open pages are told as goal dev tells them (see hmr.js):
|
|
13
13
|
// a stylesheet is swapped in place, and code renders the page again with each component's state.
|
|
14
|
+
// With a postcss.config.js, the stylesheets in public/ go through PostCSS as goal build's do (see
|
|
15
|
+
// css.js), and the app's .env is read into process.env as goal dev reads it.
|
|
14
16
|
|
|
15
|
-
import { readFileSync, readdirSync } from 'node:fs';
|
|
17
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
16
18
|
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
17
19
|
import { fileURLToPath } from 'node:url';
|
|
18
20
|
import { compile } from './compiler.js';
|
|
19
21
|
import { desugar } from './syntax.js';
|
|
22
|
+
import { exportsOf } from './types.js';
|
|
20
23
|
import { createApp } from './app.js';
|
|
24
|
+
import { postcss, postcssConfig } from './css.js';
|
|
21
25
|
|
|
22
26
|
const SRC = dirname(fileURLToPath(import.meta.url)); // compiled code imports the helpers from here
|
|
23
27
|
const SKIP = new Set(['node_modules', 'dist', 'public']);
|
|
@@ -57,6 +61,10 @@ export function goal({ config = {} } = {}) {
|
|
|
57
61
|
const names = desugar(readFileSync(target, 'utf8'), spec).serverFns.filter((f) => f.exported).map((f) => f.name);
|
|
58
62
|
return { base: slash(relative(root, target)).slice(0, -5), names };
|
|
59
63
|
},
|
|
64
|
+
typesOf: (spec) => {
|
|
65
|
+
const target = resolve(dirname(file), spec);
|
|
66
|
+
return exportsOf(readFileSync(target, 'utf8'), slash(relative(root, target)));
|
|
67
|
+
},
|
|
60
68
|
});
|
|
61
69
|
};
|
|
62
70
|
|
|
@@ -65,6 +73,7 @@ export function goal({ config = {} } = {}) {
|
|
|
65
73
|
config: () => ({ appType: 'custom' }), // the app's routes answer pages, not an index.html
|
|
66
74
|
configResolved(c) {
|
|
67
75
|
root = c.root;
|
|
76
|
+
if (existsSync(join(root, '.env'))) process.loadEnvFile(join(root, '.env'));
|
|
68
77
|
},
|
|
69
78
|
// A component's browser code: /ui/Panel.goal.Panel.client.js; a file's render module, imported as
|
|
70
79
|
// goal-render:./Panel.goal: /ui/Panel.goal.render.js. Both are made from the .goal file.
|
|
@@ -87,9 +96,20 @@ export function goal({ config = {} } = {}) {
|
|
|
87
96
|
},
|
|
88
97
|
configureServer(server) {
|
|
89
98
|
// Before Vite's own middleware: the .goal files stay on the server, as with goal build.
|
|
90
|
-
server.middlewares.use((req, res, next) => {
|
|
91
|
-
if (
|
|
92
|
-
|
|
99
|
+
server.middlewares.use(async (req, res, next) => {
|
|
100
|
+
if (/\.goal(\?|$)/.test(req.url)) return res.writeHead(404).end();
|
|
101
|
+
// A stylesheet in public/, through the app's PostCSS
|
|
102
|
+
const path = req.url.split('?')[0];
|
|
103
|
+
const file = join(server.config.publicDir, path);
|
|
104
|
+
const css = path.endsWith('.css') && file.startsWith(join(server.config.publicDir, sep)) && existsSync(file) && (await postcss(root, true));
|
|
105
|
+
if (!css) return next();
|
|
106
|
+
let out;
|
|
107
|
+
try {
|
|
108
|
+
out = await css(readFileSync(file, 'utf8'), file, file);
|
|
109
|
+
} catch (e) {
|
|
110
|
+
return next(e);
|
|
111
|
+
}
|
|
112
|
+
res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-cache' }).end(out);
|
|
93
113
|
});
|
|
94
114
|
// After it: what Vite doesn't serve, the app answers.
|
|
95
115
|
return () =>
|
|
@@ -116,6 +136,7 @@ export function goal({ config = {} } = {}) {
|
|
|
116
136
|
version++;
|
|
117
137
|
server.moduleGraph.invalidateAll(); // the server code reads the new files
|
|
118
138
|
tell({ type: file.endsWith('.css') ? 'css' : 'update', version });
|
|
139
|
+
if (!file.endsWith('.css') && postcssConfig(root)) tell({ type: 'css', version }); // the CSS may follow the code, as Tailwind's does
|
|
119
140
|
return []; // the pages update themselves
|
|
120
141
|
},
|
|
121
142
|
};
|