@kerf-js/start 0.0.0-stage → 0.1.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/LICENSE +16 -0
- package/README.md +1468 -2
- package/crate/Cargo.lock +1347 -0
- package/crate/Cargo.toml +72 -0
- package/crate/README.md +322 -0
- package/crate/rust-toolchain.toml +3 -0
- package/crate/src/build/emit.rs +103 -0
- package/crate/src/build.rs +367 -0
- package/crate/src/ctx.rs +186 -0
- package/crate/src/envelope.rs +163 -0
- package/crate/src/functions.rs +173 -0
- package/crate/src/lib.rs +118 -0
- package/crate/src/native.rs +212 -0
- package/crate/src/otel.rs +62 -0
- package/crate/src/server.rs +203 -0
- package/package.json +123 -3
- package/src/app.mjs +136 -0
- package/src/asset-receipt.d.mts +13 -0
- package/src/asset-receipt.mjs +61 -0
- package/src/auth/better-auth.ts +280 -0
- package/src/auth/drizzle.ts +17 -0
- package/src/auth/emails.ts +44 -0
- package/src/auth.ts +62 -0
- package/src/boot.ts +57 -0
- package/src/builtin.tsx +19 -0
- package/src/bus/postgres.ts +104 -0
- package/src/bus.ts +51 -0
- package/src/cache.ts +4 -0
- package/src/capture.ts +50 -0
- package/src/changes-sql.d.mts +20 -0
- package/src/changes-sql.mjs +115 -0
- package/src/changes.ts +352 -0
- package/src/channel/connections.ts +216 -0
- package/src/channel/socket.ts +396 -0
- package/src/channel-fake.ts +70 -0
- package/src/channel.ts +250 -0
- package/src/client.tsx +27 -0
- package/src/contract/describe.mjs +237 -0
- package/src/contract.mjs +299 -0
- package/src/cron.ts +74 -0
- package/src/data/after.ts +57 -0
- package/src/data/cache.ts +354 -0
- package/src/data/definitions.ts +94 -0
- package/src/data/draft.ts +104 -0
- package/src/data/foundation.ts +95 -0
- package/src/data/live-api.ts +22 -0
- package/src/data/mutation.ts +138 -0
- package/src/data/primitives.ts +135 -0
- package/src/data/query.ts +106 -0
- package/src/data/transport.ts +123 -0
- package/src/data/types.ts +333 -0
- package/src/data.ts +125 -0
- package/src/db/bun-sqlite.d.ts +13 -0
- package/src/db/changes-mysql.ts +126 -0
- package/src/db/changes-postgres.ts +238 -0
- package/src/db/changes-sqlite.ts +183 -0
- package/src/db/core.ts +95 -0
- package/src/db/index.ts +43 -0
- package/src/db/mysql.ts +84 -0
- package/src/db/postgres.ts +102 -0
- package/src/db/sqlite.ts +166 -0
- package/src/derive.d.mts +19 -0
- package/src/derive.mjs +237 -0
- package/src/dev-runtime.mjs +46 -0
- package/src/email.ts +146 -0
- package/src/exec/errors.ts +87 -0
- package/src/exec/impl.ts +21 -0
- package/src/exec/landing.ts +66 -0
- package/src/exec/limit.ts +25 -0
- package/src/exec/once.ts +24 -0
- package/src/exec/scope.ts +328 -0
- package/src/exec/touch.ts +80 -0
- package/src/exec/validation.ts +176 -0
- package/src/exec/warm.ts +50 -0
- package/src/exec.ts +400 -0
- package/src/extension.ts +48 -0
- package/src/first-paint.ts +74 -0
- package/src/form/value.ts +15 -0
- package/src/form.tsx +223 -0
- package/src/gate.css +6 -0
- package/src/hub/channels.ts +102 -0
- package/src/hub/connections.ts +147 -0
- package/src/hub/delivery.ts +62 -0
- package/src/hub/feed.ts +168 -0
- package/src/hub/presence.ts +64 -0
- package/src/hub/route.ts +159 -0
- package/src/hub/subscriptions.ts +213 -0
- package/src/hub/topic.ts +98 -0
- package/src/hub/tracked.ts +12 -0
- package/src/hub/types.ts +190 -0
- package/src/hub/view.ts +147 -0
- package/src/hub.ts +196 -0
- package/src/index.ts +184 -0
- package/src/inline.mjs +359 -0
- package/src/inspect/compare.mjs +162 -0
- package/src/inspect/routes.mjs +154 -0
- package/src/inspect/samples.mjs +59 -0
- package/src/inspect/url.mjs +2 -0
- package/src/inspect.mjs +239 -0
- package/src/jobs.ts +223 -0
- package/src/link/election.ts +178 -0
- package/src/link/lines.ts +27 -0
- package/src/link.ts +385 -0
- package/src/list-drizzle.ts +136 -0
- package/src/list.ts +315 -0
- package/src/listen.ts +54 -0
- package/src/live/api.ts +18 -0
- package/src/live/backoff.ts +6 -0
- package/src/live/frames.ts +42 -0
- package/src/live/read.ts +77 -0
- package/src/live/sub-types.ts +24 -0
- package/src/live/transport.ts +86 -0
- package/src/live/types.ts +52 -0
- package/src/live-fake.ts +57 -0
- package/src/live-target.mjs +231 -0
- package/src/live.ts +390 -0
- package/src/media.ts +50 -0
- package/src/migrations.mjs +27 -0
- package/src/mux-session.ts +6 -0
- package/src/mux.ts +232 -0
- package/src/og/DefaultCard.tsx +91 -0
- package/src/og/fonts.mjs +72 -0
- package/src/og/images.mjs +124 -0
- package/src/og/index.mjs +222 -0
- package/src/og/native.mjs +36 -0
- package/src/range.mjs +31 -0
- package/src/router.ts +199 -0
- package/src/routes.mjs +193 -0
- package/src/run/admission.ts +67 -0
- package/src/run/boot.tsx +115 -0
- package/src/run/cache-presentation.ts +67 -0
- package/src/run/cache.ts +254 -0
- package/src/run/helpers.ts +197 -0
- package/src/run/listeners.ts +166 -0
- package/src/run/navigation.ts +385 -0
- package/src/run/page-skeleton.tsx +35 -0
- package/src/run/prefetch.ts +129 -0
- package/src/run/retain-view.ts +18 -0
- package/src/run/shape-preparation.ts +97 -0
- package/src/run/shape-styles.ts +72 -0
- package/src/run/source-context/pin.ts +124 -0
- package/src/run/source-context.ts +311 -0
- package/src/run.tsx +74 -0
- package/src/rust/common.ts +163 -0
- package/src/rust/native.ts +282 -0
- package/src/rust.ts +207 -0
- package/src/server/background.ts +34 -0
- package/src/server/card.tsx +65 -0
- package/src/server/compression.ts +115 -0
- package/src/server/core.ts +70 -0
- package/src/server/cron.ts +49 -0
- package/src/server/dispatch.ts +73 -0
- package/src/server/form.ts +92 -0
- package/src/server/functions.ts +133 -0
- package/src/server/handler.ts +57 -0
- package/src/server/head.ts +96 -0
- package/src/server/health.ts +36 -0
- package/src/server/jobs.ts +112 -0
- package/src/server/lifecycle.ts +48 -0
- package/src/server/log.ts +42 -0
- package/src/server/media.ts +61 -0
- package/src/server/navigation-cache.ts +75 -0
- package/src/server/navigation.tsx +86 -0
- package/src/server/page-cold.ts +96 -0
- package/src/server/page-stream.tsx +181 -0
- package/src/server/page-types.ts +51 -0
- package/src/server/page-warm.ts +131 -0
- package/src/server/page.ts +69 -0
- package/src/server/payload.ts +89 -0
- package/src/server/prerender.ts +64 -0
- package/src/server/preview.tsx +67 -0
- package/src/server/render.ts +197 -0
- package/src/server/request.ts +192 -0
- package/src/server/resolver.ts +228 -0
- package/src/server/routes.ts +150 -0
- package/src/server/security.ts +50 -0
- package/src/server/services.ts +69 -0
- package/src/server/shutdown.ts +23 -0
- package/src/server/text.ts +29 -0
- package/src/server/types.ts +170 -0
- package/src/server.tsx +138 -0
- package/src/shape.d.mts +3 -0
- package/src/shape.mjs +97 -0
- package/src/share/display.ts +50 -0
- package/src/share/network.ts +119 -0
- package/src/share/receive.ts +70 -0
- package/src/share/state.ts +30 -0
- package/src/share/tab-queue.ts +28 -0
- package/src/share-server.ts +293 -0
- package/src/share.ts +397 -0
- package/src/sheets.mjs +87 -0
- package/src/sidecar/build.mjs +170 -0
- package/src/sidecar/cargo.mjs +164 -0
- package/src/sidecar/common.mjs +17 -0
- package/src/sidecar/dev-build.mjs +91 -0
- package/src/sidecar/dev-watch.mjs +88 -0
- package/src/sidecar/manifest.mjs +19 -0
- package/src/sidecar/process.mjs +58 -0
- package/src/sidecar/refresh.mjs +19 -0
- package/src/sidecar.mjs +162 -0
- package/src/socket/check.ts +50 -0
- package/src/socket/deliver.ts +16 -0
- package/src/socket/publish.ts +56 -0
- package/src/socket/rooms.ts +41 -0
- package/src/socket/route.ts +79 -0
- package/src/socket/shared.ts +26 -0
- package/src/socket/types.ts +48 -0
- package/src/socket.ts +400 -0
- package/src/stream.ts +22 -0
- package/src/verify/app.ts +39 -0
- package/src/verify/cleanup.ts +27 -0
- package/src/verify/database.ts +11 -0
- package/src/verify/live.ts +63 -0
- package/src/verify/notify.ts +35 -0
- package/src/verify/skip.ts +19 -0
- package/src/verify/support.ts +149 -0
- package/src/verify/timing.ts +15 -0
- package/src/verify/trigger.ts +14 -0
- package/src/verify.ts +152 -0
- package/src/view.tsx +132 -0
- package/src/vite/asset-bytes.mjs +95 -0
- package/src/vite/assets.mjs +117 -0
- package/src/vite/config-hooks.mjs +166 -0
- package/src/vite/dev-hooks.mjs +103 -0
- package/src/vite/dev.mjs +102 -0
- package/src/vite/entries.mjs +149 -0
- package/src/vite/module-hooks.mjs +290 -0
- package/src/vite/route-modules.mjs +289 -0
- package/src/vite/server-functions.mjs +222 -0
- package/src/vite/shape-entry-css.mjs +187 -0
- package/src/vite/shape-override.mjs +226 -0
- package/src/vite/shared.mjs +55 -0
- package/src/vite/sheets.mjs +92 -0
- package/src/vite/state.mjs +89 -0
- package/src/vite/syntax.mjs +139 -0
- package/src/vite.mjs +202 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type * as NodeZlib from 'node:zlib'
|
|
2
|
+
|
|
3
|
+
/** A complete page's text. Its Response holds no body until `compressed` gives it one: compressed, it's never read. */
|
|
4
|
+
export const whole = new WeakMap<Response, string>()
|
|
5
|
+
|
|
6
|
+
type Encoding = 'br' | 'gzip'
|
|
7
|
+
type Zlib = typeof NodeZlib
|
|
8
|
+
|
|
9
|
+
let loaded: Promise<Zlib | undefined> | undefined
|
|
10
|
+
const loadZlib = () => (loaded ??= import('node:zlib').catch(() => undefined))
|
|
11
|
+
const brotli = (zlib: Zlib, sizeHint: number) => ({
|
|
12
|
+
params: {
|
|
13
|
+
[zlib.constants.BROTLI_PARAM_QUALITY]: 5,
|
|
14
|
+
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: sizeHint,
|
|
15
|
+
},
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
const PACKED_MAX = 16 * 1024 * 1024 // characters of text held, per encoding
|
|
19
|
+
const PACKED_ENTRY_MAX = 1024 * 1024
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Compressed bodies by their whole text, most recently used last. The text is the key, not a hash of it, so a response
|
|
23
|
+
* is only ever reused for the same bytes: two users can share an entry only if each was already being sent that page.
|
|
24
|
+
*/
|
|
25
|
+
const packed: Record<Encoding, { entries: Map<string, Promise<Uint8Array>>; held: number }> = {
|
|
26
|
+
br: { entries: new Map(), held: 0 },
|
|
27
|
+
gzip: { entries: new Map(), held: 0 },
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function compressWhole(zlib: Zlib, encoding: Encoding, text: string): Promise<Uint8Array> {
|
|
31
|
+
const cache = packed[encoding]
|
|
32
|
+
const hit = cache.entries.get(text)
|
|
33
|
+
if (hit) {
|
|
34
|
+
cache.entries.delete(text)
|
|
35
|
+
cache.entries.set(text, hit)
|
|
36
|
+
return hit
|
|
37
|
+
}
|
|
38
|
+
const out = new Promise<Uint8Array>((ok, no) => {
|
|
39
|
+
const done = (e: Error | null, b: Buffer) => (e ? no(e) : ok(b))
|
|
40
|
+
if (encoding === 'br') zlib.brotliCompress(text, brotli(zlib, Buffer.byteLength(text)), done)
|
|
41
|
+
else zlib.gzip(text, done)
|
|
42
|
+
})
|
|
43
|
+
if (text.length > PACKED_ENTRY_MAX) return out
|
|
44
|
+
cache.entries.set(text, out)
|
|
45
|
+
cache.held += text.length
|
|
46
|
+
for (const key of cache.entries.keys()) {
|
|
47
|
+
if (cache.held <= PACKED_MAX) break
|
|
48
|
+
cache.entries.delete(key)
|
|
49
|
+
cache.held -= key.length
|
|
50
|
+
}
|
|
51
|
+
return out
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A stream of chunks, each flushed as it arrives so a Boundary reaches the client when it resolves. */
|
|
55
|
+
function compressStream(
|
|
56
|
+
zlib: Zlib,
|
|
57
|
+
encoding: Encoding,
|
|
58
|
+
source: ReadableStream<Uint8Array>,
|
|
59
|
+
): ReadableStream<Uint8Array> {
|
|
60
|
+
const z = encoding === 'br' ? zlib.createBrotliCompress(brotli(zlib, 0)) : zlib.createGzip()
|
|
61
|
+
const reader = source.getReader()
|
|
62
|
+
return new ReadableStream<Uint8Array>({
|
|
63
|
+
start(out) {
|
|
64
|
+
z.on('data', (d: Buffer) => out.enqueue(new Uint8Array(d)))
|
|
65
|
+
z.on('end', () => out.close())
|
|
66
|
+
z.on('error', (e) => out.error(e))
|
|
67
|
+
;(async () => {
|
|
68
|
+
for (;;) {
|
|
69
|
+
const { done, value } = await reader.read()
|
|
70
|
+
if (done) return void z.end()
|
|
71
|
+
z.write(value)
|
|
72
|
+
await new Promise((ok) => {
|
|
73
|
+
z.flush(ok as () => void)
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
})().catch((e) => out.error(e))
|
|
77
|
+
},
|
|
78
|
+
cancel(reason) {
|
|
79
|
+
z.destroy()
|
|
80
|
+
return reader.cancel(reason)
|
|
81
|
+
},
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* HTML and data go out brotli or gzipped when the client takes it. A response that is complete is compressed once and
|
|
87
|
+
* kept, since most pages come out the same for every visitor; one still streaming is flushed chunk by chunk. A runtime
|
|
88
|
+
* with no node:zlib sits behind a platform that compresses.
|
|
89
|
+
*/
|
|
90
|
+
export async function compressed(request: Request, response: Response): Promise<Response> {
|
|
91
|
+
const page = whole.get(response)
|
|
92
|
+
const plain = () => (page === undefined ? response : new Response(page, response))
|
|
93
|
+
if (page === undefined && (!response.body || response.headers.has('content-encoding')))
|
|
94
|
+
return response
|
|
95
|
+
const type = response.headers.get('content-type') ?? ''
|
|
96
|
+
if (!/^(text\/html|application\/json)/.test(type)) return plain()
|
|
97
|
+
const accepts = request.headers.get('accept-encoding') ?? ''
|
|
98
|
+
const encoding = /\bbr\b/.test(accepts) ? 'br' : /\bgzip\b/.test(accepts) ? 'gzip' : undefined
|
|
99
|
+
const zlib = encoding && (await loadZlib())
|
|
100
|
+
if (!zlib) return plain()
|
|
101
|
+
const text = page ?? (type.startsWith('application/json') ? await response.text() : undefined)
|
|
102
|
+
const body =
|
|
103
|
+
text === undefined
|
|
104
|
+
? compressStream(zlib, encoding, response.body!)
|
|
105
|
+
: await compressWhole(zlib, encoding, text)
|
|
106
|
+
const headers = new Headers(response.headers)
|
|
107
|
+
headers.set('content-encoding', encoding)
|
|
108
|
+
headers.append('vary', 'Accept-Encoding')
|
|
109
|
+
headers.delete('content-length')
|
|
110
|
+
return new Response(body as BodyInit, {
|
|
111
|
+
status: response.status,
|
|
112
|
+
statusText: response.statusText,
|
|
113
|
+
headers,
|
|
114
|
+
})
|
|
115
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { region } from '@kerf-js/core/ssr'
|
|
3
|
+
import { createRouteState, type Component, type RoutePayload } from '../router'
|
|
4
|
+
import { ErrorPage, NotFoundPage } from '../builtin'
|
|
5
|
+
import { deployUrl } from '../derive.mjs'
|
|
6
|
+
import type { Scope } from '../exec'
|
|
7
|
+
import { routeTree } from './routes'
|
|
8
|
+
import type { Head } from './page-types'
|
|
9
|
+
import type { HandlerOptions, Resolved } from './types'
|
|
10
|
+
|
|
11
|
+
const HEADS_MAX = 512
|
|
12
|
+
|
|
13
|
+
/** Handler-local routing, component and head-cache state. */
|
|
14
|
+
export function makeCore(options: HandlerOptions, als: AsyncLocalStorage<Scope>) {
|
|
15
|
+
const { manifest, modules, site = {} } = options
|
|
16
|
+
const byId = new Map(manifest.routes.map((r) => [r.id, r]))
|
|
17
|
+
const mod = (file?: string) => (file ? modules[file] : undefined)
|
|
18
|
+
const comps: Record<string, Component> = { 404: NotFoundPage, error: ErrorPage }
|
|
19
|
+
for (const l of manifest.layouts) if (mod(l.file)?.default) comps[l.id] = mod(l.file)!.default!
|
|
20
|
+
for (const r of manifest.routes) if (mod(r.file)?.default) comps[r.id] = mod(r.file)!.default!
|
|
21
|
+
const statics = new Set(options.statics)
|
|
22
|
+
/**
|
|
23
|
+
* What each route's last render needed in its head, by status, Save-Data and levels: the next request sends that head
|
|
24
|
+
* before it renders. `null`: a route whose render sets headers, so it renders first.
|
|
25
|
+
*/
|
|
26
|
+
const heads = new Map<string, Head | null>()
|
|
27
|
+
const remember = (shape: string, head: Head) => {
|
|
28
|
+
if (heads.size >= HEADS_MAX && !heads.has(shape)) heads.clear()
|
|
29
|
+
heads.set(shape, head)
|
|
30
|
+
}
|
|
31
|
+
const publicUrl = deployUrl(
|
|
32
|
+
site,
|
|
33
|
+
(globalThis as unknown as { process?: { env: Record<string, string | undefined> } }).process
|
|
34
|
+
?.env,
|
|
35
|
+
)
|
|
36
|
+
let warned = false
|
|
37
|
+
/**
|
|
38
|
+
* The origin canonical, og:url and og:image are built on. Without a configured one, the request's: right for what
|
|
39
|
+
* a browser asked, but it's whatever `Host` said, so a production server says so once. A prerender has no public
|
|
40
|
+
* request at all (it would write `localhost` into a file), so its pages stay relative and H001 reports them.
|
|
41
|
+
*/
|
|
42
|
+
const originOf = (request: Request) => {
|
|
43
|
+
if (publicUrl) return publicUrl
|
|
44
|
+
if (request.headers.has('x-nitro-prerender') || options.requestOrigin === false)
|
|
45
|
+
return undefined
|
|
46
|
+
if (!options.dev && !warned) {
|
|
47
|
+
warned = true
|
|
48
|
+
options.onDiagnostic?.({
|
|
49
|
+
code: 'H001',
|
|
50
|
+
severity: 'warning',
|
|
51
|
+
message:
|
|
52
|
+
"H001 `site.url` is not set, so canonical, og:url and og:image use the request's Host header. Set `site.url`, or `KERF_SITE_URL` in the deploy environment.",
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
return new URL(request.url).origin
|
|
56
|
+
}
|
|
57
|
+
/** The route state of a server render: where a static level is in it, it marks where each level starts (`region`). */
|
|
58
|
+
const stateOf = (r: Resolved, payload: RoutePayload) => {
|
|
59
|
+
const route = createRouteState(
|
|
60
|
+
{ ...payload, m: r.levels.map((lv) => ({ id: lv.id, params: lv.params, data: lv.raw })) },
|
|
61
|
+
comps,
|
|
62
|
+
)
|
|
63
|
+
if (r.levels.some((l) => statics.has(l.id)))
|
|
64
|
+
route.around = (d, id, body) =>
|
|
65
|
+
region(statics.has(id), d, statics.has(r.levels[d - 1]?.id ?? ''), body)
|
|
66
|
+
return route
|
|
67
|
+
}
|
|
68
|
+
const tree = routeTree(manifest, modules, als)
|
|
69
|
+
return { manifest, site, byId, mod, comps, statics, heads, remember, originOf, stateOf, tree }
|
|
70
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { matcher, type CronJobs } from '../cron'
|
|
2
|
+
import { errorText, inScope, type BackgroundDeps } from './background'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Runs the app's cron jobs: a timer wakes at each minute, and every job due then runs once. With several instances
|
|
6
|
+
* the cache store decides which one runs it (a window per job and minute, one call allowed): with `redisStore()`
|
|
7
|
+
* that's exactly one; with the memory store each instance counts alone, so each runs it.
|
|
8
|
+
*/
|
|
9
|
+
export function startCron(jobs: CronJobs, deps: BackgroundDeps): () => void {
|
|
10
|
+
const due = Object.entries(jobs).map(([name, job]) => ({
|
|
11
|
+
name,
|
|
12
|
+
job,
|
|
13
|
+
at: matcher(job.schedule, name),
|
|
14
|
+
}))
|
|
15
|
+
if (!due.length) return () => {}
|
|
16
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
17
|
+
const tick = async () => {
|
|
18
|
+
const at = new Date(Math.floor(Date.now() / 60_000) * 60_000)
|
|
19
|
+
arm()
|
|
20
|
+
for (const { name, job, at: matches } of due) {
|
|
21
|
+
if (!matches(at)) continue
|
|
22
|
+
const claim = await deps.store.consume?.(`cron:${name}:${at.getTime()}`, {
|
|
23
|
+
window: 120,
|
|
24
|
+
max: 1,
|
|
25
|
+
})
|
|
26
|
+
if (claim && !claim.allowed) continue
|
|
27
|
+
void run(name, job, at)
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const run = async (name: string, job: CronJobs[string], at: Date) => {
|
|
31
|
+
try {
|
|
32
|
+
await inScope(deps, `/_kerf/cron/${encodeURIComponent(name)}`, (ctx) =>
|
|
33
|
+
job.run({ ctx, name, at }),
|
|
34
|
+
)
|
|
35
|
+
} catch (e) {
|
|
36
|
+
deps.scopeOptions.onDiagnostic?.({
|
|
37
|
+
code: 'J001',
|
|
38
|
+
severity: 'error',
|
|
39
|
+
message: `J001: cron job \`${name}\` failed: ${errorText(e)}`,
|
|
40
|
+
})
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const arm = () => {
|
|
44
|
+
timer = setTimeout(() => void tick(), 60_000 - (Date.now() % 60_000) + 50)
|
|
45
|
+
;(timer as { unref?: () => void }).unref?.() // a schedule never keeps a process alive by itself
|
|
46
|
+
}
|
|
47
|
+
arm()
|
|
48
|
+
return () => clearTimeout(timer)
|
|
49
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { EXTENSION, type ServerExtension } from '../extension'
|
|
2
|
+
import * as exec from '../exec'
|
|
3
|
+
import type { Scope } from '../exec'
|
|
4
|
+
import { enter } from '../data/foundation'
|
|
5
|
+
import { rtRoute } from '../hub'
|
|
6
|
+
import { socketRoute } from '../socket'
|
|
7
|
+
import { serverFunction } from './functions'
|
|
8
|
+
import type { HandlerOptions } from './types'
|
|
9
|
+
|
|
10
|
+
interface Dispatch {
|
|
11
|
+
options: HandlerOptions
|
|
12
|
+
authBase: string
|
|
13
|
+
extensions: Map<string, ServerExtension>
|
|
14
|
+
form: (url: URL, request: Request, scope: Scope) => Promise<Response>
|
|
15
|
+
media: (url: URL, request: Request) => Promise<Response>
|
|
16
|
+
og: (url: URL, request: Request) => Promise<Response>
|
|
17
|
+
data: (path: string, request: Request, scope: Scope) => Promise<Response>
|
|
18
|
+
prerenderList: (request: Request, url: URL) => Promise<Response>
|
|
19
|
+
page: (url: URL, request: Request, scope: Scope) => Promise<Response>
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Select the endpoint for a request. */
|
|
23
|
+
export function makeDispatch({
|
|
24
|
+
options,
|
|
25
|
+
authBase,
|
|
26
|
+
extensions,
|
|
27
|
+
form,
|
|
28
|
+
media,
|
|
29
|
+
og,
|
|
30
|
+
data,
|
|
31
|
+
prerenderList,
|
|
32
|
+
page,
|
|
33
|
+
}: Dispatch) {
|
|
34
|
+
/** Everything under `/_kerf/x/<key>/`, for the extension with that key. Nothing else reaches it. */
|
|
35
|
+
async function extensionRoute(url: URL, request: Request, scope: Scope) {
|
|
36
|
+
const [key = '', ...rest] = url.pathname.slice(EXTENSION.length).split('/')
|
|
37
|
+
const extension = extensions.get(key)
|
|
38
|
+
if (!extension?.handle) return new Response('Not found', { status: 404 })
|
|
39
|
+
return extension.handle(request, rest.join('/'), {
|
|
40
|
+
invalidate: (tags) => exec.invalidate(scope, tags),
|
|
41
|
+
report: (d) => options.onDiagnostic?.(d),
|
|
42
|
+
ctx: () => scope.ctx(),
|
|
43
|
+
call: (id, input) => enter(scope, () => exec.callById(scope, id, input)),
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return (request: Request, scope: Scope): Promise<Response> => {
|
|
48
|
+
const url = new URL(request.url)
|
|
49
|
+
if (options.auth && (url.pathname === authBase || url.pathname.startsWith(authBase + '/')))
|
|
50
|
+
return Promise.resolve(options.auth.handler(request))
|
|
51
|
+
if (url.pathname.startsWith('/_kerf/fn/')) return serverFunction(options, url, request, scope)
|
|
52
|
+
if (url.pathname.startsWith(EXTENSION)) return extensionRoute(url, request, scope)
|
|
53
|
+
if (
|
|
54
|
+
request.method === 'POST' &&
|
|
55
|
+
!url.pathname.startsWith('/_kerf/') &&
|
|
56
|
+
/^(application\/x-www-form-urlencoded|multipart\/form-data)/.test(
|
|
57
|
+
request.headers.get('content-type') ?? '',
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
return form(url, request, scope)
|
|
61
|
+
if (url.pathname === '/_kerf/rt') return rtRoute(request, scope, options.realtime?.origins)
|
|
62
|
+
if (url.pathname === '/_kerf/ws') return socketRoute(request, scope, options.realtime?.origins)
|
|
63
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
64
|
+
return Promise.resolve(new Response('Method not allowed', { status: 405 }))
|
|
65
|
+
if (url.pathname.startsWith('/_kerf/m/')) return media(url, request)
|
|
66
|
+
if (url.pathname.startsWith('/_kerf/og/') && url.pathname.endsWith('.png'))
|
|
67
|
+
return og(url, request)
|
|
68
|
+
if (url.pathname.startsWith('/_kerf/data/') || url.pathname === '/_kerf/data')
|
|
69
|
+
return data((url.pathname.slice('/_kerf/data'.length) || '/') + url.search, request, scope)
|
|
70
|
+
if (url.pathname === '/_kerf/og-routes') return prerenderList(request, url)
|
|
71
|
+
return page(url, request, scope)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import {
|
|
2
|
+
decodeForm,
|
|
3
|
+
fieldsOf,
|
|
4
|
+
fns,
|
|
5
|
+
isRedirect,
|
|
6
|
+
StartError,
|
|
7
|
+
FnError,
|
|
8
|
+
type SchemaIssue,
|
|
9
|
+
} from '../data'
|
|
10
|
+
import * as exec from '../exec'
|
|
11
|
+
import type { Scope } from '../exec'
|
|
12
|
+
import { bodyLimit, echoed, limited, withHeaders } from './request'
|
|
13
|
+
import type { HandlerOptions } from './types'
|
|
14
|
+
export function makeForm(
|
|
15
|
+
options: HandlerOptions,
|
|
16
|
+
page: (url: URL, request: Request, scope: Scope) => Promise<Response>,
|
|
17
|
+
) {
|
|
18
|
+
/**
|
|
19
|
+
* A form POST to a page (research 29 §5): the mutation, then 303 (Post/Redirect/Get) or the page again with the
|
|
20
|
+
* errors and what was typed. A form can't send `x-kerf`, so the CSRF proof is the browser's own origin headers.
|
|
21
|
+
*/
|
|
22
|
+
return async function form(url: URL, request: Request, scope: Scope): Promise<Response> {
|
|
23
|
+
const origin = request.headers.get('origin')
|
|
24
|
+
const from = request.headers.get('sec-fetch-site')
|
|
25
|
+
if (
|
|
26
|
+
!(origin
|
|
27
|
+
? origin === url.origin && (!from || from === 'same-origin')
|
|
28
|
+
: from === 'same-origin')
|
|
29
|
+
) {
|
|
30
|
+
options.onDiagnostic?.({
|
|
31
|
+
code: 'F002',
|
|
32
|
+
severity: 'error',
|
|
33
|
+
message: `F002: a form POST to ${url.pathname} without the same-origin proof (\`Origin\` or \`Sec-Fetch-Site\`)`,
|
|
34
|
+
})
|
|
35
|
+
return new Response('Forbidden', { status: 403 })
|
|
36
|
+
}
|
|
37
|
+
let fields: FormData
|
|
38
|
+
try {
|
|
39
|
+
fields = await (await limited(request, bodyLimit(options.site?.limits, request))).formData()
|
|
40
|
+
} catch (e) {
|
|
41
|
+
if (!(e instanceof StartError)) throw e
|
|
42
|
+
options.onDiagnostic?.({ code: e.code, severity: 'error', message: e.message })
|
|
43
|
+
return new Response('Payload too large', { status: 413 })
|
|
44
|
+
}
|
|
45
|
+
const named = fields.get('$fn')
|
|
46
|
+
const id = typeof named === 'string' ? named : ''
|
|
47
|
+
const f = fns.get(id)
|
|
48
|
+
if (f?.kind !== 'mutation') {
|
|
49
|
+
options.onDiagnostic?.({
|
|
50
|
+
code: 'F003',
|
|
51
|
+
severity: 'error',
|
|
52
|
+
message: `F003: a form POST names \`${id}\`, which is no mutation (the page is older than the server)`,
|
|
53
|
+
})
|
|
54
|
+
return new Response('Not found', { status: 404 })
|
|
55
|
+
}
|
|
56
|
+
const see = (href: string) =>
|
|
57
|
+
withHeaders(
|
|
58
|
+
new Response(null, {
|
|
59
|
+
status: 303,
|
|
60
|
+
headers: { location: href, 'cache-control': 'no-cache' },
|
|
61
|
+
}),
|
|
62
|
+
scope,
|
|
63
|
+
)
|
|
64
|
+
const input = decodeForm(fields)
|
|
65
|
+
try {
|
|
66
|
+
await exec.runMutation(scope, f, input, [], true)
|
|
67
|
+
return see(url.pathname + url.search)
|
|
68
|
+
} catch (e) {
|
|
69
|
+
if (isRedirect(e)) return see(e.href)
|
|
70
|
+
const known = e instanceof StartError || e instanceof FnError
|
|
71
|
+
if (!known)
|
|
72
|
+
options.onDiagnostic?.({
|
|
73
|
+
code: 'E_FN',
|
|
74
|
+
severity: 'error',
|
|
75
|
+
message: `${id}: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`,
|
|
76
|
+
})
|
|
77
|
+
const failure = e as { issues?: SchemaIssue[]; status?: number; message?: string } | null
|
|
78
|
+
const issues = failure?.issues
|
|
79
|
+
const { errors, message } = fieldsOf(issues)
|
|
80
|
+
const key = fields.get('$form')
|
|
81
|
+
scope.form = {
|
|
82
|
+
id,
|
|
83
|
+
...(typeof key === 'string' && { key }),
|
|
84
|
+
values: echoed(input),
|
|
85
|
+
errors,
|
|
86
|
+
message: issues ? message : (exec.shown(e, scope) as Error).message,
|
|
87
|
+
status: issues ? 422 : (failure?.status ?? 500),
|
|
88
|
+
}
|
|
89
|
+
return page(url, request, scope)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { sessionChanged } from '../auth'
|
|
2
|
+
import { fns, isRedirect, FnError, StartError } from '../data'
|
|
3
|
+
import * as exec from '../exec'
|
|
4
|
+
import type { Scope } from '../exec'
|
|
5
|
+
import { bodyLimit, limited, multipartBody, withHeaders } from './request'
|
|
6
|
+
import type { HandlerOptions } from './types'
|
|
7
|
+
|
|
8
|
+
/** `/_kerf/fn/<id>`: GET runs a query, POST a mutation (CSRF-checked), both answering JSON (research 27 §3). */
|
|
9
|
+
export async function serverFunction(
|
|
10
|
+
options: HandlerOptions,
|
|
11
|
+
url: URL,
|
|
12
|
+
request: Request,
|
|
13
|
+
scope: Scope,
|
|
14
|
+
): Promise<Response> {
|
|
15
|
+
const id = decodeURIComponent(url.pathname.slice('/_kerf/fn/'.length))
|
|
16
|
+
const f = fns.get(id)
|
|
17
|
+
const out = (body: unknown, status = 200) => {
|
|
18
|
+
const res = withHeaders(Response.json(body, { status }), scope)
|
|
19
|
+
res.headers.set('cache-control', 'no-store') // a function's answer is never stored, whatever it set
|
|
20
|
+
return res
|
|
21
|
+
}
|
|
22
|
+
const fail = (
|
|
23
|
+
code: string,
|
|
24
|
+
message: string,
|
|
25
|
+
status: number,
|
|
26
|
+
extra: object = {},
|
|
27
|
+
sent?: unknown,
|
|
28
|
+
) => {
|
|
29
|
+
options.onDiagnostic?.({ code, severity: 'error', message })
|
|
30
|
+
return out(
|
|
31
|
+
{ e: { code, message: sent instanceof Error ? sent.message : message, ...extra } },
|
|
32
|
+
status,
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
if (!f)
|
|
36
|
+
return fail(
|
|
37
|
+
'Q009',
|
|
38
|
+
`Q009: no server function \`${id}\` (the page is older than the server, or the module isn't a server module): reload`,
|
|
39
|
+
404,
|
|
40
|
+
)
|
|
41
|
+
let fromForm = false
|
|
42
|
+
if (f.kind === 'stream')
|
|
43
|
+
return fail('Q009', `Q009: \`${id}\` is a stream: its client reads it over \`/_kerf/rt\``, 405)
|
|
44
|
+
try {
|
|
45
|
+
if (f.kind === 'query') {
|
|
46
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
47
|
+
return fail('Q009', `Q009: \`${id}\` is a query: GET only`, 405)
|
|
48
|
+
const raw = url.searchParams.get('i')
|
|
49
|
+
const e = await exec.fetchQuery(scope, f, raw === null ? undefined : JSON.parse(raw))
|
|
50
|
+
return out({ v: e.v, t: e.tags })
|
|
51
|
+
}
|
|
52
|
+
if (request.method !== 'POST') return fail('Q010', `Q010: mutation \`${id}\` needs POST`, 405)
|
|
53
|
+
const origin = request.headers.get('origin')
|
|
54
|
+
const from = request.headers.get('sec-fetch-site')
|
|
55
|
+
const cross =
|
|
56
|
+
(origin && origin !== url.origin) || (from && from !== 'same-origin' && from !== 'none')
|
|
57
|
+
const type = request.headers.get('content-type') ?? ''
|
|
58
|
+
const multipart = type.startsWith('multipart/form-data') // `<Form>` with a file; `x-kerf` still forces a preflight
|
|
59
|
+
if (
|
|
60
|
+
cross ||
|
|
61
|
+
request.headers.get('x-kerf') !== '1' ||
|
|
62
|
+
!(multipart || type.startsWith('application/json'))
|
|
63
|
+
)
|
|
64
|
+
return fail(
|
|
65
|
+
'Q010',
|
|
66
|
+
`Q010: mutation \`${id}\` without the CSRF proof (POST + JSON + \`x-kerf: 1\`, same origin): call it through its stub`,
|
|
67
|
+
403,
|
|
68
|
+
)
|
|
69
|
+
const read = await limited(request, bodyLimit(options.site?.limits, request))
|
|
70
|
+
const body = multipart
|
|
71
|
+
? await multipartBody(read)
|
|
72
|
+
: ((await read.json()) as { i?: unknown; f?: [string, unknown][]; c?: 1 })
|
|
73
|
+
fromForm = !!body.c
|
|
74
|
+
// A token opens only the functions listed for it, and what a mutation refreshes would run as that token too.
|
|
75
|
+
const refresh =
|
|
76
|
+
Array.isArray(body.f) && !request.headers.has('authorization') ? body.f.slice(0, 200) : []
|
|
77
|
+
const answer = await exec.runMutation(scope, f, body.i, refresh, fromForm)
|
|
78
|
+
if (options.dev && sessionChanged(scope.headers))
|
|
79
|
+
options.onDiagnostic?.({
|
|
80
|
+
code: 'A004',
|
|
81
|
+
severity: 'warning',
|
|
82
|
+
message: `\`${id}\` changed the session cookie without a redirect: the tab keeps what the last session cached. \`redirect()\` after it`,
|
|
83
|
+
})
|
|
84
|
+
return out(answer)
|
|
85
|
+
} catch (e) {
|
|
86
|
+
return functionError(e, { fromForm, scope, options, id, out, fail })
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function functionError(
|
|
91
|
+
e: unknown,
|
|
92
|
+
c: {
|
|
93
|
+
fromForm: boolean
|
|
94
|
+
scope: Scope
|
|
95
|
+
options: HandlerOptions
|
|
96
|
+
id: string
|
|
97
|
+
out: (body: unknown, status?: number) => Response
|
|
98
|
+
fail: (
|
|
99
|
+
code: string,
|
|
100
|
+
message: string,
|
|
101
|
+
status: number,
|
|
102
|
+
extra?: object,
|
|
103
|
+
sent?: unknown,
|
|
104
|
+
) => Response
|
|
105
|
+
},
|
|
106
|
+
): Response {
|
|
107
|
+
const { fromForm, scope, options, id, out, fail } = c
|
|
108
|
+
// The session changed: a full load, so nothing cached for the last user survives in the tab (research 28 §3).
|
|
109
|
+
if (isRedirect(e)) return out({ r: e.href, ...(sessionChanged(scope.headers) && { x: 1 }) })
|
|
110
|
+
if (e instanceof FnError) return out({ e: { code: e.code, message: e.message } }, e.status)
|
|
111
|
+
// A wrong field in a form is an answer, not a fault: nothing to log.
|
|
112
|
+
if (e instanceof StartError && fromForm && e.extra.issues)
|
|
113
|
+
return out({ e: { code: e.code, message: e.message, issues: e.extra.issues } }, 422)
|
|
114
|
+
if (e instanceof StartError)
|
|
115
|
+
return fail(
|
|
116
|
+
e.code,
|
|
117
|
+
e.message,
|
|
118
|
+
(e.extra.status as number) ?? 500,
|
|
119
|
+
e.extra.issues ? { issues: e.extra.issues } : e.extra.typed ? { data: e.extra.data } : {},
|
|
120
|
+
exec.shown(e, scope),
|
|
121
|
+
)
|
|
122
|
+
options.onDiagnostic?.({
|
|
123
|
+
code: 'E_FN',
|
|
124
|
+
severity: 'error',
|
|
125
|
+
message: `${id}: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`,
|
|
126
|
+
})
|
|
127
|
+
return out(
|
|
128
|
+
{
|
|
129
|
+
e: { message: options.dev && e instanceof Error ? e.message : 'Server function failed.' },
|
|
130
|
+
},
|
|
131
|
+
500,
|
|
132
|
+
)
|
|
133
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import * as exec from '../exec'
|
|
3
|
+
import type { Scope } from '../exec'
|
|
4
|
+
import { hub } from '../hub'
|
|
5
|
+
import { compressed } from './compression'
|
|
6
|
+
import { stamped } from './request'
|
|
7
|
+
import { secured } from './security'
|
|
8
|
+
import { requestIdOf } from './log'
|
|
9
|
+
import { health } from './health'
|
|
10
|
+
import type { makeServices } from './services'
|
|
11
|
+
import type { HandlerOptions } from './types'
|
|
12
|
+
|
|
13
|
+
/** Wrap endpoint routing in the request scope and boot lifecycle. */
|
|
14
|
+
export function makeHandler(
|
|
15
|
+
options: HandlerOptions,
|
|
16
|
+
als: AsyncLocalStorage<Scope>,
|
|
17
|
+
services: ReturnType<typeof makeServices>,
|
|
18
|
+
route: (request: Request, scope: Scope) => Promise<Response>,
|
|
19
|
+
) {
|
|
20
|
+
return async (incoming: Request): Promise<Response> =>
|
|
21
|
+
secured(await handle(incoming), incoming, options)
|
|
22
|
+
async function handle(incoming: Request): Promise<Response> {
|
|
23
|
+
const request = stamped(incoming, options.site?.trustProxy)
|
|
24
|
+
await services.loadExtensions()
|
|
25
|
+
services.check()
|
|
26
|
+
const scope = exec.createScope(request, services.scopeOptions)
|
|
27
|
+
scope.requestId = requestIdOf(incoming, options.site)
|
|
28
|
+
const { pathname } = new URL(request.url)
|
|
29
|
+
if (pathname === '/_kerf/health') return health(options.dev)
|
|
30
|
+
// The build's prerender only lists cards: it holds no secrets and may have no database.
|
|
31
|
+
if (pathname === '/_kerf/og-routes') return als.run(scope, () => route(request, scope))
|
|
32
|
+
await services.boot()
|
|
33
|
+
if (options.liveRequired?.length) await hub().probed
|
|
34
|
+
if (hub().refused)
|
|
35
|
+
return Response.json(
|
|
36
|
+
{
|
|
37
|
+
e: {
|
|
38
|
+
code: 'R015',
|
|
39
|
+
message: options.dev ? hub().refused!.message : 'Live data is unavailable.',
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
{ status: 503, headers: { 'cache-control': 'no-store' } },
|
|
43
|
+
)
|
|
44
|
+
let response: Response
|
|
45
|
+
try {
|
|
46
|
+
response = await als.run(scope, () => route(request, scope))
|
|
47
|
+
} catch (e) {
|
|
48
|
+
void exec.finishScope(scope)
|
|
49
|
+
throw e
|
|
50
|
+
}
|
|
51
|
+
const out = await compressed(request, exec.finishing(response, scope))
|
|
52
|
+
try {
|
|
53
|
+
out.headers.set('x-request-id', scope.requestId)
|
|
54
|
+
} catch {} // a response with fixed headers goes without it
|
|
55
|
+
return out
|
|
56
|
+
}
|
|
57
|
+
}
|