@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/index.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// @kerf-js/start: what route files import (research 25) and server modules define (research 27). A route module exports
|
|
2
|
+
// its component (`default`) and, when it needs them, `load` (async data, often `await q.fetch()`), `meta` (research
|
|
3
|
+
// 20 §3: static, awaited before the first byte, never reactive) and `prerender` (the params `kerf build` writes as
|
|
4
|
+
// static pages, with their share cards; `true` on a route without params).
|
|
5
|
+
//
|
|
6
|
+
// // src/routes/users/[id].tsx
|
|
7
|
+
// export const load = async ({ params }: LoadArgs<'/users/[id]'>) => (await db.user(params.id)) ?? notFound()
|
|
8
|
+
// export const meta: Meta<typeof load> = ({ data }) => ({ title: data.name, description: data.bio })
|
|
9
|
+
// export default function User(props: RouteProps<typeof load, '/users/[id]'>) { return <h1>{props.data.name}</h1> }
|
|
10
|
+
|
|
11
|
+
import type { Merged, Meta as MetaObject, Site } from '@kerf-js/core/ssr'
|
|
12
|
+
import type { Context } from './data'
|
|
13
|
+
|
|
14
|
+
export { Link, currentPath } from './view'
|
|
15
|
+
export { Form, type FormApi, type FormProps } from './form'
|
|
16
|
+
export { navigate, type NavigateOptions } from './router'
|
|
17
|
+
export {
|
|
18
|
+
query,
|
|
19
|
+
mutation,
|
|
20
|
+
redirect,
|
|
21
|
+
raise,
|
|
22
|
+
invalid,
|
|
23
|
+
invalidate,
|
|
24
|
+
after,
|
|
25
|
+
preview,
|
|
26
|
+
serverCall,
|
|
27
|
+
cache,
|
|
28
|
+
skip,
|
|
29
|
+
isRedirect,
|
|
30
|
+
stale,
|
|
31
|
+
StartError,
|
|
32
|
+
FnError,
|
|
33
|
+
type Query,
|
|
34
|
+
type Mutation,
|
|
35
|
+
type QueryDef,
|
|
36
|
+
type MutationDef,
|
|
37
|
+
type AuthScope,
|
|
38
|
+
type Context,
|
|
39
|
+
type Errors,
|
|
40
|
+
type FnOptions,
|
|
41
|
+
type Life,
|
|
42
|
+
type LiveMode,
|
|
43
|
+
type LiveOptions,
|
|
44
|
+
type LiveQuery,
|
|
45
|
+
type LiveStatus,
|
|
46
|
+
type OptimisticCache,
|
|
47
|
+
type Redirect,
|
|
48
|
+
type Skip,
|
|
49
|
+
type StandardSchemaV1,
|
|
50
|
+
} from './data'
|
|
51
|
+
export {
|
|
52
|
+
stream,
|
|
53
|
+
type Stream,
|
|
54
|
+
type StreamDef,
|
|
55
|
+
type StreamOptions,
|
|
56
|
+
type StreamStatus,
|
|
57
|
+
} from './stream'
|
|
58
|
+
export {
|
|
59
|
+
channel,
|
|
60
|
+
sharedState,
|
|
61
|
+
type Channel,
|
|
62
|
+
type ChannelDef,
|
|
63
|
+
type ChannelStatus,
|
|
64
|
+
type Connection,
|
|
65
|
+
type PublishOptions,
|
|
66
|
+
type SharedBox,
|
|
67
|
+
type SharedState,
|
|
68
|
+
} from './channel'
|
|
69
|
+
export {
|
|
70
|
+
liveHealth,
|
|
71
|
+
realtime,
|
|
72
|
+
realtimeStats,
|
|
73
|
+
topic,
|
|
74
|
+
tracked,
|
|
75
|
+
type Limits,
|
|
76
|
+
type LiveState,
|
|
77
|
+
type RealtimeOptions,
|
|
78
|
+
type Topic,
|
|
79
|
+
type Tracked,
|
|
80
|
+
} from './hub'
|
|
81
|
+
export {
|
|
82
|
+
dbChanges,
|
|
83
|
+
type Change,
|
|
84
|
+
type ChangeOptions,
|
|
85
|
+
type Probe,
|
|
86
|
+
type Sink,
|
|
87
|
+
type Source,
|
|
88
|
+
} from './changes'
|
|
89
|
+
export { memoryBus, type Bus } from './bus'
|
|
90
|
+
export {
|
|
91
|
+
listInput,
|
|
92
|
+
type DbAdapter,
|
|
93
|
+
type ListPage,
|
|
94
|
+
type ListParams,
|
|
95
|
+
type ListRequest,
|
|
96
|
+
type ListSource,
|
|
97
|
+
type ListSpec,
|
|
98
|
+
type SourceSpec,
|
|
99
|
+
} from './list'
|
|
100
|
+
export type { Merged, Site } from '@kerf-js/core/ssr'
|
|
101
|
+
|
|
102
|
+
/** Filled by the generated `.kerf/routes.d.ts` with every route file's path (`'/users/[id]': true`). */
|
|
103
|
+
export interface RouteFiles {}
|
|
104
|
+
|
|
105
|
+
/** Route paths as files name them (`/users/[id]`); any string until `.kerf/routes.d.ts` is generated. */
|
|
106
|
+
// oxlint-disable-next-line typescript/no-redundant-type-constituents -- `RouteFiles` is empty here and filled by a generated file
|
|
107
|
+
export type RoutePath = keyof RouteFiles extends never ? string : keyof RouteFiles & string
|
|
108
|
+
|
|
109
|
+
/** `'/users/[id]/posts/[...rest]'` → `{ id: string; rest: string }`. */
|
|
110
|
+
export type ParamsOf<P extends string> = string extends P
|
|
111
|
+
? Record<string, string>
|
|
112
|
+
: { [K in ParamNames<P>]: string }
|
|
113
|
+
type ParamNames<P extends string> = P extends `${string}[${infer N}]${infer Rest}`
|
|
114
|
+
? (N extends `...${infer S}` ? S : N) | ParamNames<Rest>
|
|
115
|
+
: never
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* What `load` gets. `request` is the incoming request (headers, cookies), its `url` the page's own on a full load and on
|
|
119
|
+
* a client navigation alike (never the `/_kerf/data/<path>` endpoint the browser fetched); `signal` aborts with it; `ctx` is what server
|
|
120
|
+
* functions get (the app's part from `src/context.server.ts`). `await listTodos.fetch()` here shares the request
|
|
121
|
+
* cache with the page's `listTodos()`, and `redirect()` answers 307.
|
|
122
|
+
*/
|
|
123
|
+
export interface LoadArgs<P extends string = string> {
|
|
124
|
+
params: ParamsOf<P>
|
|
125
|
+
request: Request
|
|
126
|
+
signal: AbortSignal
|
|
127
|
+
ctx: Context
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
declare const notFoundBrand: unique symbol
|
|
131
|
+
/** Return (or throw) it from `load`: the page renders the 404 route with status 404, and `meta` isn't called. */
|
|
132
|
+
export interface NotFound {
|
|
133
|
+
readonly isNotFound: true
|
|
134
|
+
readonly [notFoundBrand]?: true
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The not-found result, in the shape router-core's loaders recognise (`isNotFound`). */
|
|
138
|
+
export function notFound(): NotFound {
|
|
139
|
+
return { isNotFound: true }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
type AnyLoad = (args: never) => unknown
|
|
143
|
+
|
|
144
|
+
/** A loader's data: what it resolves to, without `notFound()`. Top-level promise fields are deferred (streamed). */
|
|
145
|
+
export type DataOf<L> = L extends AnyLoad ? Exclude<Awaited<ReturnType<L>>, NotFound> : undefined
|
|
146
|
+
|
|
147
|
+
/** The data `meta` and cards see: deferred (promise) fields left out, since they're still streaming (H007). */
|
|
148
|
+
export type Settled<D> = D extends object
|
|
149
|
+
? { [K in keyof D as D[K] extends PromiseLike<unknown> ? never : K]: D[K] }
|
|
150
|
+
: D
|
|
151
|
+
|
|
152
|
+
/** A route or layout component's props. `children` is the next level (layouts render it where the page goes). */
|
|
153
|
+
export interface RouteProps<L = undefined, P extends string = string> {
|
|
154
|
+
params: ParamsOf<P>
|
|
155
|
+
data: DataOf<L>
|
|
156
|
+
children?: unknown
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export type { MetaObject }
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* `export const meta: Meta<typeof load> = ({ params, data }) => ({ title: data.name })`. Plain data, computed once
|
|
163
|
+
* per request after the loaders and before the first byte; it can't read boxes (H006) or deferred fields (H007).
|
|
164
|
+
*/
|
|
165
|
+
export type Meta<L = undefined, P extends string = string> =
|
|
166
|
+
| MetaObject
|
|
167
|
+
| ((args: { params: ParamsOf<P>; data: Settled<DataOf<L>> }) => MetaObject | Promise<MetaObject>)
|
|
168
|
+
|
|
169
|
+
/** A card's props (`*.og.tsx`, research 20 §4): the route's params and settled data, the merged metadata, the site. */
|
|
170
|
+
export interface OgProps<L = undefined, P extends string = string> {
|
|
171
|
+
params: ParamsOf<P>
|
|
172
|
+
data: Settled<DataOf<L>>
|
|
173
|
+
meta: Merged
|
|
174
|
+
site: Site
|
|
175
|
+
/** The page's path, and the title and description the built-in card would show. */
|
|
176
|
+
path: string
|
|
177
|
+
title: string
|
|
178
|
+
description: string
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The params of a param route whose cards `kerf build` renders (static routes always are). */
|
|
182
|
+
export type Prerender<P extends string = string> =
|
|
183
|
+
| ParamsOf<P>[]
|
|
184
|
+
| (() => ParamsOf<P>[] | Promise<ParamsOf<P>[]>)
|
package/src/inline.mjs
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
// A page's stylesheets. All of them inline while the document fits the first flight; past that, the rules the server's
|
|
2
|
+
// HTML can reach, with every sheet behind them as an immutable link that doesn't hold the paint.
|
|
3
|
+
|
|
4
|
+
import { esc } from '@kerf-js/core/markup'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The one order every app shares. Layers rank by first appearance, so this goes before any sheet: veneer's own too, or the
|
|
8
|
+
* order would follow whichever component's sheet a page lists first.
|
|
9
|
+
*/
|
|
10
|
+
export const LAYER_ORDER =
|
|
11
|
+
'@layer veneer,app,theme,base,components,utilities;@layer veneer.tokens,veneer.base,veneer.signature,veneer.layout,veneer.components,veneer.inputs,veneer.inputs-rich,veneer.data,veneer.app,veneer.flows,veneer.marketing,veneer.canvas,veneer.flow;'
|
|
12
|
+
/** Head plus shell, in compressed bytes: about what a first flight carries, less headers and TLS. */
|
|
13
|
+
export const FIRST_PAINT_BYTES = 12 * 1024
|
|
14
|
+
/** Compression at the server's brotli 5, measured on built veneer pages (5.9 to 6.2 for CSS, 3.7 to 4 for HTML). */
|
|
15
|
+
const CSS_RATIO = 6
|
|
16
|
+
const HTML_RATIO = 4
|
|
17
|
+
const CRITICAL_MAX = 64
|
|
18
|
+
/** The most stylesheet text one page carries inline with `criticalCss: false`, in characters. Past it a sheet stays a link. */
|
|
19
|
+
export const INLINE_CSS_MAX = 48 * 1024
|
|
20
|
+
|
|
21
|
+
// What the shell has, however its markup is quoted.
|
|
22
|
+
const ATTR = /\b(data-[\w-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/gi
|
|
23
|
+
const CLASS = /\bclass\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+))/gi
|
|
24
|
+
const PROP = /--[A-Za-z_][\w-]*/g
|
|
25
|
+
// What a selector asks for. An attribute selector goes first and whole, or `[href$=".pdf"]` reads as a class.
|
|
26
|
+
const SELECTOR_WORD =
|
|
27
|
+
/\[\s*([\w-]+)\s*(?:([~|^$*]?=)\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^\s\]]+))\s*(\w)?\s*)?\]|\.((?:[\w-]|[^\0-\x7f]|\\.)+)/g
|
|
28
|
+
// A reference the shell's text can't be compared with, so nothing is ruled out on its value.
|
|
29
|
+
const ENTITY = /&(?!(?:amp|quot|lt|gt);)/
|
|
30
|
+
const ANY_VALUE = '=*'
|
|
31
|
+
// Set on <html> by a script or `setDial`, so the server's HTML can't vouch for them.
|
|
32
|
+
const ROOT_ATTR =
|
|
33
|
+
/^data-(?:theme|expression|density|form|pointer|motion|flair|fields|veneer|scope)$/
|
|
34
|
+
// `dialScript` restores these before the first paint, so the server's HTML doesn't show their values.
|
|
35
|
+
const DIAL = /^data-(?:theme|expression|density|form|pointer|motion|flair|fields)$/
|
|
36
|
+
// Rules that can't paint until someone acts, so the late sheet is soon enough for them. A state the server can render
|
|
37
|
+
// (`:checked`, `aria-checked`, `:disabled`) has to stay.
|
|
38
|
+
const LATER =
|
|
39
|
+
/:(?:hover|active|focus|focus-visible|focus-within|popover-open|modal)\b|::(?:backdrop|selection)/
|
|
40
|
+
const PRINT = /^@media\s+print\s*(?:and\b[^,]*)?$/i
|
|
41
|
+
const FORCED_COLORS = /^@media\s*\(\s*forced-colors\s*:\s*active\s*\)\s*(?:and\b[^,]*)?$/i
|
|
42
|
+
const GROUPING = /^@(?:media|supports|layer|container|scope|starting-style)\b/
|
|
43
|
+
|
|
44
|
+
const print = (nodes) =>
|
|
45
|
+
nodes.map((n) => (n.body === undefined ? `${n.head};` : `${n.head}{${n.body}}`)).join('')
|
|
46
|
+
|
|
47
|
+
/** Calls `visit` at each top-level comma and bracket of `text` from `from`, skipping strings, and stops at the end of the bracket it began in. */
|
|
48
|
+
function scan(text, from, visit) {
|
|
49
|
+
let depth = 0,
|
|
50
|
+
quote = ''
|
|
51
|
+
for (let i = from; i < text.length; i++) {
|
|
52
|
+
const c = text[i]
|
|
53
|
+
if (quote) {
|
|
54
|
+
if (c === '\\') i++
|
|
55
|
+
else if (c === quote) quote = ''
|
|
56
|
+
continue
|
|
57
|
+
}
|
|
58
|
+
if (c === '"' || c === "'") quote = c
|
|
59
|
+
else if (c === '(' || c === '[') depth++
|
|
60
|
+
else if (c === ')' || c === ']') {
|
|
61
|
+
if (--depth < 0) return i
|
|
62
|
+
} else if (c === ',' && !depth) visit(i)
|
|
63
|
+
}
|
|
64
|
+
return text.length
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function selectors(head) {
|
|
68
|
+
const out = []
|
|
69
|
+
let from = 0
|
|
70
|
+
scan(head, 0, (i) => {
|
|
71
|
+
out.push(head.slice(from, i))
|
|
72
|
+
from = i + 1
|
|
73
|
+
})
|
|
74
|
+
out.push(head.slice(from))
|
|
75
|
+
return out
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A selector with what proves nothing removed: `:not()`, and `:is()`, `:where()` or `:has()` holding alternatives. */
|
|
79
|
+
function required(selector) {
|
|
80
|
+
let rest = selector
|
|
81
|
+
for (;;) {
|
|
82
|
+
const m = /:(not|is|where|has)\(/.exec(rest)
|
|
83
|
+
if (!m) return rest
|
|
84
|
+
const open = m.index + m[0].length
|
|
85
|
+
let comma = false
|
|
86
|
+
const end = scan(rest, open, () => {
|
|
87
|
+
comma = true
|
|
88
|
+
})
|
|
89
|
+
rest =
|
|
90
|
+
rest.slice(0, m.index) +
|
|
91
|
+
(m[1] === 'not' || comma ? '' : ` ${rest.slice(open, end)} `) +
|
|
92
|
+
rest.slice(end + 1)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* What a selector needs the shell to have: `data-x` and `.class`, and a value for a plain `=` on a plain word. An
|
|
98
|
+
* operator, a flag, a value with a space or an escape can match text the shell's words don't show, so only the name counts.
|
|
99
|
+
*/
|
|
100
|
+
function* demands(selector) {
|
|
101
|
+
for (const m of selector.matchAll(SELECTOR_WORD)) {
|
|
102
|
+
if (m[7]) {
|
|
103
|
+
if (!/\\[\da-f]/i.test(m[7])) yield `.${m[7].replace(/\\(.)/g, '$1')}`
|
|
104
|
+
continue
|
|
105
|
+
}
|
|
106
|
+
const name = m[1].toLowerCase()
|
|
107
|
+
if (!name.startsWith('data-')) continue
|
|
108
|
+
yield name
|
|
109
|
+
const value = m[3] ?? m[4] ?? m[5]
|
|
110
|
+
if (m[2] === '=' && !m[6] && /^[\w-]+$/.test(value)) yield { value }
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const ROOTED = /^\s*(?::root|html|body)\b/
|
|
115
|
+
|
|
116
|
+
/** Can the shell match this, going by the attributes, their values and the classes it has? Anything else stays. */
|
|
117
|
+
function present(rest, found) {
|
|
118
|
+
if (ROOTED.test(rest)) return true
|
|
119
|
+
let root = false
|
|
120
|
+
for (const d of demands(rest)) {
|
|
121
|
+
if (typeof d === 'string') {
|
|
122
|
+
root = ROOT_ATTR.test(d)
|
|
123
|
+
if (!root && !found.has(d)) return false
|
|
124
|
+
} else if (!root && !found.has(ANY_VALUE) && !found.has(d.value)) return false
|
|
125
|
+
}
|
|
126
|
+
return true
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Could this paint before anyone acts, on the shell the server sent? */
|
|
130
|
+
function paints(selector, found) {
|
|
131
|
+
const rest = required(selector)
|
|
132
|
+
return !LATER.test(rest.replace(/\[[^\]]*\]/g, '')) && present(rest, found)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A sheet without what can't show in the first paint. */
|
|
136
|
+
function firstPaint(css, parse, found) {
|
|
137
|
+
const walk = (source) =>
|
|
138
|
+
print(
|
|
139
|
+
parse(source).flatMap((n) => {
|
|
140
|
+
if (n.body === undefined) return [n]
|
|
141
|
+
if (PRINT.test(n.head) || FORCED_COLORS.test(n.head)) return []
|
|
142
|
+
if (GROUPING.test(n.head)) {
|
|
143
|
+
const body = walk(n.body)
|
|
144
|
+
return body ? [{ head: n.head, body }] : []
|
|
145
|
+
}
|
|
146
|
+
if (n.head[0] === '@') return [n]
|
|
147
|
+
const kept = selectors(n.head).filter((s) => paints(s, found))
|
|
148
|
+
return kept.length ? [{ head: kept.join(','), body: n.body }] : []
|
|
149
|
+
}),
|
|
150
|
+
)
|
|
151
|
+
return walk(css)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** `@font-face` rules no remaining rule names: veneer's metric fallbacks for families this page doesn't set. */
|
|
155
|
+
function usedFaces(css, parse) {
|
|
156
|
+
const rest = print(parse(css).filter((n) => !n.head.startsWith('@font-face')))
|
|
157
|
+
return print(
|
|
158
|
+
parse(css).filter((n) => {
|
|
159
|
+
if (!n.head.startsWith('@font-face')) return true
|
|
160
|
+
const family = /font-family:\s*["']?([^"';}]+)/.exec(n.body)?.[1]
|
|
161
|
+
return !family || rest.includes(family)
|
|
162
|
+
}),
|
|
163
|
+
)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const critical = new Map()
|
|
167
|
+
const vocabularies = new Map()
|
|
168
|
+
|
|
169
|
+
/** Every attribute, value and class the sheets name: only these can change a page's rules, so only they key the cache. */
|
|
170
|
+
function vocabulary(sheets, id) {
|
|
171
|
+
let words = vocabularies.get(id)
|
|
172
|
+
if (!words) {
|
|
173
|
+
words = new Set()
|
|
174
|
+
words.dials = []
|
|
175
|
+
for (const s of sheets) {
|
|
176
|
+
let name
|
|
177
|
+
for (const d of demands(s.css)) {
|
|
178
|
+
words.add(d.value ?? d)
|
|
179
|
+
if (typeof d === 'string') name = d
|
|
180
|
+
else if (DIAL.test(name)) words.dials.push(d.value)
|
|
181
|
+
}
|
|
182
|
+
for (const m of s.css.matchAll(PROP)) words.add(m[0])
|
|
183
|
+
}
|
|
184
|
+
if (vocabularies.size >= CRITICAL_MAX) vocabularies.delete(vocabularies.keys().next().value)
|
|
185
|
+
vocabularies.set(id, words)
|
|
186
|
+
}
|
|
187
|
+
return words
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Adds to `found` what these sources have of the sheets' words. */
|
|
191
|
+
function read(sources, known, found) {
|
|
192
|
+
const see = (w) => {
|
|
193
|
+
if (known.has(w)) found.add(w)
|
|
194
|
+
}
|
|
195
|
+
const once = (seen, value) => !seen.has(value) && !!seen.add(value) // a page of rows repeats a few values thousands of times
|
|
196
|
+
const names = new Set(),
|
|
197
|
+
values = new Set(),
|
|
198
|
+
classes = new Set()
|
|
199
|
+
for (const source of sources) {
|
|
200
|
+
for (const m of source.matchAll(ATTR)) {
|
|
201
|
+
if (once(names, m[1])) see(m[1].toLowerCase())
|
|
202
|
+
const value = m[2] ?? m[3] ?? m[4]
|
|
203
|
+
if (!value || !once(values, value)) continue
|
|
204
|
+
if (ENTITY.test(value)) found.add(ANY_VALUE)
|
|
205
|
+
for (const w of value.split(/\s+/)) see(w)
|
|
206
|
+
}
|
|
207
|
+
for (const m of source.matchAll(CLASS)) {
|
|
208
|
+
const value = m[1] ?? m[2] ?? m[3]
|
|
209
|
+
if (!once(classes, value)) continue
|
|
210
|
+
if (ENTITY.test(value)) found.add(ANY_VALUE)
|
|
211
|
+
for (const w of value.split(/\s+/)) see(`.${w}`)
|
|
212
|
+
}
|
|
213
|
+
for (const m of source.matchAll(PROP)) see(m[0])
|
|
214
|
+
}
|
|
215
|
+
return found
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** The rules `found` reaches in these sheets. Kept by the page's shape, not its text, so rows don't miss it. */
|
|
219
|
+
function criticalCss(sheets, found, { parse, purge }) {
|
|
220
|
+
const key = `${sheets.map((s) => s.href).join()}|${[...found].sort((a, b) => (a < b ? -1 : 1)).join()}`
|
|
221
|
+
let css = critical.get(key)
|
|
222
|
+
if (css === undefined) {
|
|
223
|
+
// Keeps a value the shell's words can't vouch for, as firstPaint does.
|
|
224
|
+
const has = (w) => found.has(w) || found.has(ANY_VALUE) || !/^-{0,2}[\w-]+$/.test(w)
|
|
225
|
+
css = usedFaces(
|
|
226
|
+
purge(
|
|
227
|
+
sheets.map((s) => firstPaint(s.css, parse, found)),
|
|
228
|
+
{ has },
|
|
229
|
+
).join(''),
|
|
230
|
+
parse,
|
|
231
|
+
)
|
|
232
|
+
if (critical.size >= CRITICAL_MAX) critical.delete(critical.keys().next().value)
|
|
233
|
+
critical.set(key, css)
|
|
234
|
+
}
|
|
235
|
+
return css
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** A stylesheet's short id. The browser runs this same function (`LATE_SHEETS`), so both sides agree. */
|
|
239
|
+
export function sheetId(href) {
|
|
240
|
+
let x = 2166136261
|
|
241
|
+
for (let i = 0; i < href.length; i++) x = Math.imul(x ^ href.charCodeAt(i), 16777619)
|
|
242
|
+
return (x >>> 0).toString(36)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Browser: lists the stylesheets it now has, by `sheetId`, in the `kerf-css` cookie (the latest 32). A page whose sheets
|
|
247
|
+
* are all there is sent links, not rules to paint with first (`pageStyles`). Sent as its source, so it reads nothing else.
|
|
248
|
+
*/
|
|
249
|
+
function keepSheets(id) {
|
|
250
|
+
const c = document.cookie.match(/(?:^|; )kerf-css=([^;]*)/),
|
|
251
|
+
s = c ? c[1].split('.') : []
|
|
252
|
+
document.querySelectorAll('link[rel=stylesheet]').forEach(function (l) {
|
|
253
|
+
const x = l.sheet && id(l.getAttribute('href'))
|
|
254
|
+
if (x && s.indexOf(x) < 0) s.push(x)
|
|
255
|
+
})
|
|
256
|
+
document.cookie = 'kerf-css=' + s.slice(-32).join('.') + ';path=/;max-age=31536000;samesite=lax'
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** The sheet ids the request's `kerf-css` cookie lists. */
|
|
260
|
+
export function keptSheets(cookie) {
|
|
261
|
+
const m = cookie && /(?:^|;\s*)kerf-css=([^;]*)/.exec(cookie)
|
|
262
|
+
return m ? new Set(m[1].split('.')) : undefined
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Switches on the head's deferred sheets once they're all here, or after 3s without the one that failed. One at a time,
|
|
267
|
+
* each is a restyle of the whole page, and 20 of them cost a table of 50 rows more than all its script. `keep`: then
|
|
268
|
+
* lists them in `kerf-css` (`keepSheets`), for a visitor who already has the site's cookies: one without gets none.
|
|
269
|
+
*/
|
|
270
|
+
const lateSheets = (keep) =>
|
|
271
|
+
`(a=>Promise.race([Promise.all(a.map(l=>l.sheet||new Promise(r=>{l.addEventListener('load',r);l.addEventListener('error',r)}))),new Promise(r=>setTimeout(r,3e3))]).then(()=>{a.forEach(l=>l.media='all')${keep ? `;(${keepSheets.toString()})(${sheetId.toString()})` : ''}}))([...document.querySelectorAll('link[data-late]')])`
|
|
272
|
+
export const LATE_SHEETS = lateSheets(false)
|
|
273
|
+
export const LATE_SHEETS_KEPT = lateSheets(true)
|
|
274
|
+
/** The client entry's second chance: a `<style>` a CSP refused has no sheet, so the disabled link beside it is all that's left. */
|
|
275
|
+
export const REFUSED_SHEETS = `document.querySelectorAll('style+link[disabled]').forEach(l=>{l.previousElementSibling.sheet||(l.disabled=false)})`
|
|
276
|
+
// Put the `<style>` before this script in front of the head's first link.
|
|
277
|
+
const MOVE = `(s=>{var d=document,l=d.head.querySelector('link[rel=stylesheet]');l&&l.before(s)})(document.currentScript.previousElementSibling)`
|
|
278
|
+
const blocking = (href) => `<link rel="stylesheet" href="${esc(href)}">\n`
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* `assets.inline` is `{ href: css }`, and `assets.critical` kerf's `{ parse, purge }` (none in dev). Returns the head's
|
|
282
|
+
* stylesheets, and `late(sheets, chunk)`: what a streamed chunk needs in front of it. A parser-inserted link holds all
|
|
283
|
+
* that follows until it loads, so a sheet the head has already asked for is never one: the chunk brings the rules its own
|
|
284
|
+
* HTML reaches, and they move in front of those sheets, which have to keep winning once they load. A sheet the head
|
|
285
|
+
* lacks can only be a link, and its Boundary swaps once it's here. `seen`: an earlier render's `{ split, found }`, for a head
|
|
286
|
+
* sent before this page's HTML exists; its `late` then brings what the HTML has beyond that. `have`: the sheet ids the
|
|
287
|
+
* browser says it has (`keptSheets`). With all of the page's, it gets links (`links`): nothing to inline, or to look for.
|
|
288
|
+
* `keep`: the request has cookies, so the page may list the sheets it loads in one more.
|
|
289
|
+
*/
|
|
290
|
+
export function pageStyles(assets, css = [], html = '', extra = {}) {
|
|
291
|
+
const { head, seen, have, keep = false } = extra
|
|
292
|
+
const first = `<style>${LAYER_ORDER}</style>\n`
|
|
293
|
+
if (have && css.length && css.every((c) => have.has(sheetId(c.href)))) {
|
|
294
|
+
const carried = new Set(css.map((c) => c.href))
|
|
295
|
+
return {
|
|
296
|
+
head: first + css.map((c) => blocking(c.href)).join(''),
|
|
297
|
+
split: false,
|
|
298
|
+
links: true,
|
|
299
|
+
found: () => new Set(),
|
|
300
|
+
late(sheets = []) {
|
|
301
|
+
const hrefs = sheets.map((s) => s.href).filter((h) => !carried.has(h))
|
|
302
|
+
for (const h of hrefs) carried.add(h)
|
|
303
|
+
return hrefs.map(blocking).join('')
|
|
304
|
+
},
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const inline = css
|
|
308
|
+
.filter((c) => assets.inline?.[c.href] !== undefined)
|
|
309
|
+
.map((c) => ({ href: c.href, css: assets.inline[c.href] }))
|
|
310
|
+
const raw = inline.reduce((n, s) => n + s.css.length, 0)
|
|
311
|
+
const split = seen
|
|
312
|
+
? seen.split
|
|
313
|
+
: !!assets.critical &&
|
|
314
|
+
inline.length > 0 &&
|
|
315
|
+
raw / CSS_RATIO + (html.length + (head?.length ?? 0)) / HTML_RATIO > FIRST_PAINT_BYTES
|
|
316
|
+
const carried = new Set(css.map((c) => c.href))
|
|
317
|
+
const known = split && vocabulary(inline, inline.map((s) => s.href).join())
|
|
318
|
+
let sent =
|
|
319
|
+
split &&
|
|
320
|
+
(seen
|
|
321
|
+
? new Set(seen.found)
|
|
322
|
+
: read([html, head ?? ''], known, new Set(head?.includes('veneer:dials') ? known.dials : [])))
|
|
323
|
+
const tags = split
|
|
324
|
+
? `<style>${criticalCss(inline, sent, assets.critical)}</style>\n` +
|
|
325
|
+
css
|
|
326
|
+
.map((c) =>
|
|
327
|
+
assets.inline?.[c.href] === undefined
|
|
328
|
+
? blocking(c.href)
|
|
329
|
+
: `<link rel="stylesheet" href="${esc(c.href)}" media="print" data-late>`,
|
|
330
|
+
)
|
|
331
|
+
.join('') +
|
|
332
|
+
`<noscript>${inline.map((s) => blocking(s.href).trim()).join('')}</noscript>\n<script>${keep ? LATE_SHEETS_KEPT : LATE_SHEETS}</script>\n`
|
|
333
|
+
: css
|
|
334
|
+
.map((c) =>
|
|
335
|
+
assets.inline?.[c.href] === undefined
|
|
336
|
+
? blocking(c.href)
|
|
337
|
+
: `<style>${assets.inline[c.href]}</style>\n<link rel="stylesheet" href="${esc(c.href)}" disabled>\n`,
|
|
338
|
+
)
|
|
339
|
+
.join('')
|
|
340
|
+
return {
|
|
341
|
+
head: first + tags,
|
|
342
|
+
split,
|
|
343
|
+
links: false,
|
|
344
|
+
/** The words the page's rules have reached so far. */
|
|
345
|
+
found: () => sent || new Set(),
|
|
346
|
+
late(sheets = [], chunk = '') {
|
|
347
|
+
const hrefs = sheets.map((s) => s.href).filter((h) => !carried.has(h))
|
|
348
|
+
for (const h of hrefs) carried.add(h)
|
|
349
|
+
const links = hrefs.map(blocking).join('')
|
|
350
|
+
if (!split) return links
|
|
351
|
+
const found = read([chunk], known, new Set(sent))
|
|
352
|
+
if (found.size === sent.size) return links
|
|
353
|
+
// All of them, repeats too: veneer's rules weigh nothing, so order decides, and new ones alone would land after the head's.
|
|
354
|
+
const rules = criticalCss(inline, found, assets.critical)
|
|
355
|
+
sent = found
|
|
356
|
+
return links + (rules && `<style>${rules}</style><script>${MOVE}</script>\n`)
|
|
357
|
+
},
|
|
358
|
+
}
|
|
359
|
+
}
|