From 454a07a1e55296fbc43b30c373be60d871b09431 Mon Sep 17 00:00:00 2001 From: Matt Johnston Date: Fri, 27 Nov 2026 18:23:43 -0400 Subject: [PATCH 1/2] feat: check a config callback's ctx annotation as a prerequisite What a config callback declares about `ctx` joins that call's prerequisites. In a `pipeline`, the config-only form infers it from the annotation and adds it to the entry's `In`, so a missing provider fails with `middleware-prereq`. Nested, the cascade types the callback's `ctx` as `NoInfer`, so an anchored stack checks it in place, and the propagation form carries what the cascade cannot confirm outward like any other requirement. The cascade keeps its single `Base` type parameter with no inference site, so nested handlers stay on the return-type path. Optional keys stay optional: `pipeline` reports a key as unmet only when it is required, and still checks the type of one that is present. Refs FUNC-1178 --- src/core/define-composite.test.ts | 35 ++++ src/core/define-composite.ts | 48 ++++-- src/core/define-middleware.test.ts | 149 ++++++++++++++++++ src/core/define-middleware.ts | 69 ++++++-- src/core/pipeline.test.ts | 24 +++ src/core/pipeline.ts | 8 +- src/core/types.ts | 66 +++++++- .../feature-flag/with-feature-flag.test.ts | 97 +++++++++++- 8 files changed, 461 insertions(+), 35 deletions(-) diff --git a/src/core/define-composite.test.ts b/src/core/define-composite.test.ts index ea079c2..7980643 100644 --- a/src/core/define-composite.test.ts +++ b/src/core/define-composite.test.ts @@ -4,6 +4,7 @@ import { defineComposite } from './define-composite.js' import { defineMiddleware } from './define-middleware.js' import { pipeline } from './pipeline.js' import type { + BaseContext, Conflict, Contributions, FetchHandler, @@ -335,6 +336,40 @@ describe('defineComposite — types (tsc-verified)', () => { const res = await handler(new Request('http://localhost/')) expect(await res.json()).toEqual({ y: true, x: 1 }) }) + + it('makes a config callback’s ctx annotation a prerequisite, in both forms', () => { + type Picker = (req: Request, ctx: BaseContext) => boolean + const withPick = defineMiddleware< + 'picked', + { pick: Picker }, + Record, + boolean + >({ + key: 'picked', + run: (config) => async (req, ctx) => ({ picked: config.pick(req, ctx) }), + }) + const withPicked = defineComposite({ + build: (config: { pick: Picker }) => + [withPick(config), passing('extra', 1)()] as const, + }) + const withX = passing('x', 1) + const pick = (_req: Request, ctx: { x: number }) => ctx.x > 0 + + const _flat = pipeline([withX(), withPicked({ pick })], async (_req, ctx) => + Response.json({ p: ctx.picked, e: ctx.extra }), + ) satisfies FetchHandler + const _unmet = pipeline( + [withPicked({ pick })], + // @ts-expect-error — middleware-prereq: key 'x' is not yet on the context + async (_req, ctx) => Response.json({ p: ctx.picked }), + ) + const _nested = withX( + withPicked({ pick }, async (_req, ctx) => + Response.json({ p: ctx.picked, x: ctx.x }), + ), + ) satisfies FetchHandler + void [_flat, _unmet, _nested] + }) }) describe('defineComposite — gate behavior', () => { diff --git a/src/core/define-composite.ts b/src/core/define-composite.ts index ff12602..4e625ac 100644 --- a/src/core/define-composite.ts +++ b/src/core/define-composite.ts @@ -20,7 +20,15 @@ import type { NoConflict } from './define-middleware.js' import { isContext } from './runtime.js' import type { BaseContext } from './runtime.js' -import type { AnyEntry, ConfigArgs, Entry } from './types.js' +import type { + AnyEntry, + ConfigArgs, + ConfigReading, + Entry, + Mismatch, + Mistyped, + RequiredKeys, +} from './types.js' type AnyHandler = (req: Request, ctx: object) => Promise @@ -67,9 +75,9 @@ type Produced = keyof In extends never ? (req: Request, ctx?: Base) => Promise : (req: Request, ctx: Base) => Promise -type CompositeArgs = undefined extends Config - ? [handler: Handler] | [config: Config, handler: Handler] - : [config: Config, handler: Handler] +type CompositeArgs = undefined extends Config + ? [handler: Handler] | [config: Arg, handler: Handler] + : [config: Arg, handler: Handler] /** * The shape of a composite produced by {@link defineComposite}. @@ -89,7 +97,8 @@ export interface Composite< // Handler call, cascade form. `Base` flows inward from the contextual return // type; `NoInfer` keeps the handler argument a dead inference site so the // push chains through any nesting depth. See `Middleware` for the full - // reasoning — this is the record-valued twin of that overload. + // reasoning — this is the record-valued twin of that overload, config + // callbacks included. ( ...args: CompositeArgs< Config, @@ -97,17 +106,22 @@ export interface Composite< Contributes, Base, (req: Request, ctx: NoInfer & Contributes) => Promise - > + >, + ConfigReading> > ): Produced // Handler call, propagation form. `Ctx` is read outward off the wrapped - // handler and republished minus everything this composite contributes. + // handler, and `Need` off config callbacks' `ctx` annotations, and both are + // republished minus everything this composite contributes. // `Partial` is the record analogue of the single-key // `{ [K in Key]?: Contribution }` constraint that keeps `Omit` honest: a // requirement whose type disagrees with what we contribute is not discharged. < Base extends In & BaseContext, - Ctx extends BaseContext & Partial = BaseContext, + Need extends BaseContext = BaseContext, + Ctx extends BaseContext & Partial = BaseContext & + NoInfer & + Contributes, >( ...args: CompositeArgs< Config, @@ -115,14 +129,22 @@ export interface Composite< Contributes, Base, (req: Request, ctx: Ctx) => Promise - > + >, + [Mistyped] extends [never] + ? ConfigReading + : Mismatch> > ): Produced< - Base & Omit, - In & Omit + Base & Omit & NoInfer, + In & + Omit & + NoInfer>> > - // Config-only call — returns the Entry for a `pipeline` array. - (...args: ConfigArgs): Entry + // Config-only call — returns the Entry for a `pipeline` array. A config + // callback's `ctx` annotation joins its `In`. + ( + ...args: ConfigArgs> + ): Entry> } /** diff --git a/src/core/define-middleware.test.ts b/src/core/define-middleware.test.ts index 754920b..af976d4 100644 --- a/src/core/define-middleware.test.ts +++ b/src/core/define-middleware.test.ts @@ -1060,6 +1060,155 @@ describe('type guarantees (tsc-verified)', () => { }) }) +// --------------------------------------------------------------------------- +// A config callback reads the upstream context. What its `ctx` annotation +// declares is a prerequisite of that call, checked in both composition forms. +// --------------------------------------------------------------------------- +describe('a config callback’s ctx annotation (tsc-verified)', () => { + const withTagged = defineMiddleware< + 'tagged', + { tagOf: (req: Request, ctx: BaseContext) => string }, + Record, + string + >({ + key: 'tagged', + run: (config) => async (req, ctx) => ({ tagged: config.tagOf(req, ctx) }), + }) + const withA = passing('alpha', { v: 1 }) + const withB = passing('beta', { v: 2 }) + const readsAlpha = (_req: Request, ctx: { alpha: { v: number } }) => + String(ctx.alpha.v) + + it('runs the callback against the upstream context', async () => { + const app = pipeline( + [withA(), withTagged({ tagOf: readsAlpha })], + async (_req, ctx) => Response.json({ tagged: ctx.tagged }), + ) + const res = await app(new Request('http://localhost/')) + expect(await res.json()).toEqual({ tagged: '1' }) + }) + + it('pipeline: an earlier entry meets the annotation', () => { + const _app = pipeline( + [ + withA(), + withTagged({ + tagOf: (_req, ctx: { alpha: { v: number } }) => String(ctx.alpha.v), + }), + ], + async (_req, ctx) => Response.json({ tagged: ctx.tagged }), + ) satisfies FetchHandler + void _app + }) + + it('pipeline: an annotation no earlier entry meets fails to compile', () => { + const _app = pipeline( + [withB(), withTagged({ tagOf: readsAlpha })], + // @ts-expect-error — middleware-prereq: key 'alpha' is not yet on the context + async (_req, ctx) => Response.json({ tagged: ctx.tagged }), + ) + void _app + }) + + it('pipeline: an earlier entry with the key at the wrong type fails to compile', () => { + const withAlphaString = passing('alpha', { v: 'one' }) + const _app = pipeline( + [withAlphaString(), withTagged({ tagOf: readsAlpha })], + // @ts-expect-error — middleware-prereq: key 'alpha' … incompatible type + async (_req, ctx) => Response.json({ tagged: ctx.tagged }), + ) + void _app + }) + + it('pipeline: an optional key needs no provider, but is checked when present', () => { + const readsMaybeAlpha = (_req: Request, ctx: { alpha?: { v: number } }) => + String(ctx.alpha?.v ?? 0) + const _app = pipeline( + [withB(), withTagged({ tagOf: readsMaybeAlpha })], + async (_req, ctx) => Response.json({ tagged: ctx.tagged }), + ) satisfies FetchHandler + void _app + + const withAlphaString = passing('alpha', { v: 'one' }) + const _bad = pipeline( + [withAlphaString(), withTagged({ tagOf: readsMaybeAlpha })], + // @ts-expect-error — alpha.v is a string, the callback reads a number + async (_req, ctx) => Response.json({ tagged: ctx.tagged }), + ) + void _bad + }) + + it('nested, anchored: an enclosing layer meets the annotation', () => { + const _app = withA( + withB( + withTagged( + { + tagOf: (_req, ctx: { alpha: { v: number } }) => String(ctx.alpha.v), + }, + async (_req, ctx) => Response.json({ t: ctx.tagged, b: ctx.beta.v }), + ), + ), + ) satisfies FetchHandler + void _app + }) + + it('nested, built apart: the annotation travels outward to the provider', () => { + const inner = withTagged({ tagOf: readsAlpha }, async (_req, ctx) => + Response.json({ t: ctx.tagged }), + ) + const _app = withA(inner) satisfies FetchHandler + void _app + }) + + it('nested: an annotation no layer meets fails where the stack is checked', () => { + const stack = withB(withTagged({ tagOf: readsAlpha }, innerOk)) + // @ts-expect-error — nothing in the stack contributes `alpha` + const _entry: FetchHandler = stack + void _entry + }) + + it('nested: an enclosing provider of the wrong type fails to compile', () => { + const withAlphaString = passing('alpha', { v: 'one' }) + const _bad = withAlphaString( + // @ts-expect-error — middleware-prereq: key 'alpha' … incompatible type + withTagged({ tagOf: readsAlpha }, innerOk), + ) satisfies FetchHandler + void _bad + }) + + it('nested, anchored: an unannotated callback reads the enclosing keys', () => { + const _app = withA( + withTagged( + { tagOf: (_req, ctx) => String(ctx.alpha.v) }, + async (_req, ctx) => Response.json({ t: ctx.tagged }), + ), + ) satisfies FetchHandler + void _app + }) + + it('a callback declared against the middleware’s own `In` adds nothing', () => { + const withAudit = defineMiddleware< + 'audit', + { + tagOf: ( + req: Request, + ctx: { alpha: { v: number } } & BaseContext, + ) => string + }, + { alpha: { v: number } }, + string + >({ + key: 'audit', + run: (config) => async (req, ctx) => ({ audit: config.tagOf(req, ctx) }), + }) + const _app = pipeline( + [withA(), withAudit({ tagOf: (_req, ctx) => String(ctx.alpha.v) })], + async (_req, ctx) => Response.json({ audit: ctx.audit }), + ) satisfies FetchHandler + void _app + }) +}) + // --------------------------------------------------------------------------- // A middleware that publishes a hand-written signature, as the authoring guide's // "Variant: a hand-written signature" does, over an ordinary runtime. Middleware diff --git a/src/core/define-middleware.ts b/src/core/define-middleware.ts index 8e6d295..25e25cf 100644 --- a/src/core/define-middleware.ts +++ b/src/core/define-middleware.ts @@ -1,4 +1,13 @@ -import type { ConfigArgs, Conflict, ContributedKeys, Entry } from './types.js' +import type { + ConfigArgs, + ConfigReading, + Conflict, + ContributedKeys, + Entry, + Mismatch, + Mistyped, + RequiredKeys, +} from './types.js' import type { BaseContext } from './runtime.js' import { bufferRequest, isContext, seedContext } from './runtime.js' @@ -335,9 +344,9 @@ type Produced = keyof In extends never * placeholder is threaded through call sites. Otherwise `config` is required and * positional. Either way, passing `config` explicitly still typechecks. */ -type MiddlewareArgs = undefined extends Config - ? [handler: Handler] | [config: Config, handler: Handler] - : [config: Config, handler: Handler] +type MiddlewareArgs = undefined extends Config + ? [handler: Handler] | [config: Arg, handler: Handler] + : [config: Arg, handler: Handler] /** * The shape of a middleware produced by {@link defineMiddleware}. @@ -348,17 +357,21 @@ type MiddlewareArgs = undefined extends Config * of the call's return. `Base` is constrained to `In & BaseContext` for * prerequisite enforcement, and the handler parameter is wrapped in * {@link NoConflict} for collision detection — both surface at the call site. - * - **Handler (propagation)** — the same call when the wrapped handler declares - * prerequisites this layer cannot meet from the inward push alone. `Ctx` is - * read *outward* off that handler and re-published as this layer's own - * requirement, minus the key it contributes. + * - **Handler (propagation)** — the same call when the wrapped handler, or a + * config callback's `ctx` annotation, declares prerequisites this layer cannot + * meet from the inward push alone. They are read *outward* and re-published as + * this layer's own requirement, minus the key it contributes. * - **Config-only** — `mw(config)` (or `mw()` for config-less) returns an - * {@link Entry} for use in a {@link pipeline} array. + * {@link Entry} for use in a {@link pipeline} array. A config callback's `ctx` + * annotation joins the entry's `In`. * * The two directions cannot share one signature: the cascade needs the handler * argument to be a dead inference site, and the propagation needs it to be the * live one. Splitting them into ordered overloads lets each keep what it needs. * + * A config callback is typed through {@link ConfigReading}: its `ctx` is the + * inward `Base` in the cascade, and its annotation in the other two. + * * @category Types */ export interface Middleware< @@ -390,6 +403,12 @@ export interface Middleware< // `NoInfer` is a TypeScript 5.4 intrinsic and it is emitted into the published // `.d.ts`, so it sets the consumer TypeScript floor (documented under // Requirements in the root README). Replacing it means replacing that floor. + // + // A config callback's `ctx` is `NoInfer` too: an annotation there + // would otherwise be a candidate for `Base`, and one candidate is enough to + // take the handler off the return-type path. An annotation this `Base` does + // not satisfy fails this form, and the propagation form below carries it + // outward instead. ( ...args: MiddlewareArgs< Config, @@ -400,7 +419,8 @@ export interface Middleware< req: Request, ctx: NoInfer & { [K in Key]: Contribution }, ) => Promise - > + >, + ConfigReading> > ): Produced // Handler call, propagation form — reached only when the cascade overload @@ -427,15 +447,31 @@ export interface Middleware< // a layer contributing `alpha: { v: string }`. The optional-key constraint // makes the requirement's type checked against `Contribution` where the key is // present, and is vacuous where it isn't. + // + // `Need` is what config callbacks' `ctx` annotations declare; it travels + // outward the same way. It replaces those keys of `Ctx` because two + // disagreeing types would meet as `never`, which any provider discharges; a + // `Base` that already disagrees is a `Mismatch`. Only its required keys make + // `ctx` required, so optional ones stay optional. < Base extends In & BaseContext, - Ctx extends BaseContext & { [K in Key]?: Contribution } = BaseContext, + Need extends BaseContext = BaseContext, + // The default types an unannotated handler when an annotated callback + // failed the cascade before the handler was reached. + Ctx extends BaseContext & { [K in Key]?: Contribution } = BaseContext & + NoInfer & { [K in Key]: Contribution }, >( ...args: MiddlewareArgs< Config, - NoConflict Promise> + NoConflict Promise>, + [Mistyped] extends [never] + ? ConfigReading + : Mismatch> > - ): Produced, In & Omit> + ): Produced< + Base & Omit & NoInfer, + In & Omit & NoInfer>> + > // Config-only call — `mw(config)` (or `mw()` for config-less) returns an // Entry for use in a `pipeline` array. Falls through from the handler overload // because config-only calls either have the wrong arity (required-config mw) @@ -447,5 +483,10 @@ export interface Middleware< // leaves a mapped type `Contributions` cannot infer through, collapsing every // composite part's contributions to the constraint. Concrete instantiations // are unaffected, so the shorthand is safe at call sites. - (...args: ConfigArgs): Entry<{ [K in Key]: Contribution }, In> + // + // `config` is the only argument, so `Need` can be inferred from it without + // touching any handler's typing. `pipeline` then checks it as part of `In`. + ( + ...args: ConfigArgs> + ): Entry<{ [K in Key]: Contribution }, In & NoInfer> } diff --git a/src/core/pipeline.test.ts b/src/core/pipeline.test.ts index cee7d1a..6a956cd 100644 --- a/src/core/pipeline.test.ts +++ b/src/core/pipeline.test.ts @@ -218,6 +218,30 @@ describe('type guarantees (tsc-verified)', () => { void _bad }) + it('prerequisite: an optional key is never unmet, but its type is still checked', () => { + const withMaybeAuth = defineMiddleware< + 'profile', + void, + { auth?: { userId: string } }, + { displayName: string } + >({ + key: 'profile', + run: () => async () => ({ profile: { displayName: 'x' } }), + }) + + const _ok = pipeline([withMaybeAuth()], async (_req, ctx) => + Response.json({ name: ctx.profile.displayName }), + ) satisfies FetchHandler + void _ok + + const _bad = pipeline( + [passing('auth', { userId: 1 })(), withMaybeAuth()], + // @ts-expect-error — middleware-prereq: key 'auth' is on the upstream context with an incompatible type + async () => Response.json({ ok: true }), + ) + void _bad + }) + it('does not let a host-supplied env (arg 2) leak into ctx', async () => { const withA = passing('a', { v: 1 }) const handler = pipeline([withA()], async (_req, ctx) => diff --git a/src/core/pipeline.ts b/src/core/pipeline.ts index 6f123b2..dfcea1e 100644 --- a/src/core/pipeline.ts +++ b/src/core/pipeline.ts @@ -28,6 +28,7 @@ import type { Entry, Mismatch, Mistyped, + RequiredKeys, Widened, } from './types.js' @@ -56,8 +57,11 @@ type Duplicated = ? never : Extract -/** Prerequisites an entry declares that are not yet on the context. */ -type Unmet = Extract, string> +/** + * Prerequisites an entry declares that are not yet on the context. An optional + * key is never unmet; `Mistyped` still checks its type where it is present. + */ +type Unmet = Extract, keyof Ctx>, string> /** * Validate a tuple of entries in order against a seed context. Each entry's diff --git a/src/core/types.ts b/src/core/types.ts index bb1215e..b1c5aff 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -4,6 +4,8 @@ * @packageDocumentation */ +import type { BaseContext } from './runtime.js' + /** * Sentinel type used to surface a key collision with the upstream context as a * TypeScript error at the call site. Both composition paths put it in the @@ -66,11 +68,67 @@ export type Mistyped = /** * Config arg is optional exactly when the middleware's Config admits `undefined`. * Used by both `defineMiddleware` (to type the config-only overload) and - * `pipeline` (internally). + * `pipeline` (internally). `Arg` is the type the argument is checked against, + * when it differs from `Config` (see {@link ConfigReading}). + */ +export type ConfigArgs = undefined extends Config + ? [config?: Arg] + : [config: Arg] + +/** The keys of `T` that are not optional. */ +export type RequiredKeys = { + [K in keyof T]-?: Record extends Pick ? never : K +}[keyof T] + +/** + * `Config` with the `ctx` of each config callback widened to `X & Ctx`, where + * `X` is its declared type. A config callback is a top-level function property + * whose first parameter takes the `Request` and whose second is declared as the + * upstream context: it accepts `In & BaseContext` and names no key beyond `In`. + * + * The call signatures of {@link Middleware} and {@link Composite} check `config` + * against it, so what a callback's `ctx` annotation declares becomes part of + * that call's prerequisites. A `Config` with no config callback is returned + * as is, so an error about it names the author's type. */ -export type ConfigArgs = undefined extends Config - ? [config?: Config] - : [config: Config] +export type ConfigReading = Config extends unknown + ? [ConfigCallbacks] extends [never] + ? Config + : { + [P in keyof Config]: P extends ConfigCallbacks + ? WithCtx + : Config[P] + } + : never + +type ConfigCallbacks = { + [P in keyof Config]-?: ReadsUpstream< + Exclude, + In + > extends true + ? P + : never +}[keyof Config] + +type ReadsUpstream = F extends (...args: infer A) => unknown + ? A extends [infer R, infer X, ...unknown[]] + ? [Request] extends [R] + ? [In & BaseContext] extends [X] + ? [Exclude] extends [never] + ? true + : false + : false + : false + : false + : false + +type WithCtx = F extends ( + req: infer R, + ctx: infer X, + ...rest: infer Rest +) => infer O + ? (req: R, ctx: X & Ctx, ...rest: Rest) => O + : F type AnyFetchHandler = (req: Request, ctx: object) => Promise diff --git a/src/middleware/feature-flag/with-feature-flag.test.ts b/src/middleware/feature-flag/with-feature-flag.test.ts index 05f2b6d..b3a536b 100644 --- a/src/middleware/feature-flag/with-feature-flag.test.ts +++ b/src/middleware/feature-flag/with-feature-flag.test.ts @@ -118,8 +118,8 @@ describe('withFeatureFlag', () => { }) const evaluate = vi.fn( - (_req: Request, ctx: object) => - 'user' in ctx && (ctx as { user: { id: string } }).user.id === 'tester', + (_req: Request, ctx: { user: { id: string } }) => + ctx.user.id === 'tester', ) const app = pipeline( @@ -171,3 +171,96 @@ describe('withFeatureFlag', () => { expect(await res.json()).toEqual({ keys: ['featureFlag'] }) }) }) + +// What `evaluate` declares about `ctx` is a prerequisite of that call, so a +// stack with nothing to supply it fails to compile in either form. +describe('withFeatureFlag — evaluate reads the upstream (tsc-verified)', () => { + type User = { id: string } + const testers = new Set(['tester']) + const withUser = defineMiddleware<'user', void, Record, User>({ + key: 'user', + run: () => async () => ({ user: { id: 'tester' } }), + }) + const withRegion = defineMiddleware< + 'region', + void, + Record, + string + >({ + key: 'region', + run: () => async () => ({ region: 'eu' }), + }) + + it('pipeline: an annotated evaluate reads an earlier entry', () => { + const _app = pipeline( + [ + withUser(), + withFeatureFlag({ + name: 'beta', + evaluate: (_req, ctx: { user: User }) => testers.has(ctx.user.id), + }), + ], + async (_req, ctx) => + Response.json({ flag: ctx.featureFlag.name, user: ctx.user.id }), + ) satisfies FetchHandler + void _app + }) + + it('pipeline: an annotated evaluate with no provider fails to compile', () => { + const _app = pipeline( + [ + withRegion(), + withFeatureFlag({ + name: 'beta', + evaluate: (_req, ctx: { user: User }) => testers.has(ctx.user.id), + }), + ], + // @ts-expect-error — middleware-prereq: key 'user' is not yet on the context + async (_req, ctx) => Response.json({ flag: ctx.featureFlag.name }), + ) + void _app + }) + + it('pipeline: an optional key compiles with or without a provider', () => { + const evaluate = (_req: Request, ctx: { user?: User }) => + ctx.user !== undefined && testers.has(ctx.user.id) + const _with = pipeline( + [withUser(), withFeatureFlag({ name: 'beta', evaluate })], + async (_req, ctx) => Response.json({ flag: ctx.featureFlag.name }), + ) satisfies FetchHandler + const _without = pipeline( + [withRegion(), withFeatureFlag({ name: 'beta', evaluate })], + async (_req, ctx) => Response.json({ flag: ctx.featureFlag.name }), + ) satisfies FetchHandler + void [_with, _without] + }) + + it('nested: an annotated evaluate reads an enclosing layer', () => { + const _app = withUser( + withFeatureFlag( + { + name: 'beta', + evaluate: (_req, ctx: { user: User }) => testers.has(ctx.user.id), + }, + async (_req, ctx) => + Response.json({ flag: ctx.featureFlag.name, user: ctx.user.id }), + ), + ) satisfies FetchHandler + void _app + }) + + it('nested: an annotated evaluate with no provider fails to compile', () => { + const stack = withRegion( + withFeatureFlag( + { + name: 'beta', + evaluate: (_req, ctx: { user: User }) => testers.has(ctx.user.id), + }, + async (_req, ctx) => Response.json({ flag: ctx.featureFlag.name }), + ), + ) + // @ts-expect-error — nothing in the stack contributes `user` + const _entry: FetchHandler = stack + void _entry + }) +}) From 61b74af605a08640f99d004e0ced8256c91a1a73 Mon Sep 17 00:00:00 2001 From: Matt Johnston Date: Fri, 27 Nov 2026 18:23:43 -0400 Subject: [PATCH 2/2] docs: annotate config callbacks instead of casting them `withFeatureFlag`'s docs annotate `evaluate`'s `ctx` and describe the check. The authoring guide's config-callback variant builds `withRequestLog` with `defineMiddleware`, and describes the annotation as a checked prerequisite. Refs FUNC-1178 --- docs/authoring-guide.md | 147 ++++++++++-------- src/middleware/feature-flag/README.md | 16 +- .../feature-flag/with-feature-flag.ts | 19 +-- 3 files changed, 101 insertions(+), 81 deletions(-) diff --git a/docs/authoring-guide.md b/docs/authoring-guide.md index be129bd..4565f5b 100644 --- a/docs/authoring-guide.md +++ b/docs/authoring-guide.md @@ -1062,11 +1062,10 @@ work alone. A cache key that varies by user when a user is known. A log line that carries the caller's id when there is one. The upstream key is useful, not required. -`In` cannot say that. It is all-or-nothing: `keyof { user?: User }` is still -`'user'`, so `pipeline` treats the key as required and refuses to compose -without it, and the middleware loses its optional `ctx`, so it can no longer be -a `fetch` entry on its own (see the previous variant). Marking the property -optional changes nothing. Declaring it in `In` makes it mandatory. +`In` cannot say that. `keyof { user?: User }` is still `'user'`, so the +middleware loses its optional `ctx` and can no longer be a `fetch` entry on its +own (see the previous variant). Marking the property optional does not change +that. The pattern that works keeps `In` empty and makes the contract visible instead of required: @@ -1173,29 +1172,51 @@ somewhere and the contract is not real. Some middleware take a **callback** in their configuration rather than only plain values — a function called per request to derive something from the -request and the accumulated context. It is a useful shape, and it has one -wrinkle worth understanding before you publish it. - -`Middleware` has no generic for the accumulated -upstream: `Base` appears only in the handler position. A config callback typed -through `defineMiddleware` can therefore see the keys you declared in `In`, and -nothing else. To let it see whatever the consumer composed upstream, thread a -`Base` parameter through the config type: +request and the accumulated context. Declare the callback's `ctx` as +`BaseContext`, or as `In & BaseContext` when it reads your own prerequisites, +and `defineMiddleware` types the rest: ```ts -export interface WithRequestLogConfig { +import { defineMiddleware } from '@supabase/middleware' +import type { BaseContext, Middleware } from '@supabase/middleware' + +export interface WithRequestLogConfig { log: (line: Record) => void /** Extra fields, read off the request and the accumulated upstream context. */ - fields?: (req: Request, ctx: Base) => Record + fields?: (req: Request, ctx: BaseContext) => Record } + +export const withRequestLog: Middleware< + 'requestLog', + WithRequestLogConfig, + Record, + RequestLogContribution +> = defineMiddleware< + 'requestLog', + WithRequestLogConfig, + Record, + RequestLogContribution +>({ + key: 'requestLog', + run: (config) => async (req, ctx) => { + config.log({ + method: req.method, + url: req.url, + ...config.fields?.(req, ctx), + }) + return { requestLog: { logged: true } } + }, +}) ``` -and publish a hand-written signature over the ordinary `defineMiddleware` -runtime. [The next variant](#variant-a-hand-written-signature) writes that -signature out in full. This one covers what your consumers then see, because -the two composition forms are not equivalent. +`RequestLogContribution` is `{ logged: true }`. A config callback is a +top-level function property of the config whose first parameter takes the +`Request` and whose second is declared that way. The engine types its `ctx` per +call, so a consumer's callback can read what the consumer composed upstream. +The two composition forms get there differently. -**Nesting types it automatically.** There is nothing to annotate: +**Nesting in an anchored stack types it automatically.** There is nothing to +annotate: ```ts withValidatedBody( @@ -1207,6 +1228,10 @@ withValidatedBody( ) satisfies FetchHandler ``` +The callback's `ctx` is the context the enclosing layers push inward, the same +one the handler sees. Without an anchor that context is not known when the +callback is checked, so annotate it as in a `pipeline`. + **The `pipeline` form needs one inline annotation** on the callback's `ctx`: ```ts @@ -1232,17 +1257,16 @@ Property 'validatedBody' does not exist on type 'object' **That is evaluation order, not a defect.** `withRequestLog(config)` is a complete expression, checked before `pipeline` ever sees the array, so position -cannot flow backwards into an argument already checked. `Entry` carries no -accumulated-context parameter, and adding one would not help — the config object -was checked at the inner call site. The only shape that would fix it is -`pipeline` taking unapplied pairs, `[withRequestLog, config]`, which is a large -API change for a small gain. Document the annotation; do not redesign around it. +cannot flow backwards into an argument already checked. The only shape that +would fix it is `pipeline` taking unapplied pairs, `[withRequestLog, config]`, +which is a large API change for a small gain. Document the annotation; do not +redesign around it. -### The annotation is an assertion, not a contract +### The annotation is a prerequisite -This is the part to be careful about, and the reason the annotation deserves -more than a footnote. **Nothing checks it.** Compose the same entry with no -contributor for the key it names and it still compiles: +What the annotation declares joins that call's prerequisites, its `In`, and the +engine checks it like any other. Compose the entry with no contributor for the +key it names and the stack fails to compile, naming the key: ```ts pipeline( @@ -1256,37 +1280,32 @@ pipeline( }), ], handler, -) satisfies FetchHandler // tsc exits 0 +) ``` -At runtime that throws `TypeError: Cannot read properties of undefined`. Written -with optional chaining instead it does something worse — it silently produces a -fallback value for every request and looks like working code. - -`pipeline` is not the weak link here. It enforces declared prerequisites and -detects key collisions. The gap is that a config-callback annotation is a -_different_ channel, and only one of the two is checked: +``` +middleware-prereq: key 'validatedBody' is not yet on the context (check ordering) +``` -| Channel | Enforced by `pipeline`? | -| ---------------------------------- | ---------------------------------------------------------------------------- | -| `In` (a declared prerequisite) | **Yes** — `middleware-prereq: key 'validatedBody' is not yet on the context` | -| A config-callback param annotation | **No** — it asserts a shape; nothing verifies anyone supplies it | +An earlier entry that contributes the key at a type the annotation does not +accept fails with +`middleware-prereq: key 'validatedBody' is on the upstream context with an incompatible type`. -So the two composition forms differ in safety, not only in ergonomics. Nesting -catches a missing upstream precisely _because_ you write no annotation there — -the same code without a contributor above it fails with -`Property 'validatedBody' does not exist on type 'object'`. +Nesting checks it the same way a declared `In` is checked (see +[requiring an upstream key](#variant-requiring-an-upstream-key)). The +requirement travels outward until a layer contributes the key, so a stack built +in pieces still composes. A stack where no layer contributes it keeps a +required `ctx`, and fails where it is checked against `FetchHandler`. Two rules follow: -1. **If your middleware requires the key, declare it in `In`.** Then the engine - enforces it in both forms and names the missing key. Reach for a - config-callback annotation only for context your middleware genuinely works - without. -2. **If it optionally reads upstream context, annotate the key as optional** and - handle its absence. That is the honest assertion, and it puts the compiler - back in the loop — it will not let the callback assume a key nothing - supplies: +1. **If your middleware requires the key, declare it in `In`.** Then every + consumer gets the check without writing anything. The annotation is for + what one consumer's callback reads. +2. **If the callback reads the key only when it is there, annotate it as + optional** and handle its absence. An optional key never fails for being + missing. A provider of the wrong type still fails in a `pipeline` and in an + anchored stack: ```ts const fields = ( @@ -1295,23 +1314,19 @@ const fields = ( ) => ({ body: ctx.validatedBody?.data ?? null }) ``` -Both pipelines then compile, and neither can crash — with the contributor -present the field is populated, without it the fallback is deliberate rather -than accidental. Put the annotated form in your middleware's own `@example` -TSDoc, so the shape consumers copy is the safe one. - -Nothing else about the `pipeline` form is affected. Composition, ordering, -prerequisites and handler typing all work at full fidelity with nothing -annotated — the handler's `ctx` above sees both keys either way — and a config -callback that does not read upstream context needs no annotation in either form. +Put the annotated form in your middleware's own `@example` TSDoc, so the shape +consumers copy is the checked one. A config callback that does not read +upstream context needs no annotation in either form. ## Variant: a hand-written signature `Middleware` has four type parameters. A -middleware that needs one more writes its own signature. The case above is the -usual one: a config callback that reads the accumulated upstream needs `Base` -in scope where `config` is checked. A `Payload` parameter for a parsed body is -another. +middleware that needs one more writes its own signature, such as a `Payload` +parameter for a parsed body. The worked example below threads `Base` into the +config of `withRequestLog` from the previous variant, which shows every part of +such a signature on a middleware you already know. `defineMiddleware` types +that config callback without one, and checks its annotation; this signature +does not. The split is the same every time. The runtime is an ordinary `defineMiddleware` call, with the extra parameter erased to its constraint, so it keeps context diff --git a/src/middleware/feature-flag/README.md b/src/middleware/feature-flag/README.md index 3d31b51..42e1a56 100644 --- a/src/middleware/feature-flag/README.md +++ b/src/middleware/feature-flag/README.md @@ -50,7 +50,7 @@ ctx.featureFlag.payload // anything you returned ## Targeting the verified caller -`evaluate` receives the context accumulated by the entries placed before it. A flag composed after an auth middleware can read the caller that middleware verified, with no second lookup of its own. +`evaluate` receives the context accumulated by the entries placed before it. A flag composed after an auth middleware can read the caller that middleware verified, with no second lookup of its own. Annotate the keys it reads: ```ts pipeline( @@ -58,17 +58,21 @@ pipeline( withUser(), withFeatureFlag({ name: 'beta-checkout', - evaluate: (_req, ctx) => { - const { user } = ctx as { user?: { id: string } } - return user !== undefined && betaTesters.has(user.id) - }, + evaluate: (_req, ctx: { user: { id: string } }) => + betaTesters.has(ctx.user.id), }), ], handler, ) ``` -`ctx` is typed as `BaseContext` (`object`), because this middleware declares no prerequisites and composes at any position in a stack. Narrow it to the shape of the entries you place before it. Standalone, `ctx` is empty. +The annotation is a prerequisite of that call, checked like any other. Without `withUser` before the flag, the stack fails to compile: + +``` +middleware-prereq: key 'user' is not yet on the context (check ordering) +``` + +Nesting checks it too: `withUser(withFeatureFlag(config, handler))` compiles, and the same flag with no `withUser` around it fails where the stack is checked against `FetchHandler`. When the flag also works without the key, mark it optional (`ctx: { user?: { id: string } }`) and handle its absence. Unannotated, `ctx` is `BaseContext` (`object`), or the enclosing context when the flag is nested in an anchored stack. ## Why 404 by default diff --git a/src/middleware/feature-flag/with-feature-flag.ts b/src/middleware/feature-flag/with-feature-flag.ts index 49f550d..fc90793 100644 --- a/src/middleware/feature-flag/with-feature-flag.ts +++ b/src/middleware/feature-flag/with-feature-flag.ts @@ -32,10 +32,10 @@ export interface WithFeatureFlagConfig { * to also record a variant or provider payload. Async is fine. * * `ctx` carries the contributions of every upstream entry, so a flag placed - * after an auth middleware can target the verified caller. It is typed as - * {@link BaseContext} because this middleware declares no prerequisites and - * composes at any position; narrow it to the shape of the entries you place - * before it. + * after an auth middleware can target the verified caller. Annotate the keys + * it reads, `(req, ctx: { user: User }) => …`: the annotation is a + * prerequisite of that call, checked in a `pipeline` and in a nested stack + * like any other. Mark a key optional when the flag works without it. */ evaluate: ( req: Request, @@ -122,7 +122,10 @@ export interface FeatureFlagContribution { * }) * ``` * - * Placed after an auth entry, `evaluate` reads the caller it verified: + * Placed after an auth entry, `evaluate` reads the caller it verified. The + * annotation on `ctx` is a prerequisite of the call: without `withUser` before + * it, the stack fails to compile with + * `middleware-prereq: key 'user' is not yet on the context`. * * ```ts * pipeline( @@ -130,10 +133,8 @@ export interface FeatureFlagContribution { * withUser(), * withFeatureFlag({ * name: 'beta-checkout', - * evaluate: (_req, ctx) => { - * const { user } = ctx as { user?: { id: string } } - * return user !== undefined && betaTesters.has(user.id) - * }, + * evaluate: (_req, ctx: { user: { id: string } }) => + * betaTesters.has(ctx.user.id), * }), * ], * handler,