Repository navigation
feat: add defineComposite for bundling middleware into one - #36
Conversation
A middleware contributes exactly one key (authoring guide rule 1). Some
units of behavior genuinely own several — `withSupabase` in
`@supabase/server` establishes six — and until now their only options were
to publish a tuple consumers had to spread, or to hand-write a multi-key
function the type layer could not describe.
`defineComposite` closes that gap without weakening rule 1. A composite is
built from single-key middleware and its contributions are *derived* from
theirs, so it cannot over-declare: every key on a composite still traces to
exactly one `defineMiddleware` call. It satisfies both composition contracts
from one declaration — it nests, and it drops into a `pipeline` array.
`Entry` now carries its contributions as a record rather than a single
`Key` + `Contribution`. The three-argument spelling is preserved as an alias
(`Entry<'flag', {}, boolean>` resolves to `Entry<{ flag: boolean }>`), so
existing annotations keep compiling. `NoConflict` is widened to accept either
a literal key or a record.
`hide` marks a part's key as internal plumbing: stripped at the composite's
boundary, not merely omitted from the type, so a downstream layer sees
neither the type nor the value. This lets a composite present a flat public
contract while using an intermediate key to carry state between its parts,
instead of a request-keyed side channel that rule 3 exists to prevent.
`defineMiddleware` is unchanged, in signature and at runtime: a composite
folds its parts exactly as `pipeline` does, and each part still merges its
own single key.
Verified:
- 108 engine tests, typecheck, lint, attw, smoke, and the TS 5.4.2
consumer floor (negatives included) all green
- `@supabase/server` 1.5.2 typechecks and passes all 425 of its unit and
nestjs tests against this build, unmodified
One behavior note: a widened entry (`Entry<string, object, unknown>`, i.e.
hand-wrapped rather than produced by `defineMiddleware`) has an unknown key
set, so conflict detection skips it — matching the prior semantics, where a
`string` key never matched `keyof Ctx`. It still folds an index signature
onto the accumulated context and so poisons entries placed after it; that
pre-existing behavior is unchanged and is pinned by a test in
`@supabase/server`.
commit: |
Three follow-ups from review of the composite design. **`bufferRequest` is now exported.** The engine already exports two of the three things a host needs to act as an entry point: `seedContext` mints the context, `isContext` distinguishes an upstream one from a platform argument. The third was missing, and its absence is silent. A hand-rolled entry that seeds without buffering is a valid upstream for every layer below it, and all of them share one single-use body — the first reader locks out the rest. This is live in `@supabase/server`, whose `withSupabase` seeds its own context and never buffers, so a body-reading middleware composed below it fails on the second read. Pinned by three tests: the working stack, the unbuffered failure, and the fix. **The derivation guarantee is scoped to the constructor.** `__contributes` is an optional phantom, so any `(handler) => handler` structurally satisfies any `EntryOf` — hand-annotating a function with a record it does not produce compiles, and the keys type as present while being undefined at runtime. The phantom cannot be made required; it never exists as a value. So "cannot over-declare" is a property of `defineComposite`, which derives contributions from its parts and offers no place to name a key, not of the type. Said plainly in the `EntryOf` remarks and the authoring guide, with guidance to build composites with the constructor and reserve a bare annotation for describing a function you did not write. **Nested composites are tested rather than assumed.** A composite accepts a composite as a part: contributions derive through both levels, a key the inner one hides stays hidden through the outer, an inner outstanding prerequisite propagates outward, and a collision between an inner key and a sibling is detected. 115 engine tests, typecheck, lint, prettier, attw, smoke and the TS 5.4.2 consumer floor all green. `@supabase/server` 1.5.2 unmodified still typechecks and passes all 425 unit and nestjs tests against this build.
The composite docs described what the engine used to be rather than what it is — "before this primitive their only options were", "contributions used to be one Key plus one Contribution", "no change to defineMiddleware", "the original three-argument spelling, kept so existing annotations keep compiling". That framing is only legible to someone reading the diff, and it ages into noise once the diff is history. Rewritten to describe the design directly: - The module header states what a composite is and what a consumer gets from one, rather than the gap it filled. - The runtime note says the parts fold as `pipeline` folds them, each merging its own key — dropping the comparison to a `defineMiddleware` that no reader has a "before" for. - `Entry`'s single-key form is documented as shorthand for a middleware contributing one key, which is what it is, rather than as a compatibility shim. - Same pass over the authoring guide's Runtime subsection and the buffering test's comment. No behavior or type change. 115 tests, typecheck, lint, prettier, attw, smoke and the TS 5.4.2 floor green; `@supabase/server` 1.5.2 unmodified still typechecks and passes 398 unit + 27 nestjs tests against this build.
There was a problem hiding this comment.
Thank you @johnstonmatt !! I do think this is the right direction!!
Checked the branch (8cebd77) against @supabase/server main and all is good! :D
Two fixes before merge, then answers to your three questions.
1. hide strips an upstream key of the same name (blocking)
The boundary in define-composite.ts deletes every hidden key from the spread context, including one the upstream contributed. The types miss it because Composite is declared over Omit<Contributions, Hidden>, so NoConflict and ValidateEntries never see hidden keys and the downstream type keeps the upstream's value.
const withUpstreamAuth = passing('auth', 'from-upstream' as const)
pipeline([withUpstreamAuth(), withAuth({ mode: 'user' })], async (_req, ctx) => {
const still: 'from-upstream' = ctx.auth // compiles: type says it survives
return Response.json({ keys: Object.keys(ctx) }) // runtime: ['authMode'], auth is gone
})Same in the nested form. Without hide the same stack fails with Conflict<'auth'>. For withSupabase, which will hide auth, any third-party auth placed before it disappears silently.
Fix: scope hidden keys to the composite. Snapshot the upstream's hidden-key values before the fold; at the boundary restore the ones that were present, delete the ones that were not. Matches what the types already say, no type change needed. A symbol-keyed snapshot on the context survives the spreads. Tests: nested, flat, hidden key with no upstream counterpart, nested composites. One doc line: hidden keys are scoped to the composite.
2. The Entry alias turns a loud error silent (blocking as written)
Entry<'k', In> with two arguments is a compile error on main. Here the Contribution = never default resolves it to EntryOf<never, In>, the pipeline context folds to never, and the error lands on the next entry as middleware-conflict: key 'later' is already present. Your documented never-contribution caveat is the same mechanism. Resolved by the rename below. If the alias stays anyway: a private sentinel default instead of never, a guard turning a string key with no contribution into an error sentinel, and the two-argument negative in test/ts-floor/consumer.ts.
Your questions
- Composite worth the deconstruction? Yes. One key per
defineMiddlewareplus decomposition is what the RFC approved, and the deconstruction is committed work. Multi-key atdefineMiddlewarewould give a six-keywithSupabasewith no internal structure, losing the trust-model ordering fix and the reusable gate SDK-1596 asks for. - Alias or rename? Rename. Make
Entry<Contributes, In = {}>the record form, drop the conditional, keepAnyEntry. Consumers outside the engine: three sites in server, which I am rewriting anyway, and one file inmiddleware-openfeature. A plainSingleKeyEntry<Key, In, Contribution>is fine as a shorthand.Middlewarestaying single-key is correct. hidenaming and shape. Shape stays: contributed key names, drift-checked againstbuild. Name is low stakes;internalreads slightly better but I will not hold the PR on it. Point 1 is what matters.
Everything else looks good: bufferRequest, record-based ValidateEntries, the widened-entry note, nested-composite coverage.
Addresses both blocking points from review.
**Internal keys are scoped, not deleted.** The boundary deleted every hidden
name from the context, including one an upstream layer had contributed, while
the types said it survived — internal keys are absent from `Contributes`, so
neither `NoConflict` nor `ValidateEntries` sees them and the downstream type
keeps the upstream's value. For a composite that marks `auth` internal, any
third-party `auth` placed before it disappeared silently.
The composite now records what the upstream held under those names before its
parts run and restores it at the boundary, deleting only the names the upstream
did not have. The snapshot rides the context under a symbol unique to each
composite: a closure would race across concurrent requests, and a shared symbol
would let a nested composite clobber an enclosing one's snapshot. Composites
with no internal keys are untouched — no wrapper, no snapshot. Six tests: flat,
nested, no upstream counterpart, the composite's own value still visible to its
parts, nested composites both marking internals, and no marker left behind.
**`Entry` is the record form.** `Entry<Contributes, In = {}>`, no conditional,
with `SingleKeyEntry<Key, In, Contribution>` as the one-key shorthand and
`AnyEntry` unchanged. The two-argument spelling `Entry<'k', In>` is now a
constraint violation reported at the annotation, rather than resolving to a
`never` contribution and surfacing as a bogus conflict on the *next* entry.
Pinned as a negative in the consumer floor fixture.
One trap found while doing it, documented on `SingleKeyEntry` and at the call
site: the shorthand must not be used as the declared return type of a
config-only call signature. A generic alias in that position defeats the
`const Entries` tuple inference `defineComposite` performs on its `build`
result, collapsing every part's contributions to the constraint. `Middleware`
declares `Entry<{ [K in Key]: Contribution }, In>` directly.
**`hide` renamed to `internal`**, per review preference. Shape unchanged:
contributed key names, drift-checked against `build`.
121 engine tests, typecheck, lint, prettier, attw, smoke and the TS 5.4.2
consumer floor all green.
`@supabase/server` migration verified end to end against this build: 22 errors
before, 0 after, with 398 unit + 27 nestjs tests passing. Four files, +24/-19 —
`SingleKeyEntry` for the two public single-key returns, the engine's exported
`AnyEntry` plus a record-shaped `MiddlewareCtx` in `with-supabase.ts`, and
`Entry<Record<string, unknown>>` for the widened-entry test, which still pins
the same poisoning behavior.
`typecheck:min` — the engine's own source at TypeScript 5.4.2 — failed on the new nested test. The error was on the call, not the composition: at 5.4.2 the `Middleware` propagation overload wins where 5.9 picks the cascade, so `Omit<Ctx, 'auth'>` lands in the produced `In`, `ctx` becomes required, and `app(request)` reports "Expected 2 arguments, but got 1". Anchoring the outermost call with `satisfies FetchHandler` selects the cascade at both versions. That is what the docs already ask of an outermost call, so the test now does what a consumer should rather than relying on which overload happens to win.
|
Thanks @mandarini — both blocking points fixed, and I took the rename. 1.
|
The remark told authors not to use `SingleKeyEntry` as the declared return type
of a config-only call signature. That reads as a warning about the one thing
authors actually write — a wrapper that names an entry type to thread a generic
through a middleware, which is how `@supabase/server` declares
`withSupabaseClient<Database>`. That usage is fine.
Verified fine, and now pinned: a part declared `SingleKeyEntry<'thing', {},
Client<Database>>` composes normally, types through the generic, and can be
marked `internal` — which only works if `Contributions` resolved its key.
Concrete instantiations were never at risk; the mapped type resolves as soon as
`Key` is a literal, which it is at every call site.
The constraint is engine-internal and has exactly one site. Inside
`Middleware`, `Key` and `Contribution` are still the interface's own
parameters, so any indirection over `Entry` leaves a deferred mapped type that
`Contributions` cannot infer through. Both an alias and an interface extending
`Entry` were tried; both collapse every part's contributions to the constraint.
That reasoning moved to a comment at the site it governs, and the public remark
now shows the wrapper pattern instead of warning against it.
123 engine tests, typecheck, typecheck:min, lint, prettier, attw, smoke and the
5.4.2 consumer floor all green.
A pass over everything the branch added, for accuracy first. Wrong, now fixed: - `NoConflict` claimed to name "the first offender". It resolves to a union of messages when several keys collide, so it names all of them. - The config-only comment in `Middleware` had my note wedged into the middle of the existing sentence about overload fall-through, leaving both mangled. - The authoring guide justified stripping internal keys by saying it stops them shadowing "a layer further down", then said an upstream's key is restored. Two opposite directions read as a contradiction; both are now stated as such, one clause each. Stale after the rename: prose and identifiers still said "hidden" where the option is `internal` — `@param spec.internal`, the guide, two describe blocks and seven test titles, `Hidden`/`UpstreamHidden`, and "so it is hidden" in the example. Trimmed without losing content: `Entry`'s remarks (16 lines to 10), `SingleKeyEntry`'s example (a signature, not a body with a double cast), and the two runtime comments in `defineComposite`, which both explained the scoping and now say one thing each. Also dropped a "now matches what the types say" — the reader has no "before". No behavior or type change. 123 tests, typecheck, typecheck:min, lint, prettier, attw, smoke and the 5.4.2 consumer floor green.
mandarini
left a comment
There was a problem hiding this comment.
Re-reviewed and I'm approving! :D Thanks for taking the rename and for the concurrency-safe snapshot design!!
The TS 5.4.2 unanchored-nesting finding is filed as SDK-1731, I'll do as followup at some point!
Why
From the SDK-1713 thread. Two questions were left open:
withSupabasego in apipelinearray?: "it can't become a middleware under the one-key rule we settled at RFC approval."withSupabasedoesn't need to be middleware itself to fulfill the contract of the signature?"Multi-key was not expressible, and the one-key rule was doing double duty: sound design guidance ("a middleware that wants two slots is doing too much") resting on a representational limit that also blocked the legitimate case of several one-key middleware shipping as a unit.
This PR separates those. Rule 1 stays exactly as written, for
defineMiddleware.defineCompositeadds the composition operator the rule was missing.What
One declaration, both composition contracts — the same thing
defineMiddlewaregives a single-key middleware.Contributions are derived, never declared. Inside
defineCompositethere is no place to name a key, so a composite publishes exactly the union of what its parts contribute and cannot over-declare: every key traces to exactly onedefineMiddlewarecall.Prerequisites are derived the same way — a part's
Inthat an earlier part supplies is processed internally; anything outstanding is republished as the composite's own, exactly as a nested stack republishes an unmet requirement.internalis for plumbing.withGateabove contributes the whole auth result atctx.authand the projections republish the flat keys the public contract promises;authitself is an implementation detail. Internal keys are scoped to the composite — stripped at its boundary, not merely omitted from the type, and where an upstream layer already contributed that name, its value is restored on the way out. Stripping keeps the composite's plumbing from leaking downstream; restoring means marking a key internal can never make someone else's disappear. Each name must be a key some part actually contributes, sointernalcannot drift frombuild. Together this is what lets a composite carry state between its parts through a real ctx key instead of a request-keyed side channel, which rule 3 exists to prevent.The type change
Entrynow carries contributions as a record instead of a singleKey+Contribution:The three-argument spelling still works.
Entryis an alias that resolvesEntry<'flag', {}, boolean>toEntry<{ flag: boolean }>, so existing annotations compile unchanged — including@supabase/server's publicEntry<'supabase', Record<never, never>, SupabaseClient<Database>>. The two forms are told apart by whether the third argument is supplied, so a middleware whose contribution is genuinelynevermust use the record form; that's documented on the alias.NoConflictis widened to accept either a literal key or a record, so it serves bothMiddlewareandComposite.defineMiddlewareis untouched — signature and runtime. A composite folds its parts exactly aspipelinedoes, so each part still merges its own single key and there is no multi-key merge anywhere in the engine.One off-topic export added:
bufferRequestThe engine already exports two of the three things a host needs to be an entry point —
seedContextmints the context,isContexttells an upstream context from a platform argument. The third was missing, and its absence is silent: an entry that seeds without buffering is a valid upstream for every layer below it, and all of them share one single-use body, so the first reader locks out the rest.This fault is already live in
@supabase/servertoday.withSupabaseseeds its own context atwith-supabase.ts:245and never buffers, so a body-reading middleware composed below it fails on the second read (Body is unusable: Body has already been read). It doesn't bite yet only because little composes belowwithSupabase; as a pipeline entry it becomes the seam every downstream middleware sits behind. Three tests pin the working stack, the unbuffered failure, and the fix:Verification
typecheck:min, lint, prettier, attw, and smoke all green.test/ts-floor/consumer.ts. The negatives are the point at the floor: below it the failure mode is a check going quiet, so internal-key access,internaldrift, composite/upstream collision, an unmet republished prerequisite, and the two-argumentEntryspelling are all pinned with@ts-expect-error.@supabase/server1.5.2, unmodified, against this build: typecheck clean, and all 425 unit + nestjs tests pass.TS1360 … Omit<{ xxx: … }, "aaa">), checked againstmainas a baseline.One behavior note
A widened entry —
Entry<string, object, unknown>, i.e. hand-wrapped rather than produced bydefineMiddleware— has an unknown key set, so conflict detection skips it, matching the prior semantics where astringkey never matchedkeyof Ctx. Checkingkeyof C & keyof Ctxunconditionally instead would make a widened entry conflict with everything before it as well; the@supabase/servertest pinning this failure mode is what catches that.The pre-existing forward poisoning is unchanged: a widened entry folds an index signature onto the context, so later literal keys read as already present. Fixing that means not widening the entry.
What this unblocks
withSupabasebecomes a composite in the follow-up PR — deconstructed into its parts and declared withdefineComposite— which makes it an ordinary entry and puts placement under the caller's control:That closes SDK-1713:
GET .../oauth-protected-resource401 INVALID_CREDENTIALS200+ the metadata document401,WWW-Authenticateabsent401+WWW-Authenticate: Bearer resource_metadata="…"OPTIONSpreflight204, nomcp-protocol-version204+mcp-protocol-versionThe third row was suspected in the thread but never reproduced.
What fixes these is position. Today
withSupabaseis the outermost layer and returns its 401 atwith-supabase.ts:212, before themiddlewarearray folds in at:180, so nothing a caller composes can run ahead of the gate or observe its response. As one element of a caller-controlled fold it gets both:withOAuthProtectedResourceruns beforewithSupabaseis entered at all, which covers discovery and preflight, and the 401 becomes areturnfrom inside the chain, which the enclosing generator'syieldresolves to and stamps.Why this PR lands first. The deconstruction needs both halves of it.
defineCompositeis how six keys ship as one entry with contributions derived from the parts, and it supplies the config-only call signature that putswithSupabase(config)in an array at all. The recordEntryis what makes those six keys typed: a multi-key entry without it can only be widened, which folds an index signature ontoctxand makes any typed entry placed afterwithSupabasereport a falsemiddleware-conflict: key 'postgres' is already present on the upstream context— sowithPostgresClient()above could not compile.The
@supabase/serverside lands separately: split the gate intowithGateplus the projections that republish the flat keys, declarewithSupabase = defineComposite({ build, internal: ['auth'] }), and deprecate themiddlewarearray. The committed tests for the table above go with it, since the engine cannot depend on its own consumer.Open questions for review
defineComposite: this requires deconstructingwithSupabasefor the fix, there may (?) be lighter solutions if we determine that single-contribution is too opinionated and not worth the cost.Entryas a back-compat alias worth it, or would you rather take the breaking rename now while we're 0.x and pre-launch? The alias costs one conditional type and thenever-contribution caveat.internalnaming and shape.internal: ['auth']is a bit confusing on first glance, but if someone is defining a composite they will probably know when they need it. Is this acceptable?