@barqjs/start 0.0.0-stage → 0.2.0-next.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.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +791 -2
  3. package/dist/client-BHyIiYxt.js +1527 -0
  4. package/dist/client-BHyIiYxt.js.map +1 -0
  5. package/dist/client-DHCV7yvQ.d.ts +440 -0
  6. package/dist/client-DHCV7yvQ.d.ts.map +1 -0
  7. package/dist/client.d.ts +3 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-qA8EyOr1.d.ts +49 -0
  10. package/dist/env-qA8EyOr1.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +44 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-Bm_-MTj6.d.ts +915 -0
  15. package/dist/index-Bm_-MTj6.d.ts.map +1 -0
  16. package/dist/index.d.ts +5 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-BdVlE8qm.d.ts +576 -0
  19. package/dist/middleware-BdVlE8qm.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +282 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +98 -0
  24. package/dist/prerender.d.ts.map +1 -0
  25. package/dist/prerender.js +289 -0
  26. package/dist/prerender.js.map +1 -0
  27. package/dist/protocol.d.ts +58 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +26 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +135 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +223 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-BV3xKmLa.js +1148 -0
  36. package/dist/server-BV3xKmLa.js.map +1 -0
  37. package/dist/server.d.ts +142 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-ChnB_xug.js +1140 -0
  41. package/dist/src-ChnB_xug.js.map +1 -0
  42. package/dist/static-fn-DgjNArBe.js +123 -0
  43. package/dist/static-fn-DgjNArBe.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +672 -0
  46. package/src/context.ts +666 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +97 -0
  50. package/src/frames-client.ts +1216 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +714 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +182 -0
  56. package/src/middleware.ts +994 -0
  57. package/src/prerender.ts +477 -0
  58. package/src/protocol.ts +61 -0
  59. package/src/rate-limit.ts +202 -0
  60. package/src/serve.ts +153 -0
  61. package/src/server.ts +990 -0
  62. package/src/session.ts +449 -0
  63. package/src/start-instance.ts +147 -0
  64. package/src/static-fn.ts +181 -0
  65. package/src/static.ts +302 -0
  66. package/src/stubs.ts +32 -0
  67. package/src/timing.ts +29 -0
  68. package/src/wire-types.ts +139 -0
package/README.md CHANGED
@@ -1,3 +1,792 @@
1
- # Temporary Holding Version
1
+ # @barqjs/start
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server functions, middleware, the request context, sessions, cookies, rate
4
+ limiting, and the server the build emits. A server function is a typed `GET` or
5
+ `POST` endpoint you call like a function. A `GET` call needs barq's `x-barq-fn`
6
+ header and passes an origin check. A production server sends a thrown error's
7
+ message only when it was marked with `markSafeError`. With `verify` on, the
8
+ build refuses to ship a route whose server functions skip its middleware. The API follows TanStack Start's design:
9
+ `createServerFn`, `createMiddleware`, `createStart`, `useSession`, and the
10
+ request helpers under their names.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ bun add @barqjs/start
16
+ bun add -d @barqjs/vite vite
17
+ ```
18
+
19
+ `bun create barq` installs it for you. This document is the reference for what
20
+ that project uses. Routing, the document and API routes are in
21
+ [@barqjs/router](../router/README.md).
22
+
23
+ ## Example
24
+
25
+ The smallest server function, and a call to it:
26
+
27
+ ```tsx
28
+ import { createServerFn } from "@barqjs/start";
29
+
30
+ export const serverTime = createServerFn().handler(() => new Date());
31
+
32
+ const at = await serverTime(); // a Date, fetched from the server
33
+ ```
34
+
35
+ ## Coming from TanStack Start
36
+
37
+ `createServerFn` with `GET` as the default method, `.validator`, `.middleware`,
38
+ `.handler`, `createMiddleware` with `.server` and `.client` halves,
39
+ `createStart` with request and function middleware, `redirect`, `notFound`,
40
+ `useSession` and the request helpers follow TanStack Start under their names.
41
+ What barq adds is the build-time route-action check (`verify`), the wire-type
42
+ check on results, and the `x-barq-fn` header on `GET` calls.
43
+
44
+ ## Server functions
45
+
46
+ ```ts
47
+ import { createServerFn } from "@barqjs/start";
48
+
49
+ export const createPost = createServerFn({ method: "POST" })
50
+ .validator(PostSchema) // any Standard Schema, such as zod, valibot or arktype
51
+ .handler(async ({ data, context, signal }) => db.posts.insert(data));
52
+ ```
53
+
54
+ `.validator` is TanStack's name for it. `.inputValidator`, the name their
55
+ release candidates used, is the same method and is accepted so code written
56
+ against them keeps working. It takes a Standard Schema, a function that returns
57
+ the validated value or throws, or an object with a `parse`. The caller passes
58
+ the schema's INPUT and the handler is handed its OUTPUT, so a schema that turns
59
+ an ISO string into a `Date` is called with a string. A function validator's
60
+ parameter type is what the caller passes:
61
+
62
+ ```ts
63
+ export const byId = createServerFn()
64
+ .validator((input: { id: string }) => ({ id: Number(input.id) }))
65
+ .handler(({ data }) => db.users.find(data.id)); // data: { id: number }
66
+
67
+ await byId({ data: { id: "41" } }); // { id: 41 } is a type error
68
+ ```
69
+
70
+ A function handed a form receives the `FormData` itself.
71
+
72
+ Call it like a function. It is an HTTP endpoint:
73
+
74
+ ```tsx
75
+ const post = await createPost({ data: { title: "Hello" } });
76
+ ```
77
+
78
+ The compiler replaces this module's exports with client stubs that call
79
+ `/_barq/fn/<id>`, so the handler's body, and the database driver it imports,
80
+ is in no client chunk. The id is `<project-relative module>#<export>`, derived
81
+ once and used by both halves, because deriving it twice is how the two drift
82
+ into a call that reaches nothing.
83
+
84
+ **A function with no validator accepts no argument.** That is the safe default:
85
+ opening the input is a decision you make per function. `.validator("unchecked")`
86
+ takes anything.
87
+
88
+ ### GET and POST
89
+
90
+ `GET` is the default, as it is TanStack's. A function that writes declares
91
+ `POST`, which is also the only method a form can reach:
92
+
93
+ ```ts
94
+ export const listNotes = createServerFn() // GET
95
+ .middleware([requireSession])
96
+ .handler(({ context }) => {
97
+ setResponseHeader("cache-control", "private, max-age=60");
98
+ return notesOf(context.user);
99
+ });
100
+ ```
101
+
102
+ The call is the same either way. A `GET` call carries its payload in
103
+ `?payload=`, so one input is one URL, and a long input belongs in a `POST`.
104
+ `method` must be a literal, since the compiler reads it to write the stub; a
105
+ value it cannot read is taken as the default. Nothing is cached unless the
106
+ handler says so: an answer carries no `cache-control` and no `Vary` of its own, which is
107
+ TanStack's behaviour too.
108
+
109
+ A link still cannot reach a `GET` function, so one that writes and forgot to
110
+ say `POST` is not a one-click CSRF carrying `SameSite=Lax` cookies. Every `GET`
111
+ call carries an `x-barq-fn` header, which a link, an `<img>`, a prefetch or a
112
+ navigation cannot set, and the server answers a `GET` without it with a 403. A
113
+ script on another site that sets it is preflighted, and the origin check
114
+ refuses it either way. A function answers its own method only (a `POST` to a
115
+ `GET` function is a 405, and the reverse), a `GET` function has no form channel, and a
116
+ payload longer than `maxBodySize` is a 413. Keep `public` out of `cache-control`
117
+ for anything that reads a session: a shared cache would hand one user's answer to
118
+ the next.
119
+
120
+ A call takes three options beside `data`:
121
+
122
+ ```ts
123
+ const controller = new AbortController();
124
+ await createPost({
125
+ data: { title: "Hello" },
126
+ signal: controller.signal, // cancels the fetch; the handler's `signal` follows the request
127
+ headers: { "x-trace": id }, // wins over a client middleware's `next({ headers })`
128
+ fetch: tracedFetch, // in place of the global one
129
+ });
130
+ ```
131
+
132
+ A `Response` a middleware, a validator or the handler throws
133
+ (`throw new Response("sign in first", { status: 401 })`) is what the call
134
+ rejects with, as in TanStack: its status, headers and body are the author's
135
+ words to the caller. Any other failure rejects with `ServerFnError`, carrying
136
+ the `status`, the server's `response`, and `issues` when the validator refused
137
+ the input. A handler's own error is answered with one fixed line and nothing
138
+ else, so a thrown `Error`'s message never leaves the server. A development
139
+ server also sends `thrown`, the error's name, message and stack; production
140
+ leaves it `undefined`.
141
+
142
+ `throw redirect({ to, params, search, hash, replace, reloadDocument, href })`
143
+ and `throw notFound({ data, routeId })` from a handler reach the caller with
144
+ everything they said, and their `headers` leave on the response. `useServerFn`
145
+ from `@barqjs/router` navigates on the redirect. A redirect whose `params` or
146
+ `search` is a function cannot cross and arrives as its resolved target alone.
147
+
148
+ `fn.url` is the address `<form action={fn}>` posts to, `fn.method` the method it
149
+ answers, and `fn.serverFnMeta.id` (also `fn.meta.id`) the id it is mounted at.
150
+ A handler is handed the same two beside `data`, `context` and `signal`:
151
+
152
+ ```ts
153
+ createServerFn().handler(({ method, serverFnMeta }) => `${method} ${serverFnMeta.id}`);
154
+ ```
155
+
156
+ `json(payload, init)` builds a JSON `Response`, for a handler that answers with
157
+ one.
158
+
159
+ ### What crosses the wire
160
+
161
+ A handler's result and a validator's input are checked against what the codec
162
+ carries, so a value it would refuse at runtime is a type error where it is
163
+ written, naming where. A component is the exception, and crosses as a frame:
164
+
165
+ ```ts
166
+ createServerFn().handler(() => ({ user: { format: () => "x" } }));
167
+ // ... { readonly "cannot cross the wire": "the result.user.format is a function" }
168
+ ```
169
+
170
+ Primitives, `bigint`, `Date`, `Error`, `Map`, `Set`, `Promise`, typed arrays and
171
+ plain objects cross; a function, a symbol, a `RegExp`, a `URL`, a `Blob` and an
172
+ instance of a class with methods do not. A form crosses as a `POST`'s input. A
173
+ class with no methods is a plain object to a type and is refused by the codec
174
+ at runtime only. `createServerFn({ strict: false })` turns the check off, and
175
+ `strict: { input: false }` or `strict: { output: false }` one side of it, for a
176
+ class a `createSerializationAdapter` carries.
177
+
178
+ ### Static server functions
179
+
180
+ ```ts
181
+ import { staticFunctionMiddleware } from "@barqjs/start/client";
182
+
183
+ export const buildInfo = createServerFn({ method: "GET" })
184
+ .middleware([staticFunctionMiddleware])
185
+ .validator((input: { page: string }) => input)
186
+ .handler(({ data }) => ({ page: data.page, builtAt: new Date() }));
187
+ ```
188
+
189
+ While the build prerenders, each call writes its result to
190
+ `/_barq/static/<key>.json` in the client output, one file per function and
191
+ input. Reordering the input's keys gives the same file. In the browser the call reads
192
+ that file first and goes to the server only when there is none, so a page
193
+ prerendered whole works from a host that serves files and nothing else.
194
+
195
+ Import it from `@barqjs/start/client`, the subpath the client stub already
196
+ imports from: a chain naming anything from another package is not carried into
197
+ the browser. List it last, since the key is the input as it sees it. Only the
198
+ result is stored: a `sendContext` is not, and a `Response`, a stream or a result
199
+ of `undefined` is never written. Two calls whose keys collide stop the build.
200
+
201
+ ### Streaming
202
+
203
+ A handler that returns an async generator, or a `ReadableStream` of values,
204
+ answers over time. The caller reads an async iterable of the same values:
205
+
206
+ ```ts
207
+ export const ticks = createServerFn().handler(async function* () {
208
+ for (const row of await rows()) yield { row, at: new Date() };
209
+ });
210
+
211
+ for await (const { row, at } of await ticks()) render(row, at);
212
+ ```
213
+
214
+ Leaving the loop early stops the generator. A failure after the first value ends
215
+ the iterable with a `ServerFnError`.
216
+
217
+ ### Frames
218
+
219
+ A handler that returns a component answers with a frame: the component runs on
220
+ the server, and the page receives its markup and never its code. Its props are
221
+ slots, positions the server marks and the page fills: with components of its
222
+ own where a slot is placed, and with behaviour where a slot is read as data.
223
+
224
+ ```tsx
225
+ import type { Child } from "@barqjs/core";
226
+ import { dynamic } from "@barqjs/web";
227
+ import { type Slot, createServerFn } from "@barqjs/start";
228
+
229
+ export const getStory = createServerFn({ method: "GET" })
230
+ .validator((input: { id: string }) => input)
231
+ .handler(({ data }) => {
232
+ const story = loadStory(data.id);
233
+ return (props: { comment: Slot<{ cid: number }>; children?: Child }) => (
234
+ <article>
235
+ <h2>{story.title}</h2>
236
+ {story.comments.map((c) => (
237
+ <props.comment $key={c.id} cid={c.id}>
238
+ <p>{c.text}</p>
239
+ </props.comment>
240
+ ))}
241
+ <footer>{props.children}</footer>
242
+ </article>
243
+ );
244
+ });
245
+ ```
246
+
247
+ A route renders what its loader answered with:
248
+
249
+ ```tsx
250
+ export const Route = createFileRoute("/story")({
251
+ loader: () => getStory({ data: { id: "1" } }),
252
+ component: (props: RouteProps) => {
253
+ const Story = dynamic(() => props.data() as (props: Record<string, unknown>) => Node);
254
+ return (
255
+ <Story
256
+ comment={(slot: Incoming<{ cid: number; children: Child }>) => (
257
+ <Comment cid={slot.cid()}>{slot.children}</Comment>
258
+ )}
259
+ >
260
+ <ShareBar />
261
+ </Story>
262
+ );
263
+ },
264
+ });
265
+ ```
266
+
267
+ - **In the document**, where the server renders the route, the frame is written
268
+ inline as `<barq-frame>` with a payload script naming its slots, and the
269
+ slots hold the page's components rendered for the first paint. The page's
270
+ seed names the frame by address, so the browser asks for nothing at boot: it
271
+ claims the region where it stands, and the slots' content with it, as
272
+ hydration claims the rest of the page.
273
+ - **Over the wire**, a call from the browser answers under
274
+ `x-barq-rpc: frame` with the same markup, the region rendered on its own and
275
+ its slots empty. A slot call's `children` cross in the payload as a nested
276
+ region of server markup, the fill's own `children`.
277
+ - **One component per address.** A call's address is its function and its
278
+ arguments, and asking again answers with the same component, so a `dynamic`
279
+ over it does not remount: `applyFrameResponse` morphs the new markup into
280
+ every place the region is mounted. A slot's content is the page's, kept with
281
+ its state, moved when the server moved it (by `$key`, or by position among
282
+ the calls of that name) and given the new arguments. `barq:frame-applied`
283
+ (`FRAME_APPLIED_EVENT`) is dispatched on `document` once it is applied.
284
+ - **A region's assets** are what it declared with `useHead` and what its
285
+ `lazy()` modules need. They are owned by the frame and go when it is
286
+ unmounted, and an update waits for a stylesheet it names to load.
287
+ - **The same checks.** A frame is a server function's answer, so the origin
288
+ check, the body limit and the request middleware run before the component
289
+ does. A browser posting a form to one is sent back with a `303`.
290
+
291
+ A slot the component calls and reads, rather than places, is a binding slot:
292
+ the server's own markup, with the page's behaviour bound to it. Each property
293
+ goes whole at one position, an attribute, a class name or style property in
294
+ object form, a handler, a ref or a text child:
295
+
296
+ ```tsx
297
+ import { type BindingSlot } from "@barqjs/start";
298
+
299
+ type Like = { liked: boolean; label: string; toggle: () => void };
300
+
301
+ // In the server component, per comment:
302
+ const like = props.like({ $key: c.id, cid: c.id });
303
+ <button class={{ liked: like.liked }} aria-pressed={like.liked} onClick={like.toggle}>
304
+ {like.label}
305
+ </button>;
306
+
307
+ // In the page, the fill, run once per occurrence:
308
+ <Story
309
+ like={(slot: Incoming<{ cid: number }>): Like => {
310
+ const [liked, setLiked] = createSignal(false);
311
+ return {
312
+ get liked() {
313
+ return liked();
314
+ },
315
+ get label() {
316
+ return liked() ? "liked" : "like";
317
+ },
318
+ toggle: () => setLiked((was) => !was),
319
+ };
320
+ }}
321
+ />;
322
+ ```
323
+
324
+ The server writes a marker beside each position, with the fill's first value
325
+ in the document and none over the wire, and never has the value to compute
326
+ with: a stand-in is an object, so a comparison or a branch on one is decided on
327
+ the page, in the fill. The browser binds each position once, the claim writing
328
+ nothing the server already wrote. An update keeps the fill and its state,
329
+ leaves the positions it owns alone and binds the ones the server added.
330
+
331
+ A mutation that changes a frame says so, and its answer carries the region
332
+ beside its value, in one request:
333
+
334
+ ```ts
335
+ export const reviseStory = createServerFn({ method: "POST" })
336
+ .validator((input: { id: string }) => input)
337
+ .handler(({ data }) => {
338
+ saveRevision(data.id);
339
+ invalidateFrames(getStory);
340
+ return "saved";
341
+ });
342
+ ```
343
+
344
+ A page names the frames it has mounted on each `POST` (`x-barq-frames`, the
345
+ first 32), each one is asked for again through its own function, validator and
346
+ middleware included, and the regions it answers are applied where they stand
347
+ before the caller is handed the value.
348
+
349
+ `live(fn)` keeps a frame current over one connection. On the server a frame
350
+ that reads a standing source, an async iterable in a memo, is rendered again
351
+ each time the source moves, and each rendering goes out as a server-sent event
352
+ applied in place:
353
+
354
+ ```tsx
355
+ const board = createMemo(() => live(getBoard)());
356
+ const Board = dynamic(() => board() as (props: Record<string, unknown>) => Node);
357
+ ```
358
+
359
+ A dropped connection reconnects with backoff from the last event it applied,
360
+ which is not sent again, and `onstatus` hears `"connected"`, `"reconnecting"`
361
+ and `"closed"`. A frame the document was served through `live` connects once
362
+ the page is claimed, and closes when the last place it is mounted goes. A
363
+ `live` call to a function that answers with values rather than a frame reads
364
+ one value per event.
365
+
366
+ ### With JavaScript off
367
+
368
+ ```tsx
369
+ <form action={createPost}>
370
+ <input name="title" />
371
+ <button type="submit">post</button>
372
+ </form>
373
+ ```
374
+
375
+ `action={fn}` writes the endpoint and `method="post"` together, and the handler
376
+ receives a real `FormData`. The same function sees the same input type whether
377
+ or not JS ran, which is the divergence progressive enhancement exists to
378
+ prevent.
379
+
380
+ ## Middleware, and the check the build runs
381
+
382
+ ```ts
383
+ import { createMiddleware, createServerFn, useSession } from "@barqjs/start";
384
+
385
+ export const requireSession = createMiddleware().server(async ({ next }) => {
386
+ const session = await useSession<{ user: string }>(sessionConfig);
387
+ if (session.data.user === undefined) throw new Response("sign in first", { status: 401 });
388
+ return next({ context: { user: session.data.user } });
389
+ });
390
+
391
+ export const adminStats = createServerFn()
392
+ .middleware([requireSession])
393
+ .handler(({ context }) => stats(context.user)); // context.user: string
394
+ ```
395
+
396
+ What a middleware passes to `next({ context })` is TYPED into everything after
397
+ it: the handler's `context`, the `context` of a middleware that lists it in its
398
+ own `.middleware([...])`, and a route handler's under `server.middleware`. A key
399
+ no typed step declared still reads, as `unknown`. A bare closure states what it
400
+ adds, and is checked against it:
401
+
402
+ ```ts
403
+ const tenant: Middleware<{ tenant: string }> = async (next) => next({ context: { tenant } });
404
+ ```
405
+
406
+ A middleware's `.validator()` types its own `data` and, when the function has
407
+ none of its own, the handler's and the caller's. A client half's `next()` takes
408
+ `headers`, `sendContext` and `fetch`; the call's own `headers` and `fetch` win
409
+ over a middleware's, and a later middleware's over an earlier one's. What a
410
+ client half sends arrives on the server as `clientContext`, untyped on purpose:
411
+ it is whatever the caller chose to send.
412
+
413
+ A middleware ends in `return next(...)`, answers with a result of its own (a
414
+ `Response` included), or throws. Returning `undefined` is neither: without
415
+ `next()` the call would have no answer, and after it the handler's result would
416
+ be lost. Either way the call fails with an error naming the middleware (its
417
+ function's name when it has one), its place in the chain and the server
418
+ function, as TanStack's does. A returned `redirect()` or `notFound()` is thrown
419
+ as the answer it describes. A middleware's halves are also handed `method` and
420
+ `serverFnMeta`.
421
+
422
+ A server function in the list stands for the middleware it declared, as in
423
+ TanStack: `.middleware([whoami])` runs `whoami`'s guards, typed, and never its
424
+ handler. A second `.middleware([...])` call adds to the chain.
425
+
426
+ Middleware runs BEFORE validation, deliberately: an unauthenticated caller
427
+ should be refused without the server parsing its payload, and a rejection that
428
+ depended on well-formed input is one an attacker skips by sending malformed
429
+ input. A middleware refuses by THROWING a `Response`.
430
+
431
+ Declare the same closure on the route, and the build checks the two agree:
432
+
433
+ ```ts
434
+ // vite.config.ts
435
+ barq({ ssr: true, start: { verify: true } });
436
+
437
+ // src/routes/admin.tsx
438
+ export const Route = createFileRoute("/admin")({ middleware: [requireSession] });
439
+ ```
440
+
441
+ A server function is its own HTTP endpoint, so a guard on the route that
442
+ renders it does not run when the function is called directly. Next.js and
443
+ TanStack both document that gap and leave it to the author. `vite build` walks
444
+ the client module graph from each route to the functions it can reach, and fails
445
+ naming the route, the function, and how much of the chain is missing.
446
+
447
+ It VALIDATES AND REJECTS, never redispatches. Re-running a mis-routed action
448
+ under the owning route's middleware executes it in a different request context.
449
+ The deeper reason: a client-supplied route selecting a middleware chain lets the
450
+ caller pick the weakest chain that reaches the action.
451
+
452
+ The chain is compared by reference identity. `Middleware` is an anonymous
453
+ closure with no build-visible name, and every attempt to read `.middleware([…])`
454
+ out of source dies on the shapes people write: `[m]`, `[...chain]`,
455
+ `chain.filter(Boolean)`.
456
+
457
+ ## The request context
458
+
459
+ ```ts
460
+ import { getRequest, getRequestHeader, setCookie, setResponseHeader } from "@barqjs/start";
461
+ ```
462
+
463
+ These read an ambient request, so a loader, a route handler, a server function
464
+ and a middleware all reach it the same way. It is an `AsyncLocalStorage` and not
465
+ a module variable: two requests are in flight at once on any real server, and a
466
+ module variable hands one request's session to another. That has shipped
467
+ elsewhere as cross-user data disclosure.
468
+
469
+ `setCookie` and `deleteCookie` default to `path: "/"`. A browser would otherwise
470
+ scope the cookie to `/_barq/fn`, the directory of the URL that set it, and no
471
+ page would receive it. `appendResponseHeader` adds to a list header such as
472
+ `Vary`, where `setResponseHeader` replaces.
473
+
474
+ `setResponseHeader` and `setCookie` write to a DRAFT, because the response is
475
+ built after the handler returns and a streamed response is handed back before
476
+ its body exists. The draft rides an error out too, so a middleware that rotated
477
+ a session cookie and then refused does not lose the rotation.
478
+
479
+ ## Sessions
480
+
481
+ ```ts
482
+ import { type SessionConfig, useSession } from "@barqjs/start";
483
+
484
+ const sessionConfig: SessionConfig = {
485
+ password: process.env.SESSION_PASSWORD!, // at least 32 characters
486
+ cookie: { secure: true },
487
+ };
488
+
489
+ const session = await useSession<{ user: string }>(sessionConfig);
490
+ session.data.user;
491
+ const next = await session.update({ user: "salama" });
492
+ ```
493
+
494
+ A sealed cookie with no store behind it: AES-GCM through WebCrypto, so no
495
+ dependency and no encrypt-then-MAC composition to get wrong.
496
+
497
+ `session.data` is READ-ONLY and `update()` returns a NEW manager. The handle you
498
+ already hold is deliberately unchanged, so nothing can read a half-applied
499
+ session.
500
+
501
+ The expiry is enforced on UNSEAL as well as on the cookie, because a cookie's
502
+ own expiry is a request the client is free to ignore.
503
+
504
+ The cookie's NAME is under the seal. Two sessions sharing a password (`name:
505
+ "barq-session-admin"` beside the default) are two sessions: a value issued under
506
+ one name does not open under the other. Envelopes start `b2.`; a `b1.` cookie
507
+ from an older release opens until it expires, under any name, and is sealed as
508
+ `b2` the next time the session is updated.
509
+
510
+ The password is a KEY: anyone holding it can mint a session for any user.
511
+ Rotating it logs everyone out, which is the intended way to do that.
512
+
513
+ ## Rate limiting
514
+
515
+ ```ts
516
+ import { byIP, createServerFn, memoryStore, rateLimit } from "@barqjs/start";
517
+
518
+ const limit = rateLimit({
519
+ limit: 30,
520
+ windowMs: 60_000,
521
+ key: byIP(),
522
+ store: memoryStore(),
523
+ });
524
+
525
+ export const login = createServerFn({ method: "POST" })
526
+ .middleware([limit])
527
+ .validator(LoginSchema)
528
+ .handler(({ data }) => signIn(data));
529
+ ```
530
+
531
+ `rateLimit` returns a middleware, so the same value guards a server function or
532
+ a route's `server.middleware`. It runs before validation. Past the limit it
533
+ throws a 429 with `Retry-After`, or what `onLimit(info)` returns. A store that
534
+ throws lets the request through and logs the error, because a limiter that
535
+ refuses everything while its store is down has become the outage.
536
+
537
+ Build it ONCE at module scope. The store is the state, and a fresh one per
538
+ request counts to one forever. A store is one atomic method,
539
+ `hit(key, windowMs)`, returning `{ count, resetAt }`; Redis does it with `INCR`
540
+ and `PEXPIRE`.
541
+
542
+ Neither `key` nor `store` has a default, and that is the point:
543
+
544
+ - Keying by IP is right for a public endpoint and wrong for an authenticated
545
+ one behind a corporate NAT, where it limits a building as though it were one user.
546
+ Key by user id where there is one. Returning `null` exempts the caller.
547
+ - `memoryStore()` is correct for a single instance and wrong behind a load
548
+ balancer, where three instances permit three times the limit.
549
+
550
+ `byIP()` does not trust `X-Forwarded-For` unless you ask, because a caller who
551
+ can set that header picks their own bucket. There are two ways to ask:
552
+
553
+ - `byIP({ xForwardedFor: true })` reads the leftmost entry. That is the client
554
+ only when your edge proxy OVERWRITES the header. Behind one that appends, the
555
+ leftmost entry is whatever the caller sent.
556
+ - `byIP({ xForwardedFor: { trustedProxies: 1 } })` counts from the right: the
557
+ entry the nth proxy you run wrote. A forged prefix is never read, and a
558
+ header with fewer entries than proxies is ignored.
559
+
560
+ ### Global middleware
561
+
562
+ `src/start.ts` declares what runs for the whole application:
563
+
564
+ ```ts
565
+ import { createMiddleware, createStart } from "@barqjs/start";
566
+
567
+ const logging = createMiddleware({ type: "request" }).server(
568
+ async ({ next, request, pathname }) => {
569
+ const started = performance.now();
570
+ const response = await next({ context: { requestId: crypto.randomUUID() } });
571
+ log(request.method, pathname, performance.now() - started);
572
+ return response;
573
+ },
574
+ );
575
+
576
+ export const startInstance = createStart(() => ({
577
+ requestMiddleware: [logging], // every page, route handler and server function
578
+ functionMiddleware: [requireSession], // every server function, ahead of its own chain
579
+ serializationAdapters: [money], // a type only the application knows, both ways
580
+ serverFns: { fetch: tracedFetch }, // every call, unless a middleware or the call names one
581
+ defaultSsr: "data-only", // every route that says nothing about `ssr`
582
+ }));
583
+ ```
584
+
585
+ `createSerializationAdapter({ key, test, toSerializable, fromSerializable })`
586
+ makes an adapter. The ones named here are installed the first time the options
587
+ are read, which the server does before it answers anything and the browser
588
+ before it reads the page's seed. `defaultSsr` wins over the router's own, on
589
+ both sides.
590
+
591
+ The order is global request, global function, then the function's own. What a
592
+ request middleware passes to `next({ context })` starts every server function's
593
+ `context`, reaches a route handler's, and is `getGlobalStartContext()` anywhere
594
+ in the request. A `{ type: "function" }` middleware may have a `.client()` half,
595
+ which runs in the browser around every call.
596
+
597
+ A global request middleware runs after a call has passed the method, origin and
598
+ id checks, and before its body is read, so a forged request reaches none of it.
599
+
600
+ Register the instance and what the global middleware adds is typed too, in every
601
+ handler's `context` and in `getGlobalStartContext()` (each key optional there,
602
+ since it can be called outside a request):
603
+
604
+ ```ts
605
+ declare module "@barqjs/start" {
606
+ interface Register {
607
+ start: typeof startInstance;
608
+ }
609
+ }
610
+ ```
611
+
612
+ ### With Solid's async primitives
613
+
614
+ A server function returns a promise, so it is what an async memo reads and what
615
+ an `action` yields:
616
+
617
+ ```tsx
618
+ const notes = createMemo(async () => listNotes());
619
+ const [guesses, setGuesses] = createOptimistic<readonly Note[]>([]);
620
+
621
+ const add = action(function* (text: string) {
622
+ setGuesses((list) => [...list, { id: -1, text }]); // shown at once, dropped when this settles
623
+ yield addNote({ data: { text } });
624
+ refresh(notes); // the real row arrives with the refreshed list
625
+ });
626
+ ```
627
+
628
+ On the server the memo's call is in-process and its answer seeds the page, so
629
+ the browser does not ask again until `refresh`.
630
+
631
+ ## Subpaths
632
+
633
+ - `@barqjs/start`: the isomorphic surface. `createServerFn`, `createMiddleware`,
634
+ `createStart`, the request context, sessions, cookies, rate limiting.
635
+ - `@barqjs/start/client`: the RPC stub the compiler emits,
636
+ `staticFunctionMiddleware`, `live`, and the browser half of frames:
637
+ `applyFrameResponse` and `frameAdapter`, which `@barqjs/router`'s client
638
+ entry installs for a frame named in the seed.
639
+ - `@barqjs/start/server`: `handleServerFn`, `mount`, the origin check.
640
+ - `@barqjs/start/serve`: `serveBarq`, `createFetchHandler`, the asset
641
+ middleware.
642
+ - `@barqjs/start/prerender`: the prerenderer, for a custom build.
643
+ - `@barqjs/start/middleware` and `@barqjs/start/env`: the middleware runner and
644
+ the one-side functions, split out so the client stub can import them without
645
+ reaching `node:async_hooks`. The compiler emits these; import from
646
+ `@barqjs/start` instead.
647
+ - `@barqjs/start/protocol`: the server-entry contract router and vite share.
648
+ Not public API.
649
+
650
+ ## The build and the server
651
+
652
+ The Vite side is `@barqjs/vite`, one plugin for the compiler, the file routes
653
+ and this package's build:
654
+
655
+ ```ts
656
+ import barq from "@barqjs/vite";
657
+
658
+ barq({ ssr: true, start: { prerender: { routes: ["/"] } } }); // server-rendered
659
+ barq({ start: true }); // an SPA: `index.html` is the document, the server keeps the RPC
660
+ ```
661
+
662
+ `start` is what this package adds: server functions and API routes, the dev
663
+ server's page and function middleware, `vite preview`, and a `vite build` that
664
+ builds the client and then the server. `ssr` decides whether the server renders
665
+ pages, and with them whether both halves compile hydratable.
666
+
667
+ `vite build` emits two directories:
668
+
669
+ ```
670
+ dist/client/ the browser bundle, plus every prerendered page
671
+ dist/server/
672
+ server.js importable; default-exports the handler and serves nothing
673
+ serve.js runnable: `bun dist/server/serve.js`
674
+ index.js `{ fetch }` over server functions and pages, for a host
675
+ ```
676
+
677
+ They are two files because `bun <file>` auto-serves any default export carrying
678
+ a `fetch`, so one entry that both exported the handler and started a server
679
+ would bind the port twice. It also keeps a `serve()` out of the module `vite
680
+ build` imports to prerender.
681
+
682
+ `serve.js` answers in this order: static assets from a manifest the build wrote,
683
+ then server functions, then the page handler. The static lookup costs 0.33 µs
684
+ per request against the 0.75 µs a `statSync` costs, and a prerendered page keeps
685
+ the status it was rendered as.
686
+
687
+ `vite preview` serves `dist/client` and sends everything else through
688
+ `index.js`, so it runs what a deployment runs.
689
+
690
+ A plugin that owns the `ssr` environment, such as `@cloudflare/vite-plugin` or
691
+ Nitro, runs the server half itself. The dev server then leaves pages and server
692
+ functions to that plugin's runtime, which imports the `index` input the way a
693
+ deployment does, and a host that orchestrates `vite build` builds the server
694
+ after barq has built the client. `prerender` and `verify` import the server
695
+ bundle barq builds, so under such a host they do not run, and the build says so.
696
+
697
+ Prerendering takes three more options:
698
+
699
+ ```ts
700
+ barq({
701
+ ssr: true,
702
+ start: {
703
+ prerender: {
704
+ routes: ["/", "/404"],
705
+ retryCount: 2, // ask again after a throw or a 5xx; a 4xx is an answer
706
+ retryDelay: 500, // ms between attempts
707
+ sitemap: { host: "https://example.com" }, // outputPath defaults to sitemap.xml
708
+ },
709
+ },
710
+ });
711
+ ```
712
+
713
+ The sitemap lists every page written with a 2xx, sorted. A page prerendered at
714
+ `/404` is left out of it and is also written to `404.html` at the root, the name
715
+ a static host serves for a path it has no file for.
716
+
717
+ SPA mode renders the pages in the browser from one shell:
718
+
719
+ ```ts
720
+ barq({
721
+ ssr: true,
722
+ start: { spa: { enabled: true, maskPath: "/", prerender: { outputPath: "/_shell.html" } } },
723
+ });
724
+ ```
725
+
726
+ `ssr` stays on: the server renders the shell and the client hydrates it.
727
+
728
+ The build renders the root route once, with nothing under it, and writes that
729
+ document. The server then renders no pages: a navigation nothing else answers
730
+ gets the shell, and server functions and route handlers answer as before.
731
+
732
+ Under `static`, a name the build hashed (everything it emitted under
733
+ `build.assetsDir`) is answered `max-age=31536000, immutable`. A file with a
734
+ stable name, and every prerendered page, gets an `ETag` and a 304 instead.
735
+
736
+ Behind a proxy that terminates TLS, tell the generated server so, or the origin
737
+ check sees `http://` where the browser said `https://` and refuses every server
738
+ function:
739
+
740
+ ```ts
741
+ barq({
742
+ ssr: true,
743
+ start: {
744
+ server: {
745
+ trustProxy: "loopback", // or true, or the proxy addresses
746
+ allowedOrigins: ["https://admin.example.com"], // beyond the server's own
747
+ },
748
+ },
749
+ });
750
+ ```
751
+
752
+ ### Functions for one side
753
+
754
+ ```ts
755
+ import { createClientOnlyFn, createIsomorphicFn, createServerOnlyFn } from "@barqjs/start";
756
+
757
+ const readConfig = createServerOnlyFn(() => process.env.API_TOKEN);
758
+ const storage = createClientOnlyFn(() => localStorage);
759
+ const now = createIsomorphicFn()
760
+ .server(() => "server")
761
+ .client(() => "browser");
762
+ ```
763
+
764
+ The compiler replaces these calls in each bundle. `createServerOnlyFn` keeps its
765
+ body in the server build and becomes a throwing stub in the browser, so a secret
766
+ cannot reach the client even as dead code. `createClientOnlyFn` is the mirror.
767
+ `createIsomorphicFn` keeps one half per bundle, and a half that is not declared
768
+ is a no-op. Uncompiled code, such as a `bun test`, gets the server half.
769
+
770
+ ### Server-only and client-only files
771
+
772
+ `db.server.ts` is for what must not leave the server, `chart.client.ts` for what
773
+ cannot run there. `vite build` fails when code from a `.server.` file is in a
774
+ browser chunk or code from a `.client.` file is in the server bundle, naming the
775
+ file and what imported it. It reads the rendered bundle, so a `.server.` import
776
+ used only inside `createServerOnlyFn`, or a module whose exports are server
777
+ functions, is not a violation. `start: { importProtection: false }` turns it off.
778
+
779
+ `import "server-only"` and `import "client-only"` mark a module the same way at
780
+ the import itself: `@barqjs/vite` fails the build where the browser bundle
781
+ imports `server-only` or the server bundle imports `client-only`, naming the
782
+ importer. Add `/// <reference types="@barqjs/vite/boundary-modules" />` for
783
+ their types.
784
+
785
+ Deployment goes through [srvx](https://github.com/h3js/srvx), so Node, Bun, Deno
786
+ and Cloudflare take the same entry.
787
+
788
+ ### Entry files are optional
789
+
790
+ `src/entry-client.tsx` and `src/entry-server.tsx` are overrides. The defaults
791
+ are two lines each and the plugin supplies them; nothing in an application names
792
+ a `virtual:` or `#`-prefixed specifier.