@barqjs/start 0.0.0-stage → 0.2.0-next.1
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 +21 -0
- package/README.md +817 -2
- package/dist/client-BsyxVCyu.js +1554 -0
- package/dist/client-BsyxVCyu.js.map +1 -0
- package/dist/client-DidH0F2e.d.ts +450 -0
- package/dist/client-DidH0F2e.d.ts.map +1 -0
- package/dist/client.d.ts +25 -0
- package/dist/client.js +4 -0
- package/dist/env-Bhk_aIkx.d.ts +47 -0
- package/dist/env-Bhk_aIkx.d.ts.map +1 -0
- package/dist/env.d.ts +2 -0
- package/dist/env.js +43 -0
- package/dist/env.js.map +1 -0
- package/dist/index-B4o7eyCr.d.ts +925 -0
- package/dist/index-B4o7eyCr.d.ts.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +6 -0
- package/dist/middleware-B-tI8QHQ.d.ts +574 -0
- package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.js +281 -0
- package/dist/middleware.js.map +1 -0
- package/dist/prerender.d.ts +118 -0
- package/dist/prerender.d.ts.map +1 -0
- package/dist/prerender.js +289 -0
- package/dist/prerender.js.map +1 -0
- package/dist/protocol.d.ts +56 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +25 -0
- package/dist/protocol.js.map +1 -0
- package/dist/serve.d.ts +144 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +221 -0
- package/dist/serve.js.map +1 -0
- package/dist/server-DG6jb_NA.js +1253 -0
- package/dist/server-DG6jb_NA.js.map +1 -0
- package/dist/server.d.ts +159 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1 -0
- package/dist/src-odXG7kLA.js +1151 -0
- package/dist/src-odXG7kLA.js.map +1 -0
- package/dist/static-fn-CXjJi-It.js +122 -0
- package/dist/static-fn-CXjJi-It.js.map +1 -0
- package/package.json +106 -4
- package/src/client.ts +698 -0
- package/src/context.ts +699 -0
- package/src/cookies.ts +229 -0
- package/src/env.ts +86 -0
- package/src/fn-error.ts +121 -0
- package/src/frames-client.ts +1220 -0
- package/src/frames-server.ts +464 -0
- package/src/frames.ts +285 -0
- package/src/index.ts +740 -0
- package/src/live-client.ts +50 -0
- package/src/live-server.ts +292 -0
- package/src/middleware.ts +994 -0
- package/src/prerender.ts +477 -0
- package/src/protocol.ts +61 -0
- package/src/rate-limit.ts +202 -0
- package/src/serve.ts +153 -0
- package/src/server.ts +1026 -0
- package/src/session.ts +449 -0
- package/src/start-instance.ts +147 -0
- package/src/static-fn.ts +181 -0
- package/src/static.ts +302 -0
- package/src/stubs.ts +32 -0
- package/src/timing.ts +29 -0
- package/src/wire-types.ts +138 -0
package/src/context.ts
ADDED
|
@@ -0,0 +1,699 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The request a server function, a loader or a route handler is running for —
|
|
3
|
+
* and the response it is building.
|
|
4
|
+
*
|
|
5
|
+
* Ambient rather than threaded through every signature, because a handler five
|
|
6
|
+
* calls deep needs the cookie header and passing a `Request` down to it turns
|
|
7
|
+
* every intermediate function into plumbing. That argument applies to the
|
|
8
|
+
* RESPONSE just as hard: a login sets a cookie from inside the function that
|
|
9
|
+
* checked the password, and threading a `Response` back up through the value it
|
|
10
|
+
* returns is the plumbing again, in the other direction.
|
|
11
|
+
*
|
|
12
|
+
* `AsyncLocalStorage` and not a module-level variable: two requests are in
|
|
13
|
+
* flight at once on any real server, and a module-level variable would hand one
|
|
14
|
+
* request's handler the other's session. SvelteKit shipped exactly that:
|
|
15
|
+
* concurrent requests merged under one context, disclosing data across users.
|
|
16
|
+
* TanStack reaches for the same primitive for the same reason.
|
|
17
|
+
*
|
|
18
|
+
* THE DRAFT IS THE FIX FOR A MEASURED HOLE. Before it, a server function could
|
|
19
|
+
* not set a cookie at all on the JS path: `handleServerFn` answered the `.data`
|
|
20
|
+
* channel with `Response.json(encodeWire(result))`, so a returned `Response`
|
|
21
|
+
* went into the value codec and came back as `Seroval Error (step: 1)` — a 500
|
|
22
|
+
* with nothing in it. The no-JS form path returned it correctly, so the same
|
|
23
|
+
* function behaved differently depending on whether JS had run, which is the
|
|
24
|
+
* one divergence progressive enhancement exists to prevent.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import type { AsyncLocalStorage } from "node:async_hooks";
|
|
28
|
+
|
|
29
|
+
import type { RequestEventLocals, ResponseStub } from "@barqjs/web";
|
|
30
|
+
import {
|
|
31
|
+
commitResponseStub,
|
|
32
|
+
createRequestEvent,
|
|
33
|
+
createResponseStub,
|
|
34
|
+
foldResponseStub,
|
|
35
|
+
} from "@barqjs/web/internal";
|
|
36
|
+
import { diagnosticsEnabled, emitDiagnostic } from "@barqjs/core/internal";
|
|
37
|
+
import { provideRequestEvent } from "@barqjs/server/storage";
|
|
38
|
+
|
|
39
|
+
import { type CookieOptions, deleteCookieLine, parseCookies, serializeCookie } from "./cookies.ts";
|
|
40
|
+
import type { OpenContext } from "./middleware.ts";
|
|
41
|
+
import type { OpenSession } from "./session.ts";
|
|
42
|
+
import type { GlobalRequestContext } from "./start-instance.ts";
|
|
43
|
+
|
|
44
|
+
const REQUEST_EVENT = Symbol.for("barq.request-event");
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Headers and a status a handler asked for, merged into whatever is returned:
|
|
48
|
+
* the request event's response head, Solid's `ResponseStub`, under the name
|
|
49
|
+
* this package's helpers have always given it.
|
|
50
|
+
*/
|
|
51
|
+
export type ResponseDraft = ResponseStub;
|
|
52
|
+
|
|
53
|
+
export interface RequestContext {
|
|
54
|
+
request: Request;
|
|
55
|
+
/** What the handler has asked the response to carry. */
|
|
56
|
+
response: ResponseDraft;
|
|
57
|
+
/** Solid's `RequestEvent.locals`: what middleware hangs on the request. */
|
|
58
|
+
locals: RequestEventLocals;
|
|
59
|
+
/**
|
|
60
|
+
* The request's cookies, parsed ONCE.
|
|
61
|
+
*
|
|
62
|
+
* `getCookie` went through `parseCookies` every call, so a middleware that
|
|
63
|
+
* reads a session, a handler that reads a preference and a loader that reads a
|
|
64
|
+
* locale re-split the same header three times. The header is immutable for the
|
|
65
|
+
* life of the request, so the parse is too.
|
|
66
|
+
*/
|
|
67
|
+
cookies?: Record<string, string>;
|
|
68
|
+
/**
|
|
69
|
+
* Rules `@barqjs/css` registered while rendering THIS request.
|
|
70
|
+
*
|
|
71
|
+
* A server imports the application once and serves forever, so a module-scope
|
|
72
|
+
* rule belongs to every request and a rule a component body registers belongs
|
|
73
|
+
* to one. Kept here rather than in the css package because this is what knows
|
|
74
|
+
* which request is current — two in flight at once cannot take each other's.
|
|
75
|
+
*/
|
|
76
|
+
css?: Map<string, string>;
|
|
77
|
+
/**
|
|
78
|
+
* Reads every rule registered after THIS request's head sheet was serialised.
|
|
79
|
+
*
|
|
80
|
+
* What the page is owed once it has a head, in place of {@link css}: a rule
|
|
81
|
+
* ANOTHER request registered after this one's head is one this render can
|
|
82
|
+
* still use, as a class a module already holds, and it registers nothing
|
|
83
|
+
* when it does. So the line is the head and not who registered what.
|
|
84
|
+
*/
|
|
85
|
+
lateCss?: () => string;
|
|
86
|
+
/**
|
|
87
|
+
* What a server function's chain asked to send back, held for the request
|
|
88
|
+
* handler to put on the response.
|
|
89
|
+
*
|
|
90
|
+
* Here and not in a module-level variable for the reason this file opens
|
|
91
|
+
* with: two requests whose handlers settle in the same tick would each read
|
|
92
|
+
* whichever chain wrote last, and that is one caller's `sendContext` on
|
|
93
|
+
* another caller's response.
|
|
94
|
+
*/
|
|
95
|
+
sendContext?: Record<string, unknown>;
|
|
96
|
+
/** The server functions whose frames this request's mutation changed. */
|
|
97
|
+
invalidatedFrames?: Set<string>;
|
|
98
|
+
/**
|
|
99
|
+
* The sessions this request has opened, by cookie name.
|
|
100
|
+
*
|
|
101
|
+
* The request's cookie is what the browser HAD. A second `useSession` that
|
|
102
|
+
* read it again would start from before the first one's `update`, and its own
|
|
103
|
+
* `update` would then seal a session without that change over the top of it.
|
|
104
|
+
*/
|
|
105
|
+
sessions?: Map<string, Promise<OpenSession>>;
|
|
106
|
+
/**
|
|
107
|
+
* What the request middleware chain contributed with `next({ context })`.
|
|
108
|
+
*
|
|
109
|
+
* A server function's own chain starts from it, and a route handler is
|
|
110
|
+
* handed it, so a global middleware that resolved a session says so once.
|
|
111
|
+
*/
|
|
112
|
+
middlewareContext?: Record<string, unknown>;
|
|
113
|
+
/**
|
|
114
|
+
* Why this request must not be read, when it must not be.
|
|
115
|
+
*
|
|
116
|
+
* A PRERENDER holds a `Request` a build minted, so `getRequest()` would
|
|
117
|
+
* answer with a build machine's headers and a cookie jar that is empty for
|
|
118
|
+
* everyone. SvelteKit guards `url.search` alone and lets `cookies.get` and
|
|
119
|
+
* `request.headers` return null in silence; its own tracker records that as
|
|
120
|
+
* multi-day debugging. Refusing is the honest answer, and the message names
|
|
121
|
+
* what to do instead.
|
|
122
|
+
*/
|
|
123
|
+
refuse?: string;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The request event's storage, under the symbol `getRequestEvent` reads and
|
|
128
|
+
* `provideRequestEvent` enters, so a component asking Solid's way finds the
|
|
129
|
+
* request a handler entered.
|
|
130
|
+
*
|
|
131
|
+
* ONE storage per process, whichever copy of this module asks: a build
|
|
132
|
+
* compiles this module into its server bundle, and a host serving that bundle
|
|
133
|
+
* through its own `serveBarq` has imported a second copy. Each holding its own,
|
|
134
|
+
* the host entered the request into one and the bundle's functions read the
|
|
135
|
+
* other, so every server function that read a cookie answered 500.
|
|
136
|
+
*
|
|
137
|
+
* Read lazily, and nothing is constructed here: `@barqjs/start` is the
|
|
138
|
+
* ISOMORPHIC entry, so a browser bundle evaluates this module, and a bundler
|
|
139
|
+
* answers `node:async_hooks` there with an empty stub. No storage is no
|
|
140
|
+
* request in flight, which is what the read path reports.
|
|
141
|
+
*/
|
|
142
|
+
const SHARED = {
|
|
143
|
+
get storage(): AsyncLocalStorage<RequestContext> | undefined {
|
|
144
|
+
return (globalThis as { [REQUEST_EVENT]?: AsyncLocalStorage<RequestContext> })[REQUEST_EVENT];
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** A fresh, empty draft, one per request: Solid's `createResponseStub`. */
|
|
149
|
+
export const createResponseDraft: () => ResponseDraft = createResponseStub;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Send `@barqjs/css`'s render-time rules to whichever request is running.
|
|
153
|
+
*
|
|
154
|
+
* Installed once, by the generated server entry. Outside a request — module
|
|
155
|
+
* scope, and the browser — there is nothing to attribute a rule to, so it falls
|
|
156
|
+
* back to the package's own sheet, which is where a module-scope rule belongs.
|
|
157
|
+
*/
|
|
158
|
+
export function collectRequestCss(): string {
|
|
159
|
+
const store = SHARED.storage?.getStore();
|
|
160
|
+
if (store?.lateCss !== undefined) return store.lateCss();
|
|
161
|
+
return store?.css === undefined ? "" : [...store.css.values()].join("");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const DEV_STYLESHEETS = Symbol.for("barq.dev.stylesheets");
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The compiled module stylesheets a page made of `routes` reaches, in the order
|
|
168
|
+
* the page's modules run, when a dev server answered that, and `undefined`
|
|
169
|
+
* where none did: a build links its stylesheets instead of inlining them.
|
|
170
|
+
*
|
|
171
|
+
* A dev server imports the application once and renders every page from the
|
|
172
|
+
* one registry, so without this a page's head carried the rules of every module
|
|
173
|
+
* any earlier request had reached. `@barqjs/vite` installs the answer, read off
|
|
174
|
+
* its module graph in the order a build links the same modules' stylesheets.
|
|
175
|
+
*/
|
|
176
|
+
export function devStylesheets(
|
|
177
|
+
routes: readonly string[],
|
|
178
|
+
): Promise<DevStylesheets | undefined> | undefined {
|
|
179
|
+
const answer = (
|
|
180
|
+
globalThis as {
|
|
181
|
+
[DEV_STYLESHEETS]?: (routes: readonly string[]) => Promise<DevStylesheets>;
|
|
182
|
+
}
|
|
183
|
+
)[DEV_STYLESHEETS];
|
|
184
|
+
return answer?.(routes);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** `@barqjs/css`'s `CssScope`, restated so this package does not import that one. */
|
|
188
|
+
export interface DevStylesheets {
|
|
189
|
+
readonly keys: readonly string[];
|
|
190
|
+
readonly modules: ReadonlySet<string>;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** `@barqjs/css`'s `CssSink`, restated so this package does not import that one. */
|
|
194
|
+
interface CssSink {
|
|
195
|
+
(key: string, rules: string): boolean;
|
|
196
|
+
head?(late: () => string): void;
|
|
197
|
+
owns?(key: string): boolean;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function installCssSink(setSink: (sink: CssSink) => void): void {
|
|
201
|
+
const sink: CssSink = (key, rules) => {
|
|
202
|
+
const store = SHARED.storage?.getStore();
|
|
203
|
+
// Outside a request there is nothing to attribute the rule to — module
|
|
204
|
+
// scope, which every request needs — so it goes to the package's own sheet.
|
|
205
|
+
if (store === undefined) return false;
|
|
206
|
+
store.css ??= new Map();
|
|
207
|
+
store.css.set(key, rules);
|
|
208
|
+
return true;
|
|
209
|
+
};
|
|
210
|
+
// The FIRST read of the whole sheet in a request is its `<head>`; a later
|
|
211
|
+
// one is somebody else's and must not move the line.
|
|
212
|
+
sink.head = (late) => {
|
|
213
|
+
const store = SHARED.storage?.getStore();
|
|
214
|
+
if (store !== undefined) store.lateCss ??= late;
|
|
215
|
+
};
|
|
216
|
+
// Outside a request every rule is every page's, so nothing is owned and the
|
|
217
|
+
// registry shows what no request registered.
|
|
218
|
+
sink.owns = (key) => SHARED.storage?.getStore()?.css?.has(key) === true;
|
|
219
|
+
setSink(sink);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Run `body` with `request` as the ambient one, under the event
|
|
224
|
+
* `createRequestEvent` builds for it and `provideRequestEvent` enters.
|
|
225
|
+
*
|
|
226
|
+
* The DRAFT is the caller's to hold, because the caller is what builds the
|
|
227
|
+
* response and it does so after `body` has returned.
|
|
228
|
+
*/
|
|
229
|
+
export function withRequest<T>(
|
|
230
|
+
request: Request,
|
|
231
|
+
body: () => T,
|
|
232
|
+
options: { readonly refuse?: string; readonly response?: ResponseDraft } | string = {},
|
|
233
|
+
): T {
|
|
234
|
+
// The third argument was a bare `refuse` string before the draft existed.
|
|
235
|
+
// Both spellings work, because the string form reads better at the one call
|
|
236
|
+
// site that uses it — the prerenderer, which refuses and carries no draft.
|
|
237
|
+
const resolved = typeof options === "string" ? { refuse: options } : options;
|
|
238
|
+
return provideRequestEvent(
|
|
239
|
+
createRequestEvent(request, {
|
|
240
|
+
refuse: resolved.refuse,
|
|
241
|
+
response: resolved.response ?? createResponseStub(),
|
|
242
|
+
}),
|
|
243
|
+
body,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The request this handler is running for.
|
|
249
|
+
*
|
|
250
|
+
* Throws outside one rather than returning undefined: a handler reading cookies
|
|
251
|
+
* off `undefined` is a bug that should surface where it happens, not resolve to
|
|
252
|
+
* "no session" and let the request through.
|
|
253
|
+
*/
|
|
254
|
+
export function getRequest(): Request {
|
|
255
|
+
return context().request;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The request, or undefined outside one. For code that legitimately runs both ways.
|
|
260
|
+
*
|
|
261
|
+
* A refused context reads as ABSENT here rather than throwing: `peekRequest` is
|
|
262
|
+
* the "I may not be in a request" spelling, and a prerender is exactly that
|
|
263
|
+
* case. Code that must have one calls `getRequest` and gets the refusal.
|
|
264
|
+
*/
|
|
265
|
+
export function peekRequest(): Request | undefined {
|
|
266
|
+
const found = SHARED.storage?.getStore();
|
|
267
|
+
return found === undefined || found.refuse !== undefined ? undefined : found.request;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function context(): RequestContext {
|
|
271
|
+
const found = SHARED.storage?.getStore();
|
|
272
|
+
if (found === undefined) {
|
|
273
|
+
throw new Error(
|
|
274
|
+
"[barq] A request helper such as `getRequest()`, `getCookie()` or `setResponseHeader()` was called outside a request, so there is no request to read and no response to write to. " +
|
|
275
|
+
"These helpers are only available inside a request: call them from a server function, a route handler, a loader or a `beforeLoad`.",
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
if (found.refuse !== undefined) throw new Error(found.refuse);
|
|
279
|
+
return found;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The draft, or `undefined` outside a request.
|
|
284
|
+
*
|
|
285
|
+
* Used by the two handlers to merge on the way out, and by nothing else. A
|
|
286
|
+
* REFUSED context still answers here: a prerender may not read the request, but
|
|
287
|
+
* a `head` or a loader that sets a cache header during one is describing the
|
|
288
|
+
* page rather than the requester, and the prerenderer can write it to disk.
|
|
289
|
+
*/
|
|
290
|
+
export function peekResponseDraft(): ResponseDraft | undefined {
|
|
291
|
+
return SHARED.storage?.getStore()?.response;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Leave a chain's `sendContext` for whoever builds this request's response.
|
|
296
|
+
*
|
|
297
|
+
* Outside a request there is no response to carry it, so it is dropped: that is
|
|
298
|
+
* a server function called in-process, whose caller is handed the result alone.
|
|
299
|
+
*/
|
|
300
|
+
export function offerSendContext(sendContext: Record<string, unknown>): void {
|
|
301
|
+
const found = SHARED.storage?.getStore();
|
|
302
|
+
if (found !== undefined) found.sendContext = sendContext;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Say that this mutation changed what these server functions' frames show, so
|
|
307
|
+
* its answer carries those regions, rendered again, beside its value: single
|
|
308
|
+
* flight, one round trip. A frame the page has not mounted is not rendered.
|
|
309
|
+
* Outside a request it does nothing, as there is no answer to carry them.
|
|
310
|
+
*/
|
|
311
|
+
export function invalidateFrames(
|
|
312
|
+
...fns: readonly { readonly meta: { readonly id: string } }[]
|
|
313
|
+
): void {
|
|
314
|
+
const found = SHARED.storage?.getStore();
|
|
315
|
+
if (found === undefined) return;
|
|
316
|
+
found.invalidatedFrames ??= new Set();
|
|
317
|
+
for (const fn of fns) found.invalidatedFrames.add(fn.meta.id);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** The server functions `invalidateFrames` named in this request, or none. */
|
|
321
|
+
export function invalidatedFrames(): ReadonlySet<string> {
|
|
322
|
+
return SHARED.storage?.getStore()?.invalidatedFrames ?? EMPTY_SET;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const EMPTY_SET: ReadonlySet<string> = new Set();
|
|
326
|
+
|
|
327
|
+
/** Take the pending `sendContext`, leaving nothing behind for the next call. */
|
|
328
|
+
export function takeSendContext(): Record<string, unknown> {
|
|
329
|
+
const found = SHARED.storage?.getStore();
|
|
330
|
+
const taken = found?.sendContext ?? {};
|
|
331
|
+
if (found !== undefined) found.sendContext = undefined;
|
|
332
|
+
return taken;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* What this request's middleware chain has contributed, or an empty record
|
|
337
|
+
* outside a request. TanStack's name.
|
|
338
|
+
*
|
|
339
|
+
* Typed by what the registered global request middleware passes to
|
|
340
|
+
* `next({ context })`, each key optional: outside a request, or before the
|
|
341
|
+
* chain has reached the step that adds it, it is not there.
|
|
342
|
+
*/
|
|
343
|
+
export function getGlobalStartContext(): OpenContext<Partial<GlobalRequestContext>> {
|
|
344
|
+
const written: Record<string, unknown> = SHARED.storage?.getStore()?.middlewareContext ?? {};
|
|
345
|
+
return written;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Record what the request middleware chain is contributing, for the rest of the request. */
|
|
349
|
+
export function setRequestMiddlewareContext(context: Record<string, unknown>): void {
|
|
350
|
+
const found = SHARED.storage?.getStore();
|
|
351
|
+
if (found !== undefined) found.middlewareContext = context;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** The sessions this request has opened. See {@link RequestContext.sessions}. */
|
|
355
|
+
export function openSessions(): Map<string, Promise<OpenSession>> {
|
|
356
|
+
const found = context();
|
|
357
|
+
found.sessions ??= new Map();
|
|
358
|
+
return found.sessions;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ---------------------------------------------------------------------------
|
|
362
|
+
// The request, read
|
|
363
|
+
// ---------------------------------------------------------------------------
|
|
364
|
+
|
|
365
|
+
export function getRequestHeaders(): Headers {
|
|
366
|
+
return getRequest().headers;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function getRequestHeader(name: string): string | undefined {
|
|
370
|
+
return getRequest().headers.get(name) ?? undefined;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** The request URL, parsed. */
|
|
374
|
+
export function getRequestUrl(): URL {
|
|
375
|
+
return new URL(getRequest().url);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* How far `X-Forwarded-For` is believed.
|
|
380
|
+
*
|
|
381
|
+
* `true` takes the LEFTMOST entry, and is safe only when the edge proxy
|
|
382
|
+
* OVERWRITES the header. A proxy that appends, which is what most do, leaves
|
|
383
|
+
* whatever the client sent at the front: `X-Forwarded-For: 203.0.113.9` on the
|
|
384
|
+
* request arrives as `203.0.113.9, <real address>`, and the leftmost entry is
|
|
385
|
+
* the one the caller typed.
|
|
386
|
+
*
|
|
387
|
+
* `{ trustedProxies: n }` counts from the RIGHT instead: the entry the nth
|
|
388
|
+
* proxy in front of this process wrote, which is the address that proxy saw.
|
|
389
|
+
* Entries to its left were there before any trusted hop touched the header, so
|
|
390
|
+
* a forged prefix is never read. A header with fewer than `n` entries did not
|
|
391
|
+
* come through that chain and is ignored whole.
|
|
392
|
+
*/
|
|
393
|
+
export type ForwardedForTrust = boolean | { readonly trustedProxies: number };
|
|
394
|
+
|
|
395
|
+
/** Refuse a hop count that names no entry, where the option is written. */
|
|
396
|
+
export function assertForwardedForTrust(trust: ForwardedForTrust | undefined): void {
|
|
397
|
+
if (typeof trust !== "object") return;
|
|
398
|
+
if (!Number.isInteger(trust.trustedProxies) || trust.trustedProxies < 1) {
|
|
399
|
+
throw new RangeError(
|
|
400
|
+
`[barq] \`trustedProxies\` must be a positive integer, and it is ${trust.trustedProxies}. ` +
|
|
401
|
+
"Set it to the number of proxies you run in front of this server: each one appends one entry to `X-Forwarded-For`, and the client address is counted back from the end.",
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* The client's address, or `undefined`.
|
|
408
|
+
*
|
|
409
|
+
* `xForwardedFor` IS OFF BY DEFAULT and that is the whole design of this
|
|
410
|
+
* function. `X-Forwarded-For` is a header a client can send, so trusting it
|
|
411
|
+
* unconditionally lets any caller claim any address — and an address is exactly
|
|
412
|
+
* what rate limiting and audit logging key on. It is trustworthy only when a
|
|
413
|
+
* proxy you control overwrites it, which is a fact about the deployment that
|
|
414
|
+
* this process cannot discover. So it is opt-in, and the opt-in is per call.
|
|
415
|
+
*
|
|
416
|
+
* The LEFTMOST entry is taken when it is trusted, since that is the original
|
|
417
|
+
* client; every entry to its right was appended by a hop. {@link
|
|
418
|
+
* ForwardedForTrust} says when that is forgeable and what to pass instead.
|
|
419
|
+
*/
|
|
420
|
+
export function getRequestIP(
|
|
421
|
+
options: { readonly xForwardedFor?: ForwardedForTrust } = {},
|
|
422
|
+
): string | undefined {
|
|
423
|
+
const request = getRequest();
|
|
424
|
+
const trust = options.xForwardedFor;
|
|
425
|
+
if (trust !== undefined && trust !== false) {
|
|
426
|
+
assertForwardedForTrust(trust);
|
|
427
|
+
const entries = request.headers.get("x-forwarded-for")?.split(",") ?? [];
|
|
428
|
+
const entry = trust === true ? entries[0] : entries[entries.length - trust.trustedProxies];
|
|
429
|
+
const address = entry?.trim();
|
|
430
|
+
if (address !== undefined && address !== "") return address;
|
|
431
|
+
}
|
|
432
|
+
// What a runtime attaches when it knows. `srvx` and Bun both use this name.
|
|
433
|
+
const direct = (request as { ip?: string }).ip;
|
|
434
|
+
return direct === "" ? undefined : direct;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* The host, from the URL — and from `X-Forwarded-Host` only when asked.
|
|
439
|
+
*
|
|
440
|
+
* Same rule as `getRequestIP`, and the consequence is sharper: a host taken
|
|
441
|
+
* from an untrusted header and used to build an absolute URL is a host-header
|
|
442
|
+
* injection, which turns a password-reset link into a link to the attacker.
|
|
443
|
+
*/
|
|
444
|
+
export function getRequestHost(options: { readonly xForwardedHost?: boolean } = {}): string {
|
|
445
|
+
const request = getRequest();
|
|
446
|
+
if (options.xForwardedHost === true) {
|
|
447
|
+
const forwarded = request.headers.get("x-forwarded-host");
|
|
448
|
+
if (forwarded !== null && forwarded !== "") return forwarded;
|
|
449
|
+
}
|
|
450
|
+
return new URL(request.url).host;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** `http` or `https`. `X-Forwarded-Proto` only when asked, for the reason above. */
|
|
454
|
+
export function getRequestProtocol(options: { readonly xForwardedProto?: boolean } = {}): string {
|
|
455
|
+
const request = getRequest();
|
|
456
|
+
if (options.xForwardedProto === true) {
|
|
457
|
+
const forwarded = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
|
|
458
|
+
if (forwarded !== undefined && forwarded !== "") return forwarded;
|
|
459
|
+
}
|
|
460
|
+
return new URL(request.url).protocol.replace(":", "");
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// ---------------------------------------------------------------------------
|
|
464
|
+
// The response, written
|
|
465
|
+
// ---------------------------------------------------------------------------
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Mark the draft's response as handed to the server: Solid's
|
|
469
|
+
* `commitResponseStub`. A streamed page goes on rendering after this, and so
|
|
470
|
+
* does a streamed server function, and a header one of them writes now changes
|
|
471
|
+
* nothing the browser receives.
|
|
472
|
+
*/
|
|
473
|
+
export const markResponseSent: typeof commitResponseStub = commitResponseStub;
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* The draft a write goes to, reporting the write when the response has already
|
|
477
|
+
* gone. `api` is the public function the caller called, so the stack the
|
|
478
|
+
* report carries starts at the caller rather than in here.
|
|
479
|
+
*/
|
|
480
|
+
function draftFor(api: (...args: never[]) => unknown, argument?: unknown): ResponseDraft {
|
|
481
|
+
const draft = context().response;
|
|
482
|
+
if (draft.committed !== true) return draft;
|
|
483
|
+
if (diagnosticsEnabled()) reportLateWrite(api, argument);
|
|
484
|
+
// Somewhere the write can land and go nowhere, reported once, here.
|
|
485
|
+
return createResponseStub();
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function reportLateWrite(api: (...args: never[]) => unknown, argument: unknown): void {
|
|
489
|
+
const call = `${api.name}(${argument === undefined ? "" : JSON.stringify(argument)})`;
|
|
490
|
+
const error = new Error(`${call} ran after the response was sent`);
|
|
491
|
+
Error.captureStackTrace(error, api);
|
|
492
|
+
const caller = /^\s*at\s+(.*)$/m.exec(error.stack?.split("\n").slice(1).join("\n") ?? "")?.[1];
|
|
493
|
+
emitDiagnostic(
|
|
494
|
+
{
|
|
495
|
+
code: "LATE_HEADER_WRITE",
|
|
496
|
+
kind: "head",
|
|
497
|
+
severity: "warn",
|
|
498
|
+
message:
|
|
499
|
+
`\`${call}\` ran ${caller === undefined ? "" : `at ${caller} `}after the response's status ` +
|
|
500
|
+
"and headers had been sent, so it changed nothing the browser receives. Code runs that late " +
|
|
501
|
+
"inside a part of the page that renders after the shell (a `<Loading>` boundary or a " +
|
|
502
|
+
"loader the shell does not wait for), or in a streamed server function after its first " +
|
|
503
|
+
"value. Set the status, headers and cookies while the response is still open: in a " +
|
|
504
|
+
"`beforeLoad`, a loader the route awaits, a route handler, a middleware, or a server " +
|
|
505
|
+
"function before it returns.",
|
|
506
|
+
data: { call, error },
|
|
507
|
+
},
|
|
508
|
+
null,
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
export function getResponseHeaders(): Headers {
|
|
513
|
+
return context().response.headers;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
export function getResponseHeader(name: string): string | undefined {
|
|
517
|
+
return context().response.headers.get(name) ?? undefined;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Set a response header. An array APPENDS each value, which is what a header
|
|
522
|
+
* that may legitimately repeat needs.
|
|
523
|
+
*/
|
|
524
|
+
export function setResponseHeader(name: string, value: string | readonly string[]): void {
|
|
525
|
+
const headers = draftFor(setResponseHeader, name).headers;
|
|
526
|
+
if (typeof value === "string") {
|
|
527
|
+
headers.set(name, value);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
headers.delete(name);
|
|
531
|
+
for (const one of value) headers.append(name, one);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Add a value to a response header, keeping the ones already there.
|
|
536
|
+
*
|
|
537
|
+
* For a header that is a list: `Vary`, `Link`, `Cache-Control` built up by more
|
|
538
|
+
* than one caller. `setResponseHeader` replaces.
|
|
539
|
+
*/
|
|
540
|
+
export function appendResponseHeader(name: string, value: string): void {
|
|
541
|
+
draftFor(appendResponseHeader, name).headers.append(name, value);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
export function setResponseHeaders(headers: Record<string, string>): void {
|
|
545
|
+
for (const [name, value] of Object.entries(headers)) setResponseHeader(name, value);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export function removeResponseHeader(name: string): void {
|
|
549
|
+
draftFor(removeResponseHeader, name).headers.delete(name);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** Clear the named headers, or every header this request has drafted. */
|
|
553
|
+
export function clearResponseHeaders(names?: readonly string[]): void {
|
|
554
|
+
const headers = draftFor(clearResponseHeaders).headers;
|
|
555
|
+
if (names !== undefined) {
|
|
556
|
+
for (const name of names) headers.delete(name);
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
// Collected first, because deleting while iterating a live `Headers` skips.
|
|
560
|
+
const present: string[] = [];
|
|
561
|
+
for (const name of headers.keys()) present.push(name);
|
|
562
|
+
for (const name of present) headers.delete(name);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
export function getResponseStatus(): number {
|
|
566
|
+
return context().response.status ?? 200;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Set the status the framework's own response will carry.
|
|
571
|
+
*
|
|
572
|
+
* It does NOT override a `Response` a handler returns for itself — see
|
|
573
|
+
* `applyResponseDraft`, which says why.
|
|
574
|
+
*/
|
|
575
|
+
export function setResponseStatus(status: number, statusText?: string): void {
|
|
576
|
+
const draft = draftFor(setResponseStatus, status);
|
|
577
|
+
if (!Number.isInteger(status) || status < 200 || status > 599) {
|
|
578
|
+
throw new RangeError(
|
|
579
|
+
`[barq] \`setResponseStatus(${status})\` was given a value that is not an HTTP response status. Pass an integer from 200 to 599, such as \`setResponseStatus(404)\`.`,
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
draft.status = status;
|
|
583
|
+
if (statusText !== undefined) draft.statusText = statusText;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// ---------------------------------------------------------------------------
|
|
587
|
+
// Cookies
|
|
588
|
+
// ---------------------------------------------------------------------------
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Every cookie the REQUEST carried, by name.
|
|
592
|
+
*
|
|
593
|
+
* Parsed once and memoised on the context: the header cannot change for the life
|
|
594
|
+
* of the request, and re-splitting it per lookup made three readers three
|
|
595
|
+
* parses. The object is returned as it stands rather than copied, which is the
|
|
596
|
+
* point — copying it per call would put the allocation back.
|
|
597
|
+
*/
|
|
598
|
+
export function getCookies(): Record<string, string> {
|
|
599
|
+
const found = context();
|
|
600
|
+
found.cookies ??= parseCookies(found.request.headers.get("cookie"));
|
|
601
|
+
return found.cookies;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
export function getCookie(name: string): string | undefined {
|
|
605
|
+
return getCookies()[name];
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Set a cookie on the response.
|
|
610
|
+
*
|
|
611
|
+
* APPENDS, because several cookies are several `Set-Cookie` lines and a
|
|
612
|
+
* browser keeps only the last of a set. Setting the same NAME twice in one
|
|
613
|
+
* request is the caller's business — the last one wins in the browser, as ever.
|
|
614
|
+
*/
|
|
615
|
+
export function setCookie(name: string, value: string, options?: CookieOptions): void {
|
|
616
|
+
draftFor(setCookie, name).headers.append(
|
|
617
|
+
"set-cookie",
|
|
618
|
+
serializeCookie(name, value, rooted(options)),
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* Set a cookie in place of any line this request already drafted for its name.
|
|
624
|
+
*
|
|
625
|
+
* For a cookie one request may write more than once and of which only the last
|
|
626
|
+
* line means anything, which is a session: each of its lines runs to 4 KB, and
|
|
627
|
+
* a proxy that buffers response headers in 4 or 8 KB answers 502 to two of
|
|
628
|
+
* them. `setCookie` appends, which is right for everything else.
|
|
629
|
+
*/
|
|
630
|
+
export function replaceCookie(name: string, value: string, options?: CookieOptions): void {
|
|
631
|
+
const headers = draftFor(replaceCookie, name).headers;
|
|
632
|
+
// Serialized before anything is removed, so a cookie that is refused leaves
|
|
633
|
+
// the draft as it was.
|
|
634
|
+
const line = serializeCookie(name, value, rooted(options));
|
|
635
|
+
const prefix = `${name}=`;
|
|
636
|
+
const kept = headers.getSetCookie().filter((other) => !other.startsWith(prefix));
|
|
637
|
+
headers.delete("set-cookie");
|
|
638
|
+
for (const other of kept) headers.append("set-cookie", other);
|
|
639
|
+
headers.append("set-cookie", line);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* The options, with `path: "/"` where the caller chose none.
|
|
644
|
+
*
|
|
645
|
+
* A browser gives a cookie that names no `Path` the directory of the URL that
|
|
646
|
+
* set it (RFC 6265 §5.1.4). For a server function that is `/_barq/fn`, so the
|
|
647
|
+
* cookie would come back on other server functions and on no page at all.
|
|
648
|
+
* `serializeCookie` stays literal; the default belongs where the URL is known
|
|
649
|
+
* to be the wrong scope.
|
|
650
|
+
*/
|
|
651
|
+
function rooted(options: CookieOptions | undefined): CookieOptions {
|
|
652
|
+
return options?.path === undefined ? { ...options, path: "/" } : options;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/**
|
|
656
|
+
* Delete a cookie.
|
|
657
|
+
*
|
|
658
|
+
* `path` and `domain` MUST match the ones it was set with, or the browser
|
|
659
|
+
* deletes nothing and keeps the original — silently. They are options here for
|
|
660
|
+
* exactly that reason rather than as decoration. With no `path` it names `/`,
|
|
661
|
+
* which is what `setCookie` gave a cookie that was set with none.
|
|
662
|
+
*/
|
|
663
|
+
export function deleteCookie(name: string, options?: CookieOptions): void {
|
|
664
|
+
draftFor(deleteCookie, name).headers.append(
|
|
665
|
+
"set-cookie",
|
|
666
|
+
deleteCookieLine(name, rooted(options)),
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// ---------------------------------------------------------------------------
|
|
671
|
+
// Merging
|
|
672
|
+
// ---------------------------------------------------------------------------
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* Fold a draft into a response, Solid's fold for `commitEventResponse` without
|
|
676
|
+
* the commit: `foldResponseStub` in `@barqjs/web` says what wins and why.
|
|
677
|
+
*
|
|
678
|
+
* It does NOT override the status of a `Response` a handler returned, because
|
|
679
|
+
* a handler that built a whole response has said what it wants.
|
|
680
|
+
*/
|
|
681
|
+
export const applyResponseDraft: (
|
|
682
|
+
response: Response,
|
|
683
|
+
draft: ResponseDraft | undefined,
|
|
684
|
+
) => Response = foldResponseStub;
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* The status and text a framework-built response should carry.
|
|
688
|
+
*
|
|
689
|
+
* Separate from `applyResponseDraft` because the two answer different
|
|
690
|
+
* questions: this is "what did the handler ask for", used where the framework
|
|
691
|
+
* is deciding the status itself, and that one is "what does a returned response
|
|
692
|
+
* already say", where the handler has decided.
|
|
693
|
+
*/
|
|
694
|
+
export function draftedStatus(
|
|
695
|
+
draft: ResponseDraft | undefined,
|
|
696
|
+
fallback: number,
|
|
697
|
+
): { status: number; statusText?: string } {
|
|
698
|
+
return { status: draft?.status ?? fallback, statusText: draft?.statusText };
|
|
699
|
+
}
|