goaljs 0.6.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 CHANGED
@@ -49,8 +49,9 @@ also cover [routes](https://goallabs.github.io/goal/routes),
49
49
  [types](https://goallabs.github.io/goal/types),
50
50
  [security](https://goallabs.github.io/goal/security),
51
51
  [how it works](https://goallabs.github.io/goal/how-it-works),
52
- [performance](https://goallabs.github.io/goal/performance), and working in
53
- [Vite](https://goallabs.github.io/goal/vite).
52
+ [performance](https://goallabs.github.io/goal/performance), working in
53
+ [Vite](https://goallabs.github.io/goal/vite), and [tools](https://goallabs.github.io/goal/tools):
54
+ `goal add` sets up Tailwind CSS, Prisma, Drizzle, ESLint, Prettier, Vitest, Playwright and Sentry.
54
55
 
55
56
  ## Working on goal.js
56
57
 
@@ -59,10 +60,12 @@ npm install
59
60
  npm run demo # builds examples/demo, serves it on http://localhost:3000, updates live on save
60
61
  npm test # the tests, with 100% coverage of src/ required
61
62
  npm run bench:virtual # a 100,000-row virtual list in headless Chrome: speed and memory
63
+ npm run test:recipes # sets up each goal add recipe in a new app, for real, and tests it
62
64
  ```
63
65
 
64
66
  The docs site is the `docs/` folder, published by GitHub Pages. `editors/vscode` is the VS Code
65
- extension.
67
+ extension. `recipes/` holds the `goal add` recipes: pull requests that add a tool or a version are
68
+ welcome (see [recipes/README.md](recipes/README.md)).
66
69
 
67
70
  ## License
68
71
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "goaljs",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "goal.js: var is state, let/const are computed, server-rendered and resumable",
5
5
  "homepage": "https://goallabs.github.io/goal/",
6
6
  "repository": {
@@ -14,7 +14,8 @@
14
14
  "test": "vitest run --coverage",
15
15
  "build:demo": "node bin/goal.js build examples/demo",
16
16
  "demo": "node bin/goal.js dev examples/demo",
17
- "bench:virtual": "node bench/virtual.mjs"
17
+ "bench:virtual": "node bench/virtual.mjs",
18
+ "test:recipes": "node test/recipes/run.mjs"
18
19
  },
19
20
  "keywords": [
20
21
  "framework",
@@ -28,7 +29,8 @@
28
29
  "type": "module",
29
30
  "files": [
30
31
  "bin",
31
- "src"
32
+ "src",
33
+ "recipes"
32
34
  ],
33
35
  "dependencies": {
34
36
  "@babel/generator": "^8.1.3",
@@ -62,6 +64,7 @@
62
64
  "./loader": "./src/loader.js",
63
65
  "./build": "./src/build.js",
64
66
  "./keyed": "./src/keyed.js",
65
- "./vite": "./src/vite.js"
67
+ "./vite": "./src/vite.js",
68
+ "./eslint": "./src/eslint.js"
66
69
  }
67
70
  }
@@ -0,0 +1,100 @@
1
+ # goal add recipes
2
+
3
+ `goal add <tool>` sets a tool up in a goal.js app. This folder holds one recipe per tool. A recipe is
4
+ plain data: which packages to install, and what the app needs around them. Tool maintainers and users
5
+ are welcome to send pull requests that update a recipe for a new version, or add a tool.
6
+
7
+ ## A recipe
8
+
9
+ `recipes/<tool>.js` exports the recipe as its default export:
10
+
11
+ ```js
12
+ export default {
13
+ name: 'tailwindcss', // goal add tailwindcss
14
+ aliases: ['tailwind'], // other names goal add takes (optional)
15
+ package: 'tailwindcss', // the package whose version picks the entry
16
+ about: 'Tailwind CSS: utility classes, compiled into public/style.css',
17
+ docs: 'https://tailwindcss.com/docs',
18
+ versions: [
19
+ // Newest first. goal add uses the first entry, unless the app already has the package
20
+ // (its version picks the entry) or the version is asked for: goal add tailwindcss@3.
21
+ {
22
+ range: '4',
23
+ devDependencies: { tailwindcss: '4.3.5', '@tailwindcss/postcss': '4.3.5', postcss: '8.5.33' },
24
+ files: { 'postcss.config.js': 'export default { ... };\n' },
25
+ prepend: { 'public/style.css': ['@import "tailwindcss" source("..");'] },
26
+ lines: { '.gitignore': ['node_modules', 'dist'] },
27
+ next: ['Link the stylesheet from your pages: <link rel="stylesheet" href="/style.css" />'],
28
+ test: { run: ['npx goal build .', 'node -e "..."'] },
29
+ },
30
+ { range: '3', ... },
31
+ ],
32
+ };
33
+ ```
34
+
35
+ Each entry can have:
36
+
37
+ | Key | What `goal add` does with it |
38
+ | --- | --- |
39
+ | `range` | The versions of `package` the entry is for: `4`, `4.x`, `>=0.45 <1`, `3 \|\| 4`. |
40
+ | `dependencies`, `devDependencies` | Installs each package the app doesn't have yet, at the exact version given: the one you tested. npm saves it as a `^` range. |
41
+ | `files` | Writes each file, unless the app has it. If the app's differs, it's kept, and the recipe's is printed. |
42
+ | `prepend`, `lines` | Adds each line the file doesn't have yet, at its start or its end, and makes the file if it isn't there. `KEY=value` lines compare by key, so a `.env` keeps its values. `dist` and `/dist/` count as the same line. |
43
+ | `scripts` | Adds each `package.json` script the app doesn't have. |
44
+ | `config` | Adds keys to `goal.config.js`'s exported object, with an import: `{ import: "import { onError } from './sentry.js';", keys: { onError: 'onError' } }`. Each value is code. |
45
+ | `run` | Commands to run once, in the app's folder, after all of the above, such as `npx prisma generate`. |
46
+ | `next` | What to tell the user to do next. The recipe's `docs` link is added. |
47
+ | `test` | For `npm run test:recipes` only: `files` to add to the test app, then `run`, commands that must all succeed. |
48
+
49
+ `goal add` also sets `"type": "module"` in `package.json`, so write config files as ES modules.
50
+
51
+ ## What a goal.js app is like
52
+
53
+ Keep these in mind when you write files for an app:
54
+
55
+ - `.goal` files hold routes and components. Server code (routes and server functions) can import `.js`
56
+ files and npm packages. Components can't use `async`, `await` or `fetch`.
57
+ - `goal build` copies the app's `.js` and `.json` files into `dist/server/` and runs the server from
58
+ there, with the app's folder as the working directory. Other files, such as `.ts`, aren't copied,
59
+ so server code imports only `.js`, `.json` and packages.
60
+ - `goal dev` loads the server code again after every change. A database client belongs on
61
+ `globalThis` (`globalThis.prisma ??= new PrismaClient()`), so each change doesn't open another one.
62
+ - `goal dev`, `goal start` and the Vite plugin read the app's `.env` into `process.env`. Commands like
63
+ `prisma` or `drizzle-kit` don't, so their config loads it (`process.loadEnvFile()`).
64
+ - With a `postcss.config.js`, every stylesheet in `public/` goes through PostCSS.
65
+ - `goal.config.js` can have `onError(error, request)`, called for each error a route or server
66
+ function throws.
67
+ - The page has a strict Content-Security-Policy: no inline scripts or styles.
68
+
69
+ ## Updating a recipe for a new version
70
+
71
+ - **The setup didn't change:** raise the versions in the entry, and widen its `range` if it's narrow.
72
+ - **The setup changed** (a new config format, a new package): add an entry for the new range at the
73
+ top of `versions`. Keep the old entry, and narrow its `range`, so apps on the old version still get
74
+ a setup that works.
75
+ - **A new tool:** add `recipes/<tool>.js`, and a row for it in `docs/tools.md`.
76
+
77
+ ## Testing it
78
+
79
+ ```bash
80
+ npm install
81
+ npm test # checks every recipe's shape, among the other tests
82
+ npm run test:recipes -- tailwindcss # sets each tailwindcss entry up for real, and runs its test
83
+ npm run test:recipes -- prisma --keep # keeps the test apps, to look at
84
+ npm run test:recipes # all of them
85
+ ```
86
+
87
+ `npm run test:recipes` copies [test/recipes/app](../test/recipes/app), a small app with a route, a
88
+ component and a stylesheet, into a new folder for each entry. It runs `npm init -y`, installs this
89
+ checkout of goal.js, runs `goal add <tool>@<version>` with npm for real, and then runs the entry's
90
+ `test`. A test should show that the tool works with goal.js, not only that it installed. For example,
91
+ Tailwind CSS's test checks that a class from a `.goal` file is in the built stylesheet. Prisma's test
92
+ writes a row from `db.js`, then reads it back from the `dist/server` copy.
93
+
94
+ ## Your pull request
95
+
96
+ - The versions are exact and are the ones you tested.
97
+ - `npm test` passes, and so does `npm run test:recipes -- <tool>`.
98
+ - If the tool is new, or what `goal add` does for it changed, `docs/tools.md` says so.
99
+
100
+ A pull request that changes a recipe runs both in CI (`.github/workflows/recipes.yml`).
@@ -0,0 +1,59 @@
1
+ // goal add drizzle: Drizzle ORM with SQLite (better-sqlite3), the tables in JavaScript.
2
+
3
+ export default {
4
+ name: 'drizzle',
5
+ aliases: ['drizzle-orm'],
6
+ package: 'drizzle-orm',
7
+ about: 'Drizzle ORM with SQLite: tables in JavaScript, and a client for server code',
8
+ docs: 'https://orm.drizzle.team/docs/overview',
9
+ versions: [
10
+ {
11
+ range: '>=0.45 <1',
12
+ dependencies: { 'drizzle-orm': '0.45.4', 'better-sqlite3': '13.2.0' },
13
+ devDependencies: { 'drizzle-kit': '0.31.11' },
14
+ files: {
15
+ 'drizzle.config.js': `import { existsSync } from 'node:fs';
16
+ import { defineConfig } from 'drizzle-kit';
17
+
18
+ if (existsSync('.env')) process.loadEnvFile(); // goal.js reads .env for the app; drizzle-kit doesn't
19
+
20
+ export default defineConfig({
21
+ dialect: 'sqlite',
22
+ schema: './db/schema.js',
23
+ out: './drizzle',
24
+ dbCredentials: { url: process.env.DB_FILE_NAME },
25
+ });
26
+ `,
27
+ 'db/schema.js': `import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core';
28
+
29
+ export const notes = sqliteTable('notes', {
30
+ id: integer().primaryKey({ autoIncrement: true }),
31
+ text: text().notNull(),
32
+ createdAt: integer({ mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),
33
+ });
34
+ `,
35
+ 'db/index.js': `import { drizzle } from 'drizzle-orm/better-sqlite3';
36
+ import * as schema from './schema.js';
37
+
38
+ // One connection per process: goal dev loads the server code again after each change.
39
+ export const db = (globalThis.drizzle ??= drizzle(process.env.DB_FILE_NAME, { schema }));
40
+ `,
41
+ },
42
+ lines: { '.env': ['DB_FILE_NAME=sqlite.db'], '.gitignore': ['node_modules', 'dist', '.env', 'sqlite.db*'] },
43
+ scripts: { 'db:push': 'drizzle-kit push' },
44
+ run: ['npx drizzle-kit push'],
45
+ next: [
46
+ "Use it from server code: import { db } from './db/index.js' and import { notes } from './db/schema.js', then: return db.select().from(notes)",
47
+ 'After changing db/schema.js: npm run db:push (or npx drizzle-kit generate and migrate)',
48
+ 'DB_FILE_NAME is in .env; in production, set it in the environment',
49
+ ],
50
+ test: {
51
+ run: [
52
+ `node --input-type=module --env-file=.env -e "import { db } from './db/index.js'; import { notes } from './db/schema.js'; await db.insert(notes).values({ text: 'hi' }); process.exit((await db.select().from(notes)).length === 1 ? 0 : 1)"`,
53
+ 'npx goal build .',
54
+ `node --input-type=module --env-file=.env -e "import { db } from './dist/server/db/index.js'; import { notes } from './dist/server/db/schema.js'; process.exit((await db.select().from(notes)).length === 1 ? 0 : 1)"`,
55
+ ],
56
+ },
57
+ },
58
+ ],
59
+ };
@@ -0,0 +1,38 @@
1
+ // goal add eslint: ESLint for the app's .js and .goal files. goaljs/eslint (src/eslint.js) lets it
2
+ // read .goal files and reports each problem where it is in the file.
3
+
4
+ export default {
5
+ name: 'eslint',
6
+ package: 'eslint',
7
+ about: 'ESLint for .js and .goal files',
8
+ docs: 'https://eslint.org/docs/latest/',
9
+ versions: [
10
+ {
11
+ range: '10',
12
+ devDependencies: { eslint: '10.15.0', '@eslint/js': '10.0.1', globals: '17.14.0' },
13
+ files: {
14
+ 'eslint.config.js': `import js from '@eslint/js';
15
+ import globals from 'globals';
16
+ import goal from 'goaljs/eslint';
17
+
18
+ export default [
19
+ { ignores: ['dist/'] },
20
+ js.configs.recommended,
21
+ ...goal.configs.recommended,
22
+ { languageOptions: { globals: globals.node } },
23
+ { files: ['**/*.goal/*.jsx'], languageOptions: { globals: globals.browser } }, // event handlers run in the page
24
+ ];
25
+ `,
26
+ },
27
+ scripts: { lint: 'eslint .' },
28
+ next: ['npm run lint checks the .js and .goal files; add rules to eslint.config.js', 'Your editor\'s ESLint extension shows the problems in .goal files too once it lints them (VS Code: "eslint.validate": ["javascript", "goal"])'],
29
+ test: {
30
+ files: { 'Unused.goal': "import { Counter } from './Counter.goal';\nexport function Unused() {\n const x = 1;\n return <Counter start={1} />;\n}\n" },
31
+ run: [
32
+ `node -e "const { execSync } = require('child_process'); let out = ''; try { execSync('npx eslint .', { encoding: 'utf8' }); } catch (e) { out = e.stdout; } process.exit(/Unused\\.goal\\s+3:9\\s+error\\s+'x' is assigned a value but never used/.test(out) ? 0 : 1)"`,
33
+ 'npx eslint --ignore-pattern Unused.goal .',
34
+ ],
35
+ },
36
+ },
37
+ ],
38
+ };
@@ -0,0 +1,48 @@
1
+ // goal add playwright: Playwright browser tests against the app as goal build and goal start serve it,
2
+ // with its security headers and Content-Security-Policy.
3
+
4
+ export default {
5
+ name: 'playwright',
6
+ aliases: ['@playwright/test'],
7
+ package: '@playwright/test',
8
+ about: 'Playwright: browser tests against the built app',
9
+ docs: 'https://playwright.dev/docs/intro',
10
+ versions: [
11
+ {
12
+ range: '1',
13
+ devDependencies: { '@playwright/test': '1.65.1' },
14
+ files: {
15
+ 'playwright.config.js': `import { defineConfig, devices } from '@playwright/test';
16
+
17
+ export default defineConfig({
18
+ testDir: 'e2e',
19
+ use: { baseURL: 'http://localhost:4173' },
20
+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
21
+ // The app as production serves it
22
+ webServer: {
23
+ command: 'npx goal build . && npx goal start . --port 4173',
24
+ url: 'http://localhost:4173',
25
+ reuseExistingServer: !process.env.CI,
26
+ },
27
+ });
28
+ `,
29
+ 'e2e/home.spec.js': `import { test, expect } from '@playwright/test';
30
+
31
+ test('the home page loads with no errors', async ({ page }) => {
32
+ const errors = [];
33
+ page.on('pageerror', (e) => errors.push(e.message));
34
+ page.on('console', (m) => m.type() === 'error' && errors.push(m.text())); // a blocked inline script shows here
35
+ const res = await page.goto('/');
36
+ expect(res.status()).toBeLessThan(400);
37
+ expect(errors).toEqual([]);
38
+ });
39
+ `,
40
+ },
41
+ lines: { '.gitignore': ['node_modules', 'dist', 'test-results', 'playwright-report'] },
42
+ scripts: { 'test:e2e': 'playwright test' },
43
+ run: ['npx playwright install chromium'],
44
+ next: ['npm run test:e2e builds the app, starts it on port 4173 and runs the tests in e2e/ in Chromium', 'More browsers: add projects to playwright.config.js and npx playwright install'],
45
+ test: { run: ['npx playwright test --reporter=line'] },
46
+ },
47
+ ],
48
+ };
@@ -0,0 +1,32 @@
1
+ // goal add postcss: PostCSS, which goal build and goal dev run the stylesheets in public/ through
2
+ // (see src/css.js), with autoprefixer to start with.
3
+
4
+ export default {
5
+ name: 'postcss',
6
+ aliases: ['autoprefixer'],
7
+ package: 'postcss',
8
+ about: 'PostCSS: the stylesheets in public/ through plugins, autoprefixer first',
9
+ docs: 'https://postcss.org',
10
+ versions: [
11
+ {
12
+ range: '8',
13
+ devDependencies: { postcss: '8.5.33', autoprefixer: '10.7.0' },
14
+ files: {
15
+ 'postcss.config.js': `export default {
16
+ plugins: {
17
+ autoprefixer: {},
18
+ },
19
+ };
20
+ `,
21
+ },
22
+ lines: { '.gitignore': ['node_modules', 'dist'] },
23
+ next: [
24
+ 'goal dev and goal build run every stylesheet in public/ through the plugins in postcss.config.js',
25
+ 'Add a plugin: npm install --save-dev <plugin>, then name it in postcss.config.js',
26
+ ],
27
+ test: {
28
+ run: ['npx goal build .', `node -e "process.exit(require('fs').readFileSync('dist/public/style.css', 'utf8').includes('-webkit-user-select') ? 0 : 1)"`],
29
+ },
30
+ },
31
+ ],
32
+ };
@@ -0,0 +1,19 @@
1
+ // goal add prettier: Prettier for the app's .js, .css, .json and .md files. It leaves .goal files
2
+ // alone: it doesn't know their routes and {if}.
3
+
4
+ export default {
5
+ name: 'prettier',
6
+ package: 'prettier',
7
+ about: 'Prettier: formats .js, .css, .json and .md files',
8
+ docs: 'https://prettier.io/docs/',
9
+ versions: [
10
+ {
11
+ range: '3',
12
+ devDependencies: { prettier: '3.10.1' },
13
+ files: { '.prettierrc.json': '{}\n', '.prettierignore': 'dist\n' },
14
+ scripts: { format: 'prettier --write .', 'format:check': 'prettier --check .' },
15
+ next: ['npm run format formats the .js, .css, .json and .md files; .goal files are left as they are', 'Set options, like "singleQuote": true, in .prettierrc.json'],
16
+ test: { run: ['npx prettier --write .', 'npx prettier --check .'] },
17
+ },
18
+ ],
19
+ };
@@ -0,0 +1,67 @@
1
+ // goal add prisma: Prisma ORM with SQLite. The client is generated into node_modules and imported as
2
+ // @prisma/client, so the server code finds it from the app's folder and from dist/server alike.
3
+
4
+ export default {
5
+ name: 'prisma',
6
+ aliases: ['@prisma/client'],
7
+ package: 'prisma',
8
+ about: 'Prisma ORM with SQLite: a schema, and a client for server code',
9
+ docs: 'https://www.prisma.io/docs/orm',
10
+ versions: [
11
+ {
12
+ range: '7',
13
+ dependencies: { '@prisma/client': '7.10.1', '@prisma/adapter-better-sqlite3': '7.10.1' },
14
+ devDependencies: { prisma: '7.10.1' },
15
+ files: {
16
+ 'prisma/schema.prisma': `generator client {
17
+ provider = "prisma-client-js"
18
+ }
19
+
20
+ datasource db {
21
+ provider = "sqlite"
22
+ }
23
+
24
+ model Note {
25
+ id Int @id @default(autoincrement())
26
+ text String
27
+ createdAt DateTime @default(now())
28
+ }
29
+ `,
30
+ // Prisma 7 looks for prisma7.config.* before prisma.config.*
31
+ 'prisma7.config.js': `import { existsSync } from 'node:fs';
32
+ import { defineConfig } from 'prisma/config';
33
+
34
+ if (existsSync('.env')) process.loadEnvFile(); // goal.js reads .env for the app; the prisma command doesn't
35
+
36
+ export default defineConfig({
37
+ schema: 'prisma/schema.prisma',
38
+ datasource: { url: process.env.DATABASE_URL },
39
+ });
40
+ `,
41
+ 'db.js': `import { PrismaClient } from '@prisma/client';
42
+ import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3';
43
+
44
+ // One client per process: goal dev loads the server code again after each change.
45
+ export const db = (globalThis.prisma ??= new PrismaClient({
46
+ adapter: new PrismaBetterSqlite3({ url: process.env.DATABASE_URL }),
47
+ }));
48
+ `,
49
+ },
50
+ lines: { '.env': ['DATABASE_URL="file:./dev.db"'], '.gitignore': ['node_modules', 'dist', '.env', 'dev.db*'] },
51
+ scripts: { postinstall: 'prisma generate', 'db:push': 'prisma db push' },
52
+ run: ['npx prisma generate', 'npx prisma db push'],
53
+ next: [
54
+ "Use it from server code: import { db } from './db.js', then in a route or server function: return db.note.findMany()",
55
+ 'After changing prisma/schema.prisma: npm run db:push (or npx prisma migrate dev), and restart goal dev',
56
+ 'DATABASE_URL is in .env; in production, set it in the environment',
57
+ ],
58
+ test: {
59
+ run: [
60
+ `node --input-type=module --env-file=.env -e "import { db } from './db.js'; await db.note.create({ data: { text: 'hi' } }); process.exit((await db.note.count()) === 1 ? 0 : 1)"`,
61
+ 'npx goal build .',
62
+ `node --input-type=module --env-file=.env -e "import { db } from './dist/server/db.js'; process.exit((await db.note.count()) === 1 ? 0 : 1)"`,
63
+ ],
64
+ },
65
+ },
66
+ ],
67
+ };
@@ -0,0 +1,57 @@
1
+ // goal add sentry: errors that routes and server functions throw, reported to Sentry from
2
+ // goal.config.js's onError (see src/app.js).
3
+
4
+ export default {
5
+ name: 'sentry',
6
+ aliases: ['@sentry/node'],
7
+ package: '@sentry/node',
8
+ about: 'Sentry: errors from routes and server functions',
9
+ docs: 'https://docs.sentry.io/platforms/javascript/guides/node/',
10
+ versions: [
11
+ {
12
+ range: '11',
13
+ dependencies: { '@sentry/node': '11.18.0' },
14
+ files: {
15
+ 'sentry.js': `// Errors that routes and server functions throw, reported to Sentry: goal.config.js passes them to
16
+ // onError. Without SENTRY_DSN, in .env or the environment, nothing is sent.
17
+ import * as Sentry from '@sentry/node';
18
+
19
+ Sentry.init({ dsn: process.env.SENTRY_DSN });
20
+
21
+ export function onError(error, request) {
22
+ Sentry.captureException(error, { extra: { method: request?.method, path: request?.path } });
23
+ }
24
+ `,
25
+ },
26
+ config: { import: "import { onError } from './sentry.js';", keys: { onError: 'onError' } },
27
+ lines: { '.env': ['SENTRY_DSN='], '.gitignore': ['node_modules', 'dist', '.env'] },
28
+ next: ["Put your Sentry project's DSN in .env as SENTRY_DSN, and in the environment in production; until then nothing is sent"],
29
+ test: {
30
+ files: {
31
+ 'Boom.goal': 'route GET /boom {\n throw new Error("boom from a route");\n}\n',
32
+ 'check-sentry.mjs': `// A stand-in for Sentry, and the app with SENTRY_DSN pointing at it: a route's error must reach it.
33
+ import { createServer } from 'node:http';
34
+ import { spawn } from 'node:child_process';
35
+
36
+ const got = [];
37
+ const sentry = createServer((req, res) => {
38
+ let body = '';
39
+ req.on('data', (c) => (body += c));
40
+ req.on('end', () => (got.push(body), res.end('{}')));
41
+ });
42
+ await new Promise((ok) => sentry.listen(0, ok));
43
+ const env = { ...process.env, SENTRY_DSN: \`http://public@localhost:\${sentry.address().port}/1\` };
44
+ const app = spawn(process.execPath, ['node_modules/goaljs/bin/goal.js', 'start', '.', '--port', '4179'], { env, stdio: 'ignore' });
45
+ let res;
46
+ for (let i = 0; i < 100 && !res; i++) res = await fetch('http://localhost:4179/boom').catch(() => new Promise((ok) => setTimeout(ok, 100)));
47
+ for (let i = 0; i < 50 && !got.some((b) => b.includes('boom from a route')); i++) await new Promise((ok) => setTimeout(ok, 100));
48
+ app.kill();
49
+ sentry.close();
50
+ process.exit(res.status === 500 && got.some((b) => b.includes('boom from a route')) ? 0 : 1);
51
+ `,
52
+ },
53
+ run: ['npx goal build .', 'node check-sentry.mjs'],
54
+ },
55
+ },
56
+ ],
57
+ };
@@ -0,0 +1,60 @@
1
+ // goal add tailwindcss: Tailwind CSS, compiled by goal build and goal dev through PostCSS (see
2
+ // src/css.js), with the classes the app's .goal files use.
3
+
4
+ const ignore = { '.gitignore': ['node_modules', 'dist'] };
5
+ const link = 'Link the stylesheet from your pages: <link rel="stylesheet" href="/style.css" />';
6
+ const check = (file) => `node -e "process.exit(require('fs').readFileSync('${file}', 'utf8').includes('.text-3xl') ? 0 : 1)"`;
7
+
8
+ export default {
9
+ name: 'tailwindcss',
10
+ aliases: ['tailwind'],
11
+ package: 'tailwindcss',
12
+ about: 'Tailwind CSS: utility classes, compiled into public/style.css',
13
+ docs: 'https://tailwindcss.com/docs',
14
+ versions: [
15
+ {
16
+ range: '4',
17
+ devDependencies: { tailwindcss: '4.3.5', '@tailwindcss/postcss': '4.3.5', postcss: '8.5.33' },
18
+ files: {
19
+ 'postcss.config.js': `export default {
20
+ plugins: {
21
+ '@tailwindcss/postcss': {},
22
+ },
23
+ };
24
+ `,
25
+ },
26
+ // source(".."): the classes are looked for in the app's folder, wherever goal runs from
27
+ prepend: { 'public/style.css': ['@import "tailwindcss" source("..");'] },
28
+ lines: ignore,
29
+ next: [link, 'Use its classes in markup, like <h1 class="text-3xl font-bold">: goal dev and goal build put the ones your .goal files use in /style.css'],
30
+ test: { run: ['npx goal build .', check('dist/public/style.css')] },
31
+ },
32
+ {
33
+ range: '3',
34
+ devDependencies: { tailwindcss: '3.4.19', postcss: '8.5.33', autoprefixer: '10.7.0' },
35
+ files: {
36
+ 'tailwind.config.js': `/** @type {import('tailwindcss').Config} */
37
+ export default {
38
+ // The app's .goal files, from this file's folder
39
+ content: { relative: true, files: ['./**/*.goal', '!./node_modules/**', '!./dist/**'] },
40
+ theme: { extend: {} },
41
+ plugins: [],
42
+ };
43
+ `,
44
+ 'postcss.config.js': `import { fileURLToPath } from 'node:url';
45
+
46
+ export default {
47
+ plugins: {
48
+ tailwindcss: { config: fileURLToPath(new URL('./tailwind.config.js', import.meta.url)) },
49
+ autoprefixer: {},
50
+ },
51
+ };
52
+ `,
53
+ },
54
+ prepend: { 'public/style.css': ['@tailwind base;', '@tailwind components;', '@tailwind utilities;'] },
55
+ lines: ignore,
56
+ next: [link, 'Use its classes in markup, like <h1 class="text-3xl font-bold">: goal dev and goal build put the ones your .goal files use in /style.css'],
57
+ test: { run: ['npx goal build .', check('dist/public/style.css')] },
58
+ },
59
+ ],
60
+ };
@@ -0,0 +1,43 @@
1
+ // goal add vitest: Vitest, with goal.js's Vite plugin, so tests import components and server
2
+ // functions from .goal files as server code does.
3
+
4
+ export default {
5
+ name: 'vitest',
6
+ package: 'vitest',
7
+ about: 'Vitest: tests that import .goal files',
8
+ docs: 'https://vitest.dev/guide/',
9
+ versions: [
10
+ {
11
+ range: '5',
12
+ devDependencies: { vitest: '5.1.2' },
13
+ files: {
14
+ 'vitest.config.js': `import { defineConfig } from 'vitest/config';
15
+ import { goal } from 'goaljs/vite';
16
+
17
+ export default defineConfig({
18
+ plugins: [goal()], // tests import .goal files
19
+ test: { include: ['**/*.test.js'], exclude: ['node_modules/**', 'dist/**'] },
20
+ });
21
+ `,
22
+ },
23
+ scripts: { test: 'vitest' },
24
+ next: [
25
+ "Write tests as *.test.js. They import from .goal files: import { Counter } from './Counter.goal'",
26
+ 'A component renders to HTML: expect(String(Counter({ start: 1 }))).toContain(\'1\'); a server function is a plain async function',
27
+ 'npm test runs them and watches; npx vitest run runs them once',
28
+ ],
29
+ test: {
30
+ files: {
31
+ 'tests/counter.test.js': `import { test, expect } from 'vitest';
32
+ import { Counter } from '../Counter.goal';
33
+
34
+ test('Counter renders its start', () => {
35
+ expect(String(Counter({ start: 41 }))).toContain('41');
36
+ });
37
+ `,
38
+ },
39
+ run: ['npx vitest run'],
40
+ },
41
+ },
42
+ ],
43
+ };
package/src/add.js ADDED
@@ -0,0 +1,179 @@
1
+ // goal add <tool>: sets a tool up in the app. A recipe (recipes/<tool>.js) says, for each range of
2
+ // the tool's versions, which packages to install and what the app needs around them: files, lines in
3
+ // files like .gitignore, package.json scripts, goal.config.js keys, commands to run once, and what to
4
+ // do next. Recipes are data, kept up to date by pull request (see recipes/README.md).
5
+ //
6
+ // Nothing of the app's is overwritten: a file that's there already is kept and the recipe's version
7
+ // shown, a package the app has already isn't installed again, and its version picks the recipe.
8
+
9
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from 'node:fs';
10
+ import { join, dirname } from 'node:path';
11
+ import { execSync } from 'node:child_process';
12
+ import { fileURLToPath, pathToFileURL } from 'node:url';
13
+ import { parse } from '@babel/parser';
14
+
15
+ const RECIPES = join(dirname(fileURLToPath(import.meta.url)), '..', 'recipes');
16
+ const HELP = 'https://github.com/goallabs/goal/tree/main/recipes';
17
+
18
+ /** Every recipe, by file name. */
19
+ export async function recipes(dir = RECIPES) {
20
+ const all = [];
21
+ for (const f of readdirSync(dir).filter((f) => f.endsWith('.js')).sort()) all.push((await import(pathToFileURL(join(dir, f)).href)).default);
22
+ return all;
23
+ }
24
+
25
+ /** 4.3.5-rc.1 → [4, 3, 5]; 4 → [4, 0, 0] */
26
+ const parts = (v) => {
27
+ const p = v.split('-')[0].split('.').map(Number);
28
+ return [p[0], p[1] ?? 0, p[2] ?? 0];
29
+ };
30
+
31
+ /**
32
+ * Is the version in the range? Ranges are npm's, in part: `4` or `4.x` (any 4), `>=0.30 <0.32`
33
+ * (all of them), `3 || 4` (either). A version may be partial: `3` is 3.0.0 to a comparison.
34
+ */
35
+ export function satisfies(version, range) {
36
+ const v = parts(version);
37
+ const cmp = (w) => v[0] - w[0] || v[1] - w[1] || v[2] - w[2];
38
+ return range.split('||').some((alt) =>
39
+ alt
40
+ .trim()
41
+ .split(/\s+/)
42
+ .every((c) => {
43
+ const [, op, n] = /^(>=|<=|>|<|=)?(.*)$/.exec(c);
44
+ if (!op) return n.split('.').filter((x) => x !== 'x' && x !== '*').every((x, i) => v[i] === Number(x)); // 3 is 3.0.0 here too
45
+ const d = cmp(parts(n));
46
+ return { '>=': d >= 0, '<=': d <= 0, '>': d > 0, '<': d < 0, '=': d === 0 }[op];
47
+ }),
48
+ );
49
+ }
50
+
51
+ /** The recipe's entry for a version of its package; its newest without one. */
52
+ export function pick(recipe, version) {
53
+ if (!version) return recipe.versions[0];
54
+ const v = recipe.versions.find((e) => satisfies(version, e.range));
55
+ if (!v) throw new Error(`goal add has no recipe for ${recipe.package} ${version}, only for ${recipe.versions.map((e) => e.range).join(', ')}. To add one, see ${HELP}`);
56
+ return v;
57
+ }
58
+
59
+ /** Is this line, or one that means the same, in the list? `dist` and `/dist/`, `KEY=a` and `KEY=b` do. */
60
+ const has = (lines, line) => {
61
+ const key = (l) => /^[A-Za-z_]\w*=/.exec(l.trim())?.[0] ?? l.trim().replace(/^\/|\/$/g, '');
62
+ return lines.some((l) => key(l) === key(line));
63
+ };
64
+
65
+ /** The app's version of a package, from a range like ^4.1.0; nothing for a tag, a URL or a path. */
66
+ const coerce = (range) => /^[\^~=v]*(\d+(\.\d+){0,2})/.exec(range ?? '')?.[1];
67
+
68
+ /** goal.config.js gets the recipe's keys, and the import they need, unless it has them already. */
69
+ function configure(app, c, log) {
70
+ const file = join(app, 'goal.config.js');
71
+ const prop = (k) => (c.keys[k] === k ? k : `${k}: ${c.keys[k]}`);
72
+ if (!existsSync(file)) {
73
+ writeFileSync(file, `${c.import}\n\nexport default {\n${Object.keys(c.keys).map((k) => ` ${prop(k)},\n`).join('')}};\n`);
74
+ return log(' created goal.config.js');
75
+ }
76
+ let text = readFileSync(file, 'utf8');
77
+ let body;
78
+ try {
79
+ body = parse(text, { sourceType: 'module' }).program.body;
80
+ } catch {
81
+ body = [];
82
+ }
83
+ const obj = body.find((n) => n.type === 'ExportDefaultDeclaration')?.declaration;
84
+ if (obj?.type !== 'ObjectExpression')
85
+ return log(` goal.config.js: add this to it yourself (its default export isn't an object to add to):\n ${c.import}\n ${Object.keys(c.keys).map(prop).join(', ')}`);
86
+ const keys = new Set(obj.properties.map((p) => p.key?.name ?? p.key?.value));
87
+ const missing = Object.keys(c.keys).filter((k) => !keys.has(k));
88
+ if (!missing.length) return log(` kept goal.config.js: it has ${Object.keys(c.keys).join(', ')} already`);
89
+ text = text.slice(0, obj.start + 1) + missing.map((k) => `\n ${prop(k)},`).join('') + text.slice(obj.start + 1);
90
+ if (!text.includes(c.import)) {
91
+ const at = body.filter((n) => n.type === 'ImportDeclaration').at(-1)?.end;
92
+ text = at === undefined ? `${c.import}\n${text}` : `${text.slice(0, at)}\n${c.import}${text.slice(at)}`;
93
+ }
94
+ writeFileSync(file, text);
95
+ log(` added ${missing.join(', ')} to goal.config.js`);
96
+ }
97
+
98
+ const sh = (cmd, cwd) => execSync(cmd, { cwd, stdio: 'inherit' });
99
+
100
+ /**
101
+ * Sets a tool up in the app: `spec` is the recipe's name, with a version to pick the recipe for one
102
+ * (`tailwindcss@3`). Without a name, lists the recipes. `run` runs a command in the app's folder.
103
+ */
104
+ export async function add(app, spec, { log = console.log, run = sh, dir } = {}) {
105
+ const all = await recipes(dir);
106
+ if (!spec) {
107
+ log('goal add <tool> [app folder] sets a tool up in the app. Recipes:');
108
+ for (const r of all) log(` ${[r.name, ...(r.aliases ?? [])].join(', ').padEnd(24)} ${r.about} (${r.versions.map((e) => e.range).join(', ')})`);
109
+ return;
110
+ }
111
+ const at = spec.lastIndexOf('@');
112
+ const [name, version] = at > 0 ? [spec.slice(0, at), spec.slice(at + 1)] : [spec];
113
+ const recipe = all.find((r) => r.name === name || r.package === name || r.aliases?.includes(name));
114
+ if (!recipe) throw new Error(`goal add has no recipe for ${name}; it has ${all.map((r) => r.name).join(', ')}. To add one, see ${HELP}`);
115
+
116
+ const pkgFile = join(app, 'package.json');
117
+ const read = () => (existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, 'utf8')) : { private: true });
118
+ let pkg = read();
119
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
120
+ const mine = coerce(deps[recipe.package]);
121
+ const e = pick(recipe, version ?? mine);
122
+ log(`${recipe.name}: the recipe for ${recipe.package} ${e.range}${mine && !version ? ` (the app has ${deps[recipe.package]})` : ''}`);
123
+
124
+ if (pkg.type !== 'module') {
125
+ pkg.type = 'module';
126
+ writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
127
+ log(' set "type": "module" in package.json: goal.js apps are ES modules');
128
+ }
129
+ for (const [field, flag] of [['dependencies', '--save'], ['devDependencies', '--save-dev']]) {
130
+ const names = Object.keys(e[field] ?? {}).filter((n) => !(n in deps));
131
+ for (const n of Object.keys(e[field] ?? {}).filter((n) => n in deps)) log(` kept ${n} ${deps[n]}`);
132
+ if (!names.length) continue;
133
+ const cmd = `npm install ${flag} ${names.map((n) => `${n}@${e[field][n]}`).join(' ')}`;
134
+ log(` $ ${cmd}`);
135
+ run(cmd, app);
136
+ }
137
+
138
+ for (const [f, text] of Object.entries(e.files ?? {})) {
139
+ const file = join(app, f);
140
+ if (!existsSync(file)) {
141
+ mkdirSync(dirname(file), { recursive: true });
142
+ writeFileSync(file, text);
143
+ log(` created ${f}`);
144
+ } else if (readFileSync(file, 'utf8') === text) log(` kept ${f}: it's set up already`);
145
+ else log(` kept ${f}, which isn't the recipe's. The recipe's:\n${text.trimEnd().replace(/^(?=.)/gm, ' ')}`);
146
+ }
147
+ // Lines a file needs: at its start (prepend), like a stylesheet's @import, or at its end (lines)
148
+ for (const [where, ops] of [['start', e.prepend], ['end', e.lines]])
149
+ for (const [f, want] of Object.entries(ops ?? {})) {
150
+ const file = join(app, f);
151
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : '';
152
+ const now = text.split(/\r?\n/);
153
+ const add = want.filter((l) => !has(now, l));
154
+ if (!add.length) continue;
155
+ mkdirSync(dirname(file), { recursive: true });
156
+ const lines = add.join('\n') + '\n';
157
+ writeFileSync(file, where === 'start' ? lines + text : text + (text && !text.endsWith('\n') ? '\n' : '') + lines);
158
+ log(` added to ${f}: ${add.join(', ')}`);
159
+ }
160
+ pkg = read(); // as npm left it
161
+ const placeholder = /^echo "Error: no test specified" && exit 1$/; // npm init's
162
+ const scripts = Object.entries(e.scripts ?? {}).filter(([k, v]) => {
163
+ if (!pkg.scripts?.[k] || placeholder.test(pkg.scripts[k])) return true;
164
+ if (pkg.scripts[k] !== v) log(` kept the script ${k}: ${pkg.scripts[k]} (the recipe's: ${v})`);
165
+ return false;
166
+ });
167
+ if (scripts.length) {
168
+ pkg.scripts = { ...pkg.scripts, ...Object.fromEntries(scripts) };
169
+ writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
170
+ log(` added the script${scripts.length > 1 ? 's' : ''} ${scripts.map(([k]) => k).join(', ')} to package.json`);
171
+ }
172
+ if (e.config) configure(app, e.config, log);
173
+ for (const cmd of e.run ?? []) {
174
+ log(` $ ${cmd}`);
175
+ run(cmd, app);
176
+ }
177
+ log('Next:');
178
+ for (const n of [...(e.next ?? []), `Docs: ${recipe.docs}`]) log(` - ${n}`);
179
+ }
package/src/app.js CHANGED
@@ -186,7 +186,8 @@ function keptState(header) {
186
186
  /**
187
187
  * A request handler for node:http.
188
188
  * @param {{ method: string, path: string, handler: Function }[]} routes
189
- * @param {{ dev?: boolean, staticDirs?: string[], config?: { csp?: string | false, csrf?: boolean, bodyLimit?: number }, log?: (e: Error) => void }} [opts]
189
+ * @param {{ dev?: boolean, staticDirs?: string[], config?: { csp?: string | false, csrf?: boolean, bodyLimit?: number, onError?: (e: Error, request?: object) => void }, log?: (e: Error) => void }} [opts]
190
+ * config.onError: called with each error a route or server function throws, and the request
190
191
  */
191
192
  export function createApp(routes, { dev = false, staticDirs = [], config = {}, log = console.error } = {}) {
192
193
  const sorted = table(routes);
@@ -206,6 +207,7 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
206
207
  res.end(req.method === 'HEAD' ? undefined : body);
207
208
  };
208
209
  const fail = (status, title) => send(status, HTML, errorPage(title));
210
+ let request;
209
211
 
210
212
  try {
211
213
  const url = new URL(req.url, 'http://localhost');
@@ -271,7 +273,7 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
271
273
  return j < 0 ? null : kept.splice(0, j + 1).pop().s;
272
274
  };
273
275
  }
274
- const request = { method, path: url.pathname, url, params: m.params, query: Object.fromEntries(url.searchParams), headers: req.headers, cookies, form, files, json: body };
276
+ request = { method, path: url.pathname, url, params: m.params, query: Object.fromEntries(url.searchParams), headers: req.headers, cookies, form, files, json: body };
275
277
  const cookie = (name, value, opts) => setCookies.push(serializeCookie(name, value, opts));
276
278
  const out = await m.route.handler(request, { ctx, redirect, json, notFound, cookie });
277
279
  if (isHtml(out)) return send(200, HTML, page(out.s, [...ctx.ev], nonce, token, dev));
@@ -281,6 +283,11 @@ export function createApp(routes, { dev = false, staticDirs = [], config = {}, l
281
283
  } catch (e) {
282
284
  if (e.status === 413) return fail(413, 'Too large');
283
285
  log(e);
286
+ // goal.config.js's onError hears of it too, say to report it to an error tracker. It runs after the
287
+ // answer is on its way, and an error of its own is logged.
288
+ Promise.resolve()
289
+ .then(() => config.onError?.(e, request))
290
+ .catch(log);
284
291
  return dev ? send(500, 'text/plain; charset=utf-8', String(e.stack)) : fail(500, 'Something went wrong');
285
292
  }
286
293
  };
package/src/build.js CHANGED
@@ -3,8 +3,11 @@
3
3
  // app/**/*.goal -> dist/server/**.js (components and routes) and one client chunk per
4
4
  // interactive component in dist/client/c/
5
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)
6
+ // app/public/ -> dist/public/, served as files; stylesheets through PostCSS when the app
7
+ // has a postcss.config.js (see css.js)
8
+ // app/goal.config.js opt-outs of the security defaults and the error hook (see src/app.js),
9
+ // copied with the server code
10
+ // app/.env -> process.env, for goal start and goal dev
8
11
 
9
12
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, cpSync, rmSync, watch } from 'node:fs';
10
13
  import { join, relative, dirname, resolve, sep, posix } from 'node:path';
@@ -17,6 +20,7 @@ import { exportsOf } from './types.js';
17
20
  import { desugar } from './syntax.js';
18
21
  import { loaderScript } from './server.js';
19
22
  import { createApp } from './app.js';
23
+ import { postcss } from './css.js';
20
24
 
21
25
 
22
26
  const SRC = dirname(fileURLToPath(import.meta.url));
@@ -105,7 +109,8 @@ export function check(app) {
105
109
  * Compiles an app into dist/. Throws on a compile error or a duplicate route.
106
110
  * `dev` keeps chunks readable with source maps back to the .goal files; otherwise they are minified
107
111
  * and the source stays on the server. `publicPath` is where the site is served from.
108
- * @returns {Promise<{ version: string, chunks: { url: string, bytes: number, gzip: number }[], loader: number, routes: string[] }>}
112
+ * @returns {Promise<{ version: string, chunks: { url: string, bytes: number, gzip: number }[], loader: number, routes: string[], css: boolean }>}
113
+ * css: whether the stylesheets went through PostCSS
109
114
  */
110
115
  export async function build(app, { out = join(app, 'dist'), dev = false, publicPath = '/' } = {}) {
111
116
  const version = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
@@ -118,7 +123,6 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
118
123
  const all = files(app);
119
124
  const link = linker(app, all);
120
125
  for (const rel of all) {
121
- if (rel === 'goal.config.js') continue;
122
126
  if (!rel.endsWith('.goal')) {
123
127
  if (/\.(m?js|json)$/.test(rel)) write(join(out, 'server', rel), readFileSync(join(app, rel)));
124
128
  continue;
@@ -179,8 +183,15 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
179
183
  routeFiles.map((f, i) => `import { _$routes as r${i} } from './${f}.js?v=${version}';\n`).join('') +
180
184
  `export default [${routeFiles.map((_, i) => `...r${i}`).join(', ')}];\n`,
181
185
  );
182
- if (existsSync(join(app, 'public'))) cpSync(join(app, 'public'), join(out, 'public'), { recursive: true });
183
- return { version, chunks, loader: gzipSync(loaderScript()).length, routes: routes.map((r) => r.label) };
186
+ // The server code is ES modules, whatever the app's package.json says.
187
+ write(join(out, 'server', 'package.json'), '{ "type": "module" }\n');
188
+ const css = await postcss(app, dev);
189
+ if (existsSync(join(app, 'public'))) {
190
+ cpSync(join(app, 'public'), join(out, 'public'), { recursive: true });
191
+ for (const f of css ? readdirSync(join(app, 'public'), { recursive: true }).filter((f) => f.endsWith('.css')) : [])
192
+ writeFileSync(join(out, 'public', f), await css(readFileSync(join(app, 'public', f), 'utf8'), join(app, 'public', f), join(out, 'public', f)));
193
+ }
194
+ return { version, chunks, loader: gzipSync(loaderScript()).length, routes: routes.map((r) => r.label), css: !!css };
184
195
  }
185
196
 
186
197
  /**
@@ -188,7 +199,8 @@ export async function build(app, { out = join(app, 'dist'), dev = false, publicP
188
199
  * of pages listening at /_goal/hmr for live updates (goal dev).
189
200
  */
190
201
  export async function serve(app, { out = join(app, 'dist'), port = 3000, dev = false, version = () => '', log = console.error, hmr } = {}) {
191
- const configFile = join(app, 'goal.config.js');
202
+ if (existsSync(join(app, '.env'))) process.loadEnvFile(join(app, '.env')); // what the environment has already wins
203
+ const configFile = join(out, 'server', 'goal.config.js');
192
204
  const config = existsSync(configFile) ? (await import(pathToFileURL(configFile).href)).default : {};
193
205
  const routesFile = pathToFileURL(join(out, 'server', '_routes.js')).href;
194
206
  const server = createServer(async (req, res) => {
@@ -221,7 +233,9 @@ export async function dev(app, { port = 3000, log = console.log } = {}) {
221
233
  const r = await build(app, { dev: true });
222
234
  version = r.version;
223
235
  log(`built: ${r.routes.length} route(s), ${r.chunks.length} chunk(s)`);
224
- tell({ type: changed.length && changed.every((f) => f.endsWith('.css')) ? 'css' : 'update', version });
236
+ const type = changed.length && changed.every((f) => f.endsWith('.css')) ? 'css' : 'update';
237
+ tell({ type, version });
238
+ if (type === 'update' && r.css) tell({ type: 'css', version }); // PostCSS may make new CSS from the code, as Tailwind does
225
239
  } catch (e) {
226
240
  log(e.message);
227
241
  tell({ type: 'error', message: e.message });
package/src/cli.js CHANGED
@@ -1,19 +1,31 @@
1
1
  // goal build [app] | goal start [app] [--port N] | goal dev [app] [--port N] | goal check [app]
2
+ // | goal add [tool] [app]
2
3
 
3
4
  import { build, serve, dev, check } from './build.js';
5
+ import { add } from './add.js';
4
6
 
5
- const USAGE = 'usage: goal build|start|dev|check [app folder] [--port 3000]';
7
+ const USAGE = 'usage: goal build|start|dev|check [app folder] [--port 3000]\n goal add [tool] [app folder]';
6
8
 
7
- /** The command, the app's folder (the current one by default) and the port (3000 by default). */
9
+ /** The command, the app's folder (the current one by default), the port (3000 by default), and goal add's tool. */
8
10
  export function args(argv) {
9
11
  const [cmd, ...rest] = argv;
10
12
  const i = rest.indexOf('--port');
11
13
  const port = i < 0 ? 3000 : Number(rest.splice(i, 2)[1]);
12
- return { cmd, app: rest[0] ?? '.', port };
14
+ const tool = cmd === 'add' ? rest.shift() : undefined;
15
+ return { cmd, app: rest[0] ?? '.', port, tool };
13
16
  }
14
17
 
15
- export async function main(argv, log = console.log) {
16
- const { cmd, app, port } = args(argv);
18
+ export async function main(argv, log = console.log, opts = {}) {
19
+ const { cmd, app, port, tool } = args(argv);
20
+ if (cmd === 'add') {
21
+ try {
22
+ await add(app, tool, { log, ...opts });
23
+ return 0;
24
+ } catch (e) {
25
+ log(e.message);
26
+ return 1;
27
+ }
28
+ }
17
29
  if (cmd === 'build') {
18
30
  try {
19
31
  const r = await build(app);
package/src/css.js ADDED
@@ -0,0 +1,30 @@
1
+ // Stylesheets through PostCSS. When the app has a postcss.config.js (or .mjs, .cjs), each .css file in
2
+ // public/ goes through the plugins it names before it's served: Tailwind CSS, autoprefixer and the
3
+ // like. goal build writes the result to dist/public/; the Vite plugin answers it on request. PostCSS
4
+ // and its plugins are the app's own packages, found from the app's folder.
5
+
6
+ import { existsSync } from 'node:fs';
7
+ import { createRequire } from 'node:module';
8
+ import { resolve } from 'node:path';
9
+ import { pathToFileURL } from 'node:url';
10
+
11
+ /** The app's PostCSS config file, if it has one. */
12
+ export const postcssConfig = (app) => ['postcss.config.js', 'postcss.config.mjs', 'postcss.config.cjs'].map((f) => resolve(app, f)).find((f) => existsSync(f));
13
+
14
+ /**
15
+ * The app's PostCSS, as `(css, from, to) => Promise<string>`, or null when the app has no PostCSS
16
+ * config. The config is read anew each time, so goal dev sees it change. `dev` adds source maps.
17
+ */
18
+ export async function postcss(app, dev = false) {
19
+ const file = postcssConfig(app);
20
+ if (!file) return null;
21
+ const require = createRequire(file);
22
+ const load = async (name) => (await import(pathToFileURL(require.resolve(name)).href)).default;
23
+ let config = (await import(`${pathToFileURL(file).href}?v=${Date.now()}`)).default;
24
+ if (typeof config === 'function') config = await config({ env: dev ? 'development' : 'production' });
25
+ // { plugins: { name: options } }, each plugin a package of the app's, or { plugins: [plugin(), ...] }
26
+ const { plugins = [] } = config;
27
+ const list = Array.isArray(plugins) ? plugins : await Promise.all(Object.entries(plugins).filter(([, o]) => o !== false).map(async ([name, o]) => (await load(name))(o)));
28
+ const run = await load('postcss');
29
+ return async (css, from, to) => (await run(list).process(css, { from, to, map: dev && { inline: true } })).css;
30
+ }
package/src/eslint.js ADDED
@@ -0,0 +1,106 @@
1
+ // ESLint for .goal files:
2
+ //
3
+ // // eslint.config.js
4
+ // import goal from 'goaljs/eslint';
5
+ // export default [js.configs.recommended, ...goal.configs.recommended];
6
+ //
7
+ // ESLint checks the JavaScript each .goal file becomes (see syntax.js): routes as functions, {if} as
8
+ // ternaries, types taken out, a route's path parameters as its function's. A problem is reported
9
+ // where it is in the .goal file, and a fix is kept when the text it changes is the file's own.
10
+ // Problems in code goal.js wrote, like a route's parameters, aren't the file's and are left out. A
11
+ // file that doesn't parse gets its parse error.
12
+
13
+ import { desugar } from './syntax.js';
14
+
15
+ const seen = new Map(); // by file: what preprocess made of it, for postprocess
16
+
17
+ /** Where each line starts. */
18
+ const starts = (text) => {
19
+ const s = [0];
20
+ for (let i = 0; i < text.length; i++) if (text[i] === '\n') s.push(i + 1);
21
+ return s;
22
+ };
23
+
24
+ const processor = {
25
+ meta: { name: 'goal' },
26
+ supportsAutofix: true,
27
+ preprocess(text, file) {
28
+ try {
29
+ const r = desugar(text, file);
30
+ // The compiler declares a route's path parameters in its function; here they're its parameters.
31
+ let code = r.code;
32
+ const added = [];
33
+ for (const route of r.routes.filter((x) => x.params.length)) {
34
+ const at = code.indexOf(`${route.name}(request, _$x`) + route.name.length + 13;
35
+ const ins = `, { ${route.params.join(', ')} }`;
36
+ code = code.slice(0, at) + ins + code.slice(at);
37
+ added.push({ at, length: ins.length });
38
+ }
39
+ seen.set(file, { text, code, map: r.map, added, from: starts(code), to: starts(text) });
40
+ return [{ text: code, filename: 'goal.jsx' }];
41
+ } catch (e) {
42
+ seen.set(file, { error: e });
43
+ return [];
44
+ }
45
+ },
46
+ postprocess([messages = []], file) {
47
+ const f = seen.get(file);
48
+ seen.delete(file);
49
+ if (f.error) return [{ ruleId: null, fatal: true, severity: 2, message: f.error.message.replace(/^.*?:\d+:\d+: /, ''), line: f.error.line, column: f.error.column }];
50
+ // From a place in what ESLint saw, to one in the desugared code (-1 in a path parameter added)
51
+ const desugared = (o) => {
52
+ let d = 0;
53
+ for (const a of f.added) {
54
+ if (o < a.at) break;
55
+ if (o < a.at + a.length) return -1;
56
+ d += a.length;
57
+ }
58
+ return o - d;
59
+ };
60
+ const at = (line, column) => f.map(desugared(f.from[line - 1] + column - 1));
61
+ const ours = (line, column) => {
62
+ const o = desugared(f.from[line - 1] + column - 1);
63
+ return o < 0 || f.map(o) === f.map(o + 1); // goal.js's code maps to one place
64
+ };
65
+ const place = (o) => {
66
+ const line = f.to.findLastIndex((s) => s <= o);
67
+ return { line: line + 1, column: o - f.to[line] + 1 };
68
+ };
69
+ // A fix or suggestion over the file's own text, at its place in the file
70
+ const fix = (x) => {
71
+ const [a, b] = x.range.map((o) => f.map(desugared(o)));
72
+ return f.text.slice(a, b) === f.code.slice(...x.range) ? { range: [a, b], text: x.text } : undefined;
73
+ };
74
+ return messages
75
+ .filter((m) => !m.line || !ours(m.line, m.column))
76
+ .map((m) => {
77
+ if (!m.line) return m;
78
+ const out = { ...m, ...place(at(m.line, m.column)) };
79
+ if (m.endLine) {
80
+ const end = place(at(m.endLine, m.endColumn));
81
+ out.endLine = end.line;
82
+ out.endColumn = end.column;
83
+ }
84
+ if (m.fix) out.fix = fix(m.fix);
85
+ if (m.suggestions) out.suggestions = m.suggestions.map((s) => ({ ...s, fix: fix(s.fix) })).filter((s) => s.fix);
86
+ if (!out.fix) delete out.fix;
87
+ return out;
88
+ });
89
+ },
90
+ };
91
+
92
+ const plugin = { meta: { name: 'goaljs' }, processors: { goal: processor }, configs: {} };
93
+
94
+ plugin.configs.recommended = [
95
+ { files: ['**/*.goal'], plugins: { goal: plugin }, processor: 'goal/goal' },
96
+ {
97
+ files: ['**/*.goal/*.jsx'],
98
+ languageOptions: {
99
+ parserOptions: { ecmaFeatures: { jsx: true } },
100
+ globals: { redirect: 'readonly', json: 'readonly', notFound: 'readonly', cookie: 'readonly' }, // a route's helpers
101
+ },
102
+ rules: { 'no-var': 'off' }, // var is a component's state
103
+ },
104
+ ];
105
+
106
+ export default plugin;
package/src/vite.js CHANGED
@@ -11,14 +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';
20
22
  import { exportsOf } from './types.js';
21
23
  import { createApp } from './app.js';
24
+ import { postcss, postcssConfig } from './css.js';
22
25
 
23
26
  const SRC = dirname(fileURLToPath(import.meta.url)); // compiled code imports the helpers from here
24
27
  const SKIP = new Set(['node_modules', 'dist', 'public']);
@@ -70,6 +73,7 @@ export function goal({ config = {} } = {}) {
70
73
  config: () => ({ appType: 'custom' }), // the app's routes answer pages, not an index.html
71
74
  configResolved(c) {
72
75
  root = c.root;
76
+ if (existsSync(join(root, '.env'))) process.loadEnvFile(join(root, '.env'));
73
77
  },
74
78
  // A component's browser code: /ui/Panel.goal.Panel.client.js; a file's render module, imported as
75
79
  // goal-render:./Panel.goal: /ui/Panel.goal.render.js. Both are made from the .goal file.
@@ -92,9 +96,20 @@ export function goal({ config = {} } = {}) {
92
96
  },
93
97
  configureServer(server) {
94
98
  // Before Vite's own middleware: the .goal files stay on the server, as with goal build.
95
- server.middlewares.use((req, res, next) => {
96
- if (!/\.goal(\?|$)/.test(req.url)) return next();
97
- res.writeHead(404).end();
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);
98
113
  });
99
114
  // After it: what Vite doesn't serve, the app answers.
100
115
  return () =>
@@ -121,6 +136,7 @@ export function goal({ config = {} } = {}) {
121
136
  version++;
122
137
  server.moduleGraph.invalidateAll(); // the server code reads the new files
123
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
124
140
  return []; // the pages update themselves
125
141
  },
126
142
  };