create-acrylblends 0.2.4 → 0.2.6
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/dist/index.js +10 -7
- package/dist/index.js.map +1 -1
- package/docs/framework/README.md +2 -1
- package/docs/framework/UPSTREAM.md +1 -1
- package/docs/framework/getting-started/deploy.md +5 -5
- package/docs/framework/getting-started/service-worker.md +5 -3
- package/docs/framework/guides/create-acrylblends.md +2 -2
- package/docs/framework/guides/data.md +237 -0
- package/docs/framework/guides/forms-and-sessions.md +34 -30
- package/docs/framework/upstream.json +3 -3
- package/package.json +2 -2
- package/templates/chat/gitignore +3 -2
- package/templates/chat/migrations/001-chat.sql +12 -0
- package/templates/chat/package.json +5 -2
- package/templates/chat/src/app.ts +4 -2
- package/templates/chat/src/chat-app.ts +22 -18
- package/templates/chat/src/db.ts +30 -36
- package/templates/chat/src/index.ts +9 -4
- package/templates/chat/test/chat.test.ts +21 -9
- package/templates/chat/test/server.test.ts +1 -1
- package/templates/nodejs/package.json +2 -2
- package/templates/notes/gitignore +3 -2
- package/templates/notes/migrations/001-notes.sql +18 -0
- package/templates/notes/package.json +5 -2
- package/templates/notes/src/app.ts +4 -3
- package/templates/notes/src/auth.ts +21 -19
- package/templates/notes/src/db.ts +40 -50
- package/templates/notes/src/index.ts +9 -4
- package/templates/notes/src/notes-app.ts +35 -29
- package/templates/notes/test/notes.test.ts +27 -20
- package/templates/notes/test/server.test.ts +1 -1
|
@@ -1,9 +1,19 @@
|
|
|
1
|
+
import type { Db } from '__PACKAGE__/db'
|
|
1
2
|
import assert from 'node:assert/strict'
|
|
2
|
-
import { test } from 'node:test'
|
|
3
|
+
import { after, test } from 'node:test'
|
|
3
4
|
import { createApp } from '../src/chat-app.ts'
|
|
4
|
-
import {
|
|
5
|
+
import { openChatDb } from '../src/db.ts'
|
|
5
6
|
import type { Llm } from '../src/llm.ts'
|
|
6
7
|
|
|
8
|
+
/** A fresh database in memory with the real migrations; every one is closed when the tests end. */
|
|
9
|
+
const closers: (() => Promise<void>)[] = []
|
|
10
|
+
after(() => Promise.all(closers.map((close) => close())))
|
|
11
|
+
async function memoryDb(): Promise<Db> {
|
|
12
|
+
const { db, close } = await openChatDb(':memory:')
|
|
13
|
+
closers.push(close)
|
|
14
|
+
return db
|
|
15
|
+
}
|
|
16
|
+
|
|
7
17
|
/** A model that answers with fixed pieces and records what it was asked. */
|
|
8
18
|
function mock(pieces: string[]) {
|
|
9
19
|
const asked: { role: string; content: string }[][] = []
|
|
@@ -34,7 +44,7 @@ function events(text: string): [string, string][] {
|
|
|
34
44
|
|
|
35
45
|
test('the answer streams as events: meta, one token per piece, done', async () => {
|
|
36
46
|
const { llm } = mock(['Hel', 'lo ', 'there\nline'])
|
|
37
|
-
const app = createApp(
|
|
47
|
+
const app = createApp(await memoryDb(), llm)
|
|
38
48
|
const res = await app.request('/api/chat', post({ message: 'hi' }))
|
|
39
49
|
assert.equal(res.status, 200)
|
|
40
50
|
assert.match(res.headers.get('content-type') ?? '', /text\/event-stream/)
|
|
@@ -54,7 +64,7 @@ test('the answer streams as events: meta, one token per piece, done', async () =
|
|
|
54
64
|
|
|
55
65
|
test('history is stored, sent back to the model, and listed', async () => {
|
|
56
66
|
const { llm, asked } = mock(['ok'])
|
|
57
|
-
const app = createApp(
|
|
67
|
+
const app = createApp(await memoryDb(), llm)
|
|
58
68
|
const first = events(
|
|
59
69
|
await (await app.request('/api/chat', post({ message: 'first question' }))).text(),
|
|
60
70
|
)
|
|
@@ -82,7 +92,7 @@ test('history is stored, sent back to the model, and listed', async () => {
|
|
|
82
92
|
|
|
83
93
|
test('a bad message answers 400 with a message, an unknown conversation 404, and nothing reaches the model', async () => {
|
|
84
94
|
const { llm, asked } = mock(['x'])
|
|
85
|
-
const app = createApp(
|
|
95
|
+
const app = createApp(await memoryDb(), llm)
|
|
86
96
|
const empty = await app.request('/api/chat', post({ message: ' ' }))
|
|
87
97
|
assert.equal(empty.status, 400)
|
|
88
98
|
assert.match(JSON.stringify(await empty.json()), /Write a message/)
|
|
@@ -94,7 +104,7 @@ test('a bad message answers 400 with a message, an unknown conversation 404, and
|
|
|
94
104
|
})
|
|
95
105
|
|
|
96
106
|
test('a conversation can be deleted', async () => {
|
|
97
|
-
const app = createApp(
|
|
107
|
+
const app = createApp(await memoryDb(), mock(['a']).llm)
|
|
98
108
|
const first = events(await (await app.request('/api/chat', post({ message: 'hi' }))).text())
|
|
99
109
|
const id = (JSON.parse(first[0]![1]) as { conversation: number }).conversation
|
|
100
110
|
assert.equal((await app.request(`/api/conversations/${id}`, { method: 'DELETE' })).status, 200)
|
|
@@ -107,7 +117,7 @@ test('a failing model sends an error event with a plain message and no detail',
|
|
|
107
117
|
yield 'partial '
|
|
108
118
|
throw new Error('upstream secret detail')
|
|
109
119
|
}
|
|
110
|
-
const app = createApp(
|
|
120
|
+
const app = createApp(await memoryDb(), llm)
|
|
111
121
|
const text = await (await app.request('/api/chat', post({ message: 'hi' }))).text()
|
|
112
122
|
assert.doesNotMatch(text, /secret detail/)
|
|
113
123
|
const last = events(text).at(-1)
|
|
@@ -131,7 +141,7 @@ test('when the client goes away the model call is aborted and what arrived is ke
|
|
|
131
141
|
if (signal.aborted) throw new DOMException('aborted', 'AbortError')
|
|
132
142
|
yield 'never sent'
|
|
133
143
|
}
|
|
134
|
-
const db =
|
|
144
|
+
const db = await memoryDb()
|
|
135
145
|
const app = createApp(db, llm)
|
|
136
146
|
const controller = new AbortController()
|
|
137
147
|
const res = await app.request('/api/chat', {
|
|
@@ -145,7 +155,9 @@ test('when the client goes away the model call is aborted and what arrived is ke
|
|
|
145
155
|
controller.abort()
|
|
146
156
|
assert.equal(await aborted, true)
|
|
147
157
|
await new Promise((resolve) => setTimeout(resolve, 50))
|
|
148
|
-
const rows = db.
|
|
158
|
+
const rows = await db.all<{ role: string; content: string }>(
|
|
159
|
+
'SELECT role, content FROM messages ORDER BY id',
|
|
160
|
+
)
|
|
149
161
|
assert.deepEqual(
|
|
150
162
|
rows.map((r) => `${r.role}:${r.content}`),
|
|
151
163
|
['user:hi', 'assistant:first '],
|
|
@@ -15,7 +15,7 @@ async function start(env: Record<string, string> = {}) {
|
|
|
15
15
|
env: {
|
|
16
16
|
...process.env,
|
|
17
17
|
PORT: '0',
|
|
18
|
-
CHAT_DB: join(mkdtempSync(join(tmpdir(), 'chat-')), 'chat.
|
|
18
|
+
CHAT_DB: join(mkdtempSync(join(tmpdir(), 'chat-')), 'chat.sqlite'),
|
|
19
19
|
...env,
|
|
20
20
|
},
|
|
21
21
|
stdio: ['ignore', 'pipe', 'inherit'],
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
"scripts": {
|
|
10
10
|
"dev": "node --watch --import acrylblends/node-server/register src/index.ts",
|
|
11
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",
|
|
12
|
+
"test": "acrylblends check-deps && node --import acrylblends/node-server/register --test \"test/**/*.test.{ts,tsx}\"",
|
|
13
|
+
"check": "tsc --noEmit && tsc --noEmit -p src/client && acrylblends check-deps",
|
|
14
14
|
"build": "acrylblends build-client"
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
@@ -0,0 +1,18 @@
|
|
|
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
|
+
);
|
|
@@ -3,14 +3,17 @@
|
|
|
3
3
|
"version": "0.1.0",
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
|
+
"acryl": {
|
|
7
|
+
"opener": "src/db.ts"
|
|
8
|
+
},
|
|
6
9
|
"engines": {
|
|
7
10
|
"node": ">=22.19.0"
|
|
8
11
|
},
|
|
9
12
|
"scripts": {
|
|
10
13
|
"dev": "node --watch --import acrylblends/node-server/register src/index.ts",
|
|
11
14
|
"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",
|
|
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",
|
|
14
17
|
"build": "acrylblends build-client"
|
|
15
18
|
},
|
|
16
19
|
"dependencies": {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { openNotesDb } from './db.ts'
|
|
2
2
|
import { createApp } from './notes-app.ts'
|
|
3
3
|
|
|
4
|
-
/** The
|
|
5
|
-
|
|
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
6
|
|
|
7
|
+
export { close }
|
|
7
8
|
export default createApp(db)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import type { Db } from '__PACKAGE__/db'
|
|
1
2
|
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
|
|
2
|
-
import type { DatabaseSync } from 'node:sqlite'
|
|
3
3
|
import { promisify } from 'node:util'
|
|
4
4
|
|
|
5
5
|
const scryptAsync = promisify(scrypt) as (
|
|
@@ -22,34 +22,36 @@ export async function verifyPassword(password: string, stored: string): Promise<
|
|
|
22
22
|
return timingSafeEqual(actual, expected)
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
export function authStore(db:
|
|
25
|
+
export function authStore(db: Db) {
|
|
26
26
|
return {
|
|
27
27
|
findUser(email: string) {
|
|
28
|
-
return db.
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
return db.get<{ id: number; email: string; password_hash: string }>(
|
|
29
|
+
'SELECT id, email, password_hash FROM users WHERE email = ?',
|
|
30
|
+
email,
|
|
31
|
+
)
|
|
31
32
|
},
|
|
32
33
|
async createUser(email: string, password: string): Promise<number> {
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
|
37
40
|
},
|
|
38
|
-
startSession(userId: number): string {
|
|
41
|
+
async startSession(userId: number): Promise<string> {
|
|
39
42
|
const token = randomBytes(32).toString('hex')
|
|
40
|
-
db.
|
|
43
|
+
await db.run('INSERT INTO sessions (token, user_id) VALUES (?, ?)', token, userId)
|
|
41
44
|
return token
|
|
42
45
|
},
|
|
43
|
-
userFor(token: string | undefined) {
|
|
46
|
+
async userFor(token: string | undefined) {
|
|
44
47
|
if (!token) return undefined
|
|
45
|
-
return db
|
|
46
|
-
.
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
.get(token) as { id: number; email: string } | 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
|
+
)
|
|
50
52
|
},
|
|
51
|
-
endSession(token: string) {
|
|
52
|
-
db.
|
|
53
|
+
async endSession(token: string): Promise<void> {
|
|
54
|
+
await db.run('DELETE FROM sessions WHERE token = ?', token)
|
|
53
55
|
},
|
|
54
56
|
}
|
|
55
57
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Db } from '__PACKAGE__/db'
|
|
2
|
+
import { openDb } from '__PACKAGE__/db/sqlite'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
2
4
|
|
|
3
5
|
export interface Note {
|
|
4
6
|
id: number
|
|
@@ -8,63 +10,51 @@ export interface Note {
|
|
|
8
10
|
updated_at: string
|
|
9
11
|
}
|
|
10
12
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
|
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 })
|
|
33
19
|
}
|
|
34
20
|
|
|
35
|
-
export function notesStore(db:
|
|
21
|
+
export function notesStore(db: Db) {
|
|
36
22
|
return {
|
|
37
|
-
list(userId: number, q = ''): Note[] {
|
|
23
|
+
list(userId: number, q = ''): Promise<Note[]> {
|
|
38
24
|
const like = `%${q.replace(/[\\%_]/g, (m) => `\\${m}`)}%`
|
|
39
|
-
return db
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
|
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
|
+
)
|
|
49
31
|
},
|
|
50
|
-
|
|
51
|
-
|
|
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))!
|
|
32
|
+
get(userId: number, id: number): Promise<Note | undefined> {
|
|
33
|
+
return db.get<Note>('SELECT * FROM notes WHERE id = ? AND user_id = ?', id, userId)
|
|
55
34
|
},
|
|
56
|
-
|
|
57
|
-
db.
|
|
58
|
-
'
|
|
59
|
-
|
|
60
|
-
|
|
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!
|
|
61
44
|
},
|
|
62
|
-
|
|
63
|
-
return (
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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,
|
|
67
53
|
)
|
|
68
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
|
+
},
|
|
69
59
|
}
|
|
70
60
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { serve } from '__PACKAGE__/node-server'
|
|
2
|
-
import app, {
|
|
2
|
+
import app, { close } from './app.ts'
|
|
3
3
|
|
|
4
4
|
const port = Number(process.env.PORT || 3000)
|
|
5
5
|
// Local by default. Behind a reverse proxy on the same machine this is right; in a container set HOST=0.0.0.0.
|
|
@@ -9,11 +9,16 @@ const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
|
|
|
9
9
|
console.log(`listening on http://${info.address}:${info.port}`)
|
|
10
10
|
})
|
|
11
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.
|
|
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
13
|
function shutdown(): void {
|
|
14
14
|
server.close(() => {
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
close().then(
|
|
16
|
+
() => process.exit(0),
|
|
17
|
+
(error) => {
|
|
18
|
+
console.error(error)
|
|
19
|
+
process.exit(1)
|
|
20
|
+
},
|
|
21
|
+
)
|
|
17
22
|
})
|
|
18
23
|
server.closeIdleConnections()
|
|
19
24
|
setTimeout(() => process.exit(1), 10_000).unref()
|
|
@@ -2,13 +2,13 @@ import type { Context } from '__PACKAGE__'
|
|
|
2
2
|
import { __CLASS__ } from '__PACKAGE__'
|
|
3
3
|
import { deleteCookie, getCookie, setCookie } from '__PACKAGE__/cookie'
|
|
4
4
|
import { csrf } from '__PACKAGE__/csrf'
|
|
5
|
+
import type { Db } from '__PACKAGE__/db'
|
|
5
6
|
import { createMiddleware } from '__PACKAGE__/factory'
|
|
6
7
|
import { HTTPException } from '__PACKAGE__/http-exception'
|
|
7
8
|
import { clientModules } from '__PACKAGE__/node-server'
|
|
8
9
|
import { schemaValidator } from '__PACKAGE__/schema-validator'
|
|
9
|
-
import type { DatabaseSync } from 'node:sqlite'
|
|
10
10
|
import { authStore, verifyPassword } from './auth.ts'
|
|
11
|
-
import { notesStore
|
|
11
|
+
import { notesStore } from './db.ts'
|
|
12
12
|
import { checkCredentials, checkNote, NoteSchema } from './schema.ts'
|
|
13
13
|
import { authPage, formPage, listPage } from './views.tsx'
|
|
14
14
|
|
|
@@ -24,36 +24,42 @@ export interface AppOptions {
|
|
|
24
24
|
publicOrigin?: string
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
export function createApi(db:
|
|
27
|
+
export function createApi(db: Db) {
|
|
28
28
|
const auth = authStore(db)
|
|
29
29
|
const notes = notesStore(db)
|
|
30
30
|
return new __CLASS__<Env>()
|
|
31
31
|
.use(async (c, next) => {
|
|
32
|
-
const user = auth.userFor(getCookie(c, COOKIE))
|
|
32
|
+
const user = await auth.userFor(getCookie(c, COOKIE))
|
|
33
33
|
if (!user) return c.json({ error: 'Log in first.' }, 401)
|
|
34
34
|
c.set('user', user)
|
|
35
35
|
await next()
|
|
36
36
|
})
|
|
37
|
-
.get('/', (c) =>
|
|
38
|
-
|
|
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) =>
|
|
39
41
|
c.json(
|
|
40
42
|
{
|
|
41
|
-
note: notes.create(
|
|
43
|
+
note: await notes.create(
|
|
44
|
+
c.get('user').id,
|
|
45
|
+
c.req.valid('json').title,
|
|
46
|
+
c.req.valid('json').body,
|
|
47
|
+
),
|
|
42
48
|
},
|
|
43
49
|
201,
|
|
44
50
|
),
|
|
45
51
|
)
|
|
46
|
-
.get('/:id', (c) => {
|
|
47
|
-
const note = notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
52
|
+
.get('/:id', async (c) => {
|
|
53
|
+
const note = await notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
48
54
|
return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
|
|
49
55
|
})
|
|
50
|
-
.put('/:id', schemaValidator('json', NoteSchema), (c) => {
|
|
56
|
+
.put('/:id', schemaValidator('json', NoteSchema), async (c) => {
|
|
51
57
|
const { title, body } = c.req.valid('json')
|
|
52
|
-
const note = notes.update(c.get('user').id, Number(c.req.param('id')), title, body)
|
|
58
|
+
const note = await notes.update(c.get('user').id, Number(c.req.param('id')), title, body)
|
|
53
59
|
return note ? c.json({ note }, 200) : c.json({ error: 'No such note.' }, 404)
|
|
54
60
|
})
|
|
55
|
-
.delete('/:id', (c) =>
|
|
56
|
-
notes.remove(c.get('user').id, Number(c.req.param('id')))
|
|
61
|
+
.delete('/:id', async (c) =>
|
|
62
|
+
(await notes.remove(c.get('user').id, Number(c.req.param('id'))))
|
|
57
63
|
? c.json({ ok: true }, 200)
|
|
58
64
|
: c.json({ error: 'No such note.' }, 404),
|
|
59
65
|
)
|
|
@@ -62,7 +68,7 @@ export function createApi(db: DatabaseSync) {
|
|
|
62
68
|
export type Api = ReturnType<typeof createApi>
|
|
63
69
|
|
|
64
70
|
export function createApp(
|
|
65
|
-
db:
|
|
71
|
+
db: Db,
|
|
66
72
|
{
|
|
67
73
|
trustProxy = process.env.TRUST_PROXY === '1',
|
|
68
74
|
publicOrigin = process.env.PUBLIC_ORIGIN,
|
|
@@ -91,7 +97,7 @@ export function createApp(
|
|
|
91
97
|
})
|
|
92
98
|
|
|
93
99
|
const requireUser = createMiddleware<Env>(async (c, next) => {
|
|
94
|
-
const user = auth.userFor(getCookie(c, COOKIE))
|
|
100
|
+
const user = await auth.userFor(getCookie(c, COOKIE))
|
|
95
101
|
if (!user) return c.redirect('/login')
|
|
96
102
|
c.set('user', user)
|
|
97
103
|
await next()
|
|
@@ -107,11 +113,11 @@ export function createApp(
|
|
|
107
113
|
.trim()
|
|
108
114
|
.toLowerCase()
|
|
109
115
|
const errors = checkCredentials(email, form.password, true)
|
|
110
|
-
if (errors.length === 0 && auth.findUser(email))
|
|
116
|
+
if (errors.length === 0 && (await auth.findUser(email)))
|
|
111
117
|
errors.push('That email already has an account. Log in instead.')
|
|
112
118
|
if (errors.length > 0) return c.html(authPage('signup', errors, email), 400)
|
|
113
119
|
const id = await auth.createUser(email, String(form.password))
|
|
114
|
-
setCookie(c, COOKIE, auth.startSession(id), session(c))
|
|
120
|
+
setCookie(c, COOKIE, await auth.startSession(id), session(c))
|
|
115
121
|
return c.redirect('/notes', 303)
|
|
116
122
|
})
|
|
117
123
|
|
|
@@ -122,16 +128,16 @@ export function createApp(
|
|
|
122
128
|
.toLowerCase()
|
|
123
129
|
const errors = checkCredentials(email, form.password, false)
|
|
124
130
|
if (errors.length > 0) return c.html(authPage('login', errors, email), 400)
|
|
125
|
-
const user = auth.findUser(email)
|
|
131
|
+
const user = await auth.findUser(email)
|
|
126
132
|
if (!user || !(await verifyPassword(String(form.password), user.password_hash)))
|
|
127
133
|
return c.html(authPage('login', ['Wrong email or password.'], email), 401)
|
|
128
|
-
setCookie(c, COOKIE, auth.startSession(user.id), session(c))
|
|
134
|
+
setCookie(c, COOKIE, await auth.startSession(user.id), session(c))
|
|
129
135
|
return c.redirect('/notes', 303)
|
|
130
136
|
})
|
|
131
137
|
|
|
132
|
-
app.post('/logout', (c) => {
|
|
138
|
+
app.post('/logout', async (c) => {
|
|
133
139
|
const token = getCookie(c, COOKIE)
|
|
134
|
-
if (token) auth.endSession(token)
|
|
140
|
+
if (token) await auth.endSession(token)
|
|
135
141
|
deleteCookie(c, COOKIE, { path: '/' })
|
|
136
142
|
return c.redirect('/login', 303)
|
|
137
143
|
})
|
|
@@ -139,9 +145,9 @@ export function createApp(
|
|
|
139
145
|
app.use('/notes/*', requireUser)
|
|
140
146
|
app.use('/notes', requireUser)
|
|
141
147
|
|
|
142
|
-
app.get('/notes', (c) => {
|
|
148
|
+
app.get('/notes', async (c) => {
|
|
143
149
|
const q = (c.req.query('q') ?? '').trim()
|
|
144
|
-
return c.html(listPage(c.get('user').email, notes.list(c.get('user').id, q), q))
|
|
150
|
+
return c.html(listPage(c.get('user').email, await notes.list(c.get('user').id, q), q))
|
|
145
151
|
})
|
|
146
152
|
app.get('/notes/new', (c) =>
|
|
147
153
|
c.html(formPage(c.get('user').email, '/notes', { title: '', body: '' })),
|
|
@@ -159,11 +165,11 @@ export function createApp(
|
|
|
159
165
|
),
|
|
160
166
|
400,
|
|
161
167
|
)
|
|
162
|
-
notes.create(c.get('user').id, checked.value.title, checked.value.body)
|
|
168
|
+
await notes.create(c.get('user').id, checked.value.title, checked.value.body)
|
|
163
169
|
return c.redirect('/notes', 303)
|
|
164
170
|
})
|
|
165
|
-
app.get('/notes/:id/edit', (c) => {
|
|
166
|
-
const note = notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
171
|
+
app.get('/notes/:id/edit', async (c) => {
|
|
172
|
+
const note = await notes.get(c.get('user').id, Number(c.req.param('id')))
|
|
167
173
|
return note
|
|
168
174
|
? c.html(formPage(c.get('user').email, `/notes/${note.id}`, note))
|
|
169
175
|
: c.html(listPage(c.get('user').email, [], ''), 404)
|
|
@@ -182,12 +188,12 @@ export function createApp(
|
|
|
182
188
|
),
|
|
183
189
|
400,
|
|
184
190
|
)
|
|
185
|
-
if (!notes.update(c.get('user').id, id, checked.value.title, checked.value.body))
|
|
191
|
+
if (!(await notes.update(c.get('user').id, id, checked.value.title, checked.value.body)))
|
|
186
192
|
return c.text('No such note.', 404)
|
|
187
193
|
return c.redirect('/notes', 303)
|
|
188
194
|
})
|
|
189
|
-
app.post('/notes/:id/delete', (c) => {
|
|
190
|
-
if (!notes.remove(c.get('user').id, Number(c.req.param('id'))))
|
|
195
|
+
app.post('/notes/:id/delete', async (c) => {
|
|
196
|
+
if (!(await notes.remove(c.get('user').id, Number(c.req.param('id')))))
|
|
191
197
|
return c.text('No such note.', 404)
|
|
192
198
|
return c.redirect('/notes', 303)
|
|
193
199
|
})
|