create-acrylblends 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +14 -1
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.js +69 -9
  4. package/dist/index.js.map +1 -1
  5. package/docs/framework/README.md +2 -1
  6. package/docs/framework/UPSTREAM.md +1 -1
  7. package/docs/framework/api/summary.md +7 -4
  8. package/docs/framework/cordis/node-server.md +3 -0
  9. package/docs/framework/getting-started/deploy.md +133 -0
  10. package/docs/framework/getting-started/desktop.md +1 -1
  11. package/docs/framework/getting-started/nodejs.md +37 -16
  12. package/docs/framework/guides/client-modules.md +175 -0
  13. package/docs/framework/guides/forms-and-sessions.md +231 -0
  14. package/docs/framework/guides/jsx-dom.md +12 -7
  15. package/docs/framework/guides/validation.md +88 -1
  16. package/docs/framework/helpers/cookie.md +1 -1
  17. package/docs/framework/helpers/testing.md +17 -0
  18. package/docs/framework/upstream.json +3 -3
  19. package/package.json +2 -2
  20. package/templates/nodejs/gitignore +1 -0
  21. package/templates/nodejs/package.json +5 -4
  22. package/templates/nodejs/src/app.ts +5 -5
  23. package/templates/nodejs/src/client/counter.tsx +12 -0
  24. package/templates/nodejs/src/client/tsconfig.json +15 -0
  25. package/templates/nodejs/src/index.ts +16 -4
  26. package/templates/nodejs/src/page.tsx +12 -0
  27. package/templates/nodejs/src/routes.ts +10 -0
  28. package/templates/nodejs/test/app.test.ts +10 -0
  29. package/templates/nodejs/test/server.test.ts +48 -0
  30. package/templates/nodejs/tsconfig.json +2 -1
  31. package/templates/notes/gitignore +5 -0
  32. package/templates/notes/package.json +23 -0
  33. package/templates/notes/src/app.ts +7 -0
  34. package/templates/notes/src/auth.ts +55 -0
  35. package/templates/notes/src/client/counter.tsx +21 -0
  36. package/templates/notes/src/client/tsconfig.json +15 -0
  37. package/templates/notes/src/db.ts +70 -0
  38. package/templates/notes/src/index.ts +22 -0
  39. package/templates/notes/src/notes-app.ts +199 -0
  40. package/templates/notes/src/schema.ts +38 -0
  41. package/templates/notes/src/views.tsx +134 -0
  42. package/templates/notes/test/notes.test.ts +245 -0
  43. package/templates/notes/test/server.test.ts +59 -0
  44. package/templates/notes/tsconfig.json +19 -0
@@ -1,10 +1,10 @@
1
1
  import { __CLASS__ } from '__PACKAGE__'
2
- import { aboutPage } from './page.tsx'
2
+ import { clientModules } from '__PACKAGE__/node-server'
3
+ import { routes } from './routes.ts'
3
4
 
5
+ // Client components without a bundler: src/client is compiled when the browser asks; `npm run build` compiles it once for production (NODE_ENV=production serves only dist/client).
4
6
  const app = new __CLASS__()
5
-
6
- app.get('/', (c) => c.text('__CLASS__!'))
7
-
8
- app.get('/about', (c) => c.html(aboutPage()))
7
+ .route('/', routes)
8
+ .route('/client', clientModules({ root: 'src/client', compiled: 'dist/client' }))
9
9
 
10
10
  export default app
@@ -0,0 +1,12 @@
1
+ import { render, useState } from '__PACKAGE__/jsx/dom'
2
+
3
+ const Counter = () => {
4
+ const [count, setCount] = useState(0)
5
+ return (
6
+ <button type="button" onClick={() => setCount(count + 1)}>
7
+ Count {count}
8
+ </button>
9
+ )
10
+ }
11
+
12
+ render(<Counter />, document.getElementById('counter')!)
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2024",
4
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
5
+ "module": "NodeNext",
6
+ "moduleResolution": "NodeNext",
7
+ "strict": true,
8
+ "noEmit": true,
9
+ "allowImportingTsExtensions": true,
10
+ "jsx": "react-jsx",
11
+ "jsxImportSource": "__PACKAGE__/jsx/dom",
12
+ "types": []
13
+ },
14
+ "include": ["**/*.ts", "**/*.tsx"]
15
+ }
@@ -1,9 +1,21 @@
1
1
  import { serve } from '__PACKAGE__/node-server'
2
2
  import app from './app.ts'
3
3
 
4
- const server = serve({ fetch: app.fetch, port: Number(process.env.PORT ?? 3000) }, (info) => {
5
- console.log(`listening on http://localhost:${info.port}`)
4
+ const port = Number(process.env.PORT || 3000)
5
+ // Local by default. Behind a reverse proxy on the same machine this is right; in a container set HOST=0.0.0.0.
6
+ const hostname = process.env.HOST || '127.0.0.1'
7
+
8
+ const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
9
+ console.log(`listening on http://${info.address}:${info.port}`)
6
10
  })
7
11
 
8
- process.once('SIGINT', () => server.close(() => process.exit(0)))
9
- process.once('SIGTERM', () => server.close(() => process.exit(0)))
12
+ // Stop taking requests, let the ones in flight finish, then exit. A connection that never ends cannot keep the process alive past 10 seconds.
13
+ function shutdown(): void {
14
+ server.close(() => {
15
+ process.exit(0)
16
+ })
17
+ server.closeIdleConnections()
18
+ setTimeout(() => process.exit(1), 10_000).unref()
19
+ }
20
+ process.once('SIGINT', shutdown)
21
+ process.once('SIGTERM', shutdown)
@@ -12,3 +12,15 @@ export const aboutPage = (): string => (<About />).toString()
12
12
  export const failingPage = (): string => {
13
13
  throw new Error('a page failed')
14
14
  }
15
+
16
+ /** A page with one client component: `src/client/counter.tsx` runs in the browser, compiled on request by `clientModules` (see src/app.ts). */
17
+ export const counterPage = (): string =>
18
+ (
19
+ <html lang="en">
20
+ <body>
21
+ <h1>Counter</h1>
22
+ <div id="counter" />
23
+ <script type="module" src="/client/counter.tsx" />
24
+ </body>
25
+ </html>
26
+ ).toString()
@@ -0,0 +1,10 @@
1
+ import { __CLASS__ } from '__PACKAGE__'
2
+ import { aboutPage, counterPage } from './page.tsx'
3
+
4
+ /** The routes, in a file that does not import the Node adapter, so browser code can import the type: `import type { AppType } from '../routes.ts'`. */
5
+ export const routes = new __CLASS__()
6
+ .get('/', (c) => c.text('__CLASS__!'))
7
+ .get('/about', (c) => c.html(aboutPage()))
8
+ .get('/counter', (c) => c.html(counterPage()))
9
+
10
+ export type AppType = typeof routes
@@ -28,3 +28,13 @@ test('an error thrown in a .tsx file names the .tsx line in its stack', async ()
28
28
  }
29
29
  assert.match(stack, /page\.tsx:\d+/)
30
30
  })
31
+
32
+ test('GET /counter serves a page with a client component, and the component is compiled for the browser', async () => {
33
+ const page = await app.request('/counter')
34
+ assert.equal(page.status, 200)
35
+ assert.match(await page.text(), /<script type="module" src="\/client\/counter\.tsx">/)
36
+ const module = await app.request('/client/counter.tsx')
37
+ assert.equal(module.status, 200)
38
+ assert.match(module.headers.get('content-type') ?? '', /javascript/)
39
+ assert.doesNotMatch(await module.text(), /<Counter|<button/)
40
+ })
@@ -0,0 +1,48 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawn } from 'node:child_process'
3
+ import { once } from 'node:events'
4
+ import { test } from 'node:test'
5
+
6
+ /** Start `src/index.ts` the way `npm start` does, on a port the system chooses, and read the address it prints. */
7
+ async function start(env: Record<string, string> = {}) {
8
+ const child = spawn(
9
+ process.execPath,
10
+ ['--import', '__PACKAGE__/node-server/register', 'src/index.ts'],
11
+ { env: { ...process.env, PORT: '0', ...env }, stdio: ['ignore', 'pipe', 'inherit'] },
12
+ )
13
+ let out = ''
14
+ const address = await new Promise<string>((resolve, reject) => {
15
+ child.once('exit', (code) =>
16
+ reject(new Error(`the server exited with ${code} before it listened`)),
17
+ )
18
+ child.stdout.on('data', (chunk) => {
19
+ out += chunk
20
+ const match = /listening on (http:\/\/\S+)/.exec(out)
21
+ if (match?.[1]) resolve(match[1])
22
+ })
23
+ })
24
+ return { child, address }
25
+ }
26
+
27
+ test('the server listens on 127.0.0.1 unless HOST says otherwise', async () => {
28
+ const { child, address } = await start()
29
+ try {
30
+ assert.match(address, /^http:\/\/127\.0\.0\.1:\d+$/)
31
+ } finally {
32
+ child.kill('SIGTERM')
33
+ await once(child, 'exit')
34
+ }
35
+ })
36
+
37
+ for (const signal of ['SIGTERM', 'SIGINT'] as const) {
38
+ test(`${signal} stops the server cleanly and frees the port`, async () => {
39
+ const { child, address } = await start()
40
+ assert.equal((await fetch(address)).status, 200)
41
+ const started = Date.now()
42
+ child.kill(signal)
43
+ const [code] = await once(child, 'exit')
44
+ assert.equal(code, 0)
45
+ assert.ok(Date.now() - started < 5000, 'the server took too long to stop')
46
+ await assert.rejects(fetch(address), 'the port should be free')
47
+ })
48
+ }
@@ -14,5 +14,6 @@
14
14
  "jsx": "react-jsx",
15
15
  "jsxImportSource": "__PACKAGE__/jsx"
16
16
  },
17
- "include": ["src", "test"]
17
+ "include": ["src", "test"],
18
+ "exclude": ["src/client"]
18
19
  }
@@ -0,0 +1,5 @@
1
+ node_modules/
2
+ *.db
3
+ *.db-*
4
+ .acrylblends/
5
+ dist/
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "__APP_NAME__",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22.19.0"
8
+ },
9
+ "scripts": {
10
+ "dev": "node --watch --import acrylblends/node-server/register src/index.ts",
11
+ "start": "node --import acrylblends/node-server/register src/index.ts",
12
+ "test": "node --import acrylblends/node-server/register --test \"test/**/*.test.{ts,tsx}\"",
13
+ "check": "tsc --noEmit && tsc --noEmit -p src/client",
14
+ "build": "acrylblends build-client"
15
+ },
16
+ "dependencies": {
17
+ "__PACKAGE__": "__RANGE__",
18
+ "typescript": "6.0.3"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^24.0.0"
22
+ }
23
+ }
@@ -0,0 +1,7 @@
1
+ import { openDb } from './db.ts'
2
+ import { createApp } from './notes-app.ts'
3
+
4
+ /** The database is opened here, once, so the server can close it when it stops. */
5
+ export const db = openDb()
6
+
7
+ export default createApp(db)
@@ -0,0 +1,55 @@
1
+ import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
2
+ import type { DatabaseSync } from 'node:sqlite'
3
+ import { promisify } from 'node:util'
4
+
5
+ const scryptAsync = promisify(scrypt) as (
6
+ password: string,
7
+ salt: Buffer,
8
+ length: number,
9
+ ) => Promise<Buffer>
10
+
11
+ export async function hashPassword(password: string): Promise<string> {
12
+ const salt = randomBytes(16)
13
+ const key = await scryptAsync(password, salt, 64)
14
+ return `${salt.toString('hex')}:${key.toString('hex')}`
15
+ }
16
+
17
+ export async function verifyPassword(password: string, stored: string): Promise<boolean> {
18
+ const [salt, key] = stored.split(':')
19
+ if (!salt || !key) return false
20
+ const expected = Buffer.from(key, 'hex')
21
+ const actual = await scryptAsync(password, Buffer.from(salt, 'hex'), expected.length)
22
+ return timingSafeEqual(actual, expected)
23
+ }
24
+
25
+ export function authStore(db: DatabaseSync) {
26
+ return {
27
+ findUser(email: string) {
28
+ return db.prepare('SELECT id, email, password_hash FROM users WHERE email = ?').get(email) as
29
+ | { id: number; email: string; password_hash: string }
30
+ | undefined
31
+ },
32
+ async createUser(email: string, password: string): Promise<number> {
33
+ const info = db
34
+ .prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)')
35
+ .run(email, await hashPassword(password))
36
+ return Number(info.lastInsertRowid)
37
+ },
38
+ startSession(userId: number): string {
39
+ const token = randomBytes(32).toString('hex')
40
+ db.prepare('INSERT INTO sessions (token, user_id) VALUES (?, ?)').run(token, userId)
41
+ return token
42
+ },
43
+ userFor(token: string | undefined) {
44
+ if (!token) return undefined
45
+ return db
46
+ .prepare(
47
+ 'SELECT users.id AS id, users.email AS email FROM sessions JOIN users ON users.id = sessions.user_id WHERE token = ?',
48
+ )
49
+ .get(token) as { id: number; email: string } | undefined
50
+ },
51
+ endSession(token: string) {
52
+ db.prepare('DELETE FROM sessions WHERE token = ?').run(token)
53
+ },
54
+ }
55
+ }
@@ -0,0 +1,21 @@
1
+ import { render, useEffect, useState } from '__PACKAGE__/jsx/dom'
2
+
3
+ /** The live character counter of the note form: a client component drawn next to the textarea, compiled on request by clientModules (see src/notes-app.ts). */
4
+ const Count = ({ area }: { area: HTMLTextAreaElement }) => {
5
+ const [length, setLength] = useState(area.value.length)
6
+ useEffect(() => {
7
+ const update = () => setLength(area.value.length)
8
+ area.addEventListener('input', update)
9
+ return () => area.removeEventListener('input', update)
10
+ }, [])
11
+ return (
12
+ <>
13
+ {length} / {area.maxLength}
14
+ </>
15
+ )
16
+ }
17
+
18
+ const area = document.getElementById('body')
19
+ const out = document.querySelector('[data-island="counter"]')
20
+ if (area instanceof HTMLTextAreaElement && out instanceof HTMLElement)
21
+ render(<Count area={area} />, out)
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2024",
4
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
5
+ "module": "NodeNext",
6
+ "moduleResolution": "NodeNext",
7
+ "strict": true,
8
+ "noEmit": true,
9
+ "allowImportingTsExtensions": true,
10
+ "jsx": "react-jsx",
11
+ "jsxImportSource": "__PACKAGE__/jsx/dom",
12
+ "types": []
13
+ },
14
+ "include": ["**/*.ts", "**/*.tsx"]
15
+ }
@@ -0,0 +1,70 @@
1
+ import { DatabaseSync } from 'node:sqlite'
2
+
3
+ export interface Note {
4
+ id: number
5
+ user_id: number
6
+ title: string
7
+ body: string
8
+ updated_at: string
9
+ }
10
+
11
+ export function openDb(path = process.env.NOTES_DB ?? 'notes.db'): DatabaseSync {
12
+ const db = new DatabaseSync(path)
13
+ db.exec(`
14
+ PRAGMA foreign_keys = ON;
15
+ CREATE TABLE IF NOT EXISTS users (
16
+ id INTEGER PRIMARY KEY,
17
+ email TEXT NOT NULL UNIQUE,
18
+ password_hash TEXT NOT NULL
19
+ );
20
+ CREATE TABLE IF NOT EXISTS sessions (
21
+ token TEXT PRIMARY KEY,
22
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
23
+ );
24
+ CREATE TABLE IF NOT EXISTS notes (
25
+ id INTEGER PRIMARY KEY,
26
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
27
+ title TEXT NOT NULL,
28
+ body TEXT NOT NULL,
29
+ updated_at TEXT NOT NULL
30
+ );
31
+ `)
32
+ return db
33
+ }
34
+
35
+ export function notesStore(db: DatabaseSync) {
36
+ return {
37
+ list(userId: number, q = ''): Note[] {
38
+ const like = `%${q.replace(/[\\%_]/g, (m) => `\\${m}`)}%`
39
+ return db
40
+ .prepare(
41
+ `SELECT * FROM notes WHERE user_id = ? AND (title LIKE ? ESCAPE '\\' OR body LIKE ? ESCAPE '\\') ORDER BY updated_at DESC, id DESC`,
42
+ )
43
+ .all(userId, like, like) as unknown as Note[]
44
+ },
45
+ get(userId: number, id: number): Note | undefined {
46
+ return db
47
+ .prepare('SELECT * FROM notes WHERE id = ? AND user_id = ?')
48
+ .get(id, userId) as unknown as Note | undefined
49
+ },
50
+ create(userId: number, title: string, body: string): Note {
51
+ const info = db
52
+ .prepare('INSERT INTO notes (user_id, title, body, updated_at) VALUES (?, ?, ?, ?)')
53
+ .run(userId, title, body, new Date().toISOString())
54
+ return this.get(userId, Number(info.lastInsertRowid))!
55
+ },
56
+ update(userId: number, id: number, title: string, body: string): Note | undefined {
57
+ db.prepare(
58
+ 'UPDATE notes SET title = ?, body = ?, updated_at = ? WHERE id = ? AND user_id = ?',
59
+ ).run(title, body, new Date().toISOString(), id, userId)
60
+ return this.get(userId, id)
61
+ },
62
+ remove(userId: number, id: number): boolean {
63
+ return (
64
+ Number(
65
+ db.prepare('DELETE FROM notes WHERE id = ? AND user_id = ?').run(id, userId).changes,
66
+ ) > 0
67
+ )
68
+ },
69
+ }
70
+ }
@@ -0,0 +1,22 @@
1
+ import { serve } from '__PACKAGE__/node-server'
2
+ import app, { db } from './app.ts'
3
+
4
+ const port = Number(process.env.PORT || 3000)
5
+ // Local by default. Behind a reverse proxy on the same machine this is right; in a container set HOST=0.0.0.0.
6
+ const hostname = process.env.HOST || '127.0.0.1'
7
+
8
+ const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
9
+ console.log(`listening on http://${info.address}:${info.port}`)
10
+ })
11
+
12
+ // Stop taking requests, let the ones in flight finish, then exit. A connection that never ends cannot keep the process alive past 10 seconds.
13
+ function shutdown(): void {
14
+ server.close(() => {
15
+ db.close()
16
+ process.exit(0)
17
+ })
18
+ server.closeIdleConnections()
19
+ setTimeout(() => process.exit(1), 10_000).unref()
20
+ }
21
+ process.once('SIGINT', shutdown)
22
+ process.once('SIGTERM', shutdown)
@@ -0,0 +1,199 @@
1
+ import type { Context } from '__PACKAGE__'
2
+ import { __CLASS__ } from '__PACKAGE__'
3
+ import { deleteCookie, getCookie, setCookie } from '__PACKAGE__/cookie'
4
+ import { csrf } from '__PACKAGE__/csrf'
5
+ import { createMiddleware } from '__PACKAGE__/factory'
6
+ import { HTTPException } from '__PACKAGE__/http-exception'
7
+ import { clientModules } from '__PACKAGE__/node-server'
8
+ import { schemaValidator } from '__PACKAGE__/schema-validator'
9
+ import type { DatabaseSync } from 'node:sqlite'
10
+ import { authStore, verifyPassword } from './auth.ts'
11
+ import { notesStore, openDb } from './db.ts'
12
+ import { checkCredentials, checkNote, NoteSchema } from './schema.ts'
13
+ import { authPage, formPage, listPage } from './views.tsx'
14
+
15
+ type Env = { Variables: { user: { id: number; email: string } } }
16
+
17
+ const COOKIE = 'sid'
18
+ const MONTH = 60 * 60 * 24 * 30
19
+
20
+ export interface AppOptions {
21
+ /** Believe `X-Forwarded-Proto` (set it when a reverse proxy you run terminates HTTPS in front of the app). Default: the TRUST_PROXY=1 environment variable. */
22
+ trustProxy?: boolean
23
+ /** The address people use in the browser, for example `https://notes.example.com`. Behind a proxy the app sees `http://127.0.0.1:3000`, so csrf needs it. Default: PUBLIC_ORIGIN. */
24
+ publicOrigin?: string
25
+ }
26
+
27
+ export function createApi(db: DatabaseSync) {
28
+ const auth = authStore(db)
29
+ const notes = notesStore(db)
30
+ return new __CLASS__<Env>()
31
+ .use(async (c, next) => {
32
+ const user = auth.userFor(getCookie(c, COOKIE))
33
+ if (!user) return c.json({ error: 'Log in first.' }, 401)
34
+ c.set('user', user)
35
+ await next()
36
+ })
37
+ .get('/', (c) => c.json({ notes: notes.list(c.get('user').id, c.req.query('q') ?? '') }, 200))
38
+ .post('/', schemaValidator('json', NoteSchema), (c) =>
39
+ c.json(
40
+ {
41
+ note: notes.create(c.get('user').id, c.req.valid('json').title, c.req.valid('json').body),
42
+ },
43
+ 201,
44
+ ),
45
+ )
46
+ .get('/:id', (c) => {
47
+ const note = notes.get(c.get('user').id, Number(c.req.param('id')))
48
+ return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
49
+ })
50
+ .put('/:id', schemaValidator('json', NoteSchema), (c) => {
51
+ const { title, body } = c.req.valid('json')
52
+ const note = notes.update(c.get('user').id, Number(c.req.param('id')), title, body)
53
+ return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
54
+ })
55
+ .delete('/:id', (c) =>
56
+ notes.remove(c.get('user').id, Number(c.req.param('id')))
57
+ ? c.json({ ok: true }, 200)
58
+ : c.json({ error: 'No such note.' }, 404),
59
+ )
60
+ }
61
+
62
+ export type Api = ReturnType<typeof createApi>
63
+
64
+ export function createApp(
65
+ db: DatabaseSync = openDb(),
66
+ {
67
+ trustProxy = process.env.TRUST_PROXY === '1',
68
+ publicOrigin = process.env.PUBLIC_ORIGIN,
69
+ }: AppOptions = {},
70
+ ) {
71
+ const auth = authStore(db)
72
+ const notes = notesStore(db)
73
+ const app = new __CLASS__<Env>()
74
+ // Refuses a form POST that does not come from this site (checks Origin and Sec-Fetch-Site); JSON requests are not form-shaped and pass.
75
+ app.use(csrf(publicOrigin ? { origin: [publicOrigin] } : undefined))
76
+ // A secure cookie is only sent over HTTPS: set when the request is HTTPS, or a proxy we trust says it was.
77
+ const session = (c: Context<Env>) => ({
78
+ path: '/',
79
+ httpOnly: true,
80
+ sameSite: 'Lax' as const,
81
+ maxAge: MONTH,
82
+ secure:
83
+ new URL(c.req.url).protocol === 'https:' ||
84
+ (trustProxy && c.req.header('x-forwarded-proto') === 'https'),
85
+ })
86
+ // The log has the stack; the page never does.
87
+ app.onError((error, c) => {
88
+ if (error instanceof HTTPException) return error.getResponse()
89
+ console.error(error)
90
+ return c.text('Internal Server Error', 500)
91
+ })
92
+
93
+ const requireUser = createMiddleware<Env>(async (c, next) => {
94
+ const user = auth.userFor(getCookie(c, COOKIE))
95
+ if (!user) return c.redirect('/login')
96
+ c.set('user', user)
97
+ await next()
98
+ })
99
+
100
+ app.get('/', (c) => c.redirect('/notes'))
101
+ app.get('/signup', (c) => c.html(authPage('signup')))
102
+ app.get('/login', (c) => c.html(authPage('login')))
103
+
104
+ app.post('/signup', async (c) => {
105
+ const form = await c.req.parseBody()
106
+ const email = String(form.email ?? '')
107
+ .trim()
108
+ .toLowerCase()
109
+ const errors = checkCredentials(email, form.password, true)
110
+ if (errors.length === 0 && auth.findUser(email))
111
+ errors.push('That email already has an account. Log in instead.')
112
+ if (errors.length > 0) return c.html(authPage('signup', errors, email), 400)
113
+ const id = await auth.createUser(email, String(form.password))
114
+ setCookie(c, COOKIE, auth.startSession(id), session(c))
115
+ return c.redirect('/notes', 303)
116
+ })
117
+
118
+ app.post('/login', async (c) => {
119
+ const form = await c.req.parseBody()
120
+ const email = String(form.email ?? '')
121
+ .trim()
122
+ .toLowerCase()
123
+ const errors = checkCredentials(email, form.password, false)
124
+ if (errors.length > 0) return c.html(authPage('login', errors, email), 400)
125
+ const user = auth.findUser(email)
126
+ if (!user || !(await verifyPassword(String(form.password), user.password_hash)))
127
+ return c.html(authPage('login', ['Wrong email or password.'], email), 401)
128
+ setCookie(c, COOKIE, auth.startSession(user.id), session(c))
129
+ return c.redirect('/notes', 303)
130
+ })
131
+
132
+ app.post('/logout', (c) => {
133
+ const token = getCookie(c, COOKIE)
134
+ if (token) auth.endSession(token)
135
+ deleteCookie(c, COOKIE, { path: '/' })
136
+ return c.redirect('/login', 303)
137
+ })
138
+
139
+ app.use('/notes/*', requireUser)
140
+ app.use('/notes', requireUser)
141
+
142
+ app.get('/notes', (c) => {
143
+ const q = (c.req.query('q') ?? '').trim()
144
+ return c.html(listPage(c.get('user').email, notes.list(c.get('user').id, q), q))
145
+ })
146
+ app.get('/notes/new', (c) =>
147
+ c.html(formPage(c.get('user').email, '/notes', { title: '', body: '' })),
148
+ )
149
+ app.post('/notes', async (c) => {
150
+ const form = await c.req.parseBody()
151
+ const checked = checkNote(form)
152
+ if ('issues' in checked)
153
+ return c.html(
154
+ formPage(
155
+ c.get('user').email,
156
+ '/notes',
157
+ { title: String(form.title ?? ''), body: String(form.body ?? '') },
158
+ checked.issues.map((i) => i.message),
159
+ ),
160
+ 400,
161
+ )
162
+ notes.create(c.get('user').id, checked.value.title, checked.value.body)
163
+ return c.redirect('/notes', 303)
164
+ })
165
+ app.get('/notes/:id/edit', (c) => {
166
+ const note = notes.get(c.get('user').id, Number(c.req.param('id')))
167
+ return note
168
+ ? c.html(formPage(c.get('user').email, `/notes/${note.id}`, note))
169
+ : c.html(listPage(c.get('user').email, [], ''), 404)
170
+ })
171
+ app.post('/notes/:id', async (c) => {
172
+ const id = Number(c.req.param('id'))
173
+ const form = await c.req.parseBody()
174
+ const checked = checkNote(form)
175
+ if ('issues' in checked)
176
+ return c.html(
177
+ formPage(
178
+ c.get('user').email,
179
+ `/notes/${id}`,
180
+ { title: String(form.title ?? ''), body: String(form.body ?? '') },
181
+ checked.issues.map((i) => i.message),
182
+ ),
183
+ 400,
184
+ )
185
+ if (!notes.update(c.get('user').id, id, checked.value.title, checked.value.body))
186
+ return c.text('No such note.', 404)
187
+ return c.redirect('/notes', 303)
188
+ })
189
+ app.post('/notes/:id/delete', (c) => {
190
+ if (!notes.remove(c.get('user').id, Number(c.req.param('id'))))
191
+ return c.text('No such note.', 404)
192
+ return c.redirect('/notes', 303)
193
+ })
194
+
195
+ app.route('/api/notes', createApi(db))
196
+ // Client components without a bundler: src/client is compiled when the browser asks; `npm run build` compiles it once for production.
197
+ app.route('/client', clientModules({ root: 'src/client', compiled: 'dist/client' }))
198
+ return app
199
+ }
@@ -0,0 +1,38 @@
1
+ import type { StandardSchema } from '__PACKAGE__/schema-validator'
2
+
3
+ export interface NoteInput {
4
+ title: string
5
+ body: string
6
+ }
7
+
8
+ export const TITLE_MAX = 80
9
+ export const BODY_MAX = 2000
10
+
11
+ /** The one place a note's rules live: the HTML forms and the JSON API both use it. */
12
+ export function checkNote(
13
+ value: unknown,
14
+ ): { value: NoteInput } | { issues: { message: string; path: string[] }[] } {
15
+ const input = (value ?? {}) as Record<string, unknown>
16
+ const title = typeof input.title === 'string' ? input.title.trim() : ''
17
+ const body = typeof input.body === 'string' ? input.body : ''
18
+ const issues: { message: string; path: string[] }[] = []
19
+ if (title === '') issues.push({ message: 'Give the note a title.', path: ['title'] })
20
+ else if (title.length > TITLE_MAX)
21
+ issues.push({ message: `The title is at most ${TITLE_MAX} characters.`, path: ['title'] })
22
+ if (body.length > BODY_MAX)
23
+ issues.push({ message: `The note is at most ${BODY_MAX} characters.`, path: ['body'] })
24
+ return issues.length > 0 ? { issues } : { value: { title, body } }
25
+ }
26
+
27
+ export const NoteSchema: StandardSchema<NoteInput> = {
28
+ '~standard': { validate: (value) => checkNote(value) },
29
+ }
30
+
31
+ export function checkCredentials(email: unknown, password: unknown, signup: boolean): string[] {
32
+ const errors: string[] = []
33
+ if (typeof email !== 'string' || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email))
34
+ errors.push('Enter a valid email address.')
35
+ if (typeof password !== 'string' || password === '') errors.push('Enter a password.')
36
+ else if (signup && password.length < 8) errors.push('The password needs at least 8 characters.')
37
+ return errors
38
+ }