prunelle 0.8.0 → 0.10.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/llms.txt +68 -51
- package/package.json +7 -2
- package/src/a11y/declaration.ts +10 -17
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +94 -136
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +14 -6
- package/src/build/index.ts +23 -11
- package/src/build/island-promote.ts +42 -2
- package/src/build/islands.ts +63 -9
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +117 -1
- package/src/build/plugin-host.ts +13 -1
- package/src/build/prerender.ts +8 -3
- package/src/build/reach.ts +18 -4
- package/src/build/report.ts +1 -1
- package/src/build/resolve.ts +5 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +42 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +10 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +30 -105
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +50 -6
- package/src/cli/check.ts +49 -21
- package/src/cli/commands.ts +138 -16
- package/src/cli/docs.ts +21 -2
- package/src/cli/form-opaque-children.ts +40 -0
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +22 -16
- package/src/compiler/cacheability-private.ts +13 -3
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +322 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-rules.ts +72 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +61 -93
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/dom-attrs.ts +178 -22
- package/src/compiler/dom.ts +31 -44
- package/src/compiler/emit.ts +17 -6
- package/src/compiler/expr-context.ts +260 -207
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-body.ts +263 -21
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +324 -343
- package/src/compiler/signal-reads.ts +142 -29
- package/src/compiler/spread-handlers.ts +25 -13
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +165 -121
- package/src/compiler/ssr.ts +28 -441
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/host-check.ts +2 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +5 -2
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/attrs.ts +93 -25
- package/src/dom/extras.ts +91 -50
- package/src/dom/field-marks.ts +32 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +44 -18
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/loop.ts +259 -188
- package/src/dom/prefetch.ts +135 -0
- package/src/dom/regions.ts +515 -0
- package/src/dom/swap.ts +246 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +44 -41
- package/src/eco/index.ts +8 -5
- package/src/href.ts +31 -0
- package/src/index.ts +12 -5
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +12 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +128 -10
- package/src/reactivity/graph.ts +244 -41
- package/src/reactivity/hmr.ts +101 -0
- package/src/reactivity/index.ts +243 -239
- package/src/reactivity/resource.ts +129 -0
- package/src/reactivity/seed.ts +141 -0
- package/src/reactivity/selector.ts +85 -47
- package/src/reactivity/server-seed.ts +202 -0
- package/src/reactivity/store.ts +331 -97
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-protect.ts +3 -0
- package/src/server/action-registry.ts +11 -9
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +14 -8
- package/src/server/cache-invalidation.ts +97 -0
- package/src/server/compress.ts +55 -18
- package/src/server/consent.ts +21 -5
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +77 -8
- package/src/server/cors.ts +98 -0
- package/src/server/csp-report.ts +90 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +2 -2
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +41 -11
- package/src/server/http.ts +28 -11
- package/src/server/index.ts +122 -307
- package/src/server/loader.ts +2 -0
- package/src/server/page.ts +3 -9
- package/src/server/plugin-host.ts +66 -16
- package/src/server/plugin-route-shadow.ts +24 -0
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +49 -10
- package/src/server/region.ts +22 -2
- package/src/server/request-handler.ts +406 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +55 -8
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +53 -27
- package/src/server/router.ts +2 -1
- package/src/server/routing.ts +104 -45
- package/src/server/sanitize-html.ts +4 -2
- package/src/server/security.ts +38 -8
- package/src/server/serve-handlers.ts +16 -6
- package/src/server/served-file.ts +19 -14
- package/src/server/shared-store.ts +323 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +34 -12
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +50 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +174 -53
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +63 -58
- package/src/ssr/navigation.ts +161 -14
- package/src/ssr/region.ts +9 -3
- package/src/style.ts +12 -5
- package/src/test/browser.ts +53 -23
- package/src/test/build-reuse.ts +85 -0
- package/src/test/index.ts +51 -8
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/src/ts-plugin/diagnostics.ts +56 -18
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +4058 -2246
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// testApp() builds an app once per test run: `bun test` runs every file in one process, so a later call with the same build options, environment and files reuses the build the first one made.
|
|
2
|
+
|
|
3
|
+
import type { BuildCache, BuildManifest } from '../build/index'
|
|
4
|
+
import type { FileStamp } from '../build/graph'
|
|
5
|
+
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
|
6
|
+
import { isAbsolute, join, relative, sep } from 'node:path'
|
|
7
|
+
import { stampsMatch } from '../build/graph'
|
|
8
|
+
|
|
9
|
+
/** The build options that change what a build writes; a call passing `plugins` or an analysis callback always builds. */
|
|
10
|
+
export interface ReusableBuildOptions {
|
|
11
|
+
routesDir?: string | undefined
|
|
12
|
+
publicDir?: string | undefined
|
|
13
|
+
minify?: boolean | undefined
|
|
14
|
+
assetPrefix?: string | undefined
|
|
15
|
+
site?: string | undefined
|
|
16
|
+
cache?: unknown
|
|
17
|
+
maxJs?: unknown
|
|
18
|
+
prerender?: unknown
|
|
19
|
+
autoPrerender?: unknown
|
|
20
|
+
copyPublic?: boolean | undefined
|
|
21
|
+
dev?: boolean | undefined
|
|
22
|
+
nodeEnv?: string | undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const SKIPPED_DIRS = new Set(['node_modules', '.git', '.prunelle-cache', '.prunelle-dev', 'dist', 'data', 'data-prod'])
|
|
26
|
+
// Files up to this size are fingerprinted by content, larger ones by size and modification time.
|
|
27
|
+
const HASHED_MAX_BYTES = 64 * 1024
|
|
28
|
+
|
|
29
|
+
/** A build testApp() made: the folder it wrote and its manifest. */
|
|
30
|
+
export interface TestBuild {
|
|
31
|
+
outDir: string
|
|
32
|
+
manifest: BuildManifest
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const lastBuilds = new Map<string, { key: string, build: TestBuild, outside: ReadonlyMap<string, FileStamp> }>()
|
|
36
|
+
|
|
37
|
+
/** This process's last build of `root` when nothing it depends on has changed since. */
|
|
38
|
+
export function reusableBuild(root: string, options: ReusableBuildOptions): TestBuild | undefined {
|
|
39
|
+
const last = lastBuilds.get(root)
|
|
40
|
+
return last !== undefined && last.key === buildKey(root, options) && stampsMatch(last.outside) ? last.build : undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Remembers a build of `root`, keyed on the files as the build left them (it writes route types into `src/`) and on the files it read outside the root, which `cache` recorded. */
|
|
44
|
+
export function rememberBuild(root: string, options: ReusableBuildOptions, build: TestBuild, cache: BuildCache): void {
|
|
45
|
+
const outside = new Map<string, FileStamp>()
|
|
46
|
+
for (const stamps of [cache.lastClient?.inputStamps, cache.lastServer?.inputStamps]) {
|
|
47
|
+
for (const [file, stamp] of stamps ?? []) {
|
|
48
|
+
if (!fingerprinted(root, file))
|
|
49
|
+
outside.set(file, stamp)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
lastBuilds.set(root, { key: buildKey(root, options), build, outside })
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Whether `fingerprint()` already reads `file`: under the root and out of the folders it skips. */
|
|
56
|
+
function fingerprinted(root: string, file: string): boolean {
|
|
57
|
+
const rel = relative(root, file)
|
|
58
|
+
return !rel.startsWith('..') && !isAbsolute(rel) && !rel.split(sep).slice(0, -1).some(dir => SKIPPED_DIRS.has(dir))
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function buildKey(root: string, options: ReusableBuildOptions): string {
|
|
62
|
+
const env = Object.entries(process.env).sort(([a], [b]) => a < b ? -1 : 1)
|
|
63
|
+
return `${JSON.stringify(options)}\n${JSON.stringify(env)}\n${fingerprint(root)}`
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function fingerprint(root: string): string {
|
|
67
|
+
const parts: string[] = []
|
|
68
|
+
const walk = (dir: string, rel: string): void => {
|
|
69
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
|
|
70
|
+
const path = join(dir, entry.name)
|
|
71
|
+
const relPath = rel === '' ? entry.name : `${rel}/${entry.name}`
|
|
72
|
+
if (entry.isDirectory()) {
|
|
73
|
+
if (!SKIPPED_DIRS.has(entry.name))
|
|
74
|
+
walk(path, relPath)
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
if (!entry.isFile())
|
|
78
|
+
continue
|
|
79
|
+
const { size, mtimeMs } = statSync(path)
|
|
80
|
+
parts.push(`${relPath}:${size}:${size <= HASHED_MAX_BYTES ? Bun.hash(readFileSync(path)).toString(36) : mtimeMs}`)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
walk(root, '')
|
|
84
|
+
return Bun.hash(parts.join('\n')).toString(36)
|
|
85
|
+
}
|
package/src/test/index.ts
CHANGED
|
@@ -4,13 +4,16 @@ import type { BuildManifest, BuildOptions } from '../build/index'
|
|
|
4
4
|
import type { PrunelleApp, ServerAction, ServerRuntimeConfig } from '../server/index'
|
|
5
5
|
import { existsSync, readdirSync, rmSync } from 'node:fs'
|
|
6
6
|
import { dirname, join, resolve } from 'node:path'
|
|
7
|
-
import { build } from '../build/index'
|
|
7
|
+
import { build, createBuildCache } from '../build/index'
|
|
8
8
|
import { relPosix } from '../build/files'
|
|
9
9
|
import { processSuffix, removeDeadProcessDirs } from '../build/output'
|
|
10
10
|
import { ensureCacheGitignore } from '../build/precompress'
|
|
11
11
|
import { resolveServerConfig } from '../server/index'
|
|
12
12
|
import { FORM_TIMESTAMP_FIELD, honeypotFieldName, signFormTimestamp } from '../server/action-protect'
|
|
13
13
|
import { startBuiltApp } from '../server/loader'
|
|
14
|
+
import { rememberBuild, reusableBuild, type TestBuild } from './build-reuse'
|
|
15
|
+
import type { StubAnswer, TestClock } from './outside'
|
|
16
|
+
import { guardOutgoing, testClock } from './outside'
|
|
14
17
|
|
|
15
18
|
const TEST_DIR_PREFIX = 'test-'
|
|
16
19
|
const ABSOLUTE_URL_RE = /^https?:\/\//i
|
|
@@ -80,7 +83,11 @@ export interface TestApp {
|
|
|
80
83
|
/** Posts `fields` as a form to an action, given as one from `import()` or as its URL. */
|
|
81
84
|
submit(action: ServerAction<never, unknown> | string, fields: Record<string, string>, headers?: HeadersInit): Promise<Response>
|
|
82
85
|
clearCookies(): void
|
|
83
|
-
/**
|
|
86
|
+
/** The time the app reads, set and advanced by the test. */
|
|
87
|
+
readonly clock: TestClock
|
|
88
|
+
/** Answers the app's requests to `url` (its origin and path, any query) or to the URLs a RegExp matches. A request leaving the machine that no stub answers is refused, and fails `dispose()`; one to a loopback server of the test goes through. */
|
|
89
|
+
stub(url: string | RegExp, answer: StubAnswer): void
|
|
90
|
+
/** Runs plugin shutdown hooks and cleans up app resources (idempotent), restores the clock and `fetch`, and throws if the app sent a request no stub answered. */
|
|
84
91
|
dispose(): Promise<void>
|
|
85
92
|
[Symbol.asyncDispose](): Promise<void>
|
|
86
93
|
}
|
|
@@ -113,10 +120,19 @@ function ownOutDir(root: string): string {
|
|
|
113
120
|
return dir
|
|
114
121
|
}
|
|
115
122
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
const
|
|
123
|
+
/** Builds the app, or reuses the folder of this process's last build when its inputs match: the server modules load under a fresh `?v=`, so two apps never share module state. */
|
|
124
|
+
async function buildForTest(root: string, options: TestAppOptions): Promise<TestBuild> {
|
|
125
|
+
const reusable = options.outDir === undefined && options.plugins === undefined && options.analyze === undefined && options.analyzeJson === undefined && options.onAnalyze === undefined
|
|
126
|
+
const inputs = { routesDir: options.routesDir, publicDir: options.publicDir, minify: options.minify, assetPrefix: options.assetPrefix, site: options.site, cache: options.cache, maxJs: options.maxJs, prerender: options.prerender, autoPrerender: options.autoPrerender, copyPublic: options.copyPublic, dev: options.dev, nodeEnv: options.nodeEnv }
|
|
127
|
+
const reused = reusable ? reusableBuild(root, inputs) : undefined
|
|
128
|
+
if (reused !== undefined && existsSync(reused.outDir)) {
|
|
129
|
+
latestOutDirs.set(root, reused.outDir)
|
|
130
|
+
return reused
|
|
131
|
+
}
|
|
132
|
+
const outDir = options.outDir ?? ownOutDir(root)
|
|
133
|
+
// The build cache records every file the bundles read, which a reused build is checked against.
|
|
134
|
+
const cache = options.cache ?? createBuildCache()
|
|
135
|
+
const manifest = await build({
|
|
120
136
|
root: options.root,
|
|
121
137
|
routesDir: options.routesDir,
|
|
122
138
|
outDir,
|
|
@@ -125,7 +141,7 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
125
141
|
assetPrefix: options.assetPrefix,
|
|
126
142
|
site: options.site,
|
|
127
143
|
plugins: options.plugins,
|
|
128
|
-
cache
|
|
144
|
+
cache,
|
|
129
145
|
analyze: options.analyze,
|
|
130
146
|
analyzeJson: options.analyzeJson,
|
|
131
147
|
onAnalyze: options.onAnalyze,
|
|
@@ -134,10 +150,21 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
134
150
|
autoPrerender: options.autoPrerender,
|
|
135
151
|
copyPublic: options.copyPublic,
|
|
136
152
|
dev: options.dev,
|
|
153
|
+
splitServer: false,
|
|
137
154
|
nodeEnv: options.nodeEnv,
|
|
138
155
|
})
|
|
156
|
+
if (reusable)
|
|
157
|
+
rememberBuild(root, inputs, { outDir, manifest }, cache)
|
|
158
|
+
return { outDir, manifest }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
162
|
+
const root = resolve(options.root)
|
|
163
|
+
const { outDir, manifest } = options.prebuilt ? { outDir: options.outDir ?? latestOutDirs.get(root), manifest: undefined } : await buildForTest(root, options)
|
|
139
164
|
|
|
140
165
|
const errors: string[] = []
|
|
166
|
+
const outside = guardOutgoing(errors)
|
|
167
|
+
const time = testClock()
|
|
141
168
|
const { app, entry } = await startBuiltApp({
|
|
142
169
|
root: options.root,
|
|
143
170
|
outDir,
|
|
@@ -147,6 +174,10 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
147
174
|
errorSink: ({ error, request, source }) => {
|
|
148
175
|
errors.push(`${source} ${request.method} ${new URL(request.url).pathname}: ${error instanceof Error ? error.message : String(error)}`)
|
|
149
176
|
},
|
|
177
|
+
}).catch((error: unknown) => {
|
|
178
|
+
outside.release()
|
|
179
|
+
time.restore()
|
|
180
|
+
throw error
|
|
150
181
|
})
|
|
151
182
|
|
|
152
183
|
const cookies = new Map<string, string>()
|
|
@@ -192,12 +223,21 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
192
223
|
}
|
|
193
224
|
|
|
194
225
|
let disposed = false
|
|
226
|
+
const disposeApp = app.dispose
|
|
195
227
|
async function dispose(): Promise<void> {
|
|
196
228
|
if (disposed)
|
|
197
229
|
return
|
|
198
230
|
disposed = true
|
|
199
|
-
|
|
231
|
+
try {
|
|
232
|
+
await disposeApp?.()
|
|
233
|
+
}
|
|
234
|
+
finally {
|
|
235
|
+
time.restore()
|
|
236
|
+
outside.release()
|
|
237
|
+
}
|
|
200
238
|
}
|
|
239
|
+
// A test that disposes `testApp().app` itself restores the clock and fetch too.
|
|
240
|
+
app.dispose = dispose
|
|
201
241
|
|
|
202
242
|
return {
|
|
203
243
|
app,
|
|
@@ -253,6 +293,8 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
253
293
|
clearCookies() {
|
|
254
294
|
cookies.clear()
|
|
255
295
|
},
|
|
296
|
+
clock: time.clock,
|
|
297
|
+
stub: outside.stub,
|
|
256
298
|
dispose,
|
|
257
299
|
[Symbol.asyncDispose]: dispose,
|
|
258
300
|
}
|
|
@@ -260,3 +302,4 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
|
|
|
260
302
|
|
|
261
303
|
export { testBrowser } from './browser'
|
|
262
304
|
export type { BrowserPage, BrowserTest, BrowserTestOptions } from './browser'
|
|
305
|
+
export type { StubAnswer, TestClock } from './outside'
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// `browser.mount()`: one component alone on an empty page, built by `prunelle build` and hydrated as the app's own pages are.
|
|
2
|
+
|
|
3
|
+
import type { TestApp, TestAppOptions } from './index'
|
|
4
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { join, resolve } from 'node:path'
|
|
6
|
+
import { testApp } from './index'
|
|
7
|
+
|
|
8
|
+
export interface MountedApp {
|
|
9
|
+
readonly app: TestApp
|
|
10
|
+
readonly origin: string
|
|
11
|
+
close: () => Promise<void>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const EXPORT_NAME_RE = /^[A-Z_$][\w$]*$/i
|
|
15
|
+
|
|
16
|
+
/** Builds the app with a routes folder holding one page, which renders the component with the props the `props` query parameter carries as JSON. */
|
|
17
|
+
export async function serveMount(options: TestAppOptions, file: string, exportName: string): Promise<MountedApp> {
|
|
18
|
+
const root = resolve(options.root)
|
|
19
|
+
const component = resolve(root, file)
|
|
20
|
+
if (!existsSync(component))
|
|
21
|
+
throw new Error(`prunelle: browser.mount("${file}"): no such file: give the component's path from the app's root.`)
|
|
22
|
+
if (exportName !== 'default' && !EXPORT_NAME_RE.test(exportName))
|
|
23
|
+
throw new Error(`prunelle: browser.mount("${file}"): \`export\` must be the name of an export, got "${exportName}".`)
|
|
24
|
+
const cacheDir = join(root, '.prunelle-cache')
|
|
25
|
+
mkdirSync(cacheDir, { recursive: true })
|
|
26
|
+
const dir = mkdtempSync(join(cacheDir, 'mount-'))
|
|
27
|
+
const routesDir = join(dir, 'routes')
|
|
28
|
+
mkdirSync(routesDir)
|
|
29
|
+
const binding = exportName === 'default' ? 'Mounted' : `{ ${exportName} as Mounted }`
|
|
30
|
+
writeFileSync(join(routesDir, 'index.tsx'), `import ${binding} from ${JSON.stringify(component)}\n\nexport default function Mount({ url }: { url: URL }) {\n return <Mounted {...JSON.parse(url.searchParams.get('props') ?? '{}')} />\n}\n`)
|
|
31
|
+
let app: TestApp
|
|
32
|
+
try {
|
|
33
|
+
app = await testApp({ ...options, routesDir, minify: options.minify ?? true })
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
rmSync(dir, { recursive: true, force: true })
|
|
37
|
+
throw error
|
|
38
|
+
}
|
|
39
|
+
const server = app.app.serve(0, '127.0.0.1')
|
|
40
|
+
return {
|
|
41
|
+
app,
|
|
42
|
+
origin: `http://127.0.0.1:${server.port}`,
|
|
43
|
+
async close() {
|
|
44
|
+
server.stop(true)
|
|
45
|
+
try {
|
|
46
|
+
await app.dispose()
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
rmSync(dir, { recursive: true, force: true })
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// What a `testApp` controls outside the app: the clock it reads, and the answers to the requests it sends out.
|
|
2
|
+
|
|
3
|
+
import { setSystemTime } from 'bun:test'
|
|
4
|
+
|
|
5
|
+
export interface TestClock {
|
|
6
|
+
/** Sets the time `Date.now()` and `new Date()` give the app, its plugins and the test, until `dispose()`. */
|
|
7
|
+
set: (time: Date | number | string) => void
|
|
8
|
+
/** Moves the clock `ms` forward from where it stands. */
|
|
9
|
+
advance: (ms: number) => void
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function testClock(): { clock: TestClock, restore: () => void } {
|
|
13
|
+
let moved = false
|
|
14
|
+
const set = (time: Date | number | string): void => {
|
|
15
|
+
moved = true
|
|
16
|
+
setSystemTime(new Date(time))
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
clock: { set, advance: ms => set(Date.now() + ms) },
|
|
20
|
+
restore() {
|
|
21
|
+
if (moved)
|
|
22
|
+
setSystemTime()
|
|
23
|
+
moved = false
|
|
24
|
+
},
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type StubAnswer = Response | ((request: Request) => Response | Promise<Response>)
|
|
29
|
+
|
|
30
|
+
interface Guard {
|
|
31
|
+
stubs: Array<{ matches: (url: URL) => boolean, answer: StubAnswer }>
|
|
32
|
+
unanswered: string[]
|
|
33
|
+
errors: string[]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
37
|
+
const nativeFetch = globalThis.fetch
|
|
38
|
+
const guards = new Set<Guard>()
|
|
39
|
+
const patched = Object.assign(guardedFetch, { preconnect: nativeFetch.preconnect }) as typeof fetch
|
|
40
|
+
|
|
41
|
+
function stubFor(url: URL): StubAnswer | undefined {
|
|
42
|
+
for (const guard of [...guards].reverse()) {
|
|
43
|
+
const stub = guard.stubs.findLast(s => s.matches(url))
|
|
44
|
+
if (stub !== undefined)
|
|
45
|
+
return stub.answer
|
|
46
|
+
}
|
|
47
|
+
return undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function guardedFetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
|
|
51
|
+
const url = guards.size === 0 ? null : URL.parse(input instanceof Request ? input.url : input)
|
|
52
|
+
if (url === null)
|
|
53
|
+
return nativeFetch(input, init)
|
|
54
|
+
const answer = stubFor(url)
|
|
55
|
+
if (answer !== undefined)
|
|
56
|
+
return answer instanceof Response ? answer.clone() : await answer(new Request(input, init))
|
|
57
|
+
if (LOOPBACK.has(url.hostname) || !url.protocol.startsWith('http'))
|
|
58
|
+
return nativeFetch(input, init)
|
|
59
|
+
const sent = `${init?.method ?? (input instanceof Request ? input.method : 'GET')} ${url.href}`
|
|
60
|
+
for (const guard of guards) {
|
|
61
|
+
guard.unanswered.push(sent)
|
|
62
|
+
guard.errors.push(`fetch ${sent}: no app.stub() answers it`)
|
|
63
|
+
}
|
|
64
|
+
throw new Error(`prunelle: testApp: the app sent ${sent}, which no app.stub() answers: stub it, or send it to a loopback server of the test.`)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Refuses the requests the app sends outside the machine while the testApp lives, unless a stub answers them; a test that replaced `fetch` with its own mock keeps it. */
|
|
68
|
+
export function guardOutgoing(errors: string[]): { stub: (url: string | RegExp, answer: StubAnswer) => void, release: () => void } {
|
|
69
|
+
const guard: Guard = { stubs: [], unanswered: [], errors }
|
|
70
|
+
// Only the process's own fetch is wrapped: wrapping a mock that calls the fetch it replaced would call itself.
|
|
71
|
+
if (globalThis.fetch === nativeFetch)
|
|
72
|
+
globalThis.fetch = patched
|
|
73
|
+
const guarding = globalThis.fetch === patched
|
|
74
|
+
if (guarding)
|
|
75
|
+
guards.add(guard)
|
|
76
|
+
return {
|
|
77
|
+
stub(url, answer) {
|
|
78
|
+
if (!guarding)
|
|
79
|
+
throw new Error('prunelle: testApp: app.stub() cannot answer while the test has replaced globalThis.fetch with its own mock, which receives every request: answer from that mock, or drop it and stub here.')
|
|
80
|
+
const target = typeof url === 'string' ? new URL(url) : undefined
|
|
81
|
+
const matches = target !== undefined
|
|
82
|
+
? (sent: URL) => sent.origin === target.origin && sent.pathname === target.pathname
|
|
83
|
+
: (sent: URL) => (url as RegExp).test(sent.href)
|
|
84
|
+
guard.stubs.push({ matches, answer })
|
|
85
|
+
},
|
|
86
|
+
release() {
|
|
87
|
+
guards.delete(guard)
|
|
88
|
+
if (guards.size === 0 && globalThis.fetch === patched)
|
|
89
|
+
globalThis.fetch = nativeFetch
|
|
90
|
+
if (guard.unanswered.length > 0)
|
|
91
|
+
throw new Error(`prunelle: testApp: the app sent requests no app.stub() answered: ${guard.unanswered.join(', ')}.`)
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -68,22 +68,49 @@ function propKeyName(node: Node): string | undefined {
|
|
|
68
68
|
return undefined
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
-
|
|
72
|
-
|
|
71
|
+
/** Follows an identifier to the top-level `const` that holds it, so a config kept in a variable reads like an inline one. */
|
|
72
|
+
type ResolveConst = (node: Node) => Node
|
|
73
|
+
|
|
74
|
+
function topLevelConsts(program: Program): ResolveConst {
|
|
75
|
+
const consts = new Map<string, Node>()
|
|
76
|
+
for (const stmt of program.body) {
|
|
77
|
+
const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt
|
|
78
|
+
if (decl?.type !== 'VariableDeclaration' || decl.kind !== 'const')
|
|
79
|
+
continue
|
|
80
|
+
for (const d of decl.declarations) {
|
|
81
|
+
if (d.id.type === 'Identifier' && d.init !== null)
|
|
82
|
+
consts.set(d.id.name, d.init)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const resolve: ResolveConst = (node) => {
|
|
86
|
+
let inner = unwrapTsExpr(node)
|
|
87
|
+
for (let depth = 0; inner.type === 'Identifier' && depth < 8; depth++) {
|
|
88
|
+
const init = consts.get(inner.name)
|
|
89
|
+
if (init === undefined)
|
|
90
|
+
break
|
|
91
|
+
inner = unwrapTsExpr(init)
|
|
92
|
+
}
|
|
93
|
+
return inner
|
|
94
|
+
}
|
|
95
|
+
return resolve
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function staticString(node: Node, resolve: ResolveConst): string | undefined {
|
|
99
|
+
const inner = resolve(node)
|
|
73
100
|
if (inner.type === 'Literal' && typeof inner.value === 'string')
|
|
74
101
|
return inner.value
|
|
75
102
|
return undefined
|
|
76
103
|
}
|
|
77
104
|
|
|
78
|
-
function extractConfigObject(program: Program): Extract<Node, { type: 'ObjectExpression' }> | undefined {
|
|
105
|
+
function extractConfigObject(program: Program, resolve: ResolveConst): Extract<Node, { type: 'ObjectExpression' }> | undefined {
|
|
79
106
|
for (const stmt of program.body) {
|
|
80
107
|
if (stmt.type !== 'ExportDefaultDeclaration')
|
|
81
108
|
continue
|
|
82
|
-
const decl =
|
|
109
|
+
const decl = resolve(stmt.declaration)
|
|
83
110
|
if (decl.type === 'ObjectExpression')
|
|
84
111
|
return decl
|
|
85
112
|
if (decl.type === 'CallExpression' && decl.arguments[0] !== undefined) {
|
|
86
|
-
const arg =
|
|
113
|
+
const arg = resolve(decl.arguments[0])
|
|
87
114
|
if (arg.type === 'ObjectExpression')
|
|
88
115
|
return arg
|
|
89
116
|
}
|
|
@@ -91,8 +118,24 @@ function extractConfigObject(program: Program): Extract<Node, { type: 'ObjectExp
|
|
|
91
118
|
return undefined
|
|
92
119
|
}
|
|
93
120
|
|
|
94
|
-
function
|
|
95
|
-
const
|
|
121
|
+
function collectIgnoredRules(array: Extract<Node, { type: 'ArrayExpression' }>, resolve: ResolveConst, rules: ComplianceRule[]): void {
|
|
122
|
+
for (const el of array.elements) {
|
|
123
|
+
if (el === null)
|
|
124
|
+
continue
|
|
125
|
+
if (el.type === 'SpreadElement') {
|
|
126
|
+
const spread = resolve(el.argument)
|
|
127
|
+
if (spread.type === 'ArrayExpression')
|
|
128
|
+
collectIgnoredRules(spread, resolve, rules)
|
|
129
|
+
continue
|
|
130
|
+
}
|
|
131
|
+
const s = staticString(el, resolve)
|
|
132
|
+
if (s !== undefined)
|
|
133
|
+
rules.push(s as ComplianceRule)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function parseStaticCompliance(node: Node, resolve: ResolveConst): ComplianceConfig | undefined {
|
|
138
|
+
const obj = resolve(node)
|
|
96
139
|
if (obj.type !== 'ObjectExpression')
|
|
97
140
|
return undefined
|
|
98
141
|
const out: ComplianceConfig = {}
|
|
@@ -100,7 +143,7 @@ function parseStaticCompliance(node: Node): ComplianceConfig | undefined {
|
|
|
100
143
|
if (prop.type !== 'Property')
|
|
101
144
|
continue
|
|
102
145
|
const key = propKeyName(prop.key)
|
|
103
|
-
const val =
|
|
146
|
+
const val = resolve(prop.value)
|
|
104
147
|
if (key === 'publicBody' && val.type === 'Literal' && typeof val.value === 'boolean') {
|
|
105
148
|
out.publicBody = val.value
|
|
106
149
|
}
|
|
@@ -109,13 +152,7 @@ function parseStaticCompliance(node: Node): ComplianceConfig | undefined {
|
|
|
109
152
|
}
|
|
110
153
|
else if (key === 'ignore' && val.type === 'ArrayExpression') {
|
|
111
154
|
const rules: ComplianceRule[] = []
|
|
112
|
-
|
|
113
|
-
if (el !== null && el.type !== 'SpreadElement') {
|
|
114
|
-
const s = staticString(el)
|
|
115
|
-
if (s !== undefined)
|
|
116
|
-
rules.push(s as ComplianceRule)
|
|
117
|
-
}
|
|
118
|
-
}
|
|
155
|
+
collectIgnoredRules(val, resolve, rules)
|
|
119
156
|
out.ignore = rules
|
|
120
157
|
}
|
|
121
158
|
}
|
|
@@ -145,16 +182,17 @@ export function readStaticProjectConfig(projectRoot: string | undefined): { site
|
|
|
145
182
|
try {
|
|
146
183
|
const code = readFileSync(cfgPath, 'utf8')
|
|
147
184
|
const parsed = parseSync(cfgPath, code, { lang: 'ts', sourceType: 'module' })
|
|
148
|
-
const
|
|
185
|
+
const resolve = topLevelConsts(parsed.program)
|
|
186
|
+
const obj = parsed.errors.length === 0 ? extractConfigObject(parsed.program, resolve) : undefined
|
|
149
187
|
if (obj !== undefined) {
|
|
150
188
|
for (const prop of obj.properties) {
|
|
151
189
|
if (prop.type !== 'Property')
|
|
152
190
|
continue
|
|
153
191
|
const key = propKeyName(prop.key)
|
|
154
192
|
if (key === 'site')
|
|
155
|
-
site = staticString(prop.value)
|
|
193
|
+
site = staticString(prop.value, resolve)
|
|
156
194
|
else if (key === 'compliance')
|
|
157
|
-
compliance = parseStaticCompliance(prop.value)
|
|
195
|
+
compliance = parseStaticCompliance(prop.value, resolve)
|
|
158
196
|
}
|
|
159
197
|
}
|
|
160
198
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# __APP_NAME__
|
|
2
2
|
|
|
3
|
-
A prunelle app. Read `node_modules/prunelle/llms.txt` before writing code: it holds prunelle's whole API for the version installed here, on one page. When using
|
|
3
|
+
A prunelle app. Read `node_modules/prunelle/llms.txt` before writing code: it holds prunelle's whole API for the version installed here, on one page. When using plugins, also read each installed plugin's `llms.txt` if it ships one (`node_modules/@prunellejs/<plugin>/llms.txt` for first-party ones).
|
|
4
4
|
|
|
5
5
|
## Workflow
|
|
6
6
|
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# The app as one binary on an image holding only glibc and certificates, run by a user without root.
|
|
2
|
+
# docker build -t __APP_NAME__ . && docker run -p 127.0.0.1:3000:3000 __APP_NAME__
|
|
3
|
+
|
|
4
|
+
FROM oven/bun:__BUN_VERSION__ AS build
|
|
5
|
+
WORKDIR /app
|
|
6
|
+
COPY package.json bun.lock ./
|
|
7
|
+
RUN bun install --frozen-lockfile
|
|
8
|
+
COPY . .
|
|
9
|
+
# The image ships the data folder empty, whatever the build opened in it.
|
|
10
|
+
RUN bunx prunelle build --compile server && rm -rf data && mkdir data
|
|
11
|
+
|
|
12
|
+
FROM gcr.io/distroless/base-debian12
|
|
13
|
+
WORKDIR /app
|
|
14
|
+
COPY --from=build /app/server ./server
|
|
15
|
+
# SQLite files go here; a mounted folder must be writable by uid 1000.
|
|
16
|
+
COPY --from=build --chown=1000:1000 /app/data ./data
|
|
17
|
+
USER 1000:1000
|
|
18
|
+
# Inside the container the server listens on every interface; publish its port on 127.0.0.1 and put a proxy in front.
|
|
19
|
+
ENV HOST=0.0.0.0 PORT=3000
|
|
20
|
+
EXPOSE 3000
|
|
21
|
+
HEALTHCHECK --interval=30s --timeout=3s CMD ["./server", "--health"]
|
|
22
|
+
CMD ["./server"]
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# Generate a 32+ byte secret for production, e.g.:
|
|
2
2
|
# openssl rand -base64 32
|
|
3
3
|
AUTH_SECRET=
|
|
4
|
-
|
|
4
|
+
DATABASE=./data/app.db
|
|
5
|
+
# The address the app is served at, e.g. https://example.com
|
|
6
|
+
SITE=
|
|
5
7
|
|
|
6
8
|
# The SMTP server and the sender of sign-up confirmations and sign-in links, e.g. smtp://user:pass@smtp.example.com:587 and hello@example.com
|
|
7
9
|
MAIL_URL=
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# docker compose up -d --build, after `mkdir data-prod && sudo chown 1000:1000 data-prod` and the four settings in .env.
|
|
2
|
+
# Expected server layout:
|
|
3
|
+
# compose.yaml
|
|
4
|
+
# .env AUTH_SECRET, MAIL_URL, MAIL_FROM, SITE
|
|
5
|
+
# data-prod/ the SQLite database, owned by uid 1000
|
|
6
|
+
|
|
7
|
+
services:
|
|
8
|
+
app:
|
|
9
|
+
build: .
|
|
10
|
+
image: __APP_NAME__
|
|
11
|
+
restart: unless-stopped
|
|
12
|
+
environment:
|
|
13
|
+
AUTH_SECRET: ${AUTH_SECRET:?set AUTH_SECRET in .env (openssl rand -base64 32)}
|
|
14
|
+
MAIL_URL: ${MAIL_URL:?set MAIL_URL in .env}
|
|
15
|
+
MAIL_FROM: ${MAIL_FROM:?set MAIL_FROM in .env}
|
|
16
|
+
SITE: ${SITE:?set SITE in .env to the address the app is served at, e.g. https://example.com}
|
|
17
|
+
DATABASE: data/app.db
|
|
18
|
+
ports:
|
|
19
|
+
# Loopback only: the proxy in front ends TLS and is the one thing on a public interface.
|
|
20
|
+
- '127.0.0.1:${PORT:-3000}:3000'
|
|
21
|
+
volumes:
|
|
22
|
+
- type: bind
|
|
23
|
+
source: ./data-prod
|
|
24
|
+
target: /app/data
|
|
25
|
+
bind: { create_host_path: false }
|
|
26
|
+
read_only: true
|
|
27
|
+
tmpfs: [/tmp]
|
|
28
|
+
cap_drop: [ALL]
|
|
29
|
+
security_opt: [no-new-privileges:true]
|
|
30
|
+
logging:
|
|
31
|
+
driver: json-file
|
|
32
|
+
options: { max-size: 10m, max-file: '3' }
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { defineSchema } from '@prunellejs/db'
|
|
2
|
+
|
|
3
|
+
// What SQL cannot say: which columns are personal and why, and whose rows they are. Auth exports and erases a user's notes with their account, and `prunelle rgpd --draft` lists them.
|
|
4
|
+
export default defineSchema({
|
|
5
|
+
notes: {
|
|
6
|
+
owner: 'user_id',
|
|
7
|
+
personal: { body: 'le texte des notes' },
|
|
8
|
+
purpose: 'Garder les notes que vous écrivez.',
|
|
9
|
+
legalBasis: 'Exécution du contrat (RGPD art. 6.1.b).',
|
|
10
|
+
},
|
|
11
|
+
})
|
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import { ui } from '@prunellejs/ui/plugin'
|
|
2
2
|
import { defineConfig } from 'prunelle/config'
|
|
3
3
|
import { auth } from './src/auth'
|
|
4
|
+
import { db } from './src/db'
|
|
4
5
|
import { mail } from './src/mail'
|
|
5
6
|
|
|
6
7
|
export default defineConfig({
|
|
7
8
|
lang: 'en',
|
|
9
|
+
// The address the app is served at, for the links of mails sent outside a request, such as the warning before an inactive account is deleted.
|
|
10
|
+
site: process.env.SITE || undefined,
|
|
11
|
+
// The database of every process: accounts, notes and rate limits. A relative path lands under the app's folder, out of dist/.
|
|
12
|
+
store: process.env.DATABASE || 'data/app.db',
|
|
8
13
|
plugins: [
|
|
9
14
|
ui({ grammar: 'editorial' }),
|
|
10
15
|
mail,
|
|
11
16
|
auth,
|
|
17
|
+
db,
|
|
12
18
|
],
|
|
13
19
|
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from 'prunelle/server'
|
|
2
|
+
import { action } from 'prunelle/server'
|
|
3
|
+
import { db } from '../db'
|
|
4
|
+
|
|
5
|
+
const noteSchema: StandardSchemaV1<{ body: string }> = {
|
|
6
|
+
'~standard': {
|
|
7
|
+
version: 1,
|
|
8
|
+
vendor: 'prunelle',
|
|
9
|
+
// Read by prunelle check, and by the page, which gets `required` and `maxlength` on the field from it.
|
|
10
|
+
jsonSchema: { input: () => ({ type: 'object', properties: { body: { type: 'string', minLength: 1, maxLength: 2000 } }, required: ['body'] }) },
|
|
11
|
+
validate(raw: unknown) {
|
|
12
|
+
const body = String((raw as { body?: unknown })?.body ?? '').trim()
|
|
13
|
+
if (body === '' || body.length > 2000)
|
|
14
|
+
return { issues: [{ message: 'Write a note of 1 to 2000 characters', path: ['body'] }] }
|
|
15
|
+
return { value: { body } }
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const addNote = action(noteSchema, async ({ body }, ctx) => {
|
|
21
|
+
const user = ctx.locals.user
|
|
22
|
+
if (!user)
|
|
23
|
+
return ctx.deny(401, 'Sign in to write a note')
|
|
24
|
+
await db.sql`insert into notes (user_id, body, created_at) values (${user.id}, ${body}, ${Date.now()})`
|
|
25
|
+
return ctx.redirect('/dashboard')
|
|
26
|
+
})
|