@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.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +817 -2
  3. package/dist/client-BsyxVCyu.js +1554 -0
  4. package/dist/client-BsyxVCyu.js.map +1 -0
  5. package/dist/client-DidH0F2e.d.ts +450 -0
  6. package/dist/client-DidH0F2e.d.ts.map +1 -0
  7. package/dist/client.d.ts +25 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-Bhk_aIkx.d.ts +47 -0
  10. package/dist/env-Bhk_aIkx.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +43 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-B4o7eyCr.d.ts +925 -0
  15. package/dist/index-B4o7eyCr.d.ts.map +1 -0
  16. package/dist/index.d.ts +18 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-B-tI8QHQ.d.ts +574 -0
  19. package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +281 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +118 -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 +56 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +25 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +144 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +221 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-DG6jb_NA.js +1253 -0
  36. package/dist/server-DG6jb_NA.js.map +1 -0
  37. package/dist/server.d.ts +159 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-odXG7kLA.js +1151 -0
  41. package/dist/src-odXG7kLA.js.map +1 -0
  42. package/dist/static-fn-CXjJi-It.js +122 -0
  43. package/dist/static-fn-CXjJi-It.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +698 -0
  46. package/src/context.ts +699 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +121 -0
  50. package/src/frames-client.ts +1220 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +740 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +292 -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 +1026 -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 +138 -0
@@ -0,0 +1,994 @@
1
+ /**
2
+ * Middleware, and the input validation it composes.
3
+ *
4
+ * ITS OWN MODULE FOR ONE REASON: `client.ts` needs it. A middleware's client
5
+ * half runs in the browser, so the runner has to be reachable from the client
6
+ * stub — and `index.ts` re-exports `context.ts`, which reaches
7
+ * `node:async_hooks`. Importing the index from `client.ts` is the leak
8
+ * `DEFAULT_CLIENT_SOURCE` exists to avoid, and it is not theoretical: the same
9
+ * import through a route's `middleware` once left a fully server-rendered page
10
+ * on which nothing was interactive.
11
+ *
12
+ * Nothing here imports anything of barq's, for that reason.
13
+ */
14
+
15
+ /**
16
+ * A validator in the Standard Schema shape, which zod, valibot and arktype all
17
+ * implement. Taking the interface rather than a library keeps the dependency
18
+ * out and lets an application bring its own.
19
+ */
20
+ export interface StandardSchema<In = unknown, Out = In> {
21
+ "~standard": {
22
+ version: 1;
23
+ vendor: string;
24
+ validate: (
25
+ value: unknown,
26
+ ) =>
27
+ | { value: Out }
28
+ | { issues: ReadonlyArray<unknown> }
29
+ | Promise<{ value: Out } | { issues: ReadonlyArray<unknown> }>;
30
+ /** The spec's type carrier: what the schema takes and what it produces. */
31
+ readonly types?: { readonly input: In; readonly output: Out };
32
+ };
33
+ }
34
+
35
+ /** Anything with a Standard Schema validator on it, which is all a schema is read for. */
36
+ export interface StandardSchemaLike {
37
+ readonly "~standard": { readonly validate: (value: unknown) => unknown };
38
+ }
39
+
40
+ /** What a caller hands a schema: its declared input, or anything when it declares none. */
41
+ export type StandardInput<Schema> = [SchemaTypes<Schema>] extends [{ readonly input: infer In }]
42
+ ? In
43
+ : unknown;
44
+
45
+ /** What a schema produces: its declared output, or what its `validate` succeeds with. */
46
+ export type StandardOutput<Schema> = [SchemaTypes<Schema>] extends [{ readonly output: infer Out }]
47
+ ? Out
48
+ : Schema extends { readonly "~standard": { readonly validate: (value: unknown) => infer Result } }
49
+ ? Succeeded<Awaited<Result>>
50
+ : unknown;
51
+
52
+ /** The spec's optional `types`, read by key: a schema without it shares no member to match on. */
53
+ type SchemaTypes<Schema> = Schema extends { readonly "~standard": infer Spec }
54
+ ? "types" extends keyof Spec
55
+ ? NonNullable<Spec["types" & keyof Spec]>
56
+ : undefined
57
+ : undefined;
58
+
59
+ type Succeeded<Result> = Result extends { readonly value: infer Out } ? Out : never;
60
+
61
+ /**
62
+ * `'unchecked'` is the only way to open the input channel without a schema, and
63
+ * it has to be typed out.
64
+ *
65
+ * The default is the opposite: a server function declared with no validator
66
+ * rejects ANY argument off the wire with a 400. Every system surveyed except
67
+ * SvelteKit passes raw deserialized input straight into the handler, and the
68
+ * cost of not doing so is one word.
69
+ */
70
+ export type Validator<T> = StandardSchema<unknown, T> | "unchecked";
71
+
72
+ /**
73
+ * What `.validator()` and `.inputValidator()` accept: a Standard Schema, a
74
+ * function that returns the validated value or throws, or an object with a
75
+ * `parse` that does. TanStack's three, probed in that order, since a zod schema
76
+ * is both the first and the third and the first reports issues without
77
+ * throwing.
78
+ */
79
+ export type ValidatorInput<T> =
80
+ | Validator<T>
81
+ | ((input: unknown) => T | Promise<T>)
82
+ | { readonly parse: (input: unknown) => T | Promise<T> };
83
+
84
+ /** Any accepted validator, as the one shape the runner applies. */
85
+ export function toValidator<T>(input: ValidatorInput<T>): Validator<T> {
86
+ if (input === "unchecked") return input;
87
+ // The schema before the function: an arktype type is BOTH, and called as a
88
+ // function it returns its errors rather than throwing them.
89
+ if ("~standard" in input) return input;
90
+ if (typeof input === "function") return checkedBy(input);
91
+ return checkedBy((raw) => input.parse(raw));
92
+ }
93
+
94
+ function checkedBy<T>(check: (input: unknown) => T | Promise<T>): StandardSchema<unknown, T> {
95
+ return {
96
+ "~standard": {
97
+ version: 1,
98
+ vendor: "barq",
99
+ validate: async (value) => {
100
+ try {
101
+ return { value: await check(value) };
102
+ } catch (error) {
103
+ // A refusal that is an answer of its own stays one.
104
+ if (error instanceof Response) throw error;
105
+ return { issues: [{ message: error instanceof Error ? error.message : String(error) }] };
106
+ }
107
+ },
108
+ },
109
+ };
110
+ }
111
+
112
+ const INPUT_ERROR = Symbol.for("barq.input-error");
113
+
114
+ /**
115
+ * The caller's input was not acceptable — a 400 rather than a 500, whichever way
116
+ * it failed. One base so the handler cannot answer one of them correctly and
117
+ * turn the other into a server error, which is exactly what shipped first here.
118
+ */
119
+ export class InputError extends Error {
120
+ /**
121
+ * A brand, read by {@link isInputError}, because `instanceof` answers for one
122
+ * copy of this module: a host's request handler would read a refusal the
123
+ * bundle's validator threw as a server error and answer 500.
124
+ */
125
+ readonly [INPUT_ERROR] = true as const;
126
+ }
127
+
128
+ /** Whether a thrown value is the caller's fault, whichever copy of this module threw it. */
129
+ export function isInputError(error: unknown): error is InputError {
130
+ return (
131
+ typeof error === "object" &&
132
+ error !== null &&
133
+ (error as Record<symbol, unknown>)[INPUT_ERROR] === true
134
+ );
135
+ }
136
+
137
+ export class ValidationError extends InputError {
138
+ readonly issues: ReadonlyArray<unknown>;
139
+ constructor(issues: ReadonlyArray<unknown>) {
140
+ super(
141
+ "The `data` passed to this server function failed validation against its `.validator(schema)`, so the handler did not run. " +
142
+ "Read `error.issues` for what failed.",
143
+ );
144
+ this.name = "ValidationError";
145
+ this.issues = issues;
146
+ }
147
+ }
148
+
149
+ /** Thrown when a call arrives for a function that declared no validator. */
150
+ export class UncheckedInputError extends InputError {
151
+ constructor() {
152
+ super(
153
+ "This server function was called with `data`, but it declares no validator, so the call was refused. " +
154
+ 'Add `.validator(schema)` to validate the input, or `.validator("unchecked")` to accept it as it arrives.',
155
+ );
156
+ this.name = "UncheckedInputError";
157
+ }
158
+ }
159
+
160
+ /** The empty contribution: what a step that adds nothing adds. */
161
+ export type Empty = object;
162
+
163
+ /**
164
+ * A context the types know some of. A key no typed step declared still reads,
165
+ * as `unknown`: an untyped closure may have put it there.
166
+ */
167
+ export type OpenContext<Known extends object> = Known & Record<string, unknown>;
168
+
169
+ declare const NEXT: unique symbol;
170
+
171
+ /**
172
+ * What `next()` resolves to, as far as the types can see.
173
+ *
174
+ * At runtime it is whatever the rest of the chain answered. The type carries
175
+ * what this call contributed, so a middleware's context is read off the
176
+ * `return next({ context })` it ends with rather than declared a second time.
177
+ */
178
+ export interface NextResult<Context extends object = Empty, Sent extends object = Empty> {
179
+ readonly [NEXT]: { readonly context: Context; readonly sent: Sent };
180
+ }
181
+
182
+ /** What a middleware may hand `next`. */
183
+ export interface NextOptions<Context extends object = Empty, Sent extends object = Empty> {
184
+ /**
185
+ * MERGED into what every step below is handed, the handler included. This is
186
+ * how a middleware that authenticates hands the session down without a
187
+ * module-level store.
188
+ */
189
+ readonly context?: Context;
190
+ /**
191
+ * Context the OTHER side is given.
192
+ *
193
+ * From a server half it travels back on the response, so a middleware that
194
+ * resolved a session can tell the browser who it decided the user is without
195
+ * a second round trip. From a client half it travels to the server, where it
196
+ * arrives as `clientContext`: untrusted input, never `context`.
197
+ *
198
+ * It is SERIALIZED, so it carries what the value codec carries and nothing
199
+ * else. A `context` holding a database handle is fine; a `sendContext`
200
+ * holding one is a value the other side cannot be given.
201
+ */
202
+ readonly sendContext?: Sent;
203
+ /**
204
+ * Request headers for the fetch, from a CLIENT half: an `Authorization` a
205
+ * middleware holds the token for, a trace id.
206
+ *
207
+ * A later step's value for a name replaces an earlier one's, and the call's
208
+ * own `headers` replace both. A server half has no request to add to, so
209
+ * there it does nothing; its response headers are `setResponseHeader`'s.
210
+ */
211
+ readonly headers?: HeadersInit;
212
+ /**
213
+ * The `fetch` the call goes out through, from a CLIENT half: a retry, a
214
+ * tracer, a test double. A later step's replaces an earlier one's, and the
215
+ * call's own `fetch` option replaces both.
216
+ */
217
+ readonly fetch?: typeof fetch;
218
+ }
219
+
220
+ /**
221
+ * What a middleware calls to run the rest of the chain. `next()` with no
222
+ * argument runs it unchanged.
223
+ */
224
+ export type MiddlewareNext = <Context extends object = Empty, Sent extends object = Empty>(
225
+ options?: NextOptions<Context, Sent>,
226
+ // Read off the argument alone: inferred from where the result is returned to,
227
+ // `next()` would satisfy any context a declared `Middleware<…>` promises.
228
+ ) => Promise<NextResult<NoInfer<Context>, NoInfer<Sent>>>;
229
+
230
+ /**
231
+ * A middleware runs before the handler and decides whether there is going to be
232
+ * one. Rejecting is `throw new Response(...)`, which the request handler returns
233
+ * as it stands.
234
+ *
235
+ * Per FUNCTION, not per route. Every framework in the survey documents the same
236
+ * hole instead of closing it — Next.js: "A page-level authentication check does
237
+ * not extend to the Server Actions defined within it… the Server Action is a
238
+ * separate entry point." A middleware attached here cannot be escaped by
239
+ * reaching the function from somewhere else, because there is nowhere else.
240
+ *
241
+ * `Context` is what a bare closure promises to add, and it is checked against
242
+ * what it passes to `next`: `Middleware<{ user: string }>` that ends in
243
+ * `next()` is a type error. A built middleware needs no annotation, since its
244
+ * context is read off its body.
245
+ */
246
+ export type Middleware<Context extends object = Empty> = Empty extends Context
247
+ ? (next: MiddlewareNext) => Promise<unknown>
248
+ : (next: MiddlewareNext) => Promise<NextResult<Context>>;
249
+
250
+ /**
251
+ * What a middleware contributes to everything after it, at the type level.
252
+ * Nothing here exists at runtime.
253
+ */
254
+ export interface Contribution {
255
+ /** Added to the server `context` of every later step and of the handler. */
256
+ readonly context: object;
257
+ /** What its server halves send back to the caller. */
258
+ readonly sent: object;
259
+ /** What its client halves add to the client `context`. */
260
+ readonly clientContext: object;
261
+ /** What the first validator in the chain is handed: the caller's `data`. */
262
+ readonly input: unknown;
263
+ /** What the last validator in the chain produced: every later step's `data`. */
264
+ readonly output: unknown;
265
+ readonly validates: boolean;
266
+ }
267
+
268
+ export interface NoContribution extends Contribution {
269
+ readonly context: Empty;
270
+ readonly sent: Empty;
271
+ readonly clientContext: Empty;
272
+ readonly input: undefined;
273
+ readonly output: undefined;
274
+ readonly validates: false;
275
+ }
276
+
277
+ /** `first`, then `second`: in the order the chain runs them. */
278
+ export interface Merged<
279
+ First extends Contribution,
280
+ Second extends Contribution,
281
+ > extends Contribution {
282
+ readonly context: First["context"] & Second["context"];
283
+ readonly sent: First["sent"] & Second["sent"];
284
+ readonly clientContext: First["clientContext"] & Second["clientContext"];
285
+ readonly input: First["validates"] extends true ? First["input"] : Second["input"];
286
+ readonly output: Second["validates"] extends true ? Second["output"] : First["output"];
287
+ readonly validates: First["validates"] extends true ? true : Second["validates"];
288
+ }
289
+
290
+ /** What one `next(...)` call contributed, from the result it resolved to. */
291
+ export type FromNext<Result> =
292
+ Result extends NextResult<infer Context, infer Sent>
293
+ ? { readonly context: Plain<Context>; readonly sent: Plain<Sent> }
294
+ : never;
295
+
296
+ /** The same keys as one object, so a hover shows the context rather than how it was built. */
297
+ export type Plain<Value> = { [Key in keyof Value]: Value[Key] };
298
+
299
+ /**
300
+ * What a body contributed, from everything it can return. A branch that
301
+ * answers without calling `next` contributes nothing, and the handler never
302
+ * runs on it, so it is left out rather than widening the rest to nothing.
303
+ */
304
+ export type ContributedBy<Result> = [FromNext<Result>] extends [never]
305
+ ? { readonly context: Empty; readonly sent: Empty }
306
+ : FromNext<Result>;
307
+
308
+ declare const CONTRIBUTES: unique symbol;
309
+
310
+ /**
311
+ * The type-level record a built middleware carries.
312
+ *
313
+ * A METHOD and optional, so it exists in no value and compares bivariantly:
314
+ * one builder implementation serves every state, and what is read back is
315
+ * exact because it is read with `infer`.
316
+ */
317
+ export interface Carries<Types extends Contribution> {
318
+ [CONTRIBUTES]?(types: Types): void;
319
+ }
320
+
321
+ /** What a middleware contributes, whichever way it was written. */
322
+ export type ContributionOf<Step> =
323
+ Step extends Carries<infer Types>
324
+ ? Types
325
+ : Step extends (next: never) => Promise<infer Result>
326
+ ? Merged<
327
+ NoContribution,
328
+ NoContribution & Omit<ContributedBy<Result>, never>
329
+ > extends infer Out
330
+ ? Out extends Contribution
331
+ ? Out
332
+ : NoContribution
333
+ : NoContribution
334
+ : NoContribution;
335
+
336
+ /** What a whole chain contributes, steps in the order they run. */
337
+ export type ChainContribution<Chain> = Chain extends readonly [infer Head, ...infer Rest]
338
+ ? Merged<ContributionOf<Head>, ChainContribution<Rest>>
339
+ : Chain extends readonly []
340
+ ? NoContribution
341
+ : Chain extends readonly (infer Step)[]
342
+ ? ContributionOf<Step>
343
+ : NoContribution;
344
+
345
+ /** Where a built middleware is: the chain it declared, and what it adds itself. */
346
+ export interface MiddlewareState {
347
+ readonly chain: Contribution;
348
+ readonly own: Contribution;
349
+ }
350
+
351
+ export interface FreshMiddleware extends MiddlewareState {
352
+ readonly chain: NoContribution;
353
+ readonly own: NoContribution;
354
+ }
355
+
356
+ export interface WithChain<State extends MiddlewareState, Chain> extends MiddlewareState {
357
+ readonly chain: ChainContribution<Chain>;
358
+ readonly own: State["own"];
359
+ }
360
+
361
+ export interface OwnReplaced<
362
+ Own extends Contribution,
363
+ Context extends object,
364
+ Sent extends object,
365
+ > extends Contribution {
366
+ readonly context: Context;
367
+ readonly sent: Sent;
368
+ readonly clientContext: Own["clientContext"];
369
+ readonly input: Own["input"];
370
+ readonly output: Own["output"];
371
+ readonly validates: Own["validates"];
372
+ }
373
+
374
+ export interface WithServer<State extends MiddlewareState, Result> extends MiddlewareState {
375
+ readonly chain: State["chain"];
376
+ readonly own: OwnReplaced<
377
+ State["own"],
378
+ ContributedBy<Awaited<Result>>["context"],
379
+ ContributedBy<Awaited<Result>>["sent"]
380
+ >;
381
+ }
382
+
383
+ export interface ClientReplaced<
384
+ Own extends Contribution,
385
+ ClientContext extends object,
386
+ > extends Contribution {
387
+ readonly context: Own["context"];
388
+ readonly sent: Own["sent"];
389
+ readonly clientContext: ClientContext;
390
+ readonly input: Own["input"];
391
+ readonly output: Own["output"];
392
+ readonly validates: Own["validates"];
393
+ }
394
+
395
+ export interface WithClient<State extends MiddlewareState, Result> extends MiddlewareState {
396
+ readonly chain: State["chain"];
397
+ readonly own: ClientReplaced<State["own"], ContributedBy<Awaited<Result>>["context"]>;
398
+ }
399
+
400
+ export interface ValidatorReplaced<Own extends Contribution, In, Out> extends Contribution {
401
+ readonly context: Own["context"];
402
+ readonly sent: Own["sent"];
403
+ readonly clientContext: Own["clientContext"];
404
+ readonly input: In;
405
+ readonly output: Out;
406
+ readonly validates: true;
407
+ }
408
+
409
+ export interface WithValidator<State extends MiddlewareState, In, Out> extends MiddlewareState {
410
+ readonly chain: State["chain"];
411
+ readonly own: ValidatorReplaced<State["own"], In, Out>;
412
+ }
413
+
414
+ /** What a built middleware contributes: its chain, then itself. */
415
+ export type ContributionOfState<State extends MiddlewareState> = Merged<
416
+ State["chain"],
417
+ State["own"]
418
+ >;
419
+
420
+ /** The `data` a step is handed: what the nearest validator above it produced. */
421
+ export type DataAt<State extends MiddlewareState> = State["own"]["validates"] extends true
422
+ ? State["own"]["output"]
423
+ : State["chain"]["validates"] extends true
424
+ ? State["chain"]["output"]
425
+ : unknown;
426
+
427
+ /**
428
+ * What a built middleware's server half is handed.
429
+ *
430
+ * The OBJECT shape, where a bare `Middleware` closure takes `next` positionally.
431
+ * Both are supported and neither is deprecated: the closure is what a
432
+ * one-line guard writes, and this is what a middleware with a validator, a
433
+ * client half or a `sendContext` needs.
434
+ */
435
+ export interface MiddlewareContext<Data = unknown, Context extends object = Empty> {
436
+ readonly next: MiddlewareNext;
437
+ /**
438
+ * The input, as THIS middleware's validator left it.
439
+ *
440
+ * Validators compose along the chain: each one is handed what the one before
441
+ * it returned, and the function's own runs last. That is TanStack's pipeline
442
+ * (`createServerFn.ts:271-274`) and it is what lets a middleware normalise an
443
+ * argument every function under it then receives already normalised.
444
+ */
445
+ readonly data: Data;
446
+ /** What the middlewares outside this one contributed. */
447
+ readonly context: OpenContext<Context>;
448
+ /**
449
+ * What the client halves sent with `next({ sendContext })`, as it came off
450
+ * the wire.
451
+ *
452
+ * UNTRUSTED, and kept apart from `context` for that reason: a caller writes
453
+ * the request body by hand as readily as the stub does, so this is input to
454
+ * check and never a fact to act on. Everything read from `context` was put
455
+ * there by a server step; a value from here joins it only when a server half
456
+ * passes it on with `next({ context })`. Untyped for the same reason: a type
457
+ * here would be a claim about what a stranger sent.
458
+ *
459
+ * Empty in a client half, and for a call made in-process.
460
+ */
461
+ readonly clientContext: Readonly<Record<string, unknown>>;
462
+ readonly signal: AbortSignal;
463
+ /**
464
+ * The request, when this middleware is running for one: as a request
465
+ * middleware, global or on a route. Absent around a server function's own
466
+ * chain, where `getRequest()` is the way to it.
467
+ */
468
+ readonly request?: Request;
469
+ /** The request's path, with any base stripped. Present with `request`. */
470
+ readonly pathname?: string;
471
+ /** What the request is for. Present with `request`. */
472
+ readonly handlerType?: "router" | "serverFn";
473
+ /**
474
+ * The server function this chain is running around, by its id. Absent for a
475
+ * request middleware, and the id is empty for a function that is not mounted.
476
+ */
477
+ readonly serverFnMeta?: { readonly id: string };
478
+ /** The method the server function answers. Absent for a request middleware. */
479
+ readonly method?: "GET" | "POST";
480
+ }
481
+
482
+ /**
483
+ * What a client half is handed: the caller's raw `data`, since validators run
484
+ * on the server, and a `context` holding what the client halves before it
485
+ * added and, once `next()` has resolved, what the server sent back.
486
+ */
487
+ export interface ClientMiddlewareContext<
488
+ Context extends object = Empty,
489
+ Sent extends object = Empty,
490
+ > extends MiddlewareContext<unknown, Context & Partial<Sent>> {}
491
+
492
+ /** Any server or client half, as the runner calls it. */
493
+ export type MiddlewareFn = (context: MiddlewareContext) => unknown;
494
+
495
+ /** What a request middleware calls to run the rest of the request. */
496
+ export type RequestMiddlewareNext = <Context extends object = Empty>(options?: {
497
+ readonly context?: Context;
498
+ }) => Promise<(Response & NextResult<NoInfer<Context>>) | undefined>;
499
+
500
+ /**
501
+ * What a request middleware is handed: the request is always there.
502
+ *
503
+ * `next()` resolves to the response, or `undefined` from a route handler that
504
+ * declined, so the page render answers instead.
505
+ */
506
+ export interface RequestMiddlewareContext<Context extends object = Empty> {
507
+ readonly next: RequestMiddlewareNext;
508
+ readonly data: undefined;
509
+ readonly context: OpenContext<Context>;
510
+ readonly clientContext: Readonly<Record<string, unknown>>;
511
+ readonly signal: AbortSignal;
512
+ readonly request: Request;
513
+ readonly pathname: string;
514
+ readonly handlerType: "router" | "serverFn";
515
+ }
516
+
517
+ export type RequestMiddlewareFn = (context: RequestMiddlewareContext) => unknown;
518
+
519
+ /** What a built middleware carries, and what the runner reads off it. */
520
+ export interface MiddlewareOptions {
521
+ /**
522
+ * TanStack's two kinds. `"request"` runs for a server request and is handed
523
+ * it; `"function"` runs around a server function and may have a client half.
524
+ * One builder makes both and the runner asks only where a middleware was
525
+ * listed, so the kind decides the TYPES of what `.server` is handed.
526
+ */
527
+ readonly type?: "request" | "function";
528
+ readonly middleware?: readonly Middleware[];
529
+ readonly validator?: Validator<unknown>;
530
+ readonly server?: MiddlewareFn;
531
+ readonly client?: MiddlewareFn;
532
+ }
533
+
534
+ /**
535
+ * A middleware with more than a body: a chain of its own, an input validator,
536
+ * and separate halves for the two sides.
537
+ *
538
+ * IT IS STILL A FUNCTION. `Middleware` is a callable and the route-action
539
+ * verifier compares chains with `===`, so making this an object — which is what
540
+ * TanStack's is — would have broken both at once: a route's `middleware: [m]`
541
+ * would no longer typecheck, and every existing bare closure would need
542
+ * wrapping. A callable object is neither: it runs where a closure ran, it
543
+ * compares by identity as a closure did, and `options` is there for the runner
544
+ * that wants more.
545
+ *
546
+ * What each step adds is TYPED: a `.server` that ends in
547
+ * `next({ context: { user } })` hands `user` to every function that lists this
548
+ * middleware, typed as the body wrote it.
549
+ */
550
+ export type BuiltMiddleware<State extends MiddlewareState = MiddlewareState> = Middleware &
551
+ Carries<ContributionOfState<State>> & {
552
+ readonly options: MiddlewareOptions;
553
+ /** Middlewares that run BEFORE this one, flattened into the chain that uses it. */
554
+ middleware<const Chain extends readonly Middleware[]>(
555
+ chain: Chain,
556
+ ): BuiltMiddleware<WithChain<State, Chain>>;
557
+ /**
558
+ * Validates and narrows the input every step after this one is handed. The
559
+ * schema form is tried first: an arktype type is callable as well, and read
560
+ * as a function its declared input would be lost.
561
+ */
562
+ validator<Schema extends StandardSchemaLike>(
563
+ schema: Schema,
564
+ ): BuiltMiddleware<WithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
565
+ validator<In, Out>(
566
+ validate: (input: In) => Out,
567
+ ): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;
568
+ validator<In, Out>(schema: {
569
+ readonly parse: (input: In) => Out;
570
+ }): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;
571
+ validator(unchecked: "unchecked"): BuiltMiddleware<WithValidator<State, unknown, unknown>>;
572
+ /** `validator` under the name TanStack's release candidates used. */
573
+ inputValidator<Schema extends StandardSchemaLike>(
574
+ schema: Schema,
575
+ ): BuiltMiddleware<WithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
576
+ inputValidator<In, Out>(
577
+ validate: (input: In) => Out,
578
+ ): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;
579
+ inputValidator<In, Out>(schema: {
580
+ readonly parse: (input: In) => Out;
581
+ }): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;
582
+ inputValidator(unchecked: "unchecked"): BuiltMiddleware<WithValidator<State, unknown, unknown>>;
583
+ /** The half that runs on the server, where the handler is. */
584
+ server<Result>(
585
+ fn: (context: MiddlewareContext<DataAt<State>, State["chain"]["context"]>) => Result,
586
+ ): BuiltMiddleware<WithServer<State, Result>>;
587
+ /**
588
+ * The half that runs in the BROWSER, around the fetch.
589
+ *
590
+ * `next({ sendContext })` from here is what travels to the server half as
591
+ * `clientContext`. The compiler carries this into the client stub and leaves
592
+ * the server half behind, so a middleware may hold both without either
593
+ * reaching the wrong bundle.
594
+ */
595
+ client<Result>(
596
+ fn: (
597
+ context: ClientMiddlewareContext<State["chain"]["clientContext"], State["chain"]["sent"]>,
598
+ ) => Result,
599
+ ): BuiltMiddleware<WithClient<State, Result>>;
600
+ };
601
+
602
+ /**
603
+ * The two brands a thrown redirect and a thrown `notFound()` carry.
604
+ *
605
+ * DECLARED TWICE ON PURPOSE. The classes live in `@barqjs/router`, which this
606
+ * package must not import: the dependency runs router -> start and start is an
607
+ * OPTIONAL peer of it, so an import here would be a cycle and would break the
608
+ * router for anyone using it without server functions. `Symbol.for` is the
609
+ * global registry, so both declarations name the same symbol with no edge
610
+ * between the packages — `SERVER_FN` in `client.ts` already works this way. The other
611
+ * declaration is `REDIRECT` / `NOT_FOUND` in `packages/router/src/errors.ts`,
612
+ * and `server.test.ts` checks the two agree.
613
+ */
614
+ export const REDIRECT: unique symbol = Symbol.for("barq.redirect");
615
+ export const NOT_FOUND: unique symbol = Symbol.for("barq.not-found");
616
+
617
+ /**
618
+ * What a middleware handed back, held to TanStack's rule: it ends in
619
+ * `return next(...)`, answers with a result of its own, or throws.
620
+ *
621
+ * `undefined` is the one answer that cannot be a decision. Returned without
622
+ * `next()` having been called, the step neither ran the rest of the chain nor
623
+ * said what to answer with; returned after a `next()` that resolved to
624
+ * something, it is the `return` the body forgot, and the result the handler
625
+ * produced would be lost without a word. Either way the call would resolve to
626
+ * nothing, so it fails here, naming the step. A thrown or returned redirect
627
+ * or `notFound()` is an answer, so a returned one is thrown as one.
628
+ */
629
+ function answerOf(returned: unknown, answers: readonly unknown[], step: () => string): unknown {
630
+ if (isControl(returned)) throw returned;
631
+ if (returned !== undefined || answers.includes(undefined)) return returned;
632
+ throw new Error(
633
+ answers.length === 0
634
+ ? `[barq] ${step()} returned without calling \`next()\`, so the call has no answer. ` +
635
+ "A middleware ends in `return next(...)`, returns a result of its own, or throws (a `Response` to refuse)."
636
+ : `[barq] ${step()} called \`next()\` and returned \`undefined\` in place of its result, so the result was lost. ` +
637
+ "Return what `next()` resolved to: `return next(...)`.",
638
+ );
639
+ }
640
+
641
+ function isControl(value: unknown): boolean {
642
+ if (typeof value !== "object" || value === null) return false;
643
+ const branded = value as Record<symbol, unknown>;
644
+ return branded[REDIRECT] === true || branded[NOT_FOUND] === true;
645
+ }
646
+
647
+ /**
648
+ * Which step a refusal is about, for a person reading the error: its name when
649
+ * the closure or the half has one, its place in the chain, and the function.
650
+ */
651
+ function describeStep(
652
+ kind: string,
653
+ named: readonly ((...args: never[]) => unknown)[],
654
+ position: number,
655
+ length: number,
656
+ around: string,
657
+ ): string {
658
+ const name = named
659
+ .map((fn) => fn.name)
660
+ .find((candidate) => candidate !== "" && candidate !== "run");
661
+ const place = `${position + 1} of ${length}`;
662
+ return name === undefined
663
+ ? `The ${kind} middleware ${place} ${around}`
664
+ : `The ${kind} middleware \`${name}\` (${place}) ${around}`;
665
+ }
666
+
667
+ /** Frozen, because every call that was sent nothing is handed this one object. */
668
+ const NOTHING_SENT: Record<string, unknown> = Object.freeze({});
669
+
670
+ /** Whether a middleware was built by {@link createMiddleware}. */
671
+ export function isBuiltMiddleware(value: Middleware): value is BuiltMiddleware {
672
+ return (value as Partial<BuiltMiddleware>).options !== undefined;
673
+ }
674
+
675
+ /**
676
+ * Author a middleware that is more than one closure.
677
+ *
678
+ * `createMiddleware().server(async ({ next, context }) => next({ context: … }))`
679
+ * is the ordinary shape, and it is what a bare closure already did. What the
680
+ * builder adds is the three things a closure has nowhere to put: a chain of its
681
+ * own, an input validator, and a client half.
682
+ *
683
+ * EACH CALL RETURNS A NEW MIDDLEWARE, and the exported one is the last. That
684
+ * matters because the verifier compares by identity: a builder that mutated and
685
+ * returned itself would make every intermediate the same object as the final
686
+ * one, which is harmless, and one that shared its options object across
687
+ * branches — which TanStack's does — would make two middlewares built from one
688
+ * base overwrite each other. Neither is a risk worth carrying for an allocation.
689
+ */
690
+ export function createMiddleware(
691
+ options: MiddlewareOptions & { readonly type: "request" },
692
+ ): RequestMiddleware<FreshMiddleware>;
693
+ export function createMiddleware(options?: MiddlewareOptions): BuiltMiddleware<FreshMiddleware>;
694
+ export function createMiddleware(
695
+ options: MiddlewareOptions = {},
696
+ ): BuiltMiddleware<FreshMiddleware> | RequestMiddleware<FreshMiddleware> {
697
+ return built<FreshMiddleware>(options);
698
+ }
699
+
700
+ /**
701
+ * A typed body, stored where the runner reads it.
702
+ *
703
+ * The runner hands each body the `data` its validators produced and the
704
+ * `context` the steps outside it wrote, which is what the body's own types say;
705
+ * the types cannot follow a value through `options`, so they are restated here,
706
+ * once, rather than at every call.
707
+ */
708
+ function asBody<Data, Context extends object>(
709
+ fn: (context: MiddlewareContext<Data, Context>) => unknown,
710
+ ): MiddlewareFn {
711
+ return fn as MiddlewareFn;
712
+ }
713
+
714
+ /**
715
+ * A runner's `next`.
716
+ *
717
+ * It resolves to whatever the rest of the chain answered. `NextResult` is the
718
+ * types' record of what the caller passed, and no value carries it, so the one
719
+ * place a runner makes a `next` is the one place that says so.
720
+ */
721
+ function nextOf(step: (options?: NextOptions) => Promise<unknown>): MiddlewareNext {
722
+ return step as MiddlewareNext;
723
+ }
724
+
725
+ function built<State extends MiddlewareState>(options: MiddlewareOptions): BuiltMiddleware<State> {
726
+ // The callable body is the SERVER half, because that is where a middleware in
727
+ // a chain is invoked from. A middleware with no server half still has to be
728
+ // callable — it may exist only to validate, or only to run on the client — and
729
+ // passing straight through is what "no half here" means.
730
+ const run: Middleware = async (next) =>
731
+ options.server === undefined
732
+ ? next()
733
+ : options.server({
734
+ next,
735
+ data: undefined,
736
+ context: {},
737
+ clientContext: NOTHING_SENT,
738
+ signal: new AbortController().signal,
739
+ });
740
+
741
+ function validated<Schema extends StandardSchemaLike>(
742
+ schema: Schema,
743
+ ): BuiltMiddleware<WithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;
744
+ function validated<In, Out>(
745
+ validate: (input: In) => Out,
746
+ ): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;
747
+ function validated<In, Out>(schema: {
748
+ readonly parse: (input: In) => Out;
749
+ }): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;
750
+ function validated(
751
+ unchecked: "unchecked",
752
+ ): BuiltMiddleware<WithValidator<State, unknown, unknown>>;
753
+ function validated(schema: ValidatorInput<unknown>): BuiltMiddleware {
754
+ return built({ ...options, validator: toValidator(schema) });
755
+ }
756
+
757
+ return Object.assign(run, {
758
+ options,
759
+ middleware: <const Chain extends readonly Middleware[]>(chain: Chain) =>
760
+ built<WithChain<State, Chain>>({ ...options, middleware: chain }),
761
+ validator: validated,
762
+ inputValidator: validated,
763
+ server: <Result>(
764
+ fn: (context: MiddlewareContext<DataAt<State>, State["chain"]["context"]>) => Result,
765
+ ) => built<WithServer<State, Result>>({ ...options, server: asBody(fn) }),
766
+ client: <Result>(
767
+ fn: (
768
+ context: ClientMiddlewareContext<State["chain"]["clientContext"], State["chain"]["sent"]>,
769
+ ) => Result,
770
+ ) => built<WithClient<State, Result>>({ ...options, client: asBody(fn) }),
771
+ });
772
+ }
773
+
774
+ /**
775
+ * A middleware built with `type: "request"`: a chain of its own and a server
776
+ * body that is always handed the request. It is a {@link BuiltMiddleware}
777
+ * underneath, so it goes wherever a `Middleware` does, and what its body passes
778
+ * to `next({ context })` is typed into everything after it.
779
+ */
780
+ export type RequestMiddleware<State extends MiddlewareState = MiddlewareState> = Middleware &
781
+ Carries<ContributionOfState<State>> & {
782
+ readonly options: MiddlewareOptions;
783
+ middleware<const Chain extends readonly Middleware[]>(
784
+ chain: Chain,
785
+ ): RequestMiddleware<WithChain<State, Chain>>;
786
+ server<Result>(
787
+ fn: (context: RequestMiddlewareContext<State["chain"]["context"]>) => Result,
788
+ ): RequestMiddleware<WithServer<State, NonNullable<Awaited<Result>>>>;
789
+ };
790
+
791
+ /** Where a request middleware chain is running. */
792
+ export interface RequestMiddlewareStart {
793
+ readonly request: Request;
794
+ readonly pathname: string;
795
+ readonly handlerType: "router" | "serverFn";
796
+ /** What the chain has produced so far; mutated as it unwinds inward. */
797
+ readonly context: Record<string, unknown>;
798
+ }
799
+
800
+ /**
801
+ * Run a chain of request middleware around `run`.
802
+ *
803
+ * `next()` resolves to whatever is inside: the response, or `undefined` from a
804
+ * route handler that declined. A middleware answers with what it returns, so
805
+ * one that returns `next()` passes the answer through and one that returns a
806
+ * `Response` of its own replaces it.
807
+ */
808
+ export async function runRequestMiddleware<T>(
809
+ chain: readonly Middleware[],
810
+ start: RequestMiddlewareStart,
811
+ run: () => Promise<T>,
812
+ ): Promise<T> {
813
+ if (chain.length === 0) return run();
814
+ const flattened = flattenMiddleware(chain);
815
+ // By position, for the reason `runMiddleware` gives: a second `next()`
816
+ // re-enters the steps below it instead of skipping them.
817
+ const dispatch = async (position: number): Promise<unknown> => {
818
+ const middleware = flattened[position];
819
+ if (middleware === undefined) return run();
820
+ const answers: unknown[] = [];
821
+ const next = nextOf(async (step) => {
822
+ if (step?.context !== undefined) Object.assign(start.context, step.context);
823
+ const answer = await dispatch(position + 1);
824
+ answers.push(answer);
825
+ return answer;
826
+ });
827
+ const body = isBuiltMiddleware(middleware) ? middleware.options.server : undefined;
828
+ if (isBuiltMiddleware(middleware) && body === undefined) return next();
829
+ const returned = await (body === undefined
830
+ ? middleware(next)
831
+ : body({
832
+ next,
833
+ data: undefined,
834
+ context: start.context,
835
+ clientContext: NOTHING_SENT,
836
+ signal: start.request.signal,
837
+ request: start.request,
838
+ pathname: start.pathname,
839
+ handlerType: start.handlerType,
840
+ }));
841
+ return answerOf(returned, answers, () =>
842
+ describeStep(
843
+ "request",
844
+ body === undefined ? [middleware] : [body],
845
+ position,
846
+ flattened.length,
847
+ `on ${start.request.method} ${start.pathname}`,
848
+ ),
849
+ );
850
+ };
851
+ return (await dispatch(0)) as T;
852
+ }
853
+
854
+ /**
855
+ * The chain a middleware list really is: every nested chain spliced in ahead of
856
+ * the middleware that declared it, each step once.
857
+ *
858
+ * Depth-first and parents-first, which is TanStack's `flattenMiddlewares` and
859
+ * the only order that means anything — a middleware declares a chain because it
860
+ * DEPENDS on it, so those steps have to have run by the time it does.
861
+ *
862
+ * Deduplicated by IDENTITY, so two middlewares that both depend on
863
+ * `requireSession` do not authenticate twice. That is also what keeps the
864
+ * route-action verifier honest: it asks whether a function's flattened chain
865
+ * contains the route's steps, and a step reached through a nest counts.
866
+ */
867
+ export function flattenMiddleware(chain: readonly Middleware[], depth = 0): readonly Middleware[] {
868
+ // A chain that reaches itself would otherwise recurse until the stack goes.
869
+ // The cap is TanStack's and the number is theirs.
870
+ if (depth > 100) {
871
+ throw new RangeError(
872
+ "[barq] A middleware chain nests more than 100 levels deep, which almost always means a middleware's own `middleware` list reaches the middleware itself. " +
873
+ "Remove the cycle.",
874
+ );
875
+ }
876
+ const out: Middleware[] = [];
877
+ const push = (step: Middleware): void => {
878
+ if (!out.includes(step)) out.push(step);
879
+ };
880
+ for (const step of chain) {
881
+ if (isBuiltMiddleware(step) && step.options.middleware !== undefined) {
882
+ for (const nested of flattenMiddleware(step.options.middleware, depth + 1)) push(nested);
883
+ }
884
+ push(step);
885
+ }
886
+ return out;
887
+ }
888
+
889
+ /** One validator, applied. `"unchecked"` and absence both pass the value through. */
890
+ export async function applyValidator(
891
+ validator: Validator<unknown> | undefined,
892
+ raw: unknown,
893
+ ): Promise<unknown> {
894
+ if (validator === undefined || validator === "unchecked") return raw;
895
+ const result = await validator["~standard"].validate(raw);
896
+ if ("issues" in result) throw new ValidationError(result.issues);
897
+ return result.value;
898
+ }
899
+
900
+ /**
901
+ * Run a flattened chain, then the innermost work.
902
+ *
903
+ * ONE RUNNER FOR BOTH SIDES, and `half` is which of a built middleware's two
904
+ * bodies to call. A bare closure has neither and is invoked positionally, which
905
+ * is what it has always been — so a chain may mix the two spellings and the
906
+ * order is the order it was written in.
907
+ *
908
+ * A middleware that declares no half for THIS side is skipped rather than
909
+ * refused: a `.server(...)`-only middleware is transparent in the browser, and
910
+ * a `.client(...)`-only one is transparent on the server. That is what makes
911
+ * one exported middleware usable from a route and a server function alike.
912
+ */
913
+ export async function runMiddleware(
914
+ chain: readonly Middleware[],
915
+ half: "server" | "client",
916
+ start: {
917
+ readonly data: unknown;
918
+ readonly signal: AbortSignal;
919
+ /** What the chain has produced so far; mutated as the chain unwinds inward. */
920
+ readonly context: Record<string, unknown>;
921
+ /** What the client halves sent, on the server. Never merged into `context`. */
922
+ readonly clientContext?: Record<string, unknown>;
923
+ /** What travels back to the caller. */
924
+ readonly sendContext: Record<string, unknown>;
925
+ /** Where a client half's `next({ headers })` collects. Absent on the server. */
926
+ readonly headers?: Headers;
927
+ /** Where a client half's `next({ fetch })` lands. Absent on the server. */
928
+ readonly fetch?: { current: typeof fetch | undefined };
929
+ /** The function the chain is running around. */
930
+ readonly meta?: { readonly id: string };
931
+ /** The method that function answers. */
932
+ readonly method?: "GET" | "POST";
933
+ /** The innermost work: the handler on the server, the fetch on the client. */
934
+ readonly run: (data: unknown) => Promise<unknown>;
935
+ },
936
+ ): Promise<unknown> {
937
+ // BY POSITION, never by a counter the whole chain shares. A middleware may
938
+ // call `next` twice (a retry, a fallback), and a shared counter has already
939
+ // moved past every step below it by then, so the second call would land on
940
+ // the handler with the guards in between skipped. Each step's `next` names the
941
+ // step after it, so a repeat re-enters the same guards.
942
+ const dispatch = async (position: number, received: unknown): Promise<unknown> => {
943
+ const middleware = chain[position];
944
+ if (middleware === undefined) return start.run(received);
945
+ let data = received;
946
+ const answers: unknown[] = [];
947
+ const next = nextOf(async (step) => {
948
+ if (step?.context !== undefined) Object.assign(start.context, step.context);
949
+ if (step?.sendContext !== undefined) Object.assign(start.sendContext, step.sendContext);
950
+ if (step?.headers !== undefined && start.headers !== undefined) {
951
+ for (const [name, value] of new Headers(step.headers)) start.headers.set(name, value);
952
+ }
953
+ if (step?.fetch !== undefined && start.fetch !== undefined) start.fetch.current = step.fetch;
954
+ const answer = await dispatch(position + 1, data);
955
+ answers.push(answer);
956
+ return answer;
957
+ });
958
+ const step = (named: (...args: never[]) => unknown): string =>
959
+ describeStep(
960
+ half,
961
+ [named],
962
+ position,
963
+ chain.length,
964
+ `around the server function ${JSON.stringify(start.meta?.id ?? "")}`,
965
+ );
966
+ if (!isBuiltMiddleware(middleware)) {
967
+ // A BARE CLOSURE IS A SERVER MIDDLEWARE, always. It takes `next` and runs
968
+ // where the handler is; there is no half to choose and nothing about it
969
+ // says it is safe in a browser — `requireSession` in the reference
970
+ // application opens a sealed cookie. Calling one on the client would run
971
+ // a session check in the page, so the client half skips it and only a
972
+ // middleware that declared `.client(…)` runs there.
973
+ if (half !== "server") return next();
974
+ return answerOf(await middleware(next), answers, () => step(middleware));
975
+ }
976
+ // VALIDATION FIRST, so the body of this middleware sees what its own
977
+ // validator produced and so does everything under it. TanStack applies them
978
+ // in the same place and the same order.
979
+ if (half === "server") data = await applyValidator(middleware.options.validator, data);
980
+ const body = middleware.options[half];
981
+ if (body === undefined) return next();
982
+ const returned = await body({
983
+ next,
984
+ data,
985
+ context: start.context,
986
+ clientContext: start.clientContext ?? NOTHING_SENT,
987
+ signal: start.signal,
988
+ serverFnMeta: start.meta,
989
+ method: start.method,
990
+ });
991
+ return answerOf(returned, answers, () => step(body));
992
+ };
993
+ return dispatch(0, start.data);
994
+ }