goaljs 0.5.0 → 0.6.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 +1 -0
- package/package.json +1 -1
- package/src/app.js +9 -1
- package/src/build.js +38 -9
- package/src/cli.js +21 -5
- package/src/compiler.js +10 -4
- package/src/rt.js +32 -2
- package/src/syntax.js +139 -9
- package/src/types.js +464 -0
- package/src/vite.js +5 -0
package/README.md
CHANGED
|
@@ -46,6 +46,7 @@ npx goal dev . # build the app in this folder, serve it on http://localho
|
|
|
46
46
|
also cover [routes](https://goallabs.github.io/goal/routes),
|
|
47
47
|
[components](https://goallabs.github.io/goal/components),
|
|
48
48
|
[server functions](https://goallabs.github.io/goal/server-functions),
|
|
49
|
+
[types](https://goallabs.github.io/goal/types),
|
|
49
50
|
[security](https://goallabs.github.io/goal/security),
|
|
50
51
|
[how it works](https://goallabs.github.io/goal/how-it-works),
|
|
51
52
|
[performance](https://goallabs.github.io/goal/performance), and working in
|
package/package.json
CHANGED
package/src/app.js
CHANGED
|
@@ -153,12 +153,20 @@ function table(routes) {
|
|
|
153
153
|
.sort((a, b) => a.n - b.n || a.i - b.i);
|
|
154
154
|
}
|
|
155
155
|
|
|
156
|
+
/** A path parameter: text, or a number for one typed {id: number}, which matches only a number. */
|
|
157
|
+
function param(r, name, seg, params) {
|
|
158
|
+
if (r.types?.[name] !== 'number') return !!(params[name] = seg);
|
|
159
|
+
if (!/^-?\d+(\.\d+)?$/.test(seg)) return false;
|
|
160
|
+
params[name] = Number(seg);
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
|
|
156
164
|
function match(routes, method, segs) {
|
|
157
165
|
const allow = new Set();
|
|
158
166
|
for (const r of routes) {
|
|
159
167
|
if (r.segs.length !== segs.length) continue;
|
|
160
168
|
const params = {};
|
|
161
|
-
if (!r.segs.every((s, i) => (s[0] === '{' ? (
|
|
169
|
+
if (!r.segs.every((s, i) => (s[0] === '{' ? param(r, s.slice(1, -1), segs[i], params) : s === segs[i]))) continue;
|
|
162
170
|
if (r.method === method) return { route: r, params };
|
|
163
171
|
allow.add(r.method);
|
|
164
172
|
}
|
package/src/build.js
CHANGED
|
@@ -13,6 +13,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
13
13
|
import { gzipSync } from 'node:zlib';
|
|
14
14
|
import * as esbuild from 'esbuild';
|
|
15
15
|
import { compile } from './compiler.js';
|
|
16
|
+
import { exportsOf } from './types.js';
|
|
16
17
|
import { desugar } from './syntax.js';
|
|
17
18
|
import { loaderScript } from './server.js';
|
|
18
19
|
import { createApp } from './app.js';
|
|
@@ -65,6 +66,41 @@ const entriesPlugin = (entries, renders) => {
|
|
|
65
66
|
};
|
|
66
67
|
};
|
|
67
68
|
|
|
69
|
+
/**
|
|
70
|
+
* What the .goal files tell each other: the server functions each exports, so files can import them,
|
|
71
|
+
* and what a #strict file that imports one gets from it (see types.js), each read once.
|
|
72
|
+
*/
|
|
73
|
+
function linker(app, all) {
|
|
74
|
+
const exported = new Map();
|
|
75
|
+
for (const rel of all.filter((f) => f.endsWith('.goal')))
|
|
76
|
+
exported.set(rel, desugar(readFileSync(join(app, rel), 'utf8'), rel).serverFns.filter((f) => f.exported).map((f) => f.name));
|
|
77
|
+
const typed = new Map();
|
|
78
|
+
const to = (rel, spec) => posix.join(posix.dirname(rel), spec);
|
|
79
|
+
return {
|
|
80
|
+
serverFunctions: (rel) => (spec) => (exported.has(to(rel, spec)) ? { base: to(rel, spec).slice(0, -5), names: exported.get(to(rel, spec)) } : null),
|
|
81
|
+
typesOf: (rel) => (spec) => {
|
|
82
|
+
const target = to(rel, spec);
|
|
83
|
+
if (!exported.has(target)) return null;
|
|
84
|
+
if (!typed.has(target)) typed.set(target, exportsOf(readFileSync(join(app, target), 'utf8'), target));
|
|
85
|
+
return typed.get(target);
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** goal check: compiles every .goal file as goal build does, types too, and gives each file's first error. */
|
|
91
|
+
export function check(app) {
|
|
92
|
+
const all = files(app);
|
|
93
|
+
const link = linker(app, all);
|
|
94
|
+
const errors = [];
|
|
95
|
+
for (const rel of all.filter((f) => f.endsWith('.goal')))
|
|
96
|
+
try {
|
|
97
|
+
compile(readFileSync(join(app, rel), 'utf8'), { file: rel, base: rel.slice(0, -5), rt: RT, keyed: KEYED, serverFunctions: link.serverFunctions(rel), typesOf: link.typesOf(rel) });
|
|
98
|
+
} catch (e) {
|
|
99
|
+
errors.push(e.message);
|
|
100
|
+
}
|
|
101
|
+
return errors;
|
|
102
|
+
}
|
|
103
|
+
|
|
68
104
|
/**
|
|
69
105
|
* Compiles an app into dist/. Throws on a compile error or a duplicate route.
|
|
70
106
|
* `dev` keeps chunks readable with source maps back to the .goal files; otherwise they are minified
|
|
@@ -80,10 +116,7 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
|
|
|
80
116
|
const renders = new Map(); // render modules, by .goal file
|
|
81
117
|
rmSync(out, { recursive: true, force: true });
|
|
82
118
|
const all = files(app);
|
|
83
|
-
|
|
84
|
-
const exported = new Map();
|
|
85
|
-
for (const rel of all.filter((f) => f.endsWith('.goal')))
|
|
86
|
-
exported.set(rel, desugar(readFileSync(join(app, rel), 'utf8'), rel).serverFns.filter((f) => f.exported).map((f) => f.name));
|
|
119
|
+
const link = linker(app, all);
|
|
87
120
|
for (const rel of all) {
|
|
88
121
|
if (rel === 'goal.config.js') continue;
|
|
89
122
|
if (!rel.endsWith('.goal')) {
|
|
@@ -91,13 +124,9 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
|
|
|
91
124
|
continue;
|
|
92
125
|
}
|
|
93
126
|
const base = rel.slice(0, -5);
|
|
94
|
-
const serverFunctions = (spec) => {
|
|
95
|
-
const target = posix.join(posix.dirname(rel), spec);
|
|
96
|
-
return exported.has(target) ? { base: target.slice(0, -5), names: exported.get(target) } : null;
|
|
97
|
-
};
|
|
98
127
|
// In dev a chunk's URL names the build, so a page updated live loads the new code.
|
|
99
128
|
const chunk = (n) => `${publicPath}c/${base}.${n}.js${dev ? `?v=${version}` : ''}`;
|
|
100
|
-
const r = compile(readFileSync(join(app, rel), 'utf8'), { file: rel, base, rt: RT, keyed: KEYED, chunk, serverFunctions,
|
|
129
|
+
const r = compile(readFileSync(join(app, rel), 'utf8'), { file: rel, base, rt: RT, keyed: KEYED, chunk, dev, serverFunctions: link.serverFunctions(rel), typesOf: link.typesOf(rel) });
|
|
101
130
|
const server = r.server.replace(/((?:from|import)\s*["'])(\.{1,2}\/[^"']+?)(\.goal|\.m?js)(["'])/g, (_, a, p, ext, b) => `${a}${p}${ext === '.goal' ? '.js' : ext}?v=${version}${b}`);
|
|
102
131
|
write(join(out, 'server', base + '.js'), server);
|
|
103
132
|
if (r.routes.length || r.serverFunctions.length) routeFiles.push(base);
|
package/src/cli.js
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
|
-
// goal build [app] | goal start [app] [--port N] | goal dev [app] [--port N]
|
|
1
|
+
// goal build [app] | goal start [app] [--port N] | goal dev [app] [--port N] | goal check [app]
|
|
2
2
|
|
|
3
|
-
import { build, serve, dev } from './build.js';
|
|
3
|
+
import { build, serve, dev, check } from './build.js';
|
|
4
4
|
|
|
5
|
-
const USAGE = 'usage: goal build|start|dev [app folder] [--port 3000]';
|
|
5
|
+
const USAGE = 'usage: goal build|start|dev|check [app folder] [--port 3000]';
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
/** The command, the app's folder (the current one by default) and the port (3000 by default). */
|
|
8
|
+
export function args(argv) {
|
|
8
9
|
const [cmd, ...rest] = argv;
|
|
9
10
|
const i = rest.indexOf('--port');
|
|
10
11
|
const port = i < 0 ? 3000 : Number(rest.splice(i, 2)[1]);
|
|
11
|
-
|
|
12
|
+
return { cmd, app: rest[0] ?? '.', port };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function main(argv, log = console.log) {
|
|
16
|
+
const { cmd, app, port } = args(argv);
|
|
12
17
|
if (cmd === 'build') {
|
|
13
18
|
try {
|
|
14
19
|
const r = await build(app);
|
|
@@ -21,6 +26,17 @@ export async function main(argv, log = console.log) {
|
|
|
21
26
|
return 1;
|
|
22
27
|
}
|
|
23
28
|
}
|
|
29
|
+
if (cmd === 'check') {
|
|
30
|
+
try {
|
|
31
|
+
const errors = check(app);
|
|
32
|
+
for (const e of errors) log(e);
|
|
33
|
+
log(errors.length ? `${errors.length} file${errors.length === 1 ? '' : 's'} with errors` : 'no errors');
|
|
34
|
+
return errors.length ? 1 : 0;
|
|
35
|
+
} catch (e) {
|
|
36
|
+
log(e.message); // a file that doesn't parse
|
|
37
|
+
return 1;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
24
40
|
if (cmd === 'start' || cmd === 'dev') {
|
|
25
41
|
const server = await (cmd === 'dev' ? dev(app, { port, log }) : serve(app, { port }));
|
|
26
42
|
log(`http://localhost:${server.address().port}`);
|
package/src/compiler.js
CHANGED
|
@@ -32,6 +32,9 @@ import { generate } from '@babel/generator';
|
|
|
32
32
|
import * as t from '@babel/types';
|
|
33
33
|
import { desugar, errorAt, GoalError } from './syntax.js';
|
|
34
34
|
import { URL_ATTRS, _$u } from './rt.js';
|
|
35
|
+
import { check } from './types.js';
|
|
36
|
+
|
|
37
|
+
export { exportsOf } from './types.js'; // what a .goal file gives a #strict file importing it: for the editor too
|
|
35
38
|
|
|
36
39
|
export { GoalError };
|
|
37
40
|
|
|
@@ -77,7 +80,8 @@ function emit(node) {
|
|
|
77
80
|
* Compiles one .goal file.
|
|
78
81
|
* @param {string} source
|
|
79
82
|
* @param {{ file?: string, base?: string, rt?: string, keyed?: string, chunk?: (name: string) => string,
|
|
80
|
-
* serverFunctions?: (specifier: string) => { base: string, names: string[] } | null, dev?: boolean
|
|
83
|
+
* serverFunctions?: (specifier: string) => { base: string, names: string[] } | null, dev?: boolean,
|
|
84
|
+
* typesOf?: (specifier: string) => object | null }} [opts]
|
|
81
85
|
* file: the name in errors and source maps; base: the file's path without .goal, which names its
|
|
82
86
|
* server functions' URLs (/_m/<base>/<name>); rt and keyed: where compiled code imports the helpers
|
|
83
87
|
* and the keyed list patcher from;
|
|
@@ -93,6 +97,7 @@ export function compile(source, opts = {}) {
|
|
|
93
97
|
SRC = { source, file };
|
|
94
98
|
const ast = parse(d.code, { sourceType: 'module', plugins: ['jsx'] });
|
|
95
99
|
relocate(ast, source, d.map, file.split('/').at(-1)); // source maps name the file next to the compiled one
|
|
100
|
+
const typed = d.strict ? check(ast, d, opts.typesOf, fail) : null; // types: what other .goal files export comes from typesOf
|
|
96
101
|
|
|
97
102
|
// Server functions this file can call: its own, and the ones it imports from other .goal files.
|
|
98
103
|
for (const f of d.serverFns) o.sfns.set(f.name, `/_m/${base}/${f.name}`);
|
|
@@ -126,14 +131,14 @@ export function compile(source, opts = {}) {
|
|
|
126
131
|
t.variableDeclarator(
|
|
127
132
|
t.identifier('_$routes'),
|
|
128
133
|
t.arrayExpression([
|
|
129
|
-
...d.routes.map((r) => routeEntry(r.method, r.path, t.identifier(r.name))),
|
|
134
|
+
...d.routes.map((r) => routeEntry(r.method, r.path, t.identifier(r.name), r.types)),
|
|
130
135
|
...endpoints.map((f) =>
|
|
131
136
|
routeEntry(
|
|
132
137
|
'POST',
|
|
133
138
|
f.path,
|
|
134
139
|
t.arrowFunctionExpression(
|
|
135
140
|
[t.identifier('r'), t.identifier('x')],
|
|
136
|
-
t.callExpression(t.identifier('_$call'), [t.identifier(f.name), t.identifier('r'), t.identifier('x')]),
|
|
141
|
+
t.callExpression(t.identifier('_$call'), [t.identifier(f.name), t.identifier('r'), t.identifier('x'), ...(typed ? [t.valueToNode(typed.params.get(f.name))] : [])]),
|
|
137
142
|
),
|
|
138
143
|
),
|
|
139
144
|
),
|
|
@@ -152,11 +157,12 @@ export function compile(source, opts = {}) {
|
|
|
152
157
|
};
|
|
153
158
|
}
|
|
154
159
|
|
|
155
|
-
const routeEntry = (method, path, handler) =>
|
|
160
|
+
const routeEntry = (method, path, handler, types = {}) =>
|
|
156
161
|
t.objectExpression([
|
|
157
162
|
t.objectProperty(t.identifier('method'), t.stringLiteral(method)),
|
|
158
163
|
t.objectProperty(t.identifier('path'), t.stringLiteral(path)),
|
|
159
164
|
t.objectProperty(t.identifier('handler'), handler),
|
|
165
|
+
...(Object.keys(types).length ? [t.objectProperty(t.identifier('types'), t.valueToNode(types))] : []), // typed path parameters
|
|
160
166
|
]);
|
|
161
167
|
|
|
162
168
|
// ---------------------------------------------------------------------------------------------
|
package/src/rt.js
CHANGED
|
@@ -72,8 +72,38 @@ export const _$sf = async (url, args) => {
|
|
|
72
72
|
};
|
|
73
73
|
|
|
74
74
|
/** Runs a server function for a request from the browser: the arguments are a JSON array. */
|
|
75
|
-
export const _$call = async (fn, r, x) =>
|
|
76
|
-
Array.isArray(r.json)
|
|
75
|
+
export const _$call = async (fn, r, x, types) => {
|
|
76
|
+
if (!Array.isArray(r.json)) return x.json({ error: 'send the arguments as a JSON array' }, 400);
|
|
77
|
+
// A server function in a #strict file: arguments that aren't of its types never reach it.
|
|
78
|
+
if (types && (r.json.length > types.length || !types.every((p, i) => (r.json[i] === undefined || r.json[i] === null ? p.optional || _$ok(r.json[i], p.type) : _$ok(r.json[i], p.type)))))
|
|
79
|
+
return x.json({ error: "the arguments aren't of the types the function takes" }, 400);
|
|
80
|
+
return x.json({ v: (await fn(...r.json)) ?? null });
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** Is this JSON value of type x (see types.js)? What JSON can't carry, like a function, isn't checked here. */
|
|
84
|
+
export function _$ok(v, x) {
|
|
85
|
+
switch (x.k) {
|
|
86
|
+
case 'string':
|
|
87
|
+
case 'number':
|
|
88
|
+
case 'boolean':
|
|
89
|
+
return typeof v === x.k;
|
|
90
|
+
case 'null':
|
|
91
|
+
return v === null;
|
|
92
|
+
case 'undefined':
|
|
93
|
+
case 'void':
|
|
94
|
+
return v == null; // JSON has no undefined: null stands for it
|
|
95
|
+
case 'lit':
|
|
96
|
+
return v === x.v;
|
|
97
|
+
case 'array':
|
|
98
|
+
return Array.isArray(v) && v.every((y) => _$ok(y, x.of));
|
|
99
|
+
case 'object':
|
|
100
|
+
return !!v && typeof v === 'object' && !Array.isArray(v) && Object.entries(x.fields).every(([n, f]) => (v[n] == null ? f.optional || _$ok(v[n], f.type) : _$ok(v[n], f.type)));
|
|
101
|
+
case 'union':
|
|
102
|
+
return x.of.some((y) => _$ok(v, y));
|
|
103
|
+
default:
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
77
107
|
|
|
78
108
|
/** A render: numbers component instances, collects the page's events, and holds the CSRF token. */
|
|
79
109
|
export const _$ctx = (t = '') => ({
|
package/src/syntax.js
CHANGED
|
@@ -3,18 +3,22 @@
|
|
|
3
3
|
// route GET /users/{id} { ... } a route, at the top level of a file
|
|
4
4
|
// {if (a) <p>A</p> else if (b) <p>B</p> else <p>C</p>} if/else as a value, inside markup
|
|
5
5
|
// server function addNote(text) { ... } runs on the server, called from the browser
|
|
6
|
+
// #strict, then name: Type and type Note = { ... } types, in a file that starts with #strict
|
|
6
7
|
//
|
|
7
8
|
// desugar() parses the file with acorn (extended for these two forms), and rewrites them into plain
|
|
8
9
|
// JavaScript + JSX with small text edits: a route becomes `async function _$r0(request, _$x) { ... }`
|
|
9
10
|
// an if becomes a chain of ternaries, and a server function becomes an async function. `map` turns a position in the output back into one in the
|
|
10
|
-
// source, so errors point at what the author wrote.
|
|
11
|
+
// source, so errors point at what the author wrote. Types are read into `types` and taken out of the
|
|
12
|
+
// code (see types.js, which checks them).
|
|
11
13
|
|
|
12
14
|
import { Parser, tokTypes as tt } from 'acorn';
|
|
13
15
|
import jsx from 'acorn-jsx';
|
|
14
16
|
|
|
15
17
|
export const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
|
|
16
18
|
const SERVER = /^server[ \t]+function[ \t]+([A-Za-z_$][\w$]*)/;
|
|
17
|
-
const SEGMENT = /^(?:[A-Za-z0-9\-._~]+|\{[A-Za-z_][A-Za-z0-9_]
|
|
19
|
+
const SEGMENT = /^(?:[A-Za-z0-9\-._~]+|\{[A-Za-z_][A-Za-z0-9_]*(?:[ \t]*:[ \t]*(?:string|number))?\})$/;
|
|
20
|
+
const STRICT = /^\s*#strict[ \t]*(?=\r?\n|$)/;
|
|
21
|
+
const BASIC = new Set(['string', 'number', 'boolean', 'unknown', 'Markup', 'undefined']);
|
|
18
22
|
|
|
19
23
|
export class GoalError extends Error {
|
|
20
24
|
constructor(message, file, line, column) {
|
|
@@ -35,16 +39,23 @@ export function errorAt(source, file, pos, message) {
|
|
|
35
39
|
const Base = Parser.extend(jsx());
|
|
36
40
|
|
|
37
41
|
/**
|
|
38
|
-
* @returns {{ code: string, routes: { method: string, path: string, params: string[], name: string }[],
|
|
39
|
-
* serverFns: { name: string, exported: boolean }[], map: (pos: number) => number
|
|
42
|
+
* @returns {{ code: string, routes: { method: string, path: string, params: string[], types: object, name: string }[],
|
|
43
|
+
* serverFns: { name: string, exported: boolean }[], map: (pos: number) => number, strict: boolean,
|
|
44
|
+
* types: { decls: Map<string, { type: object, exported: boolean, at: number }>, at: Map<number, object> } }}
|
|
45
|
+
* types.at: the type written for the binding or function that starts at that source position
|
|
40
46
|
*/
|
|
41
47
|
export function desugar(source, file) {
|
|
42
48
|
const edits = [];
|
|
43
49
|
const routes = [];
|
|
44
50
|
const serverFns = [];
|
|
51
|
+
const types = { decls: new Map(), at: new Map() };
|
|
45
52
|
const fail = (pos, message) => {
|
|
46
53
|
throw errorAt(source, file, pos, message);
|
|
47
54
|
};
|
|
55
|
+
const s = STRICT.exec(source);
|
|
56
|
+
const strict = !!s;
|
|
57
|
+
if (s) edits.push({ at: s.index + s[0].indexOf('#'), del: 7, ins: '' });
|
|
58
|
+
const input = s ? source.slice(0, s.index) + s[0].replace('#strict', ' ') + source.slice(s.index + s[0].length) : source;
|
|
48
59
|
|
|
49
60
|
class GoalParser extends Base {
|
|
50
61
|
isServerFn() {
|
|
@@ -52,12 +63,128 @@ export function desugar(source, file) {
|
|
|
52
63
|
}
|
|
53
64
|
|
|
54
65
|
shouldParseExportStatement() {
|
|
66
|
+
if (this.isTypeDecl()) {
|
|
67
|
+
this.goalExportAt = this.lastTokStart; // the export keyword goes with the declaration
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
55
70
|
if (!this.isServerFn()) return super.shouldParseExportStatement();
|
|
56
71
|
this.goalExport = true;
|
|
57
72
|
return true;
|
|
58
73
|
}
|
|
59
74
|
|
|
75
|
+
isTypeDecl() {
|
|
76
|
+
return this.type === tt.name && this.value === 'type' && /^type[ \t]+[A-Za-z_$][\w$]*[ \t]*=/.test(this.input.slice(this.start));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Types: read into `types`, and taken out of the code.
|
|
80
|
+
typed(at) {
|
|
81
|
+
if (!strict) fail(at, 'types go in a #strict file: put #strict on the first line');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
goalAnnotation(at) {
|
|
85
|
+
this.typed(this.start);
|
|
86
|
+
const from = this.start;
|
|
87
|
+
this.next();
|
|
88
|
+
types.at.set(at, this.goalType());
|
|
89
|
+
edits.push({ at: from, del: this.lastTokEnd - from, ins: '' });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
parseBindingAtom() {
|
|
93
|
+
const node = super.parseBindingAtom();
|
|
94
|
+
if (this.type === tt.colon) this.goalAnnotation(node.start);
|
|
95
|
+
return node;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
parseFunctionParams(node) {
|
|
99
|
+
super.parseFunctionParams(node);
|
|
100
|
+
if (this.type === tt.colon) this.goalAnnotation(-node.start - 1); // a function's result: keyed apart from its name
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
parseParenItem(item) {
|
|
104
|
+
if (this.type === tt.colon) this.goalAnnotation(item.start); // an arrow function's parameter
|
|
105
|
+
return item;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
goalTypeDecl() {
|
|
109
|
+
const at = this.goalExportAt ?? this.start;
|
|
110
|
+
const exported = this.goalExportAt !== undefined;
|
|
111
|
+
this.goalExportAt = undefined;
|
|
112
|
+
this.typed(at);
|
|
113
|
+
const node = this.startNode();
|
|
114
|
+
this.next();
|
|
115
|
+
node.id = this.parseIdent();
|
|
116
|
+
if (types.decls.has(node.id.name)) fail(node.id.start, `the type ${node.id.name} is declared twice`);
|
|
117
|
+
this.expect(tt.eq);
|
|
118
|
+
types.decls.set(node.id.name, { type: this.goalType(), exported, at: node.id.start });
|
|
119
|
+
this.eat(tt.semi);
|
|
120
|
+
edits.push({ at, del: this.lastTokEnd - at, ins: '' });
|
|
121
|
+
return this.finishNode(node, 'GoalType');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// T | U, T[], string, 'a', { name: T, other?: U }, (x: T) => U, (T), a declared name
|
|
125
|
+
goalType() {
|
|
126
|
+
const of = [this.goalList()];
|
|
127
|
+
while (this.eat(tt.bitwiseOR)) of.push(this.goalList());
|
|
128
|
+
return of.length > 1 ? { k: 'union', of } : of[0];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
goalList() {
|
|
132
|
+
let t = this.goalPrimary();
|
|
133
|
+
while (this.type === tt.bracketL && this.input[this.end] === ']') {
|
|
134
|
+
this.next();
|
|
135
|
+
this.next();
|
|
136
|
+
t = { k: 'array', of: t };
|
|
137
|
+
}
|
|
138
|
+
return t;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
goalPrimary() {
|
|
142
|
+
const at = this.start;
|
|
143
|
+
const v = this.value;
|
|
144
|
+
if (this.eat(tt.string)) return { k: 'lit', v };
|
|
145
|
+
if (this.eat(tt.num)) return { k: 'lit', v };
|
|
146
|
+
if (this.eat(tt._true) || this.eat(tt._false)) return { k: 'lit', v: v === 'true' };
|
|
147
|
+
if (this.eat(tt._null)) return { k: 'null' };
|
|
148
|
+
if (this.eat(tt._void)) return { k: 'void' }; // what a function that returns nothing gives
|
|
149
|
+
if (this.eat(tt.name)) return BASIC.has(v) ? { k: v } : { k: 'ref', name: v, at };
|
|
150
|
+
if (this.eat(tt.braceL)) {
|
|
151
|
+
const fields = {};
|
|
152
|
+
while (!this.eat(tt.braceR)) {
|
|
153
|
+
const name = this.value;
|
|
154
|
+
if (this.type !== tt.name && this.type !== tt.string && !this.type.keyword) fail(this.start, 'write a field as name: type');
|
|
155
|
+
this.next();
|
|
156
|
+
const optional = this.eat(tt.question);
|
|
157
|
+
this.expect(tt.colon);
|
|
158
|
+
fields[name] = { type: this.goalType(), optional };
|
|
159
|
+
if (!this.eat(tt.comma) && !this.eat(tt.semi) && this.type !== tt.braceR) fail(this.start, 'separate the fields with commas');
|
|
160
|
+
}
|
|
161
|
+
return { k: 'object', fields };
|
|
162
|
+
}
|
|
163
|
+
if (this.eat(tt.parenL)) {
|
|
164
|
+
if (this.type === tt.parenR || (this.type === tt.name && /^[A-Za-z_$][\w$]*\s*\??\s*:/.test(this.input.slice(this.start)))) {
|
|
165
|
+
const params = [];
|
|
166
|
+
while (!this.eat(tt.parenR)) {
|
|
167
|
+
this.next(); // the parameter's name: only its type matters
|
|
168
|
+
const optional = this.eat(tt.question);
|
|
169
|
+
this.expect(tt.colon);
|
|
170
|
+
params.push({ type: this.goalType(), optional });
|
|
171
|
+
if (this.type !== tt.parenR) this.expect(tt.comma);
|
|
172
|
+
}
|
|
173
|
+
this.expect(tt.arrow);
|
|
174
|
+
return { k: 'fn', params, returns: this.goalType() };
|
|
175
|
+
}
|
|
176
|
+
const t = this.goalType();
|
|
177
|
+
this.expect(tt.parenR);
|
|
178
|
+
return t;
|
|
179
|
+
}
|
|
180
|
+
return fail(at, 'write a type: string, number, boolean, a list like Note[], or an object like { id: number }');
|
|
181
|
+
}
|
|
182
|
+
|
|
60
183
|
parseStatement(context, topLevel, exports) {
|
|
184
|
+
if (this.isTypeDecl()) {
|
|
185
|
+
if (!topLevel && this.goalExportAt === undefined) fail(this.start, 'declare a type at the top level of a file');
|
|
186
|
+
return this.goalTypeDecl();
|
|
187
|
+
}
|
|
61
188
|
if (this.isServerFn()) {
|
|
62
189
|
if (!topLevel && !this.goalExport) fail(this.start, 'declare a server function at the top level of a file');
|
|
63
190
|
serverFns.push({ name: SERVER.exec(this.input.slice(this.start))[1], exported: !!this.goalExport });
|
|
@@ -74,20 +201,23 @@ export function desugar(source, file) {
|
|
|
74
201
|
|
|
75
202
|
goalRoute() {
|
|
76
203
|
const start = this.start;
|
|
77
|
-
const m = /^route[ \t]+(\S+)[ \t]+(\
|
|
204
|
+
const m = /^route[ \t]+(\S+)[ \t]+((?:\{[^}\n]*\}|[^\s{])+)[ \t]+\{/.exec(this.input.slice(start));
|
|
78
205
|
if (!m) fail(start, 'write a route as: route GET /path { ... }');
|
|
79
206
|
const [head, method, path] = m;
|
|
80
207
|
if (!METHODS.includes(method)) fail(start, `unknown method ${method}; use ${METHODS.join(', ')}`);
|
|
81
208
|
const segs = path === '/' ? [] : path.slice(1).split('/');
|
|
82
209
|
if (path[0] !== '/' || !segs.every((s) => SEGMENT.test(s)))
|
|
83
210
|
fail(start, `write the path with plain words and {name} parameters, like /users/{id} (not ${path})`);
|
|
84
|
-
const params = segs.filter((s) => s[0] === '{').map((s) => s.slice(1, -1));
|
|
211
|
+
const params = segs.filter((s) => s[0] === '{').map((s) => s.slice(1, -1).split(':')[0].trim());
|
|
212
|
+
const typed = segs.filter((s) => s.includes(':'));
|
|
213
|
+
if (typed.length) this.typed(start);
|
|
214
|
+
const types = Object.fromEntries(typed.map((s) => s.slice(1, -1).split(':').map((x) => x.trim())));
|
|
85
215
|
for (const [i, p] of params.entries()) {
|
|
86
216
|
if (params.indexOf(p) !== i) fail(start, `the path names {${p}} twice`);
|
|
87
217
|
if (p === 'request') fail(start, 'name the path parameter something other than {request}');
|
|
88
218
|
}
|
|
89
219
|
const name = `_$r${routes.length}`;
|
|
90
|
-
routes.push({ method, path, params, name });
|
|
220
|
+
routes.push({ method, path: path.replace(/\{([A-Za-z0-9_]+)[^}]*\}/g, '{$1}'), params, types, name });
|
|
91
221
|
const brace = start + head.length - 1;
|
|
92
222
|
edits.push({ at: start, del: brace - start, ins: `async function ${name}(request, _$x) ` });
|
|
93
223
|
const node = this.startNode();
|
|
@@ -133,7 +263,7 @@ export function desugar(source, file) {
|
|
|
133
263
|
}
|
|
134
264
|
|
|
135
265
|
try {
|
|
136
|
-
GoalParser.parse(
|
|
266
|
+
GoalParser.parse(input, { ecmaVersion: 'latest', sourceType: 'module', allowHashBang: true });
|
|
137
267
|
} catch (e) {
|
|
138
268
|
if (e instanceof GoalError) throw e;
|
|
139
269
|
fail(e.pos, e.message.replace(/ \(\d+:\d+\)$/, ''));
|
|
@@ -158,5 +288,5 @@ export function desugar(source, file) {
|
|
|
158
288
|
}
|
|
159
289
|
return pos - shift;
|
|
160
290
|
};
|
|
161
|
-
return { code, routes, serverFns, map };
|
|
291
|
+
return { code, routes, serverFns, map, strict, types };
|
|
162
292
|
}
|
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
|
@@ -17,6 +17,7 @@ import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
|
17
17
|
import { fileURLToPath } from 'node:url';
|
|
18
18
|
import { compile } from './compiler.js';
|
|
19
19
|
import { desugar } from './syntax.js';
|
|
20
|
+
import { exportsOf } from './types.js';
|
|
20
21
|
import { createApp } from './app.js';
|
|
21
22
|
|
|
22
23
|
const SRC = dirname(fileURLToPath(import.meta.url)); // compiled code imports the helpers from here
|
|
@@ -57,6 +58,10 @@ export function goal({ config = {} } = {}) {
|
|
|
57
58
|
const names = desugar(readFileSync(target, 'utf8'), spec).serverFns.filter((f) => f.exported).map((f) => f.name);
|
|
58
59
|
return { base: slash(relative(root, target)).slice(0, -5), names };
|
|
59
60
|
},
|
|
61
|
+
typesOf: (spec) => {
|
|
62
|
+
const target = resolve(dirname(file), spec);
|
|
63
|
+
return exportsOf(readFileSync(target, 'utf8'), slash(relative(root, target)));
|
|
64
|
+
},
|
|
60
65
|
});
|
|
61
66
|
};
|
|
62
67
|
|