goaljs 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 goallabs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # goal.js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A compiled JavaScript framework where **`var` is state** and **`let`/`const` are computed**. Pages are
4
+ rendered on the server and the browser **resumes** them instead of hydrating: no component code runs at
5
+ load, and each component's code, in a small chunk of its own, loads on its first event. Components
6
+ reach the server through **server functions**, with no `async` and no `fetch`. It is **secure by
7
+ default**.
8
+
9
+ **Documentation: <https://goallabs.github.io/goal/>**
10
+
11
+ ```jsx
12
+ // app.goal
13
+ import { Counter } from './Counter.goal';
14
+
15
+ route GET / {
16
+ return <main><h1>Hello</h1><Counter start={1} /></main>;
17
+ }
18
+ ```
19
+
20
+ ```jsx
21
+ // Counter.goal
22
+ export function Counter({ start }) {
23
+ var count = start; // state
24
+ const double = count * 2; // computed
25
+
26
+ return (
27
+ <div>
28
+ <button onclick={() => count++}>+</button>
29
+ <p>{double}</p>
30
+ {if (count > 9) <b>big</b> else <span>small</span>}
31
+ </div>
32
+ );
33
+ }
34
+ ```
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ npm install goaljs
40
+ npx goal dev . # build the app in this folder, serve it on http://localhost:3000, rebuild on save
41
+ ```
42
+
43
+ [Getting started](https://goallabs.github.io/goal/getting-started) walks through a first app. The docs
44
+ also cover [routes](https://goallabs.github.io/goal/routes),
45
+ [components](https://goallabs.github.io/goal/components),
46
+ [server functions](https://goallabs.github.io/goal/server-functions),
47
+ [security](https://goallabs.github.io/goal/security),
48
+ [how it works](https://goallabs.github.io/goal/how-it-works) and
49
+ [performance](https://goallabs.github.io/goal/performance).
50
+
51
+ ## Working on goal.js
52
+
53
+ ```bash
54
+ npm install
55
+ npm run demo # builds examples/demo, serves it on http://localhost:3000, rebuilds on save
56
+ npm test # the tests, with 100% coverage of src/ required
57
+ npm run bench:virtual # a 100,000-row virtual list in headless Chrome: speed and memory
58
+ ```
59
+
60
+ The docs site is the `docs/` folder, published by GitHub Pages. `editors/vscode` is the VS Code
61
+ extension.
62
+
63
+ ## License
64
+
65
+ MIT
package/bin/goal.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ const r = await main(process.argv.slice(2));
5
+ if (typeof r === 'number') process.exitCode = r;
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "goaljs",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "goal.js: var is state, let/const are computed, server-rendered and resumable",
5
+ "homepage": "https://goallabs.github.io/goal/",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/goallabs/goal.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/goallabs/goal/issues"
12
+ },
13
+ "scripts": {
14
+ "test": "vitest run --coverage",
15
+ "build:demo": "node bin/goal.js build examples/demo",
16
+ "demo": "node bin/goal.js dev examples/demo",
17
+ "bench:virtual": "node bench/virtual.mjs"
18
+ },
19
+ "keywords": [
20
+ "framework",
21
+ "compiler",
22
+ "ssr",
23
+ "resumable",
24
+ "jsx",
25
+ "server-functions"
26
+ ],
27
+ "license": "MIT",
28
+ "type": "module",
29
+ "files": [
30
+ "bin",
31
+ "src"
32
+ ],
33
+ "dependencies": {
34
+ "@babel/generator": "^8.1.3",
35
+ "@babel/parser": "^8.1.3",
36
+ "@babel/traverse": "^8.1.3",
37
+ "@babel/types": "^8.1.3",
38
+ "acorn": "^8.19.0",
39
+ "acorn-jsx": "^5.3.2",
40
+ "esbuild": "^0.28.2"
41
+ },
42
+ "devDependencies": {
43
+ "@vitest/coverage-v8": "^5.1.1",
44
+ "happy-dom": "^21.0.4",
45
+ "vitest": "^5.1.1"
46
+ },
47
+ "bin": {
48
+ "goal": "bin/goal.js"
49
+ },
50
+ "exports": {
51
+ ".": "./src/server.js",
52
+ "./compiler": "./src/compiler.js",
53
+ "./rt": "./src/rt.js",
54
+ "./loader": "./src/loader.js",
55
+ "./build": "./src/build.js",
56
+ "./keyed": "./src/keyed.js"
57
+ }
58
+ }
package/src/app.js ADDED
@@ -0,0 +1,246 @@
1
+ // Answering requests: static files, routes, and the security defaults.
2
+ //
3
+ // Secure by default, each with an explicit way out in goal.config.js:
4
+ // - every response has strict headers: a Content-Security-Policy with a fresh nonce for the
5
+ // loader script (`csp: "...{nonce}..."` to change it, `csp: false` to drop it), nosniff,
6
+ // no framing, same-origin opener and resources, and HSTS over TLS;
7
+ // - a request that changes something (POST, PUT, PATCH, DELETE) must come from this site:
8
+ // a cross-site Origin or Sec-Fetch-Site is refused, and without `Sec-Fetch-Site: same-origin`
9
+ // it needs the CSRF token, which forms get automatically (`csrf: false` to turn it off);
10
+ // - bodies are limited (`bodyLimit`, 1 MB), redirects stay on this site unless asked,
11
+ // cookies are HttpOnly, Secure and SameSite=Lax, and errors show no details outside `goal dev`.
12
+
13
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
14
+ import { readFileSync, statSync } from 'node:fs';
15
+ import { extname, resolve, sep } from 'node:path';
16
+ import { Html, _$ctx } from './rt.js';
17
+ import { page } from './server.js';
18
+
19
+ const TYPES = {
20
+ '.css': 'text/css; charset=utf-8',
21
+ '.js': 'text/javascript; charset=utf-8',
22
+ '.json': 'application/json; charset=utf-8',
23
+ '.txt': 'text/plain; charset=utf-8',
24
+ '.svg': 'image/svg+xml',
25
+ '.png': 'image/png',
26
+ '.jpg': 'image/jpeg',
27
+ '.gif': 'image/gif',
28
+ '.webp': 'image/webp',
29
+ '.ico': 'image/x-icon',
30
+ '.woff2': 'font/woff2',
31
+ };
32
+ const HTML = 'text/html; charset=utf-8';
33
+ const SAFE = new Set(['GET', 'HEAD']);
34
+ const OVERRIDES = new Set(['PUT', 'PATCH', 'DELETE']);
35
+ const REPLY = Symbol('reply');
36
+
37
+ /** The headers every response carries. */
38
+ export function securityHeaders(nonce, { csp, tls = false } = {}) {
39
+ const h = {
40
+ 'x-content-type-options': 'nosniff',
41
+ 'referrer-policy': 'strict-origin-when-cross-origin',
42
+ 'cross-origin-opener-policy': 'same-origin',
43
+ 'cross-origin-resource-policy': 'same-origin',
44
+ 'x-frame-options': 'DENY',
45
+ 'permissions-policy': 'camera=(), microphone=(), geolocation=()',
46
+ };
47
+ if (csp !== false)
48
+ h['content-security-policy'] =
49
+ typeof csp === 'string'
50
+ ? csp.replaceAll('{nonce}', nonce)
51
+ : `default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'`;
52
+ if (tls) h['strict-transport-security'] = 'max-age=63072000; includeSubDomains';
53
+ return h;
54
+ }
55
+
56
+ /** A cookie with safe defaults: HttpOnly, Secure, SameSite=Lax, the whole site. */
57
+ export function serializeCookie(name, value, { httpOnly = true, secure = true, sameSite = 'Lax', path = '/', maxAge } = {}) {
58
+ if (!/^[\w!#$%&'*+.^`|~-]+$/.test(name)) throw new Error(`cookie name ${JSON.stringify(name)} has characters a cookie name can't have`);
59
+ let s = `${name}=${encodeURIComponent(value)}; Path=${path}; SameSite=${sameSite}`;
60
+ if (maxAge !== undefined) s += `; Max-Age=${Math.floor(maxAge)}`;
61
+ if (httpOnly) s += '; HttpOnly';
62
+ if (secure) s += '; Secure';
63
+ return s;
64
+ }
65
+
66
+ export function parseCookies(header = '') {
67
+ const out = {};
68
+ for (const part of header.split(';').map((p) => p.trim())) {
69
+ const i = part.indexOf('=');
70
+ if (i < 1) continue;
71
+ const name = part.slice(0, i).trim();
72
+ const v = part.slice(i + 1).trim();
73
+ try {
74
+ out[name] = decodeURIComponent(v);
75
+ } catch {
76
+ out[name] = v;
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+
82
+ /** Sends the user to another page on this site. `{ external: true }` allows another site. */
83
+ export function redirect(url, { external = false, status = 303 } = {}) {
84
+ if (!external && !/^\/(?![/\\])/.test(url))
85
+ throw new Error(`redirect() goes to a path on this site, like /notes, not ${url}; pass { external: true } to leave the site`);
86
+ return { [REPLY]: true, status, headers: { location: url } };
87
+ }
88
+
89
+ export const json = (value, status = 200) => ({ [REPLY]: true, status, type: 'application/json; charset=utf-8', body: JSON.stringify(value) });
90
+
91
+ const errorPage = (title) =>
92
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title></head><body><h1>${title}</h1></body></html>`;
93
+
94
+ export const notFound = () => ({ [REPLY]: true, status: 404, type: HTML, body: errorPage('Not found') });
95
+
96
+ function sameSite(req, cookieToken, sent) {
97
+ const origin = req.headers.origin;
98
+ if (origin !== undefined) {
99
+ let host;
100
+ try {
101
+ host = new URL(origin).host;
102
+ } catch {
103
+ return false;
104
+ }
105
+ if (host !== req.headers.host) return false;
106
+ }
107
+ const site = req.headers['sec-fetch-site'];
108
+ if (site === 'same-origin') return true;
109
+ if (site === 'cross-site' || site === 'same-site') return false;
110
+ if (!cookieToken || typeof sent !== 'string') return false;
111
+ const a = Buffer.from(sent);
112
+ const b = Buffer.from(cookieToken);
113
+ return a.length === b.length && timingSafeEqual(a, b);
114
+ }
115
+
116
+ function readBody(req, limit) {
117
+ return new Promise((ok, no) => {
118
+ const chunks = [];
119
+ let n = 0;
120
+ req.on('data', (c) => {
121
+ n += c.length;
122
+ if (n > limit) {
123
+ req.removeAllListeners('data');
124
+ req.resume();
125
+ no(Object.assign(new Error('body too large'), { status: 413 }));
126
+ } else chunks.push(c);
127
+ });
128
+ req.on('end', () => ok(Buffer.concat(chunks)));
129
+ req.on('error', no);
130
+ });
131
+ }
132
+
133
+ function staticFile(dirs, pathname) {
134
+ let rel;
135
+ try {
136
+ rel = decodeURIComponent(pathname);
137
+ } catch {
138
+ return null;
139
+ }
140
+ for (const dir of dirs) {
141
+ const root = resolve(dir);
142
+ const f = resolve(root, '.' + rel);
143
+ if (f.startsWith(root + sep) && statSync(f, { throwIfNoEntry: false })?.isFile()) return f;
144
+ }
145
+ return null;
146
+ }
147
+
148
+ /** Routes sorted so fixed paths win over ones with parameters. */
149
+ function table(routes) {
150
+ return routes
151
+ .map((r, i) => ({ ...r, i, segs: r.path === '/' ? [] : r.path.slice(1).split('/') }))
152
+ .map((r) => ({ ...r, n: r.segs.filter((s) => s[0] === '{').length }))
153
+ .sort((a, b) => a.n - b.n || a.i - b.i);
154
+ }
155
+
156
+ function match(routes, method, segs) {
157
+ const allow = new Set();
158
+ for (const r of routes) {
159
+ if (r.segs.length !== segs.length) continue;
160
+ const params = {};
161
+ if (!r.segs.every((s, i) => (s[0] === '{' ? ((params[s.slice(1, -1)] = segs[i]), true) : s === segs[i]))) continue;
162
+ if (r.method === method) return { route: r, params };
163
+ allow.add(r.method);
164
+ }
165
+ return allow.size ? { allow: [...allow] } : null;
166
+ }
167
+
168
+ /**
169
+ * A request handler for node:http.
170
+ * @param {{ method: string, path: string, handler: Function }[]} routes
171
+ * @param {{ dev?: boolean, staticDirs?: string[], config?: { csp?: string | false, csrf?: boolean, bodyLimit?: number }, log?: (e: Error) => void }} [opts]
172
+ */
173
+ export function createApp(routes, { dev = false, staticDirs = [], config = {}, log = console.error } = {}) {
174
+ const sorted = table(routes);
175
+ const limit = config.bodyLimit ?? 1_000_000;
176
+ return async (req, res) => {
177
+ const nonce = randomBytes(16).toString('base64');
178
+ const headers = securityHeaders(nonce, { csp: config.csp, tls: !!req.socket.encrypted });
179
+ const cookies = parseCookies(req.headers.cookie);
180
+ const setCookies = [];
181
+ let token = cookies.goal_csrf;
182
+ if (!/^[\w-]{43}$/.test(token ?? '')) {
183
+ token = randomBytes(32).toString('base64url');
184
+ setCookies.push(serializeCookie('goal_csrf', token));
185
+ }
186
+ const send = (status, type, body, extra) => {
187
+ res.writeHead(status, { ...headers, ...(type ? { 'content-type': type } : {}), ...(setCookies.length ? { 'set-cookie': setCookies } : {}), ...extra });
188
+ res.end(req.method === 'HEAD' ? undefined : body);
189
+ };
190
+ const fail = (status, title) => send(status, HTML, errorPage(title));
191
+
192
+ try {
193
+ const url = new URL(req.url, 'http://localhost');
194
+ if (SAFE.has(req.method)) {
195
+ const f = staticFile(staticDirs, url.pathname);
196
+ if (f) return send(200, TYPES[extname(f)] ?? 'application/octet-stream', readFileSync(f));
197
+ }
198
+
199
+ let method = req.method === 'HEAD' ? 'GET' : req.method;
200
+ let form = {};
201
+ let body;
202
+ if (!SAFE.has(req.method)) {
203
+ const raw = await readBody(req, limit);
204
+ const type = (req.headers['content-type'] ?? '').split(';')[0].trim();
205
+ if (raw.length) {
206
+ if (type === 'application/x-www-form-urlencoded') form = Object.fromEntries(new URLSearchParams(raw.toString()));
207
+ else if (type === 'application/json') {
208
+ try {
209
+ body = JSON.parse(raw);
210
+ } catch {
211
+ return fail(400, 'Bad request');
212
+ }
213
+ } else return fail(415, 'Unsupported media type');
214
+ }
215
+ if (config.csrf !== false && !sameSite(req, cookies.goal_csrf, form._csrf ?? req.headers['x-csrf-token'])) return fail(403, 'Forbidden');
216
+ const override = String(form._method ?? '').toUpperCase();
217
+ if (method === 'POST' && OVERRIDES.has(override)) method = override;
218
+ delete form._csrf;
219
+ delete form._method;
220
+ }
221
+
222
+ let segs;
223
+ try {
224
+ segs = url.pathname === '/' ? [] : url.pathname.replace(/\/$/, '').slice(1).split('/').map(decodeURIComponent);
225
+ } catch {
226
+ return fail(400, 'Bad request');
227
+ }
228
+ const m = match(sorted, method, segs);
229
+ if (!m) return fail(404, 'Not found');
230
+ if (m.allow) return send(405, HTML, errorPage('Method not allowed'), { allow: m.allow.join(', ') });
231
+
232
+ const ctx = _$ctx(token);
233
+ const request = { method, path: url.pathname, url, params: m.params, query: Object.fromEntries(url.searchParams), headers: req.headers, cookies, form, json: body };
234
+ const cookie = (name, value, opts) => setCookies.push(serializeCookie(name, value, opts));
235
+ const out = await m.route.handler(request, { ctx, redirect, json, notFound, cookie });
236
+ if (out instanceof Html) return send(200, HTML, page(out.s, [...ctx.ev], nonce, token));
237
+ if (out === undefined) return send(204);
238
+ if (out?.[REPLY]) return send(out.status, out.type, out.body, out.headers);
239
+ throw new Error('a route returns markup, redirect(), json(), notFound() or nothing');
240
+ } catch (e) {
241
+ if (e.status === 413) return fail(413, 'Too large');
242
+ log(e);
243
+ return dev ? send(500, 'text/plain; charset=utf-8', String(e.stack)) : fail(500, 'Something went wrong');
244
+ }
245
+ };
246
+ }
package/src/build.js ADDED
@@ -0,0 +1,182 @@
1
+ // Building and serving a goal.js app.
2
+ //
3
+ // app/**/*.goal -> dist/server/**.js (components and routes) and one client chunk per
4
+ // interactive component in dist/client/c/
5
+ // app/**/*.js -> dist/server/**.js as they are, for server code the .goal files import
6
+ // app/public/ -> dist/public/, served as files
7
+ // app/goal.config.js opt-outs of the security defaults (see src/app.js)
8
+
9
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, cpSync, rmSync, watch } from 'node:fs';
10
+ import { join, relative, dirname, resolve, sep, posix } from 'node:path';
11
+ import { createServer } from 'node:http';
12
+ import { fileURLToPath, pathToFileURL } from 'node:url';
13
+ import { gzipSync } from 'node:zlib';
14
+ import * as esbuild from 'esbuild';
15
+ import { compile } from './compiler.js';
16
+ import { desugar } from './syntax.js';
17
+ import { loaderScript } from './server.js';
18
+ import { createApp } from './app.js';
19
+
20
+
21
+ const SRC = dirname(fileURLToPath(import.meta.url));
22
+ const RT = pathToFileURL(join(SRC, 'rt.js')).href;
23
+ const KEYED = 'goal:keyed'; // the keyed list patcher, its own file: c/_/keyed.js
24
+ const SKIP = new Set(['dist', 'node_modules', 'public']);
25
+
26
+ function files(dir, root = dir) {
27
+ return readdirSync(dir, { withFileTypes: true }).flatMap((d) => {
28
+ const p = join(dir, d.name);
29
+ if (d.isDirectory()) return SKIP.has(d.name) ? [] : files(p, root);
30
+ return [relative(root, p).split(sep).join('/')];
31
+ });
32
+ }
33
+
34
+ const write = (file, text) => {
35
+ mkdirSync(dirname(file), { recursive: true });
36
+ writeFileSync(file, text);
37
+ };
38
+
39
+ const noGoal = {
40
+ name: 'goal',
41
+ setup(b) {
42
+ b.onResolve({ filter: /^file:/ }, (a) => ({ path: fileURLToPath(a.path) }));
43
+ b.onResolve({ filter: /\.goal$/ }, (a) => ({
44
+ errors: [{ text: `browser code can't import the .goal file ${a.path}; move shared helpers into a .js file` }],
45
+ }));
46
+ },
47
+ };
48
+
49
+ /** Client modules as esbuild entry points, each resolved from its .goal file's folder. */
50
+ const entriesPlugin = (entries) => {
51
+ // Each entry sits, in name, next to its .goal file, so source maps name that file from the app folder.
52
+ const byPath = new Map([...entries.values()].map((e) => [join(e.dir, `${e.name}.goal.js`), e]));
53
+ return {
54
+ name: 'goal-entries',
55
+ setup(b) {
56
+ b.onResolve({ filter: /^goal-entry:/ }, (a) => ({ path: join(entries.get(a.path.slice(11)).dir, `${entries.get(a.path.slice(11)).name}.goal.js`) }));
57
+ b.onLoad({ filter: /\.goal\.js$/ }, (a) => ({ contents: byPath.get(a.path).code, resolveDir: byPath.get(a.path).dir, loader: 'js' }));
58
+ },
59
+ };
60
+ };
61
+
62
+ /**
63
+ * Compiles an app into dist/. Throws on a compile error or a duplicate route.
64
+ * `dev` keeps chunks readable with source maps back to the .goal files; otherwise they are minified
65
+ * and the source stays on the server. `publicPath` is where the site is served from.
66
+ * @returns {Promise<{ version: string, chunks: { url: string, bytes: number, gzip: number }[], loader: number, routes: string[] }>}
67
+ */
68
+ export async function build(app, { out = join(app, 'dist'), dev = false, publicPath = '/' } = {}) {
69
+ const version = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
70
+ const chunks = [];
71
+ const routes = [];
72
+ const routeFiles = [];
73
+ const entries = new Map(); // client modules, by output name
74
+ rmSync(out, { recursive: true, force: true });
75
+ const all = files(app);
76
+ // The server functions each .goal file exports, so files can import them from each other.
77
+ const exported = new Map();
78
+ for (const rel of all.filter((f) => f.endsWith('.goal')))
79
+ exported.set(rel, desugar(readFileSync(join(app, rel), 'utf8'), rel).serverFns.filter((f) => f.exported).map((f) => f.name));
80
+ for (const rel of all) {
81
+ if (rel === 'goal.config.js') continue;
82
+ if (!rel.endsWith('.goal')) {
83
+ if (/\.(m?js|json)$/.test(rel)) write(join(out, 'server', rel), readFileSync(join(app, rel)));
84
+ continue;
85
+ }
86
+ const base = rel.slice(0, -5);
87
+ const serverFunctions = (spec) => {
88
+ const target = posix.join(posix.dirname(rel), spec);
89
+ return exported.has(target) ? { base: target.slice(0, -5), names: exported.get(target) } : null;
90
+ };
91
+ const r = compile(readFileSync(join(app, rel), 'utf8'), { file: rel, base, rt: RT, keyed: KEYED, chunk: (n) => `${publicPath}c/${base}.${n}.js`, serverFunctions });
92
+ 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}`);
93
+ write(join(out, 'server', base + '.js'), server);
94
+ if (r.routes.length || r.serverFunctions.length) routeFiles.push(base);
95
+ for (const f of r.serverFunctions) routes.push({ key: f.path, file: rel, label: `server function ${f.name} POST ${f.path}` });
96
+ for (const route of r.routes) {
97
+ const key = `${route.method} ${route.path.replace(/\{\w+\}/g, '{}')}`;
98
+ const other = routes.find((x) => x.key === key);
99
+ if (other) throw new Error(`${rel}: route ${route.method} ${route.path} is already in ${other.file}`);
100
+ routes.push({ key, file: rel, label: `${route.method} ${route.path}` });
101
+ }
102
+ for (const c of r.clients) entries.set(`${base}.${c.name}`, { code: c.code, dir: resolve(app, dirname(rel)), name: `${posix.basename(base)}.${c.name}` });
103
+ }
104
+ // All browser code in one bundle with code splitting: each component is its own file, and code
105
+ // that several share (the runtime helpers, the list patcher) goes in shared files under c/_/.
106
+ if (entries.size) {
107
+ const bundle = async (minify) =>
108
+ (
109
+ await esbuild.build({
110
+ entryPoints: { ...Object.fromEntries([...entries.keys()].map((k) => [k, `goal-entry:${k}`])), '_/keyed': join(SRC, 'keyed.js') },
111
+ external: [KEYED],
112
+ absWorkingDir: resolve(app), // source maps name the .goal files from the app folder
113
+ outdir: resolve(out, 'client', 'c'),
114
+ chunkNames: '_/[name]-[hash]',
115
+ bundle: true,
116
+ splitting: true,
117
+ minify,
118
+ sourcemap: minify ? false : 'inline',
119
+ format: 'esm',
120
+ write: false,
121
+ logLevel: 'silent',
122
+ plugins: [entriesPlugin(entries), noGoal],
123
+ })
124
+ ).outputFiles;
125
+ // A chunk with a keyed list imports the patcher from its own file, next to the chunks.
126
+ const link = (f) => {
127
+ const from = posix.dirname(relative(resolve(out, 'client', 'c'), f.path).split(sep).join('/'));
128
+ const to = posix.relative(from, '_/keyed.js');
129
+ return f.text.replaceAll(`"${KEYED}"`, JSON.stringify(to.startsWith('.') ? to : './' + to));
130
+ };
131
+ const files = (await bundle(true)).map((f) => ({ path: f.path, text: link(f) })); // the sizes reported are what production ships
132
+ for (const f of dev ? (await bundle(false)).map((f) => ({ path: f.path, text: link(f) })) : files) write(f.path, f.text);
133
+ for (const f of files) {
134
+ const rel = relative(resolve(out, 'client'), f.path).split(sep).join('/');
135
+ chunks.push({ url: publicPath + rel, bytes: Buffer.byteLength(f.text), gzip: gzipSync(f.text).length });
136
+ }
137
+ }
138
+ write(
139
+ join(out, 'server', '_routes.js'),
140
+ routeFiles.map((f, i) => `import { _$routes as r${i} } from './${f}.js?v=${version}';\n`).join('') +
141
+ `export default [${routeFiles.map((_, i) => `...r${i}`).join(', ')}];\n`,
142
+ );
143
+ if (existsSync(join(app, 'public'))) cpSync(join(app, 'public'), join(out, 'public'), { recursive: true });
144
+ return { version, chunks, loader: gzipSync(loaderScript()).length, routes: routes.map((r) => r.label) };
145
+ }
146
+
147
+ /** Serves a built app. `dev` shows error details; `version` names the build to load. */
148
+ export async function serve(app, { out = join(app, 'dist'), port = 3000, dev = false, version = () => '', log = console.error } = {}) {
149
+ const configFile = join(app, 'goal.config.js');
150
+ const config = existsSync(configFile) ? (await import(pathToFileURL(configFile).href)).default : {};
151
+ const routesFile = pathToFileURL(join(out, 'server', '_routes.js')).href;
152
+ const server = createServer(async (req, res) => {
153
+ const routes = (await import(`${routesFile}?v=${version()}`)).default;
154
+ return createApp(routes, { dev, config, log, staticDirs: [join(out, 'client'), join(out, 'public')] })(req, res);
155
+ });
156
+ return new Promise((ok) => server.listen(port, () => ok(server)));
157
+ }
158
+
159
+ /** Builds, serves with error details, and builds again when a source file changes. */
160
+ export async function dev(app, { port = 3000, log = console.log } = {}) {
161
+ let version = '';
162
+ const rebuild = async () => {
163
+ try {
164
+ const r = await build(app, { dev: true });
165
+ version = r.version;
166
+ log(`built: ${r.routes.length} route(s), ${r.chunks.length} chunk(s)`);
167
+ } catch (e) {
168
+ log(e.message);
169
+ }
170
+ };
171
+ await rebuild();
172
+ process.setSourceMapsEnabled(true); // stack traces point at the .goal files
173
+ const server = await serve(app, { port, dev: true, version: () => version, log });
174
+ let timer;
175
+ const watcher = watch(app, { recursive: true }, (_, f) => {
176
+ if (!/\.(goal|m?js|json|css)$/.test(String(f)) || String(f).startsWith('dist')) return;
177
+ clearTimeout(timer);
178
+ timer = setTimeout(rebuild, 30);
179
+ });
180
+ server.on('close', () => watcher.close());
181
+ return server;
182
+ }
package/src/cli.js ADDED
@@ -0,0 +1,31 @@
1
+ // goal build [app] | goal start [app] [--port N] | goal dev [app] [--port N]
2
+
3
+ import { build, serve, dev } from './build.js';
4
+
5
+ const USAGE = 'usage: goal build|start|dev [app folder] [--port 3000]';
6
+
7
+ export async function main(argv, log = console.log) {
8
+ const [cmd, ...rest] = argv;
9
+ const i = rest.indexOf('--port');
10
+ const port = i < 0 ? 3000 : Number(rest.splice(i, 2)[1]);
11
+ const app = rest[0] ?? '.';
12
+ if (cmd === 'build') {
13
+ try {
14
+ const r = await build(app);
15
+ for (const route of r.routes) log(route);
16
+ for (const c of r.chunks) log(`${c.url} ${c.bytes} B, ${c.gzip} B gzipped`);
17
+ log(`loader ${r.loader} B gzipped, inline`);
18
+ return 0;
19
+ } catch (e) {
20
+ log(e.message);
21
+ return 1;
22
+ }
23
+ }
24
+ if (cmd === 'start' || cmd === 'dev') {
25
+ const server = await (cmd === 'dev' ? dev(app, { port, log }) : serve(app, { port }));
26
+ log(`http://localhost:${server.address().port}`);
27
+ return server;
28
+ }
29
+ log(USAGE);
30
+ return 1;
31
+ }