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
@@ -0,0 +1,134 @@
1
+ import type { Note } from './db.ts'
2
+ import { BODY_MAX, TITLE_MAX } from './schema.ts'
3
+
4
+ const counterScript = `
5
+ const filter = document.getElementById('filter')
6
+ if (filter) filter.addEventListener('input', () => {
7
+ const q = filter.value.toLowerCase()
8
+ for (const li of document.querySelectorAll('[data-note]'))
9
+ li.hidden = !li.textContent.toLowerCase().includes(q)
10
+ })
11
+ `
12
+
13
+ const Layout = ({
14
+ title,
15
+ user,
16
+ children,
17
+ }: {
18
+ title: string
19
+ user?: string
20
+ children?: unknown
21
+ }) => (
22
+ <html lang="en">
23
+ <head>
24
+ <meta charset="utf-8" />
25
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
26
+ <title>{title}</title>
27
+ <style
28
+ dangerouslySetInnerHTML={{
29
+ __html:
30
+ 'body{font:16px system-ui;max-width:42rem;margin:2rem auto;padding:0 1rem}label{display:block;margin:.75rem 0 .25rem}input,textarea{width:100%;box-sizing:border-box;padding:.5rem}.error{color:#b00020}nav{display:flex;gap:1rem;align-items:center}nav form{margin-left:auto}li{margin:.5rem 0}',
31
+ }}
32
+ />
33
+ </head>
34
+ <body>
35
+ <nav>
36
+ <strong>Notes</strong>
37
+ {user ? (
38
+ <>
39
+ <a href="/notes">All notes</a>
40
+ <a href="/notes/new">New note</a>
41
+ <form method="post" action="/logout">
42
+ <span>{user} </span>
43
+ <button type="submit">Log out</button>
44
+ </form>
45
+ </>
46
+ ) : (
47
+ <>
48
+ <a href="/login">Log in</a>
49
+ <a href="/signup">Sign up</a>
50
+ </>
51
+ )}
52
+ </nav>
53
+ {children}
54
+ <script dangerouslySetInnerHTML={{ __html: counterScript }} />
55
+ <script type="module" src="/client/counter.tsx" />
56
+ </body>
57
+ </html>
58
+ )
59
+
60
+ const Errors = ({ errors }: { errors: string[] }) =>
61
+ errors.length > 0 ? (
62
+ <ul class="error" role="alert">
63
+ {errors.map((e) => (
64
+ <li>{e}</li>
65
+ ))}
66
+ </ul>
67
+ ) : null
68
+
69
+ export const authPage = (mode: 'login' | 'signup', errors: string[] = [], email = ''): string =>
70
+ (
71
+ <Layout title={mode === 'login' ? 'Log in' : 'Sign up'}>
72
+ <h1>{mode === 'login' ? 'Log in' : 'Sign up'}</h1>
73
+ <Errors errors={errors} />
74
+ <form method="post" action={`/${mode}`}>
75
+ <label for="email">Email</label>
76
+ <input id="email" name="email" type="email" value={email} />
77
+ <label for="password">Password</label>
78
+ <input id="password" name="password" type="password" />
79
+ <p>
80
+ <button type="submit">{mode === 'login' ? 'Log in' : 'Create account'}</button>
81
+ </p>
82
+ </form>
83
+ </Layout>
84
+ ).toString()
85
+
86
+ export const listPage = (user: string, notes: Note[], q: string): string =>
87
+ (
88
+ <Layout title="Notes" user={user}>
89
+ <h1>Your notes</h1>
90
+ <form method="get" action="/notes">
91
+ <label for="filter">Search</label>
92
+ <input id="filter" name="q" type="search" value={q} />
93
+ <button type="submit">Search</button>
94
+ </form>
95
+ {notes.length === 0 ? <p>{q ? `No note matches "${q}".` : 'No notes yet.'}</p> : null}
96
+ <ul>
97
+ {notes.map((n) => (
98
+ <li data-note>
99
+ <a href={`/notes/${n.id}/edit`}>{n.title}</a>
100
+ <form method="post" action={`/notes/${n.id}/delete`} style="display:inline">
101
+ <button type="submit">Delete</button>
102
+ </form>
103
+ </li>
104
+ ))}
105
+ </ul>
106
+ </Layout>
107
+ ).toString()
108
+
109
+ export const formPage = (
110
+ user: string,
111
+ action: string,
112
+ note: { title: string; body: string },
113
+ errors: string[] = [],
114
+ ): string =>
115
+ (
116
+ <Layout title="Note" user={user}>
117
+ <h1>{action === '/notes' ? 'New note' : 'Edit note'}</h1>
118
+ <Errors errors={errors} />
119
+ <form method="post" action={action}>
120
+ <label for="title">Title</label>
121
+ <input id="title" name="title" value={note.title} />
122
+ <label for="body">Note</label>
123
+ <textarea id="body" name="body" rows={8} maxlength={BODY_MAX}>
124
+ {note.body}
125
+ </textarea>
126
+ <small id="count" aria-live="polite" data-island="counter" />
127
+ <p>
128
+ <button type="submit">Save</button> <a href="/notes">Cancel</a>
129
+ </p>
130
+ </form>
131
+ </Layout>
132
+ ).toString()
133
+
134
+ export { TITLE_MAX }
@@ -0,0 +1,245 @@
1
+ import { testClient } from '__PACKAGE__/testing'
2
+ import assert from 'node:assert/strict'
3
+ import type { DatabaseSync } from 'node:sqlite'
4
+ import { test } from 'node:test'
5
+ import { openDb } from '../src/db.ts'
6
+ import { createApi, createApp } from '../src/notes-app.ts'
7
+
8
+ const form = (data: Record<string, string>, cookie = ''): RequestInit => ({
9
+ method: 'POST',
10
+ body: new URLSearchParams(data),
11
+ headers: { origin: 'http://localhost', ...(cookie ? { cookie } : {}) },
12
+ })
13
+
14
+ async function signedUp(app: ReturnType<typeof createApp>, email = 'a@example.com') {
15
+ const res = await app.request('/signup', form({ email, password: 'correct horse' }))
16
+ assert.equal(res.status, 303)
17
+ return (res.headers.get('set-cookie') ?? '').split(';')[0] ?? ''
18
+ }
19
+
20
+ test('the home page sends a visitor to the notes, which send them to log in', async () => {
21
+ const app = createApp(openDb(':memory:'))
22
+ assert.equal((await app.request('/')).headers.get('location'), '/notes')
23
+ const res = await app.request('/notes')
24
+ assert.equal(res.status, 302)
25
+ assert.equal(res.headers.get('location'), '/login')
26
+ })
27
+
28
+ test('sign up validates, refuses a duplicate, and starts a session', async () => {
29
+ const app = createApp(openDb(':memory:'))
30
+ assert.match(await (await app.request('/signup')).text(), /Create account/)
31
+ const bad = await app.request('/signup', form({ email: 'nope', password: 'short' }))
32
+ assert.equal(bad.status, 400)
33
+ const text = await bad.text()
34
+ assert.match(text, /valid email/)
35
+ assert.match(text, /at least 8 characters/)
36
+ const cookie = await signedUp(app)
37
+ assert.match(cookie, /^sid=/)
38
+ const again = await app.request(
39
+ '/signup',
40
+ form({ email: 'a@example.com', password: 'correct horse' }),
41
+ )
42
+ assert.equal(again.status, 400)
43
+ assert.match(await again.text(), /already has an account/)
44
+ })
45
+
46
+ test('log in checks the password; log out ends the session', async () => {
47
+ const app = createApp(openDb(':memory:'))
48
+ const first = await signedUp(app)
49
+ assert.match(await (await app.request('/login')).text(), /Log in/)
50
+ const wrong = await app.request(
51
+ '/login',
52
+ form({ email: 'a@example.com', password: 'nope nope nope' }),
53
+ )
54
+ assert.equal(wrong.status, 401)
55
+ assert.match(await wrong.text(), /Wrong email or password/)
56
+ const empty = await app.request('/login', form({ email: '', password: '' }))
57
+ assert.equal(empty.status, 400)
58
+ const ok = await app.request(
59
+ '/login',
60
+ form({ email: 'a@example.com', password: 'correct horse' }),
61
+ )
62
+ assert.equal(ok.status, 303)
63
+ const cookie = (ok.headers.get('set-cookie') ?? '').split(';')[0] ?? ''
64
+ assert.equal((await app.request('/notes', { headers: { cookie } })).status, 200)
65
+ const out = await app.request('/logout', form({}, cookie))
66
+ assert.equal(out.headers.get('location'), '/login')
67
+ assert.equal((await app.request('/notes', { headers: { cookie } })).status, 302)
68
+ assert.equal((await app.request('/notes', { headers: { cookie: first } })).status, 200)
69
+ })
70
+
71
+ test('create, search, edit and delete a note through the forms', async () => {
72
+ const app = createApp(openDb(':memory:'))
73
+ const cookie = await signedUp(app)
74
+ assert.match(
75
+ await (await app.request('/notes/new', { headers: { cookie } })).text(),
76
+ /data-island="counter"/,
77
+ )
78
+
79
+ const invalid = await app.request('/notes', form({ title: ' ', body: 'x' }, cookie))
80
+ assert.equal(invalid.status, 400)
81
+ assert.match(await invalid.text(), /Give the note a title/)
82
+
83
+ assert.equal(
84
+ (await app.request('/notes', form({ title: 'Groceries', body: 'milk and eggs' }, cookie)))
85
+ .status,
86
+ 303,
87
+ )
88
+ assert.equal(
89
+ (await app.request('/notes', form({ title: 'Ideas', body: 'a framework' }, cookie))).status,
90
+ 303,
91
+ )
92
+
93
+ const list = await (await app.request('/notes', { headers: { cookie } })).text()
94
+ assert.match(list, /Groceries/)
95
+ assert.match(list, /Ideas/)
96
+ const found = await (await app.request('/notes?q=eggs', { headers: { cookie } })).text()
97
+ assert.match(found, /Groceries/)
98
+ assert.doesNotMatch(found, /Ideas/)
99
+ assert.match(
100
+ await (await app.request('/notes?q=zzz', { headers: { cookie } })).text(),
101
+ /No note matches/,
102
+ )
103
+
104
+ const edit = await app.request('/notes/1/edit', { headers: { cookie } })
105
+ assert.match(await edit.text(), /milk and eggs/)
106
+ const toolong = await app.request('/notes/1', form({ title: 'x'.repeat(81), body: '' }, cookie))
107
+ assert.equal(toolong.status, 400)
108
+ assert.match(await toolong.text(), /at most 80/)
109
+ assert.equal(
110
+ (await app.request('/notes/1', form({ title: 'Shopping', body: 'oat milk' }, cookie))).status,
111
+ 303,
112
+ )
113
+ assert.match(await (await app.request('/notes', { headers: { cookie } })).text(), /Shopping/)
114
+ assert.equal((await app.request('/notes/99', form({ title: 'x', body: '' }, cookie))).status, 404)
115
+ assert.equal((await app.request('/notes/99/edit', { headers: { cookie } })).status, 404)
116
+
117
+ assert.equal((await app.request('/notes/1/delete', form({}, cookie))).status, 303)
118
+ assert.equal((await app.request('/notes/1/delete', form({}, cookie))).status, 404)
119
+ assert.doesNotMatch(
120
+ await (await app.request('/notes', { headers: { cookie } })).text(),
121
+ /Shopping/,
122
+ )
123
+ })
124
+
125
+ test("one user cannot read or change another user's notes", async () => {
126
+ const app = createApp(openDb(':memory:'))
127
+ const alice = await signedUp(app, 'alice@example.com')
128
+ const bob = await signedUp(app, 'bob@example.com')
129
+ await app.request('/notes', form({ title: 'Secret', body: 'alice only' }, alice))
130
+ assert.equal((await app.request('/notes/1/edit', { headers: { cookie: bob } })).status, 404)
131
+ assert.equal((await app.request('/notes/1/delete', form({}, bob))).status, 404)
132
+ assert.match(await (await app.request('/notes', { headers: { cookie: alice } })).text(), /Secret/)
133
+ })
134
+
135
+ test('the JSON API needs a session and validates input', async () => {
136
+ const db = openDb(':memory:')
137
+ const app = createApp(db)
138
+ const cookie = await signedUp(app)
139
+ const res = await app.request('/api/notes')
140
+ assert.equal(res.status, 401)
141
+ const bad = await app.request('/api/notes', {
142
+ method: 'POST',
143
+ headers: { cookie, 'content-type': 'application/json' },
144
+ body: JSON.stringify({ title: '' }),
145
+ })
146
+ assert.equal(bad.status, 400)
147
+ const body = (await bad.json()) as { issues: { message: string }[] }
148
+ assert.match(body.issues[0]?.message ?? '', /title/)
149
+ })
150
+
151
+ test('the typed client covers every API route', async () => {
152
+ const db = openDb(':memory:')
153
+ const app = createApp(db)
154
+ const cookie = await signedUp(app)
155
+ const client = testClient(createApi(db))
156
+ const as = { headers: { cookie } }
157
+
158
+ const created = await client.index.$post({ json: { title: 'First', body: 'hello' } }, as)
159
+ assert.equal(created.status, 201)
160
+ const { note } = await created.json()
161
+ assert.equal(note.title, 'First')
162
+
163
+ const listed = await client.index.$get({ query: { q: 'hel' } }, as)
164
+ assert.equal((await listed.json()).notes.length, 1)
165
+
166
+ const got = await client[':id'].$get({ param: { id: String(note.id) } }, as)
167
+ assert.equal(got.status, 200)
168
+ const missing = await client[':id'].$get({ param: { id: '99' } }, as)
169
+ assert.equal(missing.status, 404)
170
+
171
+ const updated = await client[':id'].$put(
172
+ { param: { id: String(note.id) }, json: { title: 'Renamed', body: '' } },
173
+ as,
174
+ )
175
+ assert.equal(updated.status, 200)
176
+
177
+ const gone = await client[':id'].$delete({ param: { id: String(note.id) } }, as)
178
+ assert.equal(gone.status, 200)
179
+ assert.equal((await client[':id'].$delete({ param: { id: String(note.id) } }, as)).status, 404)
180
+ })
181
+
182
+ test('csrf refuses a form POST from another site', async () => {
183
+ const app = createApp(openDb(':memory:'))
184
+ const res = await app.request('/signup', {
185
+ method: 'POST',
186
+ body: new URLSearchParams({ email: 'a@example.com', password: 'correct horse' }),
187
+ headers: { origin: 'https://evil.example' },
188
+ })
189
+ assert.equal(res.status, 403)
190
+ })
191
+
192
+ test('the session cookie is Secure over HTTPS, and behind a proxy only when the proxy is trusted', async () => {
193
+ const body = new URLSearchParams({ email: 'a@example.com', password: 'correct horse' })
194
+ const flags = async (url: string, headers: Record<string, string>, trustProxy: boolean) => {
195
+ const app = createApp(openDb(':memory:'), { trustProxy })
196
+ const origin = new URL(url).origin
197
+ const res = await app.request(url, { method: 'POST', body, headers: { origin, ...headers } })
198
+ assert.equal(res.status, 303)
199
+ return res.headers.get('set-cookie') ?? ''
200
+ }
201
+ assert.doesNotMatch(await flags('http://localhost/signup', {}, false), /Secure/i)
202
+ assert.match(await flags('https://localhost/signup', {}, false), /Secure/i)
203
+ const forwarded = { 'x-forwarded-proto': 'https' }
204
+ assert.doesNotMatch(await flags('http://localhost/signup', forwarded, false), /Secure/i)
205
+ assert.match(await flags('http://localhost/signup', forwarded, true), /Secure/i)
206
+ })
207
+
208
+ test('behind a proxy csrf accepts the public origin and still refuses others', async () => {
209
+ const app = createApp(openDb(':memory:'), { publicOrigin: 'https://notes.example.com' })
210
+ const post = (origin: string) =>
211
+ app.request('/signup', {
212
+ method: 'POST',
213
+ body: new URLSearchParams({ email: 'a@example.com', password: 'correct horse' }),
214
+ headers: { origin },
215
+ })
216
+ assert.equal((await post('https://notes.example.com')).status, 303)
217
+ assert.equal((await post('https://evil.example')).status, 403)
218
+ })
219
+
220
+ test('an error answers a plain 500 with no stack and no detail', async () => {
221
+ const broken = {
222
+ prepare() {
223
+ throw new Error('secret detail at /srv/app/db.ts:1')
224
+ },
225
+ exec() {},
226
+ } as unknown as DatabaseSync
227
+ const app = createApp(broken)
228
+ const res = await app.request('/notes', { headers: { cookie: 'sid=anything' } })
229
+ assert.equal(res.status, 500)
230
+ assert.equal(await res.text(), 'Internal Server Error')
231
+ })
232
+
233
+ test('the note form loads the character counter, a client component compiled for the browser', async () => {
234
+ const app = createApp(openDb(':memory:'))
235
+ const cookie = await signedUp(app)
236
+ assert.match(
237
+ await (await app.request('/notes/new', { headers: { cookie } })).text(),
238
+ /src="\/client\/counter\.tsx"/,
239
+ )
240
+ const module = await app.request('/client/counter.tsx')
241
+ assert.equal(module.status, 200)
242
+ assert.match(module.headers.get('content-type') ?? '', /javascript/)
243
+ assert.doesNotMatch(await module.text(), /<Count/)
244
+ assert.equal((await app.request('/client/../src/db.ts')).status, 404)
245
+ })
@@ -0,0 +1,59 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawn } from 'node:child_process'
3
+ import { once } from 'node:events'
4
+ import { mkdtempSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { join } from 'node:path'
7
+ import { test } from 'node:test'
8
+
9
+ /** Start `src/index.ts` the way `npm start` does, on a port the system chooses, and read the address it prints. */
10
+ async function start(env: Record<string, string> = {}) {
11
+ const child = spawn(
12
+ process.execPath,
13
+ ['--import', '__PACKAGE__/node-server/register', 'src/index.ts'],
14
+ {
15
+ env: {
16
+ ...process.env,
17
+ PORT: '0',
18
+ NOTES_DB: join(mkdtempSync(join(tmpdir(), 'notes-')), 'notes.db'),
19
+ ...env,
20
+ },
21
+ stdio: ['ignore', 'pipe', 'inherit'],
22
+ },
23
+ )
24
+ let out = ''
25
+ const address = await new Promise<string>((resolve, reject) => {
26
+ child.once('exit', (code) =>
27
+ reject(new Error(`the server exited with ${code} before it listened`)),
28
+ )
29
+ child.stdout.on('data', (chunk) => {
30
+ out += chunk
31
+ const match = /listening on (http:\/\/\S+)/.exec(out)
32
+ if (match?.[1]) resolve(match[1])
33
+ })
34
+ })
35
+ return { child, address }
36
+ }
37
+
38
+ test('the server listens on 127.0.0.1 unless HOST says otherwise', async () => {
39
+ const { child, address } = await start()
40
+ try {
41
+ assert.match(address, /^http:\/\/127\.0\.0\.1:\d+$/)
42
+ } finally {
43
+ child.kill('SIGTERM')
44
+ await once(child, 'exit')
45
+ }
46
+ })
47
+
48
+ for (const signal of ['SIGTERM', 'SIGINT'] as const) {
49
+ test(`${signal} stops the server cleanly and frees the port`, async () => {
50
+ const { child, address } = await start()
51
+ assert.equal((await fetch(`${address}/signup`)).status, 200)
52
+ const started = Date.now()
53
+ child.kill(signal)
54
+ const [code] = await once(child, 'exit')
55
+ assert.equal(code, 0)
56
+ assert.ok(Date.now() - started < 5000, 'the server took too long to stop')
57
+ await assert.rejects(fetch(address), 'the port should be free')
58
+ })
59
+ }
@@ -0,0 +1,19 @@
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
+ }