create-acrylblends 0.2.7 → 0.3.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 +5 -4
- package/dist/index.d.ts +1 -3
- package/dist/index.js +22 -128
- package/dist/index.js.map +1 -1
- package/docs/framework/README.md +3 -3
- package/docs/framework/UPSTREAM.md +1 -1
- package/docs/framework/agents/index.md +18 -3
- package/docs/framework/getting-started/basic.md +1 -2
- package/docs/framework/getting-started/desktop.md +3 -3
- package/docs/framework/guides/bring-your-own-tool.md +216 -0
- package/docs/framework/guides/client-modules.md +4 -3
- package/docs/framework/guides/create-acrylblends.md +5 -4
- package/docs/framework/guides/data.md +7 -6
- package/docs/framework/helpers/streaming.md +12 -27
- package/docs/framework/upstream.json +3 -3
- package/package.json +2 -3
- package/templates/bun/gitignore +0 -1
- package/templates/bun/package.json +0 -19
- package/templates/bun/src/index.ts +0 -7
- package/templates/bun/test/app.test.ts +0 -8
- package/templates/bun/tsconfig.json +0 -15
- package/templates/chat/gitignore +0 -6
- package/templates/chat/migrations/001-chat.sql +0 -12
- package/templates/chat/package.json +0 -26
- package/templates/chat/src/app.ts +0 -8
- package/templates/chat/src/chat-app.ts +0 -100
- package/templates/chat/src/client/chat.tsx +0 -115
- package/templates/chat/src/client/tsconfig.json +0 -15
- package/templates/chat/src/db.ts +0 -53
- package/templates/chat/src/index.ts +0 -27
- package/templates/chat/src/llm.ts +0 -42
- package/templates/chat/src/page.tsx +0 -38
- package/templates/chat/test/chat.test.ts +0 -165
- package/templates/chat/test/server.test.ts +0 -59
- package/templates/chat/tsconfig.json +0 -19
- package/templates/nodejs/gitignore +0 -2
- package/templates/nodejs/package.json +0 -23
- package/templates/nodejs/src/app.ts +0 -10
- package/templates/nodejs/src/client/counter.tsx +0 -12
- package/templates/nodejs/src/client/tsconfig.json +0 -15
- package/templates/nodejs/src/index.ts +0 -21
- package/templates/nodejs/src/page.tsx +0 -26
- package/templates/nodejs/src/routes.ts +0 -10
- package/templates/nodejs/test/app.test.ts +0 -40
- package/templates/nodejs/test/server.test.ts +0 -48
- package/templates/nodejs/tsconfig.json +0 -19
- package/templates/notes/gitignore +0 -6
- package/templates/notes/migrations/001-notes.sql +0 -18
- package/templates/notes/package.json +0 -26
- package/templates/notes/src/app.ts +0 -8
- package/templates/notes/src/auth.ts +0 -57
- package/templates/notes/src/client/counter.tsx +0 -21
- package/templates/notes/src/client/tsconfig.json +0 -15
- package/templates/notes/src/db.ts +0 -60
- package/templates/notes/src/index.ts +0 -27
- package/templates/notes/src/notes-app.ts +0 -205
- package/templates/notes/src/schema.ts +0 -38
- package/templates/notes/src/views.tsx +0 -134
- package/templates/notes/test/notes.test.ts +0 -252
- package/templates/notes/test/server.test.ts +0 -59
- package/templates/notes/tsconfig.json +0 -19
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { __CLASS__ } from '__PACKAGE__'
|
|
2
|
-
import { clientModules } from '__PACKAGE__/node-server'
|
|
3
|
-
import { routes } from './routes.ts'
|
|
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).
|
|
6
|
-
const app = new __CLASS__()
|
|
7
|
-
.route('/', routes)
|
|
8
|
-
.route('/client', clientModules({ root: 'src/client', compiled: 'dist/client' }))
|
|
9
|
-
|
|
10
|
-
export default app
|
|
@@ -1,12 +0,0 @@
|
|
|
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')!)
|
|
@@ -1,15 +0,0 @@
|
|
|
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,21 +0,0 @@
|
|
|
1
|
-
import { serve } from '__PACKAGE__/node-server'
|
|
2
|
-
import app 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
|
-
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)
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
/** A page written in JSX: Node.js runs it through `acrylblends/node-server/register` (see the scripts in package.json), which compiles .tsx with this app's own typescript. */
|
|
2
|
-
const About = () => (
|
|
3
|
-
<main>
|
|
4
|
-
<h1>About</h1>
|
|
5
|
-
<p>Rendered on the server with __PACKAGE__/jsx.</p>
|
|
6
|
-
</main>
|
|
7
|
-
)
|
|
8
|
-
|
|
9
|
-
export const aboutPage = (): string => (<About />).toString()
|
|
10
|
-
|
|
11
|
-
/** Throws on purpose: the template's test checks that the stack names this file, so a failure in your own pages points at the .tsx line. */
|
|
12
|
-
export const failingPage = (): string => {
|
|
13
|
-
throw new Error('a page failed')
|
|
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()
|
|
@@ -1,10 +0,0 @@
|
|
|
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
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import assert from 'node:assert/strict'
|
|
2
|
-
import { test } from 'node:test'
|
|
3
|
-
import app from '../src/app.ts'
|
|
4
|
-
|
|
5
|
-
test('GET / answers __CLASS__!', async () => {
|
|
6
|
-
const response = await app.request('/')
|
|
7
|
-
assert.equal(response.status, 200)
|
|
8
|
-
assert.equal(await response.text(), '__CLASS__!')
|
|
9
|
-
})
|
|
10
|
-
|
|
11
|
-
test('GET /about renders the JSX page', async () => {
|
|
12
|
-
const response = await app.request('/about')
|
|
13
|
-
assert.equal(response.status, 200)
|
|
14
|
-
assert.match(response.headers.get('content-type') ?? '', /html/)
|
|
15
|
-
assert.match(
|
|
16
|
-
await response.text(),
|
|
17
|
-
/<main><h1>About<\/h1><p>Rendered on the server with __PACKAGE__\/jsx\.<\/p><\/main>/,
|
|
18
|
-
)
|
|
19
|
-
})
|
|
20
|
-
|
|
21
|
-
test('an error thrown in a .tsx file names the .tsx line in its stack', async () => {
|
|
22
|
-
const { failingPage } = await import('../src/page.tsx')
|
|
23
|
-
let stack = ''
|
|
24
|
-
try {
|
|
25
|
-
failingPage()
|
|
26
|
-
} catch (error) {
|
|
27
|
-
stack = String((error as Error).stack)
|
|
28
|
-
}
|
|
29
|
-
assert.match(stack, /page\.tsx:\d+/)
|
|
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
|
-
})
|
|
@@ -1,48 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "ES2024",
|
|
4
|
-
"lib": ["ES2024", "DOM", "DOM.Iterable"],
|
|
5
|
-
"module": "NodeNext",
|
|
6
|
-
"moduleResolution": "NodeNext",
|
|
7
|
-
"strict": true,
|
|
8
|
-
"verbatimModuleSyntax": true,
|
|
9
|
-
"erasableSyntaxOnly": true,
|
|
10
|
-
"allowImportingTsExtensions": true,
|
|
11
|
-
"noEmit": true,
|
|
12
|
-
"skipLibCheck": true,
|
|
13
|
-
"types": ["node"],
|
|
14
|
-
"jsx": "react-jsx",
|
|
15
|
-
"jsxImportSource": "__PACKAGE__/jsx"
|
|
16
|
-
},
|
|
17
|
-
"include": ["src", "test"],
|
|
18
|
-
"exclude": ["src/client"]
|
|
19
|
-
}
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
CREATE TABLE users (
|
|
2
|
-
id INTEGER PRIMARY KEY,
|
|
3
|
-
email TEXT NOT NULL UNIQUE,
|
|
4
|
-
password_hash TEXT NOT NULL
|
|
5
|
-
);
|
|
6
|
-
|
|
7
|
-
CREATE TABLE sessions (
|
|
8
|
-
token TEXT PRIMARY KEY,
|
|
9
|
-
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE
|
|
10
|
-
);
|
|
11
|
-
|
|
12
|
-
CREATE TABLE notes (
|
|
13
|
-
id INTEGER PRIMARY KEY,
|
|
14
|
-
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
15
|
-
title TEXT NOT NULL,
|
|
16
|
-
body TEXT NOT NULL,
|
|
17
|
-
updated_at TEXT NOT NULL
|
|
18
|
-
);
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "__APP_NAME__",
|
|
3
|
-
"version": "0.1.0",
|
|
4
|
-
"private": true,
|
|
5
|
-
"type": "module",
|
|
6
|
-
"acryl": {
|
|
7
|
-
"opener": "src/db.ts"
|
|
8
|
-
},
|
|
9
|
-
"engines": {
|
|
10
|
-
"node": ">=22.19.0"
|
|
11
|
-
},
|
|
12
|
-
"scripts": {
|
|
13
|
-
"dev": "node --watch --import acrylblends/node-server/register src/index.ts",
|
|
14
|
-
"start": "node --import acrylblends/node-server/register src/index.ts",
|
|
15
|
-
"test": "acrylblends check-deps && node --import acrylblends/node-server/register --test \"test/**/*.test.{ts,tsx}\"",
|
|
16
|
-
"check": "tsc --noEmit && tsc --noEmit -p src/client && acrylblends check-deps",
|
|
17
|
-
"build": "acrylblends build-client"
|
|
18
|
-
},
|
|
19
|
-
"dependencies": {
|
|
20
|
-
"__PACKAGE__": "__RANGE__",
|
|
21
|
-
"typescript": "6.0.3"
|
|
22
|
-
},
|
|
23
|
-
"devDependencies": {
|
|
24
|
-
"@types/node": "^24.0.0"
|
|
25
|
-
}
|
|
26
|
-
}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { openNotesDb } from './db.ts'
|
|
2
|
-
import { createApp } from './notes-app.ts'
|
|
3
|
-
|
|
4
|
-
/** The composition root: opens the database (once) and builds the app. `index.ts` serves it; the desktop shell does too, and calls `close` when it stops. */
|
|
5
|
-
const { db, close } = await openNotesDb()
|
|
6
|
-
|
|
7
|
-
export { close }
|
|
8
|
-
export default createApp(db)
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
import type { Db } from '__PACKAGE__/db'
|
|
2
|
-
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
|
|
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: Db) {
|
|
26
|
-
return {
|
|
27
|
-
findUser(email: string) {
|
|
28
|
-
return db.get<{ id: number; email: string; password_hash: string }>(
|
|
29
|
-
'SELECT id, email, password_hash FROM users WHERE email = ?',
|
|
30
|
-
email,
|
|
31
|
-
)
|
|
32
|
-
},
|
|
33
|
-
async createUser(email: string, password: string): Promise<number> {
|
|
34
|
-
const user = await db.get<{ id: number }>(
|
|
35
|
-
'INSERT INTO users (email, password_hash) VALUES (?, ?) RETURNING id',
|
|
36
|
-
email,
|
|
37
|
-
await hashPassword(password),
|
|
38
|
-
)
|
|
39
|
-
return user!.id
|
|
40
|
-
},
|
|
41
|
-
async startSession(userId: number): Promise<string> {
|
|
42
|
-
const token = randomBytes(32).toString('hex')
|
|
43
|
-
await db.run('INSERT INTO sessions (token, user_id) VALUES (?, ?)', token, userId)
|
|
44
|
-
return token
|
|
45
|
-
},
|
|
46
|
-
async userFor(token: string | undefined) {
|
|
47
|
-
if (!token) return undefined
|
|
48
|
-
return db.get<{ id: number; email: string }>(
|
|
49
|
-
'SELECT users.id AS id, users.email AS email FROM sessions JOIN users ON users.id = sessions.user_id WHERE token = ?',
|
|
50
|
-
token,
|
|
51
|
-
)
|
|
52
|
-
},
|
|
53
|
-
async endSession(token: string): Promise<void> {
|
|
54
|
-
await db.run('DELETE FROM sessions WHERE token = ?', token)
|
|
55
|
-
},
|
|
56
|
-
}
|
|
57
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
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)
|
|
@@ -1,15 +0,0 @@
|
|
|
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,60 +0,0 @@
|
|
|
1
|
-
import type { Db } from '__PACKAGE__/db'
|
|
2
|
-
import { openDb } from '__PACKAGE__/db/sqlite'
|
|
3
|
-
import { fileURLToPath } from 'node:url'
|
|
4
|
-
|
|
5
|
-
export interface Note {
|
|
6
|
-
id: number
|
|
7
|
-
user_id: number
|
|
8
|
-
title: string
|
|
9
|
-
body: string
|
|
10
|
-
updated_at: string
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/** The folder of numbered SQL files (001-notes.sql, ...). Applied on start, each once, in one transaction. */
|
|
14
|
-
const MIGRATIONS = fileURLToPath(new URL('../migrations', import.meta.url))
|
|
15
|
-
|
|
16
|
-
/** Open the notes database and apply the migrations. Call `close` once, when the process stops. */
|
|
17
|
-
export function openNotesDb(path = process.env.NOTES_DB ?? 'data/notes.sqlite') {
|
|
18
|
-
return openDb({ path, migrations: MIGRATIONS })
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export function notesStore(db: Db) {
|
|
22
|
-
return {
|
|
23
|
-
list(userId: number, q = ''): Promise<Note[]> {
|
|
24
|
-
const like = `%${q.replace(/[\\%_]/g, (m) => `\\${m}`)}%`
|
|
25
|
-
return db.all<Note>(
|
|
26
|
-
`SELECT * FROM notes WHERE user_id = ? AND (title LIKE ? ESCAPE '\\' OR body LIKE ? ESCAPE '\\') ORDER BY updated_at DESC, id DESC`,
|
|
27
|
-
userId,
|
|
28
|
-
like,
|
|
29
|
-
like,
|
|
30
|
-
)
|
|
31
|
-
},
|
|
32
|
-
get(userId: number, id: number): Promise<Note | undefined> {
|
|
33
|
-
return db.get<Note>('SELECT * FROM notes WHERE id = ? AND user_id = ?', id, userId)
|
|
34
|
-
},
|
|
35
|
-
async create(userId: number, title: string, body: string): Promise<Note> {
|
|
36
|
-
const note = await db.get<Note>(
|
|
37
|
-
'INSERT INTO notes (user_id, title, body, updated_at) VALUES (?, ?, ?, ?) RETURNING *',
|
|
38
|
-
userId,
|
|
39
|
-
title,
|
|
40
|
-
body,
|
|
41
|
-
new Date().toISOString(),
|
|
42
|
-
)
|
|
43
|
-
return note!
|
|
44
|
-
},
|
|
45
|
-
update(userId: number, id: number, title: string, body: string): Promise<Note | undefined> {
|
|
46
|
-
return db.get<Note>(
|
|
47
|
-
'UPDATE notes SET title = ?, body = ?, updated_at = ? WHERE id = ? AND user_id = ? RETURNING *',
|
|
48
|
-
title,
|
|
49
|
-
body,
|
|
50
|
-
new Date().toISOString(),
|
|
51
|
-
id,
|
|
52
|
-
userId,
|
|
53
|
-
)
|
|
54
|
-
},
|
|
55
|
-
async remove(userId: number, id: number): Promise<boolean> {
|
|
56
|
-
const { changes } = await db.run('DELETE FROM notes WHERE id = ? AND user_id = ?', id, userId)
|
|
57
|
-
return changes > 0
|
|
58
|
-
},
|
|
59
|
-
}
|
|
60
|
-
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { serve } from '__PACKAGE__/node-server'
|
|
2
|
-
import app, { close } 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 close the database and exit. A connection that never ends cannot keep the process alive past 10 seconds.
|
|
13
|
-
function shutdown(): void {
|
|
14
|
-
server.close(() => {
|
|
15
|
-
close().then(
|
|
16
|
-
() => process.exit(0),
|
|
17
|
-
(error) => {
|
|
18
|
-
console.error(error)
|
|
19
|
-
process.exit(1)
|
|
20
|
-
},
|
|
21
|
-
)
|
|
22
|
-
})
|
|
23
|
-
server.closeIdleConnections()
|
|
24
|
-
setTimeout(() => process.exit(1), 10_000).unref()
|
|
25
|
-
}
|
|
26
|
-
process.once('SIGINT', shutdown)
|
|
27
|
-
process.once('SIGTERM', shutdown)
|
|
@@ -1,205 +0,0 @@
|
|
|
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 type { Db } from '__PACKAGE__/db'
|
|
6
|
-
import { createMiddleware } from '__PACKAGE__/factory'
|
|
7
|
-
import { HTTPException } from '__PACKAGE__/http-exception'
|
|
8
|
-
import { clientModules } from '__PACKAGE__/node-server'
|
|
9
|
-
import { schemaValidator } from '__PACKAGE__/schema-validator'
|
|
10
|
-
import { authStore, verifyPassword } from './auth.ts'
|
|
11
|
-
import { notesStore } 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: Db) {
|
|
28
|
-
const auth = authStore(db)
|
|
29
|
-
const notes = notesStore(db)
|
|
30
|
-
return new __CLASS__<Env>()
|
|
31
|
-
.use(async (c, next) => {
|
|
32
|
-
const user = await 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('/', async (c) =>
|
|
38
|
-
c.json({ notes: await notes.list(c.get('user').id, c.req.query('q') ?? '') }, 200),
|
|
39
|
-
)
|
|
40
|
-
.post('/', schemaValidator('json', NoteSchema), async (c) =>
|
|
41
|
-
c.json(
|
|
42
|
-
{
|
|
43
|
-
note: await notes.create(
|
|
44
|
-
c.get('user').id,
|
|
45
|
-
c.req.valid('json').title,
|
|
46
|
-
c.req.valid('json').body,
|
|
47
|
-
),
|
|
48
|
-
},
|
|
49
|
-
201,
|
|
50
|
-
),
|
|
51
|
-
)
|
|
52
|
-
.get('/:id', async (c) => {
|
|
53
|
-
const note = await notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
54
|
-
return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
|
|
55
|
-
})
|
|
56
|
-
.put('/:id', schemaValidator('json', NoteSchema), async (c) => {
|
|
57
|
-
const { title, body } = c.req.valid('json')
|
|
58
|
-
const note = await notes.update(c.get('user').id, Number(c.req.param('id')), title, body)
|
|
59
|
-
return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
|
|
60
|
-
})
|
|
61
|
-
.delete('/:id', async (c) =>
|
|
62
|
-
(await notes.remove(c.get('user').id, Number(c.req.param('id'))))
|
|
63
|
-
? c.json({ ok: true }, 200)
|
|
64
|
-
: c.json({ error: 'No such note.' }, 404),
|
|
65
|
-
)
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export type Api = ReturnType<typeof createApi>
|
|
69
|
-
|
|
70
|
-
export function createApp(
|
|
71
|
-
db: Db,
|
|
72
|
-
{
|
|
73
|
-
trustProxy = process.env.TRUST_PROXY === '1',
|
|
74
|
-
publicOrigin = process.env.PUBLIC_ORIGIN,
|
|
75
|
-
}: AppOptions = {},
|
|
76
|
-
) {
|
|
77
|
-
const auth = authStore(db)
|
|
78
|
-
const notes = notesStore(db)
|
|
79
|
-
const app = new __CLASS__<Env>()
|
|
80
|
-
// 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.
|
|
81
|
-
app.use(csrf(publicOrigin ? { origin: [publicOrigin] } : undefined))
|
|
82
|
-
// A secure cookie is only sent over HTTPS: set when the request is HTTPS, or a proxy we trust says it was.
|
|
83
|
-
const session = (c: Context<Env>) => ({
|
|
84
|
-
path: '/',
|
|
85
|
-
httpOnly: true,
|
|
86
|
-
sameSite: 'Lax' as const,
|
|
87
|
-
maxAge: MONTH,
|
|
88
|
-
secure:
|
|
89
|
-
new URL(c.req.url).protocol === 'https:' ||
|
|
90
|
-
(trustProxy && c.req.header('x-forwarded-proto') === 'https'),
|
|
91
|
-
})
|
|
92
|
-
// The log has the stack; the page never does.
|
|
93
|
-
app.onError((error, c) => {
|
|
94
|
-
if (error instanceof HTTPException) return error.getResponse()
|
|
95
|
-
console.error(error)
|
|
96
|
-
return c.text('Internal Server Error', 500)
|
|
97
|
-
})
|
|
98
|
-
|
|
99
|
-
const requireUser = createMiddleware<Env>(async (c, next) => {
|
|
100
|
-
const user = await auth.userFor(getCookie(c, COOKIE))
|
|
101
|
-
if (!user) return c.redirect('/login')
|
|
102
|
-
c.set('user', user)
|
|
103
|
-
await next()
|
|
104
|
-
})
|
|
105
|
-
|
|
106
|
-
app.get('/', (c) => c.redirect('/notes'))
|
|
107
|
-
app.get('/signup', (c) => c.html(authPage('signup')))
|
|
108
|
-
app.get('/login', (c) => c.html(authPage('login')))
|
|
109
|
-
|
|
110
|
-
app.post('/signup', async (c) => {
|
|
111
|
-
const form = await c.req.parseBody()
|
|
112
|
-
const email = String(form.email ?? '')
|
|
113
|
-
.trim()
|
|
114
|
-
.toLowerCase()
|
|
115
|
-
const errors = checkCredentials(email, form.password, true)
|
|
116
|
-
if (errors.length === 0 && (await auth.findUser(email)))
|
|
117
|
-
errors.push('That email already has an account. Log in instead.')
|
|
118
|
-
if (errors.length > 0) return c.html(authPage('signup', errors, email), 400)
|
|
119
|
-
const id = await auth.createUser(email, String(form.password))
|
|
120
|
-
setCookie(c, COOKIE, await auth.startSession(id), session(c))
|
|
121
|
-
return c.redirect('/notes', 303)
|
|
122
|
-
})
|
|
123
|
-
|
|
124
|
-
app.post('/login', async (c) => {
|
|
125
|
-
const form = await c.req.parseBody()
|
|
126
|
-
const email = String(form.email ?? '')
|
|
127
|
-
.trim()
|
|
128
|
-
.toLowerCase()
|
|
129
|
-
const errors = checkCredentials(email, form.password, false)
|
|
130
|
-
if (errors.length > 0) return c.html(authPage('login', errors, email), 400)
|
|
131
|
-
const user = await auth.findUser(email)
|
|
132
|
-
if (!user || !(await verifyPassword(String(form.password), user.password_hash)))
|
|
133
|
-
return c.html(authPage('login', ['Wrong email or password.'], email), 401)
|
|
134
|
-
setCookie(c, COOKIE, await auth.startSession(user.id), session(c))
|
|
135
|
-
return c.redirect('/notes', 303)
|
|
136
|
-
})
|
|
137
|
-
|
|
138
|
-
app.post('/logout', async (c) => {
|
|
139
|
-
const token = getCookie(c, COOKIE)
|
|
140
|
-
if (token) await auth.endSession(token)
|
|
141
|
-
deleteCookie(c, COOKIE, { path: '/' })
|
|
142
|
-
return c.redirect('/login', 303)
|
|
143
|
-
})
|
|
144
|
-
|
|
145
|
-
app.use('/notes/*', requireUser)
|
|
146
|
-
app.use('/notes', requireUser)
|
|
147
|
-
|
|
148
|
-
app.get('/notes', async (c) => {
|
|
149
|
-
const q = (c.req.query('q') ?? '').trim()
|
|
150
|
-
return c.html(listPage(c.get('user').email, await notes.list(c.get('user').id, q), q))
|
|
151
|
-
})
|
|
152
|
-
app.get('/notes/new', (c) =>
|
|
153
|
-
c.html(formPage(c.get('user').email, '/notes', { title: '', body: '' })),
|
|
154
|
-
)
|
|
155
|
-
app.post('/notes', async (c) => {
|
|
156
|
-
const form = await c.req.parseBody()
|
|
157
|
-
const checked = checkNote(form)
|
|
158
|
-
if ('issues' in checked)
|
|
159
|
-
return c.html(
|
|
160
|
-
formPage(
|
|
161
|
-
c.get('user').email,
|
|
162
|
-
'/notes',
|
|
163
|
-
{ title: String(form.title ?? ''), body: String(form.body ?? '') },
|
|
164
|
-
checked.issues.map((i) => i.message),
|
|
165
|
-
),
|
|
166
|
-
400,
|
|
167
|
-
)
|
|
168
|
-
await notes.create(c.get('user').id, checked.value.title, checked.value.body)
|
|
169
|
-
return c.redirect('/notes', 303)
|
|
170
|
-
})
|
|
171
|
-
app.get('/notes/:id/edit', async (c) => {
|
|
172
|
-
const note = await notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
173
|
-
return note
|
|
174
|
-
? c.html(formPage(c.get('user').email, `/notes/${note.id}`, note))
|
|
175
|
-
: c.html(listPage(c.get('user').email, [], ''), 404)
|
|
176
|
-
})
|
|
177
|
-
app.post('/notes/:id', async (c) => {
|
|
178
|
-
const id = Number(c.req.param('id'))
|
|
179
|
-
const form = await c.req.parseBody()
|
|
180
|
-
const checked = checkNote(form)
|
|
181
|
-
if ('issues' in checked)
|
|
182
|
-
return c.html(
|
|
183
|
-
formPage(
|
|
184
|
-
c.get('user').email,
|
|
185
|
-
`/notes/${id}`,
|
|
186
|
-
{ title: String(form.title ?? ''), body: String(form.body ?? '') },
|
|
187
|
-
checked.issues.map((i) => i.message),
|
|
188
|
-
),
|
|
189
|
-
400,
|
|
190
|
-
)
|
|
191
|
-
if (!(await notes.update(c.get('user').id, id, checked.value.title, checked.value.body)))
|
|
192
|
-
return c.text('No such note.', 404)
|
|
193
|
-
return c.redirect('/notes', 303)
|
|
194
|
-
})
|
|
195
|
-
app.post('/notes/:id/delete', async (c) => {
|
|
196
|
-
if (!(await notes.remove(c.get('user').id, Number(c.req.param('id')))))
|
|
197
|
-
return c.text('No such note.', 404)
|
|
198
|
-
return c.redirect('/notes', 303)
|
|
199
|
-
})
|
|
200
|
-
|
|
201
|
-
app.route('/api/notes', createApi(db))
|
|
202
|
-
// Client components without a bundler: src/client is compiled when the browser asks; `npm run build` compiles it once for production.
|
|
203
|
-
app.route('/client', clientModules({ root: 'src/client', compiled: 'dist/client' }))
|
|
204
|
-
return app
|
|
205
|
-
}
|