@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
package/src/media.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// `z.media()` (research 29 §6): the record of an upload or a CMS image, in the shape `<Media src>` already takes, so
|
|
2
|
+
// `<Media src={post.cover} alt="…" />` needs no conversion. Zod's `z` is an ES namespace and can't be extended, so this
|
|
3
|
+
// `z` is Zod's API plus `media()`.
|
|
4
|
+
|
|
5
|
+
import { z as zod } from 'zod'
|
|
6
|
+
import type { MediaAsset } from '@kerf-js/core/media'
|
|
7
|
+
|
|
8
|
+
const record = () =>
|
|
9
|
+
zod.object({
|
|
10
|
+
kind: zod.enum(['photo', 'graphic', 'vector', 'video', 'audio']),
|
|
11
|
+
src: zod.string(),
|
|
12
|
+
width: zod.number().int().nonnegative(),
|
|
13
|
+
height: zod.number().int().nonnegative(),
|
|
14
|
+
type: zod.string(),
|
|
15
|
+
sources: zod.array(zod.object({ type: zod.string(), srcset: zod.string() })),
|
|
16
|
+
dominant: zod.string().optional(),
|
|
17
|
+
placeholder: zod.string().optional(),
|
|
18
|
+
name: zod.string(),
|
|
19
|
+
quality: zod.enum(['ssimulacra2', 'fixed', 'original']).optional(),
|
|
20
|
+
poster: zod.string().optional(),
|
|
21
|
+
duration: zod.number().optional(),
|
|
22
|
+
audio: zod.boolean().optional(),
|
|
23
|
+
animated: zod.boolean().optional(),
|
|
24
|
+
loop: zod.number().optional(),
|
|
25
|
+
copy: zod
|
|
26
|
+
.object({
|
|
27
|
+
src: zod.string(),
|
|
28
|
+
type: zod.string(),
|
|
29
|
+
bytes: zod.number().optional(),
|
|
30
|
+
ratio: zod.number().optional(),
|
|
31
|
+
})
|
|
32
|
+
.optional(),
|
|
33
|
+
swap: zod.enum(['intent', 'idle', 'never']).optional(),
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
/** Zod's API plus `media()`, the record of an upload. */
|
|
37
|
+
// oxlint-disable-next-line no-redeclare -- a value and the namespace below that holds `z.infer`, one name as Zod's has
|
|
38
|
+
export const z = { ...zod, media: record } as typeof zod & { media: typeof record }
|
|
39
|
+
|
|
40
|
+
/** Zod's type helpers, under the name that has `media()`. */
|
|
41
|
+
export declare namespace z {
|
|
42
|
+
/** A schema's output type. */
|
|
43
|
+
export type infer<T> = zod.infer<T>
|
|
44
|
+
/** A schema's input type. */
|
|
45
|
+
export type input<T> = zod.input<T>
|
|
46
|
+
/** A schema's output type, under Zod's other name. */
|
|
47
|
+
export type output<T> = zod.output<T>
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type { MediaAsset }
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// The app's migrations in order (research 28 §2, 34 §4): dev reads them per request, a build embeds them. `drizzle/` has
|
|
2
|
+
// a journal; Native's `migrations/` is numbered `.sql` files; Prisma's `prisma/migrations/` is a folder per migration.
|
|
3
|
+
|
|
4
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
const DIRS = ['drizzle', 'migrations', 'prisma/migrations']
|
|
8
|
+
|
|
9
|
+
export function readMigrations(root, dir = DIRS.find((d) => existsSync(join(root, d)))) {
|
|
10
|
+
if (!dir) return []
|
|
11
|
+
const base = join(root, dir)
|
|
12
|
+
const journal = join(base, 'meta', '_journal.json')
|
|
13
|
+
if (existsSync(journal))
|
|
14
|
+
return JSON.parse(readFileSync(journal, 'utf8')).entries.map((e) => ({
|
|
15
|
+
tag: e.tag,
|
|
16
|
+
sql: readFileSync(join(base, `${e.tag}.sql`), 'utf8'),
|
|
17
|
+
}))
|
|
18
|
+
if (!existsSync(base)) return []
|
|
19
|
+
return readdirSync(base)
|
|
20
|
+
.sort()
|
|
21
|
+
.flatMap((name) => {
|
|
22
|
+
const file = name.endsWith('.sql') ? join(base, name) : join(base, name, 'migration.sql')
|
|
23
|
+
return existsSync(file)
|
|
24
|
+
? [{ tag: name.replace(/\.sql$/, ''), sql: readFileSync(file, 'utf8') }]
|
|
25
|
+
: []
|
|
26
|
+
})
|
|
27
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** What a tab compares, to learn a socket opened before it signed in isn't its own. Opaque, and only the same browser sees it. */
|
|
2
|
+
export async function sessionOf(ctx: unknown) {
|
|
3
|
+
const id = String((ctx as { user?: { id?: string | number } })?.user?.id ?? '')
|
|
4
|
+
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`kerf:${id}`))
|
|
5
|
+
return btoa(String.fromCharCode(...new Uint8Array(hash).slice(0, 12)))
|
|
6
|
+
}
|
package/src/mux.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// The server's half of `link.ts`: one WebSocket, many lines, each a connection of its own. A `c` line is an `attach`, a
|
|
2
|
+
// `r` line is a hub connection, and neither knows it isn't alone, so `id`, `exceptSelf`, `left`, buckets and session
|
|
3
|
+
// re-checks stay per tab. `limits.connections` counts the socket, which is what it was protecting.
|
|
4
|
+
|
|
5
|
+
import { StartError } from './data'
|
|
6
|
+
import type { Scope } from './exec'
|
|
7
|
+
import { sessionOf } from './mux-session'
|
|
8
|
+
import { hub, validBody, type Conn, type Hub, type Sink } from './hub'
|
|
9
|
+
import { attach, type Attached, type Peer } from './socket'
|
|
10
|
+
|
|
11
|
+
const LINES = 64
|
|
12
|
+
const HIGH = 64 * 1024
|
|
13
|
+
|
|
14
|
+
interface Physical {
|
|
15
|
+
send(text: string): void
|
|
16
|
+
close(code: number, reason?: string): void
|
|
17
|
+
backlog(): number
|
|
18
|
+
}
|
|
19
|
+
type Open = { kind: 'c'; a: Promise<Attached> } | { kind: 'r'; c: Promise<Conn | undefined> }
|
|
20
|
+
|
|
21
|
+
const parsed = (text: string): unknown => {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(text)
|
|
24
|
+
} catch {
|
|
25
|
+
return undefined
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const counts = new WeakMap<Hub, Map<string, number>>()
|
|
30
|
+
const byUser = (h: Hub) => {
|
|
31
|
+
let m = counts.get(h)
|
|
32
|
+
if (!m) counts.set(h, (m = new Map()))
|
|
33
|
+
return m
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface Socket {
|
|
37
|
+
peer: Physical
|
|
38
|
+
request: Request
|
|
39
|
+
scope: Scope
|
|
40
|
+
h: Hub
|
|
41
|
+
lines: Map<string, Open>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function openLines(
|
|
45
|
+
{ peer, request, scope, h, lines }: Socket,
|
|
46
|
+
end: (id: string, code: number, reason?: string) => void,
|
|
47
|
+
) {
|
|
48
|
+
function openC(id: string) {
|
|
49
|
+
const p: Peer = {
|
|
50
|
+
send: (t) => {
|
|
51
|
+
if (lines.has(id)) peer.send(`f:${id}:${t}`)
|
|
52
|
+
},
|
|
53
|
+
close: (code, reason) => end(id, code, reason),
|
|
54
|
+
backlog: () => peer.backlog(),
|
|
55
|
+
}
|
|
56
|
+
lines.set(id, {
|
|
57
|
+
kind: 'c',
|
|
58
|
+
a: attach(p, request, scope, h, true).catch(() => {
|
|
59
|
+
end(id, 1011)
|
|
60
|
+
return { message() {}, close() {} } as unknown as Attached
|
|
61
|
+
}),
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function openR(id: string, hello: string) {
|
|
66
|
+
const body = parsed(hello)
|
|
67
|
+
if (!validBody(body) || body.k)
|
|
68
|
+
return peer.send(
|
|
69
|
+
`x:${id}:4000:${JSON.stringify({ code: 'Q002', message: 'a realtime line opened with a body of the wrong shape' })}`,
|
|
70
|
+
)
|
|
71
|
+
const sink: Sink = {
|
|
72
|
+
write: (event, data) => {
|
|
73
|
+
if (lines.has(id)) peer.send(`r:${id}:${event}:${data}`)
|
|
74
|
+
},
|
|
75
|
+
ping: () => {
|
|
76
|
+
if (lines.has(id)) peer.send(`r:${id}:ping:`)
|
|
77
|
+
},
|
|
78
|
+
backlog: () => peer.backlog(),
|
|
79
|
+
close: () => end(id, 1000),
|
|
80
|
+
}
|
|
81
|
+
const c = h.connect(request, scope, body, sink, true).catch((e) => {
|
|
82
|
+
const out =
|
|
83
|
+
e instanceof StartError
|
|
84
|
+
? { code: e.code, message: e.message }
|
|
85
|
+
: { message: 'Realtime failed.' }
|
|
86
|
+
end(id, 4000, JSON.stringify(out))
|
|
87
|
+
return undefined
|
|
88
|
+
})
|
|
89
|
+
lines.set(id, { kind: 'r', c })
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return { openC, openR }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function messages(
|
|
96
|
+
{ peer, request, scope, h, lines }: Socket,
|
|
97
|
+
{
|
|
98
|
+
allowed,
|
|
99
|
+
end,
|
|
100
|
+
shut,
|
|
101
|
+
openC,
|
|
102
|
+
openR,
|
|
103
|
+
}: {
|
|
104
|
+
allowed: () => boolean
|
|
105
|
+
end: (id: string, code: number, reason?: string) => void
|
|
106
|
+
shut: (id: string, line: Open) => void
|
|
107
|
+
openC: (id: string) => void
|
|
108
|
+
openR: (id: string, hello: string) => void
|
|
109
|
+
},
|
|
110
|
+
) {
|
|
111
|
+
return (text: string) => {
|
|
112
|
+
if (text === 'p') return peer.send('p')
|
|
113
|
+
if (text.length > h.limits.body + 64) return peer.close(1009, 'too big')
|
|
114
|
+
if (!allowed()) {
|
|
115
|
+
scope.options.onDiagnostic?.({
|
|
116
|
+
code: 'R008',
|
|
117
|
+
severity: 'error',
|
|
118
|
+
message: `R008: one browser sent over ${h.limits.perSecond * 8} messages a second`,
|
|
119
|
+
})
|
|
120
|
+
return peer.close(1008, 'rate limit')
|
|
121
|
+
}
|
|
122
|
+
const at = text.indexOf(':', 2)
|
|
123
|
+
const id = text.slice(2, at),
|
|
124
|
+
rest = text.slice(at + 1)
|
|
125
|
+
const line = lines.get(id)
|
|
126
|
+
if (text[0] === 'f') {
|
|
127
|
+
if (line?.kind === 'c') void line.a.then((a) => a.message(rest))
|
|
128
|
+
else if (line) {
|
|
129
|
+
let body: Body | undefined
|
|
130
|
+
try {
|
|
131
|
+
body = JSON.parse(rest)
|
|
132
|
+
} catch {}
|
|
133
|
+
if (validBody(body))
|
|
134
|
+
void line.c
|
|
135
|
+
.then((c) => c && h.change(c, request, scope.options, body))
|
|
136
|
+
.catch(() => end(id, 1011))
|
|
137
|
+
}
|
|
138
|
+
} else if (text[0] === 'x') {
|
|
139
|
+
if (line) shut(id, line)
|
|
140
|
+
} else if (text[0] === 'o') {
|
|
141
|
+
if (line) return
|
|
142
|
+
if (lines.size >= LINES) return peer.send(`x:${id}:1008:too many lines`)
|
|
143
|
+
if (rest[0] === 'c') openC(id)
|
|
144
|
+
else if (rest[0] === 'r') openR(id, rest.slice(2))
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface Muxed {
|
|
150
|
+
message(text: string): void
|
|
151
|
+
close(): void
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function muxed(
|
|
155
|
+
peer: Physical,
|
|
156
|
+
request: Request,
|
|
157
|
+
scope: Scope,
|
|
158
|
+
h: Hub = hub(),
|
|
159
|
+
): Promise<Muxed> {
|
|
160
|
+
const ctx = await scope.ctx()
|
|
161
|
+
const user = (ctx as { user?: { id?: string } }).user?.id
|
|
162
|
+
const users = byUser(h)
|
|
163
|
+
if (user !== undefined) {
|
|
164
|
+
if ((users.get(user) ?? 0) >= h.limits.connections) {
|
|
165
|
+
peer.close(1008, 'too many sockets')
|
|
166
|
+
scope.options.onDiagnostic?.({
|
|
167
|
+
code: 'R009',
|
|
168
|
+
severity: 'error',
|
|
169
|
+
message: `R009: user \`${user}\` already has ${h.limits.connections} sockets`,
|
|
170
|
+
})
|
|
171
|
+
return { message() {}, close() {} }
|
|
172
|
+
}
|
|
173
|
+
users.set(user, (users.get(user) ?? 0) + 1)
|
|
174
|
+
}
|
|
175
|
+
const lines = new Map<string, Open>()
|
|
176
|
+
const socket = { peer, request, scope, h, lines }
|
|
177
|
+
const bucket = { tokens: h.limits.burst * 8, at: Date.now() }
|
|
178
|
+
let closed = false
|
|
179
|
+
|
|
180
|
+
/** Every tab has the per-socket bucket; this is what stops them adding up without end. */
|
|
181
|
+
const allowed = () => {
|
|
182
|
+
const now = Date.now(),
|
|
183
|
+
rate = h.limits.perSecond * 8
|
|
184
|
+
bucket.tokens = Math.min(h.limits.burst * 8, bucket.tokens + ((now - bucket.at) * rate) / 1000)
|
|
185
|
+
bucket.at = now
|
|
186
|
+
return bucket.tokens-- >= 1
|
|
187
|
+
}
|
|
188
|
+
const end = (id: string, code: number, reason = '') => {
|
|
189
|
+
if (!lines.delete(id) || closed) return
|
|
190
|
+
peer.send(`x:${id}:${code}:${reason}`)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const { openC, openR } = openLines(socket, end)
|
|
194
|
+
|
|
195
|
+
function shut(id: string, line: Open) {
|
|
196
|
+
lines.delete(id)
|
|
197
|
+
if (line.kind === 'c') void line.a.then((a) => a.close())
|
|
198
|
+
else void line.c.then((c) => c && h.close(c))
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const drain = setInterval(() => {
|
|
202
|
+
if (peer.backlog() >= HIGH) return
|
|
203
|
+
for (const l of lines.values()) if (l.kind === 'r') void l.c.then((c) => c && h.drain(c))
|
|
204
|
+
}, 100)
|
|
205
|
+
;(drain as { unref?(): void }).unref?.()
|
|
206
|
+
|
|
207
|
+
const release = () => {
|
|
208
|
+
clearInterval(drain)
|
|
209
|
+
if (user === undefined) return
|
|
210
|
+
const n = (users.get(user) ?? 1) - 1
|
|
211
|
+
if (n) users.set(user, n)
|
|
212
|
+
else users.delete(user)
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
peer.send(`h:${await sessionOf(ctx)}`)
|
|
216
|
+
} catch (e) {
|
|
217
|
+
release() // the caller never gets a close() for a socket that failed to open
|
|
218
|
+
throw e
|
|
219
|
+
}
|
|
220
|
+
const message = messages(socket, { allowed, end, shut, openC, openR })
|
|
221
|
+
return {
|
|
222
|
+
message(text) {
|
|
223
|
+
return message(text)
|
|
224
|
+
},
|
|
225
|
+
close() {
|
|
226
|
+
if (closed) return
|
|
227
|
+
closed = true
|
|
228
|
+
for (const [id, line] of Array.from(lines)) shut(id, line)
|
|
229
|
+
release()
|
|
230
|
+
},
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// The `image: 'auto'` default card (research 20 §4.1, §10): the page's title and description, the app's name and its
|
|
2
|
+
// address, on the app's look. Colours and faces come from `site.card`, which veneer and the text plugin fill in; one
|
|
3
|
+
// image goes to every feed, so a card has one scheme, and each is checked against both kinds of feed.
|
|
4
|
+
import { untrack } from '@kerf-js/core'
|
|
5
|
+
import type { Site } from '@kerf-js/core/ssr'
|
|
6
|
+
import { cardTitleSize } from '../derive.mjs'
|
|
7
|
+
|
|
8
|
+
type CardColors = NonNullable<NonNullable<Site['card']>['light']>
|
|
9
|
+
|
|
10
|
+
export interface DefaultProps {
|
|
11
|
+
title: string
|
|
12
|
+
description: string
|
|
13
|
+
site: Site
|
|
14
|
+
path?: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const SCHEMES: Record<'dark' | 'light', Required<CardColors>> = {
|
|
18
|
+
dark: { background: '#100f0b', text: '#ebe8e0', subtle: '#a8a59d', accent: '#5fcf97' },
|
|
19
|
+
light: { background: '#f7f4ec', text: '#1f1d18', subtle: '#615e56', accent: '#1f7a50' },
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const family = (name: string | undefined) => (name ? `'${name}',Inter` : 'Inter')
|
|
23
|
+
|
|
24
|
+
/** The title without the template the site wraps around it: the card shows the site's name on its own. */
|
|
25
|
+
function heading(title: string, template: string | undefined) {
|
|
26
|
+
const [before = '', after = ''] = template?.split('%s') ?? []
|
|
27
|
+
return title.startsWith(before) &&
|
|
28
|
+
title.endsWith(after) &&
|
|
29
|
+
title.length > before.length + after.length
|
|
30
|
+
? title.slice(before.length, title.length - after.length)
|
|
31
|
+
: title
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Everything the card draws, worked out once: a card renders one time, to a string. */
|
|
35
|
+
function look({ title, description, site, path }: DefaultProps) {
|
|
36
|
+
const card = site.card ?? {}
|
|
37
|
+
const scheme = card.scheme ?? 'dark'
|
|
38
|
+
const c = { ...SCHEMES[scheme], ...card[scheme] }
|
|
39
|
+
for (const k of ['background', 'text', 'subtle', 'accent'] as const) if (card[k]) c[k] = card[k]!
|
|
40
|
+
const host = site.url?.replace(/^https?:\/\//, '').replace(/\/+$/, '')
|
|
41
|
+
const shown = heading(title, site.title)
|
|
42
|
+
return {
|
|
43
|
+
c,
|
|
44
|
+
description,
|
|
45
|
+
title: shown,
|
|
46
|
+
name: site.name ?? '',
|
|
47
|
+
size: cardTitleSize(shown),
|
|
48
|
+
display: family(card.fonts?.display?.family),
|
|
49
|
+
body: family(card.fonts?.body?.family),
|
|
50
|
+
address: host && host + (path && path !== '/' ? path.replace(/[?#].*/, '') : ''),
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function DefaultCard(props: DefaultProps) {
|
|
55
|
+
const { c, title, description, name, size, display, body, address } = untrack(() => look(props))
|
|
56
|
+
return (
|
|
57
|
+
<div
|
|
58
|
+
style={`display:flex;flex-direction:column;width:100%;height:100%;padding:68px 76px 60px;background-color:${c.background};color:${c.text};font-family:${body}`}
|
|
59
|
+
>
|
|
60
|
+
<div
|
|
61
|
+
style={`display:flex;align-items:center;font-family:${display};font-size:32px;font-weight:600;letter-spacing:-0.3px`}
|
|
62
|
+
>
|
|
63
|
+
<div
|
|
64
|
+
style={`width:22px;height:22px;border-radius:5px;background-color:${c.accent};margin-right:16px`}
|
|
65
|
+
/>
|
|
66
|
+
<span>{name}</span>
|
|
67
|
+
</div>
|
|
68
|
+
<div style="display:flex;flex-direction:column;justify-content:center;flex:1;min-height:0;padding:24px 0">
|
|
69
|
+
<div
|
|
70
|
+
style={`display:block;font-family:${display};font-size:${size}px;font-weight:700;line-height:1.08;letter-spacing:-1.5px;overflow-wrap:anywhere;line-clamp:3`}
|
|
71
|
+
>
|
|
72
|
+
{title}
|
|
73
|
+
</div>
|
|
74
|
+
{description ? (
|
|
75
|
+
<div
|
|
76
|
+
style={`display:block;margin-top:26px;font-size:30px;line-height:1.38;color:${c.subtle};line-clamp:3`}
|
|
77
|
+
>
|
|
78
|
+
{description}
|
|
79
|
+
</div>
|
|
80
|
+
) : null}
|
|
81
|
+
</div>
|
|
82
|
+
{address ? (
|
|
83
|
+
<div
|
|
84
|
+
style={`display:flex;align-items:center;font-size:24px;color:${c.subtle};border-top:1px solid ${c.subtle}44;padding-top:22px`}
|
|
85
|
+
>
|
|
86
|
+
{address}
|
|
87
|
+
</div>
|
|
88
|
+
) : null}
|
|
89
|
+
</div>
|
|
90
|
+
)
|
|
91
|
+
}
|
package/src/og/fonts.mjs
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Fonts in any format the web uses, for either Takumi build. Takumi native reads TTF, OTF, WOFF and WOFF2; the wasm
|
|
2
|
+
// build doesn't read WOFF (1.0), and Satori never read WOFF2. So WOFF is unpacked to its SFNT here (zlib per table,
|
|
3
|
+
// with the platform's DecompressionStream, which Node, Bun and workerd all have), and every build gets every format.
|
|
4
|
+
|
|
5
|
+
const tag = (b, o) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3])
|
|
6
|
+
|
|
7
|
+
/** 'woff' | 'woff2' | 'ttf' | 'otf' | null, from the file's magic number. */
|
|
8
|
+
export function fontFormat(bytes) {
|
|
9
|
+
const t = tag(bytes, 0)
|
|
10
|
+
if (t === 'wOFF') return 'woff'
|
|
11
|
+
if (t === 'wOF2') return 'woff2'
|
|
12
|
+
if (t === 'OTTO') return 'otf'
|
|
13
|
+
if (t === '\0\x01\0\0' || t === 'true') return 'ttf'
|
|
14
|
+
return null
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function inflate(bytes) {
|
|
18
|
+
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate'))
|
|
19
|
+
return new Uint8Array(await new Response(stream).arrayBuffer())
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** WOFF 1.0 → the SFNT (TTF/OTF) it wraps (W3C WOFF 1.0 §4–5). */
|
|
23
|
+
export async function woffToSfnt(woff) {
|
|
24
|
+
const v = new DataView(woff.buffer, woff.byteOffset, woff.byteLength)
|
|
25
|
+
const numTables = v.getUint16(12)
|
|
26
|
+
const tables = []
|
|
27
|
+
for (let i = 0; i < numTables; i++) {
|
|
28
|
+
const at = 44 + i * 20
|
|
29
|
+
const offset = v.getUint32(at + 4),
|
|
30
|
+
compLength = v.getUint32(at + 8),
|
|
31
|
+
origLength = v.getUint32(at + 12)
|
|
32
|
+
const raw = woff.subarray(offset, offset + compLength)
|
|
33
|
+
tables.push({
|
|
34
|
+
tag: v.getUint32(at),
|
|
35
|
+
checksum: v.getUint32(at + 16),
|
|
36
|
+
data: compLength < origLength ? await inflate(raw) : raw,
|
|
37
|
+
})
|
|
38
|
+
}
|
|
39
|
+
let size = 12 + 16 * numTables
|
|
40
|
+
for (const t of tables) size += (t.data.length + 3) & ~3
|
|
41
|
+
const out = new Uint8Array(size)
|
|
42
|
+
const w = new DataView(out.buffer)
|
|
43
|
+
const log2 = Math.floor(Math.log2(numTables))
|
|
44
|
+
w.setUint32(0, v.getUint32(4)) // flavor
|
|
45
|
+
w.setUint16(4, numTables)
|
|
46
|
+
w.setUint16(6, 16 << log2)
|
|
47
|
+
w.setUint16(8, log2)
|
|
48
|
+
w.setUint16(10, numTables * 16 - (16 << log2))
|
|
49
|
+
let offset = 12 + 16 * numTables
|
|
50
|
+
tables.forEach((t, i) => {
|
|
51
|
+
const at = 12 + i * 16
|
|
52
|
+
w.setUint32(at, t.tag)
|
|
53
|
+
w.setUint32(at + 4, t.checksum)
|
|
54
|
+
w.setUint32(at + 8, offset)
|
|
55
|
+
w.setUint32(at + 12, t.data.length)
|
|
56
|
+
out.set(t.data, offset)
|
|
57
|
+
offset += (t.data.length + 3) & ~3
|
|
58
|
+
})
|
|
59
|
+
return out
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** `{ name, data, weight?, style? }[]` in any format → the same with bytes every Takumi build reads. */
|
|
63
|
+
export async function normalizeFonts(fonts) {
|
|
64
|
+
return Promise.all(
|
|
65
|
+
fonts.map(async (f) => {
|
|
66
|
+
const data = f.data instanceof Uint8Array ? f.data : new Uint8Array(f.data)
|
|
67
|
+
const format = fontFormat(data)
|
|
68
|
+
if (!format) throw new Error(`kerf/og: font "${f.name}" isn't TTF, OTF, WOFF or WOFF2`)
|
|
69
|
+
return { ...f, data: format === 'woff' ? await woffToSfnt(data) : data }
|
|
70
|
+
}),
|
|
71
|
+
)
|
|
72
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// `<img src>` in a card: fetched at render with a timeout and a size cap (research 20 §4.1), cached by URL, and left
|
|
2
|
+
// out of the card (keeping its box, so the layout doesn't move) when the fetch fails, instead of failing the request.
|
|
3
|
+
|
|
4
|
+
/** An LRU of fetched image bytes by URL, capped by total bytes. */
|
|
5
|
+
export function imageCache(maxBytes = 32 << 20) {
|
|
6
|
+
const map = new Map()
|
|
7
|
+
let bytes = 0
|
|
8
|
+
return {
|
|
9
|
+
get(src) {
|
|
10
|
+
const hit = map.get(src)
|
|
11
|
+
if (hit) {
|
|
12
|
+
map.delete(src)
|
|
13
|
+
map.set(src, hit)
|
|
14
|
+
}
|
|
15
|
+
return hit
|
|
16
|
+
},
|
|
17
|
+
set(src, data) {
|
|
18
|
+
if (data.length > maxBytes) return
|
|
19
|
+
map.set(src, data)
|
|
20
|
+
bytes += data.length
|
|
21
|
+
for (const [k, v] of map) {
|
|
22
|
+
if (bytes <= maxBytes) break
|
|
23
|
+
map.delete(k)
|
|
24
|
+
bytes -= v.length
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Whether an IP address is one the open internet can't reach: loopback, private, link-local (cloud metadata), CGNAT… */
|
|
31
|
+
export function privateAddress(ip) {
|
|
32
|
+
const v4 = /^(?:::ffff:)?(\d+)\.(\d+)\.(\d+)\.(\d+)$/i.exec(ip)
|
|
33
|
+
if (v4) {
|
|
34
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])]
|
|
35
|
+
return (
|
|
36
|
+
a === 0 ||
|
|
37
|
+
a === 10 ||
|
|
38
|
+
a === 127 ||
|
|
39
|
+
(a === 100 && b >= 64 && b <= 127) ||
|
|
40
|
+
(a === 169 && b === 254) ||
|
|
41
|
+
(a === 172 && b >= 16 && b <= 31) ||
|
|
42
|
+
(a === 192 && b === 168) ||
|
|
43
|
+
(a === 198 && (b === 18 || b === 19)) ||
|
|
44
|
+
a >= 224
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
const v6 = ip.toLowerCase().replace(/^\[|\]$/g, '')
|
|
48
|
+
return (
|
|
49
|
+
v6 === '::' ||
|
|
50
|
+
v6 === '::1' ||
|
|
51
|
+
['fc', 'fd'].some((p) => v6.startsWith(p)) || // unique local
|
|
52
|
+
['fe8', 'fe9', 'fea', 'feb'].some((p) => v6.startsWith(p)) || // link-local
|
|
53
|
+
v6.startsWith('ff') || // multicast
|
|
54
|
+
v6.startsWith('::ffff:') // mapped v4 in hex form: refused rather than decoded
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The default `allow`: https only, to a host whose every address is public, so a card can't be pointed at the
|
|
60
|
+
* server's own network (`localhost`, `10.…`, `169.254.169.254`). Where there's no DNS module, literal addresses only.
|
|
61
|
+
*/
|
|
62
|
+
export async function publicHttps(url) {
|
|
63
|
+
if (url.protocol !== 'https:') return false
|
|
64
|
+
const host = url.hostname.replace(/^\[|\]$/g, '')
|
|
65
|
+
if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.internal'))
|
|
66
|
+
return false
|
|
67
|
+
if (/^[\d.]+$/.test(host) || host.includes(':')) return !privateAddress(host)
|
|
68
|
+
let dns
|
|
69
|
+
try {
|
|
70
|
+
dns = await import('node:dns/promises')
|
|
71
|
+
} catch {
|
|
72
|
+
return true
|
|
73
|
+
}
|
|
74
|
+
const addresses = await dns.lookup(host, { all: true, verbatim: true })
|
|
75
|
+
return addresses.length > 0 && addresses.every((a) => !privateAddress(a.address))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Fetches every remote `src` in the tree. `allow(url)` (may be async) decides which hosts a card may load from (the
|
|
80
|
+
* on-demand route renders data from `load`, so this is the SSRF guard); the default, `publicHttps`, allows https to
|
|
81
|
+
* public addresses only.
|
|
82
|
+
* Returns the images Takumi needs, and the srcs that failed.
|
|
83
|
+
*/
|
|
84
|
+
export async function loadImages(
|
|
85
|
+
srcs,
|
|
86
|
+
{
|
|
87
|
+
cache,
|
|
88
|
+
timeoutMs = 1500,
|
|
89
|
+
maxBytes = 4 << 20,
|
|
90
|
+
allow = publicHttps,
|
|
91
|
+
fetch = globalThis.fetch,
|
|
92
|
+
} = {},
|
|
93
|
+
) {
|
|
94
|
+
const images = [],
|
|
95
|
+
failed = []
|
|
96
|
+
await Promise.all(
|
|
97
|
+
[...new Set(srcs)].map(async (src) => {
|
|
98
|
+
if (src.startsWith('data:')) return // Takumi decodes data URIs itself
|
|
99
|
+
const hit = cache?.get(src)
|
|
100
|
+
if (hit) return void images.push({ src, data: hit })
|
|
101
|
+
try {
|
|
102
|
+
const url = new URL(src)
|
|
103
|
+
if (!(await allow(url))) throw new Error('not allowed')
|
|
104
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), redirect: 'error' })
|
|
105
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
|
106
|
+
if (!res.headers.get('content-type')?.startsWith('image/')) throw new Error('not an image')
|
|
107
|
+
if (Number(res.headers.get('content-length') ?? 0) > maxBytes) throw new Error('too large')
|
|
108
|
+
const data = new Uint8Array(await res.arrayBuffer())
|
|
109
|
+
if (data.length > maxBytes) throw new Error('too large')
|
|
110
|
+
cache?.set(src, data)
|
|
111
|
+
images.push({ src, data })
|
|
112
|
+
} catch (e) {
|
|
113
|
+
failed.push({
|
|
114
|
+
src,
|
|
115
|
+
reason:
|
|
116
|
+
e?.name === 'TimeoutError'
|
|
117
|
+
? `timed out after ${timeoutMs} ms`
|
|
118
|
+
: String(e?.message ?? e),
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
}),
|
|
122
|
+
)
|
|
123
|
+
return { images, failed }
|
|
124
|
+
}
|