diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8095058..59cac63 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,7 +81,7 @@ jobs: @tanstack/react-router@1.132.0 @tanstack/react-start@1.169.0 \ react-router@7.0.0 next@16.0.0 expo-router@5.0.2 \ expo-secure-store@14.2.0 react-native@0.79.0 effect@4.1.0 \ - @monarcode/effetch@0.1.0-rc.2 + @monarcode/effetch@0.1.0-rc.3 - name: Build and test run: pnpm run build && pnpm test && pnpm run test:types diff --git a/CHANGELOG.md b/CHANGELOG.md index 10e20d5..b5ec993 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## 0.1.0-rc.1 + +The Effect guide and example move to effetch and effetch-query `0.1.0-rc.3`. +The public API is unchanged. + +### Changed + +- The `@monarcode/effetch` peer range is `^0.1.0-rc.3`, up from `rc.2`. + effetch-query 0.1.0-rc.3, which the Effect guide uses, needs it, and the + guide, the example and the tests use effetch's rc.3 APIs. + +### Docs + +- The Effect guide and the TanStack Start example with effetch use + effetch's and effetch-query's rc.3 APIs: the API client is a + `Fetch.Service`, effetch-query's `fromClient` reads its `defaultError`, + and the refresh turns a 401 or 403 into `null` with `Fetch.catchStatus`. +- The Effect guide says what `sessionBearer` does that effetch's own + `bearer` doesn't, and that after a refresh it sends only a `GET` or `HEAD` + again, where `bearer` with a `refresh` option sends any method again. +- `sessionBearer` says that streams work through it up to the response's + headers, and that a stream open when the user signs out keeps reading. + ## 0.1.0-rc.0 The first release candidate for `0.1.0`. The public API is now frozen, and diff --git a/examples/tanstack-start-spa-effetch/package.json b/examples/tanstack-start-spa-effetch/package.json index 76c336e..35b0445 100644 --- a/examples/tanstack-start-spa-effetch/package.json +++ b/examples/tanstack-start-spa-effetch/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@effect/atom-react": "4.1.3", - "@monarcode/effetch": "0.1.0-rc.2", - "@monarcode/effetch-query": "0.1.0-rc.2", + "@monarcode/effetch": "0.1.0-rc.3", + "@monarcode/effetch-query": "0.1.0-rc.3", "@monarcode/session-kit": "workspace:*", "@tanstack/react-router": "1.170.46", "@tanstack/react-start": "1.169.5", diff --git a/examples/tanstack-start-spa-effetch/src/api.ts b/examples/tanstack-start-spa-effetch/src/api.ts index 7d465af..c6ac8cf 100644 --- a/examples/tanstack-start-spa-effetch/src/api.ts +++ b/examples/tanstack-start-spa-effetch/src/api.ts @@ -1,14 +1,13 @@ import * as Fetch from "@monarcode/effetch"; import { retry } from "@monarcode/effetch/plugins"; import { sessionBearer } from "@monarcode/session-kit/effetch"; -import * as Context from "effect/Context"; -import * as Effect from "effect/Effect"; import * as HttpClient from "effect/http/HttpClient"; import * as Layer from "effect/Layer"; import { API_BASE_URL, ApiError } from "./backend"; -const make = Fetch.make({ +/** The app's API client: effetch's `get`, `post` and the rest, for DummyJSON. */ +export class ApiClient extends Fetch.Service()("ApiClient", { baseUrl: API_BASE_URL, defaultError: ApiError, // `retry` resends a GET after a network error or a status such as 503. @@ -17,17 +16,11 @@ const make = Fetch.make({ // sends a GET or HEAD again once. `optional`: a call made while signed out // goes without a token. plugins: [retry(), sessionBearer({ baseUrl: API_BASE_URL, optional: true })], -}).pipe( +}) {} + +/** The API client, over whichever `Auth` is provided. */ +export const ApiClientLive = ApiClient.layer.pipe( // Effect adds tracing headers to every request, which fail the preflight // of an API that doesn't allow them. - Effect.provideService(HttpClient.TracerPropagationEnabled, false), + Layer.provide(Layer.succeed(HttpClient.TracerPropagationEnabled)(false)), ); - -/** The app's API client: effetch's `get`, `post` and the rest, for DummyJSON. */ -export class ApiClient extends Context.Service< - ApiClient, - Effect.Success ->()("ApiClient") {} - -/** The API client, over whichever `Auth` is provided. */ -export const ApiClientLive = Layer.effect(ApiClient, make); diff --git a/examples/tanstack-start-spa-effetch/src/query.ts b/examples/tanstack-start-spa-effetch/src/query.ts index 3d0972b..5ce7809 100644 --- a/examples/tanstack-start-spa-effetch/src/query.ts +++ b/examples/tanstack-start-spa-effetch/src/query.ts @@ -1,9 +1,8 @@ import { QueryClient } from "@monarcode/effetch-query"; -import { endpoints } from "@monarcode/effetch-query/effetch"; +import { fromClient } from "@monarcode/effetch-query/effetch"; import type * as ManagedRuntime from "effect/ManagedRuntime"; import { ApiClient } from "./api"; -import { ApiError } from "./backend"; import { appRuntime, type AppRuntime } from "./runtime"; declare module "@monarcode/effetch-query" { @@ -13,7 +12,7 @@ declare module "@monarcode/effetch-query" { } /** Turns endpoints of the API client into queries and mutations. */ -export const api = endpoints(ApiClient, { defaultError: ApiError }); +export const api = fromClient(ApiClient); /** * Makes the query cache, which runs queries and mutations with `appRuntime`'s diff --git a/examples/tanstack-start-spa-effetch/src/refresh.ts b/examples/tanstack-start-spa-effetch/src/refresh.ts index 7ee2a68..d4e7d0c 100644 --- a/examples/tanstack-start-spa-effetch/src/refresh.ts +++ b/examples/tanstack-start-spa-effetch/src/refresh.ts @@ -26,11 +26,7 @@ export const refreshSession = (refreshToken: string, signal: AbortSignal) => output: SessionTokens, }); }).pipe( - Effect.catchTag("HttpError", (error) => - error.status === 401 || error.status === 403 - ? Effect.succeed(null) - : Effect.fail(error), - ), + Fetch.catchStatus([401, 403], () => Effect.succeed(null)), Effect.provide(FetchHttpClient.layer), ), { signal }, diff --git a/package.json b/package.json index bf0436f..91a42e4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@monarcode/session-kit", - "version": "0.1.0-rc.0", + "version": "0.1.0-rc.1", "description": "Schema-driven, type-safe sessions for React, with TanStack Router, React Router, Expo Router, Next.js, TanStack Start, and Effect support", "keywords": [ "auth", @@ -123,8 +123,8 @@ "use-sync-external-store": "^1.6.0" }, "devDependencies": { - "@monarcode/effetch": "0.1.0-rc.2", - "@monarcode/effetch-query": "0.1.0-rc.2", + "@monarcode/effetch": "0.1.0-rc.3", + "@monarcode/effetch-query": "0.1.0-rc.3", "@tanstack/react-router": "1.170.46", "@tanstack/react-start": "1.169.5", "@types/jsdom": "21.1.7", @@ -151,7 +151,7 @@ "zod": "4.6.7" }, "peerDependencies": { - "@monarcode/effetch": "^0.1.0-rc.2", + "@monarcode/effetch": "^0.1.0-rc.3", "@tanstack/react-router": "^1.132.0", "@tanstack/react-start": "^1.169.0", "effect": "^4.1.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 601b842..402b924 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -19,11 +19,11 @@ importers: version: 1.7.0(react@19.3.1) devDependencies: '@monarcode/effetch': - specifier: 0.1.0-rc.2 - version: 0.1.0-rc.2(effect@4.1.3) + specifier: 0.1.0-rc.3 + version: 0.1.0-rc.3(effect@4.1.3) '@monarcode/effetch-query': - specifier: 0.1.0-rc.2 - version: 0.1.0-rc.2(@effect/atom-react@4.1.3(effect@4.1.3)(react@19.3.1)(scheduler@0.28.0))(@monarcode/effetch@0.1.0-rc.2(effect@4.1.3))(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(effect@4.1.3)(react@19.3.1) + specifier: 0.1.0-rc.3 + version: 0.1.0-rc.3(@effect/atom-react@4.1.3(effect@4.1.3)(react@19.3.1)(scheduler@0.28.0))(@monarcode/effetch@0.1.0-rc.3(effect@4.1.3))(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(effect@4.1.3)(react@19.3.1) '@tanstack/react-router': specifier: 1.170.46 version: 1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -408,11 +408,11 @@ importers: specifier: 4.1.3 version: 4.1.3(effect@4.1.3)(react@19.3.1)(scheduler@0.28.0) '@monarcode/effetch': - specifier: 0.1.0-rc.2 - version: 0.1.0-rc.2(effect@4.1.3) + specifier: 0.1.0-rc.3 + version: 0.1.0-rc.3(effect@4.1.3) '@monarcode/effetch-query': - specifier: 0.1.0-rc.2 - version: 0.1.0-rc.2(@effect/atom-react@4.1.3(effect@4.1.3)(react@19.3.1)(scheduler@0.28.0))(@monarcode/effetch@0.1.0-rc.2(effect@4.1.3))(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(effect@4.1.3)(react@19.3.1) + specifier: 0.1.0-rc.3 + version: 0.1.0-rc.3(@effect/atom-react@4.1.3(effect@4.1.3)(react@19.3.1)(scheduler@0.28.0))(@monarcode/effetch@0.1.0-rc.3(effect@4.1.3))(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(effect@4.1.3)(react@19.3.1) '@monarcode/session-kit': specifier: workspace:* version: link:../.. @@ -1627,11 +1627,11 @@ packages: '@mdx-js/mdx@3.1.1': resolution: {integrity: sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ==} - '@monarcode/effetch-query@0.1.0-rc.2': - resolution: {integrity: sha512-ylmxNLYrk8JzQZMQMZNJyrbVVq79ZooDtIoq7ZnZB1vJO7tVHKI4gQsaSUZ33VJfb+/gqXA4UE3FKr0rS9hEEQ==} + '@monarcode/effetch-query@0.1.0-rc.3': + resolution: {integrity: sha512-hfdW4AE7St9izEkHuvdejU/X5smmYwG6T8gRJZa+d8H4DYfpIPKFMHoOBfgXNpx0oXG6J5nWJEPoB0tXNmpTyg==} peerDependencies: '@effect/atom-react': ^4.1.0 - '@monarcode/effetch': '>=0.1.0-rc.2 <0.2.0' + '@monarcode/effetch': '>=0.1.0-rc.3 <0.2.0' '@tanstack/react-router': '>=1.170.33 <2.0.0' effect: ^4.1.0 react: '>=19.0.0 <20.0.0' @@ -1645,8 +1645,8 @@ packages: react: optional: true - '@monarcode/effetch@0.1.0-rc.2': - resolution: {integrity: sha512-bsoJ7CJPOxCwm74yIQyOAdY23+8f88VfYFKUsKrbbbtCjKRoTep8x+ub3BSamHXxDHXoE4Hw/eV03VEsICzB8g==} + '@monarcode/effetch@0.1.0-rc.3': + resolution: {integrity: sha512-LHOELQLZGaouwwvIcMAkovTyvWZ4fbDYgtuN9Xt4QcPgUY8ajQAjIXJTZn5WrHBCl/qA9t1a/jq1TKkMju8uUg==} peerDependencies: effect: ^4.0.0 @@ -7278,16 +7278,16 @@ snapshots: transitivePeerDependencies: - supports-color - '@monarcode/effetch-query@0.1.0-rc.2(@effect/atom-react@4.1.3(effect@4.1.3)(react@19.3.1)(scheduler@0.28.0))(@monarcode/effetch@0.1.0-rc.2(effect@4.1.3))(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(effect@4.1.3)(react@19.3.1)': + '@monarcode/effetch-query@0.1.0-rc.3(@effect/atom-react@4.1.3(effect@4.1.3)(react@19.3.1)(scheduler@0.28.0))(@monarcode/effetch@0.1.0-rc.3(effect@4.1.3))(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(effect@4.1.3)(react@19.3.1)': dependencies: effect: 4.1.3 optionalDependencies: '@effect/atom-react': 4.1.3(effect@4.1.3)(react@19.3.1)(scheduler@0.28.0) - '@monarcode/effetch': 0.1.0-rc.2(effect@4.1.3) + '@monarcode/effetch': 0.1.0-rc.3(effect@4.1.3) '@tanstack/react-router': 1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1) react: 19.3.1 - '@monarcode/effetch@0.1.0-rc.2(effect@4.1.3)': + '@monarcode/effetch@0.1.0-rc.3(effect@4.1.3)': dependencies: effect: 4.1.3 diff --git a/site/content/docs/(latest)/effect.mdx b/site/content/docs/(latest)/effect.mdx index 869fa0f..a9e0839 100644 --- a/site/content/docs/(latest)/effect.mdx +++ b/site/content/docs/(latest)/effect.mdx @@ -39,10 +39,10 @@ npm install @monarcode/session-kit effect @monarcode/effetch `effect` and `@monarcode/effetch` are optional peer dependencies of Session kit. `./effect` and `./effetch` need `effect` 4.1 or newer, and `./effetch` -also needs `@monarcode/effetch`. +also needs `@monarcode/effetch` 0.1.0-rc.3 or newer. To [cache with effetch-query](#cache-with-effetch-query), also install -effetch-query 0.1.0-rc.2 or newer, and its `@effect/atom-react` peer for +effetch-query 0.1.0-rc.3 or newer, and its `@effect/atom-react` peer for React: ```npm @@ -126,11 +126,7 @@ export const refreshSession = (refreshToken: string, signal: AbortSignal) => output: SessionTokens, }); }).pipe( - Effect.catchTag("HttpError", (error) => - error.status === 401 || error.status === 403 - ? Effect.succeed(null) - : Effect.fail(error), - ), + Fetch.catchStatus([401, 403], () => Effect.succeed(null)), Effect.provide(FetchHttpClient.layer), ), { signal }, @@ -208,43 +204,36 @@ export const showGreeting = () => ## 6. Call your API with effetch -Make the app's API client with effetch's `Fetch.make`: the backend's base +Make the app's API client as an effetch `Fetch.Service`: the backend's base URL, its error body, and the plugins every call goes through. The `sessionBearer` plugin does what [`createAuthFetch`](/docs/client/requests) does: it sends the access token, and refreshes after a 401. Put `sessionBearer` last, so that a retry reads the current token. Give it the -client's `baseUrl`, since the token goes only to that origin. `Fetch.make` -then needs the `Auth` service, once: +client's `baseUrl`, since the token goes only to that origin. The client's +layer then needs the `Auth` service, once: ```ts title="src/api.ts" import * as Fetch from "@monarcode/effetch"; import { retry } from "@monarcode/effetch/plugins"; import { sessionBearer } from "@monarcode/session-kit/effetch"; -import * as Context from "effect/Context"; -import * as Effect from "effect/Effect"; import * as HttpClient from "effect/http/HttpClient"; import * as Layer from "effect/Layer"; import { API_BASE_URL, ApiError } from "./backend.js"; -const make = Fetch.make({ +export class ApiClient extends Fetch.Service()("ApiClient", { baseUrl: API_BASE_URL, defaultError: ApiError, plugins: [retry(), sessionBearer({ baseUrl: API_BASE_URL, optional: true })], -}).pipe( +}) {} + +/** The API client, over whichever `Auth` is provided. */ +export const ApiClientLive = ApiClient.layer.pipe( // Effect adds tracing headers to every request, which fail the preflight // of an API that doesn't allow them. - Effect.provideService(HttpClient.TracerPropagationEnabled, false), + Layer.provide(Layer.succeed(HttpClient.TracerPropagationEnabled)(false)), ); - -export class ApiClient extends Context.Service< - ApiClient, - Effect.Success ->()("ApiClient") {} - -/** The API client, over whichever `Auth` is provided. */ -export const ApiClientLive = Layer.effect(ApiClient, make); ``` Calls can fail with `AuthFailure`. When one client serves public and private @@ -252,6 +241,17 @@ endpoints, as this one does, give the plugin `optional: true`: a call made while signed out is then sent without a token, and a private endpoint answers with its own 401. A locked client still fails with `LOCKED`. +effetch's own `bearer` plugin can refresh after a 401 too, with its +`refresh` option, but it doesn't know the session. `sessionBearer` reads it +from Session kit. A call fails with `SESSION_CHANGED` if the account changes +while it runs, and a second 401 signs the user out. Its +[reference](/docs/reference/effetch#sessionbearer) lists the rest. + +After a refresh, `bearer` sends a request of any method again, a `POST` +included. `sessionBearer` sends only a `GET` or `HEAD` again, as +`createAuthFetch` does, and returns the 401 of any other request for you to +retry. + Effect code yields the client and calls its methods, such as `get` and `post`. The sign-in call skips the plugin with `sessionBearer: false`, because it's how the user gets a token. To read the current user and to sign @@ -376,16 +376,14 @@ export const logStatus = Auth.changes.pipe( effetch-query caches endpoints: a route and its schemas, defined with `Fetch.endpoint`, which it calls with the app's API client. Its queries and mutations run with the app's runtime, so components never run an Effect by -hand. Give it the client's `defaultError`, which an endpoint can't read from -the client: +hand. `fromClient` reads the client's `defaultError` from its class: ```ts title="src/query.ts" import { QueryClient } from "@monarcode/effetch-query"; -import { endpoints } from "@monarcode/effetch-query/effetch"; +import { fromClient } from "@monarcode/effetch-query/effetch"; import type * as ManagedRuntime from "effect/ManagedRuntime"; import { ApiClient } from "./api.js"; -import { ApiError } from "./backend.js"; import { appRuntime, type AppRuntime } from "./runtime.js"; declare module "@monarcode/effetch-query" { @@ -394,7 +392,7 @@ declare module "@monarcode/effetch-query" { } } -export const api = endpoints(ApiClient, { defaultError: ApiError }); +export const api = fromClient(ApiClient); export const makeQueryClient = () => QueryClient.make({ runtime: appRuntime }); ``` diff --git a/site/content/docs/(latest)/reference/compatibility.mdx b/site/content/docs/(latest)/reference/compatibility.mdx index 2118a4a..50943ae 100644 --- a/site/content/docs/(latest)/reference/compatibility.mdx +++ b/site/content/docs/(latest)/reference/compatibility.mdx @@ -19,7 +19,7 @@ import use: | `react-router` | `^7.0.0 \|\| ^8.0.0` | `/react-router`, `/react-router/server` | | `next` | `^16.0.0` | `/next` | | `effect` | `^4.1.0` | `/effect`, `/effetch` | -| `@monarcode/effetch` | `^0.1.0-rc.2` | `/effetch` | +| `@monarcode/effetch` | `^0.1.0-rc.3` | `/effetch` | | `expo-router` | `^5.0.2` through `^58` | `/expo` | | `expo-secure-store` | `^14.2.0` through `^58` | `/expo` | | `expo-file-system` | `^18.1.0` through `^58` | `/expo` | diff --git a/site/content/docs/(latest)/reference/effetch.mdx b/site/content/docs/(latest)/reference/effetch.mdx index 09b159a..3bdaea4 100644 --- a/site/content/docs/(latest)/reference/effetch.mdx +++ b/site/content/docs/(latest)/reference/effetch.mdx @@ -29,4 +29,4 @@ Options for [`sessionBearer`](#sessionbearer). ### SessionBearerPlugin -The plugin [`sessionBearer`](#sessionbearer) returns. Its calls can fail with `AuthFailure`, and `Fetch.make` needs the `Auth` service. +The plugin [`sessionBearer`](#sessionbearer) returns. Its calls can fail with `AuthFailure`, and a client made with it needs the `Auth` service. diff --git a/src/effetch/index.ts b/src/effetch/index.ts index 927d015..1e65511 100644 --- a/src/effetch/index.ts +++ b/src/effetch/index.ts @@ -59,7 +59,7 @@ export interface SessionBearerOptions { /** * The plugin {@link sessionBearer} returns. Its calls can fail with - * `AuthFailure`, and `Fetch.make` needs the `Auth` service. + * `AuthFailure`, and a client made with it needs the `Auth` service. * * A call can skip it with `plugins: { sessionBearer: false }`, or override * `optional` and `signOutOnRepeated401`. @@ -114,6 +114,11 @@ const refuseRedirects = ( * If the session changes during a call, it fails with `SESSION_CHANGED` * rather than return a response meant for another account. * + * Streams, such as `api.sse` and stream endpoints, work the same way up to + * the response's headers. A stream that's open when the user signs out or + * switches accounts keeps reading until it ends. Stop it yourself if it + * mustn't outlive the session. + * * The token never leaves your API. A request on another origin, or with a * username or password in its URL, dies with `INVALID_OPTIONS`. With * Effect's `FetchHttpClient`, a redirect fails as a `NetworkError` rather @@ -123,7 +128,7 @@ const refuseRedirects = ( * effetch's `bearer` does. * * Put it last in `plugins`, after `retry`, so each attempt reads the current - * token. `Fetch.make` then needs the `Auth` service, but calls don't. + * token. The client then needs the `Auth` service, but calls don't. * * On the server, make the effetch client per request, and provide it the * `Auth` layer for that request's session (`RequestAuth`). It reads the @@ -131,7 +136,7 @@ const refuseRedirects = ( * * @example * ```ts - * import type * as Effect from "effect/Effect"; + * import * as Effect from "effect/Effect"; * import * as Schema from "effect/Schema"; * import * as Fetch from "@monarcode/effetch"; * import { retry } from "@monarcode/effetch/plugins"; @@ -140,20 +145,15 @@ const refuseRedirects = ( * const baseUrl = "https://api.example.com"; * const Profile = Schema.Struct({ email: Schema.String }); * - * export const makeApi = Fetch.make({ + * export class Api extends Fetch.Service()("Api", { * baseUrl, * plugins: [retry(), sessionBearer({ baseUrl })], - * }); - * type Api = Effect.Success; + * }) {} * - * export const getProfile = (api: Api) => api.get("/me", { output: Profile }); - * - * // Signing in needs no token: skip the plugin. - * export const login = (api: Api, username: string, password: string) => - * api.post("/login", { - * body: { username, password }, - * plugins: { sessionBearer: false }, - * }); + * export const getProfile = Effect.gen(function* () { + * const api = yield* Api; + * return yield* api.get("/me", { output: Profile }); + * }); * ``` * * @see {@link SessionBearerOptions} for `optional` and `signOutOnRepeated401` diff --git a/tests/consumer.ts b/tests/consumer.ts index 8f38412..85b189e 100644 --- a/tests/consumer.ts +++ b/tests/consumer.ts @@ -548,7 +548,8 @@ void [ effectMisuse, ]; -// effetch: make needs Auth once; calls fail with AuthFailure and can override. +// effetch: the client needs Auth once; calls fail with AuthFailure and can +// override. const sessionPlugin: SessionBearerPlugin = sessionBearer({ baseUrl: "https://api.example.com", optional: undefined, @@ -565,6 +566,22 @@ const madeWithAuth: Effect.Effect< // @ts-expect-error make needs the Auth service. const madeWithoutAuth: Effect.Effect = makeSessionApi; +// A Fetch.Service client's layer needs Auth, as make does. +class SessionApi extends Fetch.Service()("SessionApi", { + baseUrl: "https://api.example.com", + plugins: [sessionPlugin], +}) {} +const serviceWithAuth: Layer.Layer< + SessionApi, + never, + HttpClient.HttpClient | Auth +> = SessionApi.layer; +// @ts-expect-error the client's layer needs the Auth service. +const serviceWithoutAuth: Layer.Layer< + SessionApi, + never, + HttpClient.HttpClient +> = SessionApi.layer; declare const sessionApi: Fetch.Client; const sessionCall: Effect.Effect = sessionApi.get("/me"); @@ -575,7 +592,13 @@ sessionApi.get("/me", { sessionApi.get("/feed", { plugins: { sessionBearer: { optional: true } } }); // @ts-expect-error Calls can override only optional and signOutOnRepeated401. sessionApi.get("/me", { plugins: { sessionBearer: { baseUrl: "x" } } }); -void [madeWithAuth, madeWithoutAuth, sessionCall]; +void [ + madeWithAuth, + madeWithoutAuth, + serviceWithAuth, + serviceWithoutAuth, + sessionCall, +]; // Server custody: the engine and the mirror client. const serverAuth = createServerAuth({ diff --git a/tests/effetch.test.ts b/tests/effetch.test.ts index f7e9f9e..a16280a 100644 --- a/tests/effetch.test.ts +++ b/tests/effetch.test.ts @@ -15,10 +15,12 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpClient from "effect/http/HttpClient"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import { cleanups, @@ -57,19 +59,13 @@ function serve(...statuses: number[]) { return sent; } -/** An effetch client with `sessionBearer` last, using `auth`. */ -const makeApi = ( +/** Runs `effect` with `auth` and the mocked `fetch`. */ +const runWith = ( auth: TestClient, - options: Partial = {}, + effect: Effect.Effect, ) => Effect.runPromise( - Fetch.make({ - baseUrl, - plugins: [ - retry({ times: 1, schedule: Schedule.spaced("0 millis") }), - sessionBearer({ baseUrl, ...options }), - ], - }).pipe( + effect.pipe( Effect.provide( Layer.merge(FetchHttpClient.layer, Auth.layer(auth as never)), ), @@ -80,6 +76,22 @@ const makeApi = ( ), ); +/** An effetch client with `sessionBearer` last, using `auth`. */ +const makeApi = ( + auth: TestClient, + options: Partial = {}, +) => + runWith( + auth, + Fetch.make({ + baseUrl, + plugins: [ + retry({ times: 1, schedule: Schedule.spaced("0 millis") }), + sessionBearer({ baseUrl, ...options }), + ], + }), + ); + /** The call's status: 200 when it succeeds, else its `HttpError`'s. */ const status = (call: Effect.Effect) => Effect.runPromise( @@ -395,11 +407,13 @@ test("on a request's server session, optional sends a signed-out call without a assert.equal(sent[0]?.authorization, null); }); -test("concurrent requests each build their API client over their own session", async () => { - const { serverAuth } = serverSide("effetch-server"); - const users = 20; - const jars = await Promise.all( - Array.from({ length: users }, async (_, index) => { +/** `count` cookie jars, each signed in with `token-`. */ +const signedInJars = ( + serverAuth: ReturnType["serverAuth"], + count: number, +) => + Promise.all( + Array.from({ length: count }, async (_, index) => { const cookies = new Map(); const jar: CookieJar = { writable: true, @@ -414,13 +428,43 @@ test("concurrent requests each build their API client over their own session", a return jar; }), ); - // Later requests answer first, so the calls interleave the same way each run. + +/** + * Answers each request with the token it was sent, recording its headers. + * Later tokens answer first, so calls interleave the same way each run. + */ +function serveWhoami(count: number) { + const sent: Headers[] = []; setGlobal("fetch", async (_url: URL | string, init: RequestInit = {}) => { - const token = new Headers(init.headers).get("authorization"); + const headers = new Headers(init.headers); + sent.push(headers); + const token = headers.get("authorization"); const index = Number(token?.split("-")[1]); - await new Promise((resolve) => setTimeout(resolve, users - index)); + await new Promise((resolve) => setTimeout(resolve, count - index)); return Response.json({ token }); }); + return sent; +} + +/** The server's runtime: what belongs to no user, with the mocked `fetch`. */ +const serverRuntime = () => { + const runtime = ManagedRuntime.make( + Layer.merge( + FetchHttpClient.layer, + Layer.succeed(FetchHttpClient.Fetch, (url, init) => + globalThis.fetch(url, init), + ), + ), + ); + cleanups.push(() => runtime.dispose()); + return runtime; +}; + +test("concurrent requests each build their API client over their own session", async () => { + const { serverAuth } = serverSide("effetch-server"); + const users = 20; + const jars = await signedInJars(serverAuth, users); + serveWhoami(users); const Whoami = Schema.Struct({ token: Schema.NullOr(Schema.String) }); const whoami = Fetch.endpoint("GET /whoami", { output: Whoami }); @@ -444,15 +488,7 @@ test("concurrent requests each build their API client over their own session", a // Built once: what belongs to no user. Per request: the session and the // client that uses it. - const runtime = ManagedRuntime.make( - Layer.merge( - FetchHttpClient.layer, - Layer.succeed(FetchHttpClient.Fetch, (url, init) => - globalThis.fetch(url, init), - ), - ), - ); - cleanups.push(() => runtime.dispose()); + const runtime = serverRuntime(); // One layer for every request, as an app declares it: each `Effect.provide` // must still build it again. const ApiClientLive = Layer.effect(ApiClient, make); @@ -485,3 +521,141 @@ test("concurrent requests each build their API client over their own session", a assert.equal(result.user, sessions[index]?.sessionId); }); }); + +const Tick = Schema.Struct({ n: Schema.Finite }); + +/** 401 for `access-1`, else an event stream of two ticks. */ +function serveEvents() { + const sent: (string | null)[] = []; + setGlobal("fetch", async (_url: URL | string, init: RequestInit = {}) => { + const authorization = new Headers(init.headers).get("authorization"); + sent.push(authorization); + if (authorization === "Bearer access-1") + return new Response(null, { status: 401 }); + return new Response('data: {"n":1}\n\ndata: {"n":2}\n\n', { + headers: { "content-type": "text/event-stream" }, + }); + }); + return sent; +} + +test("a stream gets a 401, renews the token and is sent again", async () => { + const auth = renewing(); + await auth.signIn(input()); + const sent = serveEvents(); + const api = await makeApi(auth); + const ticks = await Effect.runPromise( + api.sse("/events", { output: Tick }).pipe( + Stream.map((event) => event.data.n), + Stream.runCollect, + ), + ); + assert.deepEqual([...ticks], [1, 2]); + assert.deepEqual(sent, ["Bearer access-1", "Bearer access-2"]); +}); + +test("a stream endpoint of a Fetch.Service client is sent again after a 401", async () => { + const auth = renewing(); + await auth.signIn(input()); + const sent = serveEvents(); + class Api extends Fetch.Service()("Api", { + baseUrl, + plugins: [sessionBearer({ baseUrl })], + }) {} + const events = Fetch.endpoint("GET /events", { + stream: "sse", + output: Tick, + }); + class Feeds extends Fetch.Endpoints()("Feeds", Api, { events }) {} + const ticks = await runWith( + auth, + Effect.gen(function* () { + const feeds = yield* Feeds; + return yield* feeds.events().pipe( + Stream.map((event) => event.data.n), + Stream.runCollect, + ); + }).pipe(Effect.provide(Feeds.layer.pipe(Layer.provideMerge(Api.layer)))), + ); + assert.deepEqual([...ticks], [1, 2]); + assert.deepEqual(sent, ["Bearer access-1", "Bearer access-2"]); +}); + +test("a stream open when the user signs out keeps reading until it ends", async () => { + const auth = client(); + await auth.signIn(input()); + const encoder = new TextEncoder(); + let finish = () => {}; + setGlobal( + "fetch", + async () => + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode('data: {"n":1}\n\n')); + finish = () => { + controller.enqueue(encoder.encode('data: {"n":2}\n\n')); + controller.close(); + }; + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ), + ); + const api = await makeApi(auth); + const ticks = await Effect.runPromise( + api.sse("/events", { output: Tick }).pipe( + Stream.map((event) => event.data.n), + // Signs out after the first event, then sends the second. + Stream.tap((n) => + n === 1 + ? Effect.promise(async () => { + await auth.signOut(); + finish(); + }) + : Effect.void, + ), + Stream.runCollect, + ), + ); + assert.equal(auth.state.get().status, "unauthenticated"); + assert.deepEqual([...ticks], [1, 2]); +}); + +test("a Fetch.Service client built per request sends each request's token", async () => { + const { serverAuth } = serverSide("effetch-service"); + const users = 10; + const jars = await signedInJars(serverAuth, users); + const headers = serveWhoami(users); + + class Api extends Fetch.Service()("Api", { + baseUrl, + plugins: [sessionBearer({ baseUrl })], + }) {} + // As the Effect guide makes it: without tracing headers. + const ApiLive = Api.layer.pipe( + Layer.provide(Layer.succeed(HttpClient.TracerPropagationEnabled)(false)), + ); + const runtime = serverRuntime(); + const requestLayer = (jar: CookieJar) => + ApiLive.pipe(Layer.provideMerge(Auth.layer(serverAuth.forRequest(jar)))); + const Whoami = Schema.Struct({ token: Schema.NullOr(Schema.String) }); + const program = Effect.gen(function* () { + const api = yield* Api; + return (yield* api.get("/whoami", { output: Whoami })).token; + }); + + const sent = await Promise.all( + jars.map((jar) => + runtime.runPromise(Effect.provide(program, requestLayer(jar))), + ), + ); + assert.deepEqual( + sent, + jars.map((_, index) => `Bearer token-${index}`), + ); + for (const sent of headers) { + assert.equal(sent.get("traceparent"), null); + assert.equal(sent.get("b3"), null); + } +});