From 82dcdeaae99dac89ec4b5be54ab3890a07f83495 Mon Sep 17 00:00:00 2001 From: monarcode Date: Mon, 23 Nov 2026 10:30:39 +0100 Subject: [PATCH] docs(site): add type hovers and the generated API reference --- .github/workflows/ci.yml | 7 +- AGENTS.md | 15 +- CHANGELOG.md | 6 + README.md | 35 +- package.json | 3 +- pnpm-lock.yaml | 360 +++++++++- scripts/check-docs.mjs | 35 + scripts/reference-docs.mjs | 475 ++++++++++++ .../docs/(latest)/reference/compatibility.mdx | 63 ++ .../docs/(latest)/reference/fetch-test.mdx | 169 +++++ .../content/docs/(latest)/reference/fetch.mdx | 677 ++++++++++++++++++ .../content/docs/(latest)/reference/index.mdx | 109 +-- .../content/docs/(latest)/reference/meta.json | 9 +- .../docs/(latest)/reference/plugins.mdx | 235 ++++++ .../docs/(latest)/testing/requests.mdx | 3 +- site/package.json | 4 + site/src/components/mdx.tsx | 12 + site/src/lib/mdx-options.ts | 184 +++++ site/src/styles/app.css | 1 + site/tsconfig.json | 3 +- site/vite.config.ts | 11 +- 21 files changed, 2285 insertions(+), 131 deletions(-) create mode 100644 scripts/reference-docs.mjs create mode 100644 site/content/docs/(latest)/reference/compatibility.mdx create mode 100644 site/content/docs/(latest)/reference/fetch-test.mdx create mode 100644 site/content/docs/(latest)/reference/fetch.mdx create mode 100644 site/content/docs/(latest)/reference/plugins.mdx create mode 100644 site/src/lib/mdx-options.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f5af5f0..764da51 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,7 +90,8 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - # Prerenders every page, so it catches MDX syntax errors and broken - # pages, which `check` doesn't build. - - name: Build the docs site + # Builds the package, which the hovers and type tables read, then + # prerenders every page. That catches MDX syntax errors, broken pages + # and type errors in examples, which `check` doesn't build. + - name: Build the package and the docs site run: pnpm run build:site diff --git a/AGENTS.md b/AGENTS.md index 7fa5d19..2a601e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,9 +58,20 @@ to static files. It's a package in the pnpm workspace and isn't published. to them, so when a feature changes, update its page, and the README only if its quick start or links change. Link between pages with root-relative paths (`/docs/errors/status-errors`). +- Every `ts` block on a page gets Twoslash type hovers, read from the + built package in `dist`, and a type error in one fails the site's build. + `no-twoslash` in a block's meta turns its hovers off, but the docs check + still compiles it, so use it only for an example whose hovers mislead. +- The API reference pages (`reference/fetch.mdx`, `plugins.mdx` and + `fetch-test.mdx`) are generated from the JSDoc by + `scripts/reference-docs.mjs`. Don't edit them: after changing a public + export or its docs, run `pnpm run docs:reference`. A new export needs a + group in that script, and the docs check fails until it has one and the + pages match. - `pnpm run check` doesn't build the site. After changing `site/`, run - `pnpm run build:site`, which prerenders the site into `site/dist/client`. - `pnpm --dir site run dev` serves it while you write. + `pnpm run build:site`, which builds the package, then prerenders the site + into `site/dist/client`. `pnpm --dir site run dev` serves it while you + write, once `pnpm run build` has built `dist`. ## Before declaring any work done diff --git a/CHANGELOG.md b/CHANGELOG.md index 13292b4..e67e13d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ All notable changes to `@monarcode/effetch`, newest first. - Documentation site at [effetch.pages.dev/docs](https://effetch.pages.dev/docs), with a page for each guide that was in the README, and search. The package's `homepage` points to it. +- The site's examples show each name's type and docs on hover, and its + [API reference](https://effetch.pages.dev/docs/reference) lists every + export of `Fetch`, the plugins and `FetchTest`, with tables of the option + types. A [Compatibility](https://effetch.pages.dev/docs/reference/compatibility) + page lists the supported Effect versions, runtimes and TypeScript + settings. ### Changed diff --git a/README.md b/README.md index 8687d13..29a005e 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ export const getTodo = (id: number) => ## Documentation -The guides are at +The guides and the API reference are at **[effetch.pages.dev/docs](https://effetch.pages.dev/docs)**. ## Install @@ -151,7 +151,9 @@ Calling an API from a web page on another origin? Read - [Platform notes](https://effetch.pages.dev/docs/platforms): browsers and React Native. - [Coming from axios or ky](https://effetch.pages.dev/docs/coming-from-axios-or-ky). - [Upgrade from 0.1.0-rc.3](https://effetch.pages.dev/docs/upgrading). -- [Reference](https://effetch.pages.dev/docs/reference): the entry points, and +- [Reference](https://effetch.pages.dev/docs/reference): every export of + `Fetch`, the plugins and `FetchTest`, with + [Compatibility](https://effetch.pages.dev/docs/reference/compatibility) and [Limitations](https://effetch.pages.dev/docs/reference/limitations). ## Examples @@ -190,19 +192,22 @@ pnpm install pnpm run check ``` -| Script | What it does | -| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `pnpm run build` | Builds `dist/` (ESM and `.d.ts`) with tsdown. | -| `pnpm test` | Runs the tests and type tests with Vitest. | -| `pnpm run typecheck` | Typechecks `src`, `test` and `examples`. | -| `pnpm run lint` | Lints with oxlint (`lint:effect` runs the Effect language service). | -| `pnpm run format` | Formats with oxfmt (`format:check` only checks). | -| `pnpm run check:docs` | Checks every public export has a description, `@example` and `@since`, and compiles every example in the JSDoc, this README and the docs site's pages. | -| `pnpm run smoke` | Packs the package, installs it in a fresh project, typechecks and runs a consumer, and checks go-to-definition, hovers and completions. | -| `pnpm run check` | All of the above, plus publint and attw. CI runs it on every push to `main` and every pull request. | -| `pnpm run build:site` | Prerenders the docs site in `site/` to `site/dist/client`. `check` doesn't build the site; CI does. | - -To work on the docs site, run `pnpm --dir site run dev`. +| Script | What it does | +| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `pnpm run build` | Builds `dist/` (ESM and `.d.ts`) with tsdown. | +| `pnpm test` | Runs the tests and type tests with Vitest. | +| `pnpm run typecheck` | Typechecks `src`, `test` and `examples`. | +| `pnpm run lint` | Lints with oxlint (`lint:effect` runs the Effect language service). | +| `pnpm run format` | Formats with oxfmt (`format:check` only checks). | +| `pnpm run check:docs` | Checks every public export has a description, `@example` and `@since`, compiles every example in the JSDoc, this README and the docs site's pages, and checks the site's API reference matches the JSDoc. | +| `pnpm run smoke` | Packs the package, installs it in a fresh project, typechecks and runs a consumer, and checks go-to-definition, hovers and completions. | +| `pnpm run check` | All of the above, plus publint and attw. CI runs it on every push to `main` and every pull request. | +| `pnpm run build:site` | Builds the package, then prerenders the docs site in `site/` to `site/dist/client`, failing on a type error in an example. `check` doesn't build the site; CI does. | +| `pnpm run docs:reference` | Writes the site's API reference pages from the JSDoc. Run it after changing a public export or its docs. | + +To work on the docs site, run `pnpm run build`, then `pnpm --dir site run dev`. +The site's type hovers and tables read the built package, so build again +after changing `src/`. The pre-commit hook runs `lint` and `format:check`. diff --git a/package.json b/package.json index dd6da78..7af2e14 100644 --- a/package.json +++ b/package.json @@ -70,10 +70,11 @@ "format": "oxfmt --write .", "format:check": "oxfmt --check .", "build": "tsdown", - "build:site": "pnpm --dir site run build", + "build:site": "pnpm run build && pnpm --dir site run build", "dev": "tsdown --watch", "typecheck": "tsc --noEmit", "check:docs": "node scripts/check-docs.mjs", + "docs:reference": "node scripts/reference-docs.mjs", "test": "vitest run", "test:watch": "vitest", "check:package": "publint --strict && attw --pack . --profile esm-only", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ff6ddd3..01c027c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -50,6 +50,9 @@ importers: site: dependencies: + '@monarcode/effetch': + specifier: workspace:* + version: link:.. '@tanstack/react-router': specifier: 1.170.46 version: 1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -59,15 +62,24 @@ importers: '@tanstack/start-static-server-functions': specifier: 1.167.44 version: 1.167.44(@tanstack/react-start@1.169.5(@types/react@19.3.0)(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.2.19)(vite@8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))) + '@types/hast': + specifier: 3.0.4 + version: 3.0.4 fumadocs-core: specifier: 16.19.0 - version: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) + version: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) fumadocs-mdx: specifier: 15.6.0 - version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react@19.3.1)(rolldown@1.2.19)(vite@8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) + version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react@19.3.1)(rolldown@1.2.19)(vite@8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) + fumadocs-twoslash: + specifier: 4.0.4 + version: 4.0.4(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5))(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(shiki@4.6.0) + fumadocs-typescript: + specifier: 5.6.0 + version: 5.6.0(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5))(@types/estree@1.0.9)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1) fumadocs-ui: specifier: npm:@fumadocs/base-ui@16.19.0 - version: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)' + version: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)' lucide-react: specifier: 1.72.0 version: 1.72.0(@types/react@19.3.0)(react@19.3.1) @@ -1223,6 +1235,9 @@ packages: '@types/estree@1.0.9': resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@types/hast@3.0.4': + resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==} + '@types/hast@3.0.5': resolution: {integrity: sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==} @@ -1252,6 +1267,132 @@ packages: '@types/unist@3.0.3': resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} + '@typescript/typescript-aix-ppc64@7.1.0-beta': + resolution: {integrity: sha512-DXDG+jIWxBHGdoO70tcHON33rCnSzsEZj9P13oyf/r/KEGIo6awsdSNVNjAw0uMwEpqRu75IrgCcW58YcVkZHg==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-android-arm64@7.1.0-beta': + resolution: {integrity: sha512-UZx6PxoQavuvaVTrSf3aw0Oy/J/uJpRylipA0kzc038jMvZXh0UtE8vnQp20FqtdgD5bhXZ0aJrRJyoTSUO58Q==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [android] + + '@typescript/typescript-darwin-arm64@7.1.0-beta': + resolution: {integrity: sha512-q7mxblcyX0E7hXsY4k+Q6KWKK5mGmfVq+BDesdTgRVgjodk27aIxER77Zyj9+TgSTlCje8F7+JM6f6hl2BuNdw==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.1.0-beta': + resolution: {integrity: sha512-D5EYqG5Wm/guw9+0j8+Mn1Jbr/gfS/VtFTuoH8PJtFbcqeDaQGMulc7SW8q51QG6Y3wGOGX3nbsTOw6fIKWWAA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.1.0-beta': + resolution: {integrity: sha512-9A0XX0tcnH9qPdolSKKzSjTb93dlB0UEcAJbHYEsrFX2fkFNSum9+dvkQQJ9vLc+7vxHetDPujq9Qe6wx+Xhow==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.1.0-beta': + resolution: {integrity: sha512-EDf/dBHfY0TxX3NmUTek0hbffeyZlh3+ls6WQW3ICB8vYxwYLFnzg7wkgEUvl9eRlpiJ/nmc2S8arPMzINJ7rg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.1.0-beta': + resolution: {integrity: sha512-hNqQBgQ5b5oGqN76QqbAU6CwYhJZ6iOcWc2kPTUs2OentgpxZktETziH6KIyRFJPaiBncognwn2ZLu3DNhHiWw==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.1.0-beta': + resolution: {integrity: sha512-AvN9HmzOQh46G4312ooSgMHhbB7DtnLwg8D9mo324X49B7weMwtJrBG1MxT9IyI8kzDd7YRtW+1hWGun7WG7Qw==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.1.0-beta': + resolution: {integrity: sha512-xbUustlBrFflt2pNEyG5ye+d4WGPc/rfr2xK29MXeobPSw297JqwuKRrvbKM5o3fE/eUM/c+urVm6jQ3IaMVTw==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.1.0-beta': + resolution: {integrity: sha512-fS4/G7/0bXZ3NSq3nBMAXyg65I3tO4S7j08VNQ2g1aNC/qq79gE7Qne1BNjVsjMFfHBVBFjQYoTQCjmVU2iFlg==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.1.0-beta': + resolution: {integrity: sha512-0upCCxYPX8X6gOwkvfv+Ee7/ufyy7k97mTrGE0e5BxLlnUEa+w+rtgnv2dsKcxFdwdeZYVlZKCqgN/xCBV08+A==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.1.0-beta': + resolution: {integrity: sha512-0jKU9YRgOPRgiy5V/UWv37kB53PaTpIbwGCbbOMUPPAkrjVRNOIAJaz7Wa7s3H7mdDebX1LopUEPEJR+7Xa7zg==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.1.0-beta': + resolution: {integrity: sha512-j+d04s2kxaPQh6DLPb01sknAQfzsrdSZy15jBRHyLEZoaaQ19dVjbFRlkNVvYwUG7ZdP8+y5b/7RmPxdtHUKdQ==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.1.0-beta': + resolution: {integrity: sha512-kcD51ihf+pnI5KT4uQQYG04OpwznaZYBlIQhDhl8fflFd27NktxXsUeguxZyvUMyWfum7IF2bBS6Jv7ox0AgFQ==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.1.0-beta': + resolution: {integrity: sha512-8W85YyoGK+rgGoSU9jJQUpELbrKcZcbdJk2jPNQ6UKDKI7ryPlPFTrV2jCE5RQuv4Tt96hMDTc33s4YfRrLFBA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.1.0-beta': + resolution: {integrity: sha512-iGsTE0ve2PG0AcyZinwAR0LnGEZhu/y4dceS0hZsYCaKdYETvQtvtlNWlmYKempsBr6C7Il7dMXHVk+VFm9u0g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.1.0-beta': + resolution: {integrity: sha512-Z2FERdHB9fAKI+KGqdWn04O7uNlnB+VYiEm6INE1aZuzzLNd3KBqQ6IpKUJF2ny4GigGU6nVu75XD9tAUODPng==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.1.0-beta': + resolution: {integrity: sha512-NVG3qeyCq/rJEOhaRjR3LsWgjrjo5vJW25omVLeHAVnpKIG4pE4cenwwKGR06DiJ1s0QTOymcJeKXMEpsiNBVg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.1.0-beta': + resolution: {integrity: sha512-ovAdoWXEn2B5/fyWG69pLU3FWmQwPWOjQV5TFbcxtpnOv+R3g8ySGHl1NYRq7Lb/GYdFDvaGcZ+SiU7iKuiMsA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.1.0-beta': + resolution: {integrity: sha512-lJbo71IEOfL7ZZIZnArRaOLqjn9BAfoSzyUQn0aSjfSpDZL4ru0afUsdBfo6PQEjD6ssdmi0n/RwaPADX6bsvQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.1.0-beta': + resolution: {integrity: sha512-UKcHvbybY2tDTvFW2b1vwiAvDlIRooo69lh8CXWVhOQejcvpM5+IgbiFW9EIwR5Wi5X/v+BdN7gdWbigBuJ3rw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + '@ungap/structured-clone@1.4.0': resolution: {integrity: sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==} @@ -1837,6 +1978,42 @@ packages: vite: optional: true + fumadocs-twoslash@4.0.4: + resolution: {integrity: sha512-owFAAcETiGMWnM0FbvHG3hjaMScmvxcQmc8F4bhGLg9O6IFeJV+uXiaaLFE6aeIt7NPVZYZUfiHcbgp3mFWytw==} + peerDependencies: + '@types/react': '*' + fumadocs-core: ^16.15.7 + fumadocs-ui: ^16.7.16 + react: ^19.2.0 + react-dom: ^19.2.0 + shiki: ^4.4.3 + peerDependenciesMeta: + '@types/react': + optional: true + + fumadocs-typescript@5.6.0: + resolution: {integrity: sha512-ZJLYaK8zxsQggj1MTRhtFZxmPSUAhqZrhjo+zYupNcWDW+CfF2YhyYx42a/FWwGxErX0ZzXNLlQvBqkdWGHFlA==} + peerDependencies: + '@types/estree': '*' + '@types/hast': '*' + '@types/mdast': '*' + '@types/react': '*' + fumadocs-core: ^16.17.8 + fumadocs-ui: ^16.7.0 + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + '@types/estree': + optional: true + '@types/hast': + optional: true + '@types/mdast': + optional: true + '@types/react': + optional: true + fumadocs-ui: + optional: true + gensync@1.0.0-beta.2: resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} engines: {node: '>=6.9.0'} @@ -2667,6 +2844,11 @@ packages: engines: {node: '>=14.17'} hasBin: true + typescript@7.1.0-beta: + resolution: {integrity: sha512-cjWjZAJDsmZzsNC5GwHNlW0YPM65jZa5oR0KyQcYX3KSVIfTvtBq//vewISyatKk4OLi5grZjHhIVE9fdrw1UQ==} + engines: {node: '>=16.20.0'} + hasBin: true + ufo@1.6.4: resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==} @@ -3236,14 +3418,14 @@ snapshots: optionalDependencies: '@types/react': 19.3.0 - '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)': + '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)': dependencies: '@base-ui/react': 1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@fuma-translate/react': 1.0.2(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@fumadocs/tailwind': 0.1.5(tailwindcss@4.3.5) class-variance-authority: 0.7.1 cn: 0.5.2 - fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) + fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) lucide-react: 1.72.0(@types/react@19.3.0)(react@19.3.1) motion: 14.14.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1) next-themes: 0.4.6(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -3294,7 +3476,7 @@ snapshots: dependencies: '@types/estree': 1.0.9 '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 '@types/mdx': 2.0.14 acorn: 8.19.0 collapse-white-space: 2.1.0 @@ -3929,6 +4111,10 @@ snapshots: '@types/estree@1.0.9': {} + '@types/hast@3.0.4': + dependencies: + '@types/unist': 3.0.3 + '@types/hast@3.0.5': dependencies: '@types/unist': 3.0.3 @@ -3957,6 +4143,69 @@ snapshots: '@types/unist@3.0.3': {} + '@typescript/typescript-aix-ppc64@7.1.0-beta': + optional: true + + '@typescript/typescript-android-arm64@7.1.0-beta': + optional: true + + '@typescript/typescript-darwin-arm64@7.1.0-beta': + optional: true + + '@typescript/typescript-darwin-x64@7.1.0-beta': + optional: true + + '@typescript/typescript-freebsd-arm64@7.1.0-beta': + optional: true + + '@typescript/typescript-freebsd-x64@7.1.0-beta': + optional: true + + '@typescript/typescript-linux-arm64@7.1.0-beta': + optional: true + + '@typescript/typescript-linux-arm@7.1.0-beta': + optional: true + + '@typescript/typescript-linux-loong64@7.1.0-beta': + optional: true + + '@typescript/typescript-linux-mips64el@7.1.0-beta': + optional: true + + '@typescript/typescript-linux-ppc64@7.1.0-beta': + optional: true + + '@typescript/typescript-linux-riscv64@7.1.0-beta': + optional: true + + '@typescript/typescript-linux-s390x@7.1.0-beta': + optional: true + + '@typescript/typescript-linux-x64@7.1.0-beta': + optional: true + + '@typescript/typescript-netbsd-arm64@7.1.0-beta': + optional: true + + '@typescript/typescript-netbsd-x64@7.1.0-beta': + optional: true + + '@typescript/typescript-openbsd-arm64@7.1.0-beta': + optional: true + + '@typescript/typescript-openbsd-x64@7.1.0-beta': + optional: true + + '@typescript/typescript-sunos-x64@7.1.0-beta': + optional: true + + '@typescript/typescript-win32-arm64@7.1.0-beta': + optional: true + + '@typescript/typescript-win32-x64@7.1.0-beta': + optional: true + '@ungap/structured-clone@1.4.0': {} '@vitejs/plugin-react@6.3.0(vite@8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))': @@ -4337,7 +4586,7 @@ snapshots: fsevents@2.3.3: optional: true - fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7): + fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7): dependencies: '@fumari/image-size': 0.1.1 acorn: 8.19.0 @@ -4364,7 +4613,7 @@ snapshots: '@mdx-js/mdx': 3.1.1 '@tanstack/react-router': 1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 '@types/mdast': 4.0.4 '@types/react': 19.3.0 lucide-react: 1.72.0(@types/react@19.3.0)(react@19.3.1) @@ -4374,7 +4623,7 @@ snapshots: transitivePeerDependencies: - supports-color - fumadocs-mdx@15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react@19.3.1)(rolldown@1.2.19)(vite@8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)): + fumadocs-mdx@15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react@19.3.1)(rolldown@1.2.19)(vite@8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)): dependencies: '@mdx-js/mdx': 3.1.1 '@standard-schema/spec': 1.1.0 @@ -4383,7 +4632,7 @@ snapshots: chokidar: 6.0.0 esbuild: 0.28.2 estree-util-value-to-estree: 3.5.0 - fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) + fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) github-slugger: 2.0.0 magic-string: 1.4.5 mdast-util-from-markdown: 2.1.0 @@ -4409,6 +4658,47 @@ snapshots: transitivePeerDependencies: - supports-color + fumadocs-twoslash@4.0.4(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5))(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(shiki@4.6.0): + dependencies: + '@base-ui/react': 1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@types/hast': 3.0.5 + cn: 0.5.2 + fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) + fumadocs-ui: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)' + mdast-util-from-markdown: 2.1.0 + mdast-util-to-hast: 13.2.2 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + shiki: 4.6.0 + typescript: 7.1.0-beta + optionalDependencies: + '@types/react': 19.3.0 + transitivePeerDependencies: + - '@date-fns/tz' + - date-fns + - supports-color + + fumadocs-typescript@5.6.0(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5))(@types/estree@1.0.9)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1): + dependencies: + estree-util-value-to-estree: 3.5.0 + fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) + hast-util-to-estree: 3.1.3 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + remark: 15.0.1 + remark-rehype: 11.1.2 + shiki: 4.6.0 + typescript: 7.1.0-beta + unified: 11.0.5 + optionalDependencies: + '@types/estree': 1.0.9 + '@types/hast': 3.0.4 + '@types/mdast': 4.0.4 + '@types/react': 19.3.0 + fumadocs-ui: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)' + transitivePeerDependencies: + - supports-color + gensync@1.0.0-beta.2: {} get-caller-file@2.0.5: {} @@ -4427,19 +4717,19 @@ snapshots: hast-util-from-dom@5.0.1: dependencies: - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 hastscript: 9.0.3 web-namespaces: 2.0.1 hast-util-parse-selector@4.0.0: dependencies: - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 hast-util-to-estree@3.1.3: dependencies: '@types/estree': 1.0.9 '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 comma-separated-tokens: 2.0.3 devlop: 1.1.0 estree-util-attach-comments: 3.0.0 @@ -4458,7 +4748,7 @@ snapshots: hast-util-to-html@9.0.7: dependencies: - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 '@types/unist': 3.0.3 ccount: 2.0.1 comma-separated-tokens: 2.0.3 @@ -4473,7 +4763,7 @@ snapshots: hast-util-to-jsx-runtime@2.3.7: dependencies: '@types/estree': 1.0.9 - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 '@types/unist': 3.0.3 comma-separated-tokens: 2.0.3 devlop: 1.1.0 @@ -4492,11 +4782,11 @@ snapshots: hast-util-whitespace@3.0.0: dependencies: - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 hastscript@9.0.3: dependencies: - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 comma-separated-tokens: 2.0.3 hast-util-parse-selector: 4.0.0 property-information: 7.2.0 @@ -4723,7 +5013,7 @@ snapshots: mdast-util-mdx-expression@2.0.1: dependencies: '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 '@types/mdast': 4.0.4 devlop: 1.1.0 mdast-util-from-markdown: 2.1.0 @@ -4734,7 +5024,7 @@ snapshots: mdast-util-mdx-jsx@3.2.2: dependencies: '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 '@types/mdast': 4.0.4 '@types/unist': 3.0.3 ccount: 2.0.1 @@ -4761,7 +5051,7 @@ snapshots: mdast-util-mdxjs-esm@2.0.1: dependencies: '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 '@types/mdast': 4.0.4 devlop: 1.1.0 mdast-util-from-markdown: 2.1.0 @@ -4776,7 +5066,7 @@ snapshots: mdast-util-to-hast@13.2.2: dependencies: - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 '@types/mdast': 4.0.4 '@ungap/structured-clone': 1.4.0 devlop: 1.1.0 @@ -5299,7 +5589,7 @@ snapshots: rehype-recma@1.0.0: dependencies: '@types/estree': 1.0.9 - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 hast-util-to-estree: 3.1.3 transitivePeerDependencies: - supports-color @@ -5333,7 +5623,7 @@ snapshots: remark-rehype@11.1.2: dependencies: - '@types/hast': 3.0.5 + '@types/hast': 3.0.4 '@types/mdast': 4.0.4 mdast-util-to-hast: 13.2.2 unified: 11.0.5 @@ -5560,6 +5850,30 @@ snapshots: typescript@6.0.3: {} + typescript@7.1.0-beta: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.1.0-beta + '@typescript/typescript-android-arm64': 7.1.0-beta + '@typescript/typescript-darwin-arm64': 7.1.0-beta + '@typescript/typescript-darwin-x64': 7.1.0-beta + '@typescript/typescript-freebsd-arm64': 7.1.0-beta + '@typescript/typescript-freebsd-x64': 7.1.0-beta + '@typescript/typescript-linux-arm': 7.1.0-beta + '@typescript/typescript-linux-arm64': 7.1.0-beta + '@typescript/typescript-linux-loong64': 7.1.0-beta + '@typescript/typescript-linux-mips64el': 7.1.0-beta + '@typescript/typescript-linux-ppc64': 7.1.0-beta + '@typescript/typescript-linux-riscv64': 7.1.0-beta + '@typescript/typescript-linux-s390x': 7.1.0-beta + '@typescript/typescript-linux-x64': 7.1.0-beta + '@typescript/typescript-netbsd-arm64': 7.1.0-beta + '@typescript/typescript-netbsd-x64': 7.1.0-beta + '@typescript/typescript-openbsd-arm64': 7.1.0-beta + '@typescript/typescript-openbsd-x64': 7.1.0-beta + '@typescript/typescript-sunos-x64': 7.1.0-beta + '@typescript/typescript-win32-arm64': 7.1.0-beta + '@typescript/typescript-win32-x64': 7.1.0-beta + ufo@1.6.4: {} unconfig-core@7.5.0: diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs index 326256b..a4abde2 100644 --- a/scripts/check-docs.mjs +++ b/scripts/check-docs.mjs @@ -4,6 +4,8 @@ import path from "node:path"; import ts from "typescript"; +import { renderReference } from "./reference-docs.mjs"; + const root = path.resolve(import.meta.dirname, ".."); const entries = [ "src/index.ts", @@ -31,6 +33,10 @@ const parsed = ts.getParsedCommandLineOfConfigFile( const options = { ...parsed.options, noEmit: true, plugins: [] }; const problems = []; let exportCount = 0; +// Every export the walk below checks, by the name readers use, such as +// `Fetch.make`, `bearer` or `Fetch.HttpError.With`. The reference must list +// each one. +const documented = new Set(); if (!existsSync(sitePages)) { problems.push( @@ -143,6 +149,7 @@ const checkDeclaration = (name, node, alias) => { checkNamespace(name, node); return; } + documented.add(name); if (isImplementation(node)) { return; } @@ -258,6 +265,34 @@ const codeBlocks = (file, lines, firstLine) => { return blocks; }; +// The reference pages are what `scripts/reference-docs.mjs` renders from the +// JSDoc, so they can't fall behind it, and they list every export. +let reference = { files: new Map(), names: [...documented] }; +try { + reference = renderReference(program); +} catch (error) { + problems.push(error instanceof Error ? error.message : String(error)); +} +for (const [file, body] of reference.files) { + const onDisk = path.join(root, file); + if (!existsSync(onDisk) || readFileSync(onDisk, "utf8") !== body) { + problems.push( + `${file}: out of date with the JSDoc. Run \`pnpm run docs:reference\`.`, + ); + } +} +const listed = new Set(reference.names); +for (const name of documented) { + if (!listed.has(name)) { + problems.push(`${name} is missing from the API reference`); + } +} +for (const name of listed) { + if (!documented.has(name)) { + problems.push(`the API reference lists ${name}, which isn't exported`); + } +} + const examples = []; const publicSources = program .getSourceFiles() diff --git a/scripts/reference-docs.mjs b/scripts/reference-docs.mjs new file mode 100644 index 0000000..dadd4f9 --- /dev/null +++ b/scripts/reference-docs.mjs @@ -0,0 +1,475 @@ +#!/usr/bin/env node +// Writes the docs site's API reference from the JSDoc: a page per namespace +// or entry point, listing every export with the first paragraph of its docs, +// grouped by the guide that covers it. +// +// pnpm run docs:reference +// +// `check-docs` renders the same pages and fails when the files differ, so the +// reference can't fall behind the code. Don't edit the pages by hand. + +import { execFileSync } from "node:child_process"; +import { realpathSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import ts from "typescript"; + +const root = path.resolve(import.meta.dirname, ".."); +const OUT = "site/content/docs/(latest)/reference"; +/** Where the type tables read the declarations: the site's workspace link. */ +const DIST = "node_modules/@monarcode/effetch/dist"; + +/** + * Each page: the module whose exports it lists, the name readers reach them + * through, and its groups. An export's group comes from `names`, then from + * the file that declares it; one that has neither fails the render, so a new + * export can't be left off. + */ +const PAGES = [ + { + slug: "fetch", + title: "Fetch", + description: + "Every member of the Fetch namespace: clients, calls, errors, plugins, endpoints, streams and pages.", + module: "src/Fetch.ts", + qualifier: "Fetch", + importLine: 'import { Fetch } from "@monarcode/effetch";', + intro: "`@monarcode/effetch` exports one name, the `Fetch` namespace. Its members, grouped by the guide that covers them:", + groups: [ + ["Clients", ["Declare a client", "/docs/clients"]], + ["Calls", ["Methods", "/docs/calls"]], + ["Responses", ["Read the response", "/docs/calls/responses"]], + ["Uploads", ["Upload files", "/docs/calls/uploads"]], + ["Errors", ["Call errors", "/docs/errors"]], + ["Plugins", ["Write a plugin", "/docs/plugins/writing"]], + [ + "Endpoints and services", + ["Endpoints or methods", "/docs/endpoints"], + ], + ["Streaming", ["Streaming responses", "/docs/streaming"]], + ["Pagination", ["Pagination", "/docs/pagination"]], + ], + files: { + "src/Client.ts": "Clients", + "src/Service.ts": "Clients", + "src/Options.ts": "Calls", + "src/Path.ts": "Calls", + "src/Output.ts": "Responses", + "src/Input.ts": "Uploads", + "src/Errors.ts": "Errors", + "src/Status.ts": "Errors", + "src/Plugin.ts": "Plugins", + "src/Endpoint.ts": "Endpoints and services", + "src/Endpoints.ts": "Endpoints and services", + "src/Streams.ts": "Streaming", + "src/Paginate.ts": "Pagination", + }, + names: { + CallError: "Errors", + QuerySchema: "Endpoints and services", + ResponseMode: "Responses", + StatusError: "Errors", + StatusErrorMap: "Errors", + StatusErrorSchema: "Errors", + StatusErrorServices: "Errors", + Success: "Responses", + }, + }, + { + slug: "plugins", + title: "Plugins", + description: + "Every export of @monarcode/effetch/plugins: the built-in plugins and their options.", + module: "src/plugins/index.ts", + intro: "`@monarcode/effetch/plugins` exports the built-in plugins, their options and the types they return:", + groups: [ + ["Bearer tokens", ["Refresh a token", "/docs/plugins/token-refresh"]], + [ + "Retries", + ["Retry-After and a time limit", "/docs/plugins/retry-after"], + ], + [ + "Time limits", + ["Choose a time limit", "/docs/plugins#choose-a-time-limit"], + ], + [ + "Logging", + ["Built-in plugins", "/docs/plugins#what-each-plugin-does"], + ], + [ + "Console logging", + ["Log to the console", "/docs/plugins/console-logging"], + ], + ], + files: { + "src/plugins/bearer.ts": "Bearer tokens", + "src/plugins/retry.ts": "Retries", + "src/plugins/timeout.ts": "Time limits", + "src/plugins/logger.ts": "Logging", + "src/plugins/consoleLogger.ts": "Console logging", + }, + names: {}, + }, + { + slug: "fetch-test", + title: "FetchTest", + description: + "Every member of the FetchTest namespace: the fake backend for tests and the requests it records.", + module: "src/test/FetchTest.ts", + qualifier: "FetchTest", + importLine: 'import { FetchTest } from "@monarcode/effetch/test";', + intro: "`@monarcode/effetch/test` exports one name, the `FetchTest` namespace. Its members:", + groups: [ + ["Fake backend", ["Test with a fake backend", "/docs/testing"]], + [ + "Recorded requests", + ["Check what was sent", "/docs/testing/requests"], + ], + ], + files: { "src/test/FetchTest.ts": "Fake backend" }, + names: { + Recorder: "Recorded requests", + RequestBody: "Recorded requests", + RequestQuery: "Recorded requests", + requests: "Recorded requests", + SentRequest: "Recorded requests", + }, + }, +]; + +/** + * Interfaces that get a table of their properties: the options and settings + * an app passes in, and the objects it reads or builds. + */ +const TABLE_SUFFIX = /(?:Options|Config|Settings|Context)$/; +const TABLES = new Set([ + "Client", + "ConsoleLoggerCall", + "ConsoleLoggerRedact", + "EndpointDefinition", + "Plugin", + "RespondRequest", + "SentRequest", + "SseEvent", + "TestEvent", +]); + +/** + * The reference: its pages by path from the repository root, formatted as + * Oxfmt writes them, and the qualified name of every export they list, such + * as `Fetch.make`, `bearer` and `Fetch.HttpError.With`. `program` must cover + * each page's module; one is created when it's left out. + */ +export function renderReference(program = createProgram()) { + const checker = program.getTypeChecker(); + const pages = PAGES.map((page) => collect(page, program, checker)); + const tabled = new Set( + pages.flatMap((page) => + page.entries + .filter((entry) => entry.table) + .map((entry) => entry.short), + ), + ); + for (const name of TABLES) + if (!tabled.has(name)) + throw new Error( + `reference-docs: TABLES lists ${name}, which isn't an exported interface`, + ); + // Every entry's page and anchor, by symbol, for the JSDoc's links. + const targets = new Map(); + for (const page of pages) + for (const entry of page.entries) + targets.set(entry.symbol, { page: page.slug, entry }); + const files = new Map(); + const names = []; + for (const page of pages) { + files.set( + `${OUT}/${page.slug}.mdx`, + format(render(page, checker, targets)), + ); + names.push(...page.entries.map((entry) => entry.name)); + } + return { files, names }; +} + +/** A page's entries, each with its symbol, group, anchor and declaration. */ +function collect(page, program, checker) { + const file = program.getSourceFile(path.join(root, page.module)); + if (!file) + throw new Error(`reference-docs: ${page.module} isn't in the program`); + const prefix = page.qualifier ? `${page.qualifier}.` : ""; + const entries = []; + const exports = checker + .getExportsOfModule(checker.getSymbolAtLocation(file)) + .sort(byName); + for (const exported of exports) { + const symbol = resolve(exported, checker); + const declaration = documented(symbol); + const source = path + .relative(root, declaration.getSourceFile().fileName) + .split(path.sep) + .join("/"); + const group = Object.hasOwn(page.names, exported.name) + ? page.names[exported.name] + : Object.hasOwn(page.files, source) + ? page.files[source] + : undefined; + if (!group) + throw new Error( + `reference-docs: no group for ${prefix}${exported.name} (${source}). Add it to the "${page.slug}" page in scripts/reference-docs.mjs.`, + ); + if (!page.groups.some(([title]) => title === group)) + throw new Error( + `reference-docs: ${prefix}${exported.name} is in the "${group}" group, which the "${page.slug}" page doesn't have`, + ); + const entry = { + name: `${prefix}${exported.name}`, + short: exported.name, + symbol, + declaration, + group, + value: Boolean(symbol.flags & ts.SymbolFlags.Value), + table: + ts.isInterfaceDeclaration(declaration) && + (TABLE_SUFFIX.test(exported.name) || TABLES.has(exported.name)), + source, + members: [], + }; + // A namespace merged with the export, such as `HttpError.With`. + for (const member of namespaceMembers(symbol, checker)) + entry.members.push({ + name: `${entry.name}.${member.name}`, + short: `${exported.name}.${member.name}`, + symbol: member, + declaration: documented(member), + group, + value: false, + table: false, + source, + members: [], + }); + entries.push(entry); + } + // Anchors: the name in lower case. A type that shares its name with a + // value, as `Endpoint` does with `endpoint`, gets `-type`. + const values = new Set( + entries + .filter((entry) => entry.value) + .map((entry) => entry.short.toLowerCase()), + ); + const ids = new Set(page.groups.map(([title]) => slug(title))); + const assign = (entry) => { + const id = entry.short.toLowerCase().replace(/\./g, "-"); + entry.id = !entry.value && values.has(id) ? `${id}-type` : id; + if (ids.has(entry.id)) + throw new Error( + `reference-docs: two headings on ${page.slug} have the ID "${entry.id}"`, + ); + ids.add(entry.id); + }; + for (const entry of entries) { + assign(entry); + entry.members.forEach(assign); + } + const used = new Set(entries.map((entry) => entry.group)); + for (const [title] of page.groups) + if (!used.has(title)) + throw new Error( + `reference-docs: the "${title}" group on ${page.slug} is empty`, + ); + return { + ...page, + entries: entries.flatMap((entry) => [entry, ...entry.members]), + top: entries, + }; +} + +function render(page, checker, targets) { + const importLine = + page.importLine ?? + `import { ${page.top + .filter((entry) => entry.value) + .map((entry) => entry.short) + .join(", ")} } from "@monarcode/effetch/${page.slug}";`; + let body = `--- +title: ${JSON.stringify(page.title)} +description: ${JSON.stringify(page.description)} +--- + +{/* Written by scripts/reference-docs.mjs from the JSDoc. Run \`pnpm run docs:reference\` after changing it; don't edit this page. */} + +${page.intro} + +\`\`\`ts +${importLine} +\`\`\` +`; + for (const [title, [guide, guideUrl]] of page.groups) { + body += `\n## ${title} [#${slug(title)}]\n\nGuide: [${guide}](${guideUrl}).\n`; + const entries = page.top + .filter((entry) => entry.group === title) + .sort((a, b) => Number(b.value) - Number(a.value) || byName(a, b)); + for (const entry of entries.flatMap((entry) => [ + entry, + ...entry.members, + ])) { + body += `\n### ${entry.name} [#${entry.id}]\n\n${summaryOf(entry.declaration, page, checker, targets)}\n`; + if (entry.table) { + const declared = entry.source + .replace(/^src\//, "") + .replace(/\.ts$/, ".d.ts"); + body += `\n\n`; + } + } + } + return body; +} + +/** + * A declaration's first paragraph, with a list it introduces. A link to an + * export on the reference becomes a link to its entry; others become code. + */ +function summaryOf(node, page, checker, targets) { + const doc = ts.getJSDocCommentsAndTags(node).filter(ts.isJSDoc).at(-1); + const comment = doc?.comment; + let text = ""; + for (const part of typeof comment === "string" + ? [{ text: comment }] + : (comment ?? [])) { + if ( + ts.isJSDocLink(part) || + ts.isJSDocLinkCode(part) || + ts.isJSDocLinkPlain(part) + ) { + text += link(part, page, checker, targets); + } else text += part.text; + } + const blocks = text.trim().split(/\n\s*\n/); + const kept = [blocks[0] ?? ""]; + // A list right after the first paragraph finishes its sentence. + if (/^\s*- /.test(blocks[1] ?? "")) kept.push(blocks[1]); + return kept.map(toMarkdown).join("\n\n"); +} + +/** + * A `{@link}` as Markdown, labelled as the JSDoc writes it, so the sentence + * around it still reads ("an `HttpError`"). A URL stays a link. + */ +function link(part, page, checker, targets) { + const written = part.name?.getText() ?? ""; + const url = /^https?$/.test(written) && part.text.startsWith("://"); + if (url) { + const [address, ...words] = `${written}${part.text}`.trim().split(/\s+/); + const label = words.join(" ").replace(/^\|\s*/, ""); + return `[${escapeMdx(label || address)}](${address})`; + } + const label = part.text.replace(/^\s*\|?\s*/, "").trim() || written; + const symbol = part.name && checker.getSymbolAtLocation(part.name); + const target = symbol && targets.get(resolve(symbol, checker)); + if (!target) return `\`${label}\``; + const href = + target.page === page.slug + ? `#${target.entry.id}` + : `/docs/reference/${target.page}#${target.entry.id}`; + return `[\`${label}\`](${href})`; +} + +/** One block of JSDoc text as Markdown: list items keep their own lines. */ +function toMarkdown(block) { + const lines = []; + for (const line of block.split("\n").map((part) => part.trim())) { + if (lines.length === 0 || line.startsWith("- ")) lines.push(line); + else lines[lines.length - 1] += ` ${line}`; + } + return lines.map(escapeMdx).join("\n"); +} + +/** Escapes what MDX would read as JSX or an expression, outside code spans. */ +function escapeMdx(text) { + return text + .split(/(`[^`]*`)/) + .map((part, index) => + index % 2 ? part : part.replace(/[{}<>]/g, (char) => `\\${char}`), + ) + .join(""); +} + +function resolve(symbol, checker) { + return symbol.flags & ts.SymbolFlags.Alias + ? checker.getAliasedSymbol(symbol) + : symbol; +} + +/** The declaration that carries the docs: an overload's, not its body's. */ +function documented(symbol) { + const declarations = symbol.declarations ?? []; + const described = declarations.find((node) => + ts + .getJSDocCommentsAndTags(node) + .some( + (doc) => + ts.isJSDoc(doc) && ts.getTextOfJSDocComment(doc.comment)?.trim(), + ), + ); + const declaration = described ?? declarations[0]; + if (!declaration) + throw new Error(`reference-docs: ${symbol.name} has no declaration`); + return declaration; +} + +/** The exported members of a namespace merged with a symbol, by name. */ +function namespaceMembers(symbol, checker) { + if (!(symbol.flags & ts.SymbolFlags.Namespace)) return []; + return checker + .getExportsOfModule(symbol) + .filter((member) => + member.declarations?.some((node) => ts.isModuleBlock(node.parent)), + ) + .sort(byName); +} + +function byName(a, b) { + const name = (item) => item.short ?? item.name; + return ( + name(a).localeCompare(name(b), "en", { sensitivity: "base" }) || + name(a).localeCompare(name(b)) + ); +} + +function slug(title) { + return title + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, ""); +} + +/** The page as Oxfmt writes it, so `format:check` passes on what's written. */ +function format(text) { + return execFileSync( + path.join(root, "node_modules", ".bin", "oxfmt"), + ["--stdin-filepath=reference.mdx"], + { cwd: root, input: text, encoding: "utf8" }, + ); +} + +function createProgram() { + return ts.createProgram( + PAGES.map((page) => path.join(root, page.module)), + { + strict: true, + noEmit: true, + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + target: ts.ScriptTarget.ES2022, + skipLibCheck: true, + }, + ); +} + +const invoked = process.argv[1] && realpathSync(process.argv[1]); +if (invoked === realpathSync(fileURLToPath(import.meta.url))) { + const { files } = renderReference(); + for (const [file, body] of files) writeFileSync(path.join(root, file), body); + console.log(`✓ wrote ${files.size} reference pages to ${OUT}`); +} diff --git a/site/content/docs/(latest)/reference/compatibility.mdx b/site/content/docs/(latest)/reference/compatibility.mdx new file mode 100644 index 0000000..dd7c1fd --- /dev/null +++ b/site/content/docs/(latest)/reference/compatibility.mdx @@ -0,0 +1,63 @@ +--- +title: Compatibility +description: The Effect versions, runtimes and TypeScript settings Effetch supports and is tested with. +--- + +Check this page before you upgrade Effect, or to see whether your runtime +and TypeScript settings are supported. + +## Effect + +Effetch has one peer dependency, `effect`, in the range `^4.0.0`. Install it +next to Effetch, as [Installation](/docs/installation) shows. + +CI tests two versions in the range: + +- The full check (types, tests, the build and the installed package) runs + with the `effect` version pinned in Effetch's own `devDependencies`, + which can be older than the newest 4.x. +- A second job typechecks, tests and builds with `effect` 4.0.0, the oldest + version in the range. + +## Runtimes + +Effetch runs wherever Effect's `HttpClient` does: browsers, React Native +(with Hermes and Metro), Node.js 20 and newer, Bun and Deno. Its code uses +no Node.js modules or globals, and joins URLs as strings rather than with +the `URL` constructor. + +Effetch sends requests through the `HttpClient` you provide, so what your +runtime needs depends on that client. `FetchHttpClient.layer` uses the +global `fetch`. For what differs in browsers and React Native, see +[Platform notes](/docs/platforms). + +CI runs the tests and the installed package on Node.js 24. + +## Modules + +The package is ESM only, and marks itself as free of side effects +(`"sideEffects": false`), so bundlers drop what you don't import. Its +`exports` map has a `types` and a `default` condition for each entry point. + +## TypeScript + +Effetch needs TypeScript 5.4 or newer. With `skipLibCheck: false`, Effect's +own declarations need TypeScript 5.7 or newer. + +CI checks the types with TypeScript 6.0.3: + +- A project that installs the packed package compiles under `NodeNext` and + `Bundler` resolution, with `skipLibCheck: false`, and emits declaration + files that name Effetch's types. +- Are the Types Wrong checks that the types resolve under Node.js's ESM + resolution and bundlers'. +- Effetch's tests, examples and the examples in these docs compile with + `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess` on. The + installed-package project compiles with them off. + +## What's next + +- [Limitations](/docs/reference/limitations): the known limits of paths, + plugins and streams. +- [Platform notes](/docs/platforms): set up Effetch for browsers and React + Native. diff --git a/site/content/docs/(latest)/reference/fetch-test.mdx b/site/content/docs/(latest)/reference/fetch-test.mdx new file mode 100644 index 0000000..4e5c091 --- /dev/null +++ b/site/content/docs/(latest)/reference/fetch-test.mdx @@ -0,0 +1,169 @@ +--- +title: "FetchTest" +description: "Every member of the FetchTest namespace: the fake backend for tests and the requests it records." +--- + +{/* Written by scripts/reference-docs.mjs from the JSDoc. Run `pnpm run docs:reference` after changing it; don't edit this page. */} + +`@monarcode/effetch/test` exports one name, the `FetchTest` namespace. Its members: + +```ts +import { FetchTest } from "@monarcode/effetch/test"; +``` + +## Fake backend [#fake-backend] + +Guide: [Test with a fake backend](/docs/testing). + +### FetchTest.fail [#fail] + +Makes a handler that answers every request to `endpoint` with the error status `status`, for [`layer`](#layer). To answer some requests with an error and others with data, return a [`reply`](#reply) from [`respond`](#respond) instead. + +### FetchTest.layer [#layer] + +Makes a fake backend: an `HttpClient` layer that answers requests with `handlers`, without a network. Provide it where `FetchHttpClient.layer` goes, under a real client with its plugins, so a test runs the same code as production, schemas included. + +- **Matching.** A request is answered by the handler whose route matches its method and path. Without `options.baseUrl`, a route matches the end of the path, so `GET /todos/:id` answers `https://api.test/v1/todos/1`. When several routes match, the longest wins, then the one with the most literal segments (`/todos/count` before `/todos/:id`), then the one listed first. A route with an absolute URL matches that URL only. +- **No match.** A request no handler matches is a defect. Its message lists the routes the backend has, and the ones that match the path with another method. +- **Recording.** The layer also provides the [`Recorder`](#recorder), with a new record each time it's built. Read it with [`requests`](#requests). +- **Services.** The layer needs the services its handlers need. A handler runs with the services the layer was built with, and those of the call it answers, which win when both have one. + +### FetchTest.reply [#reply] + +Makes a response that a [`respond`](#respond) handler sends as it is, for any status: a `201` with a `location` header, a `404` for a missing item, a `500`. The body isn't checked against the endpoint's schemas. + +### FetchTest.respond [#respond] + +Makes a handler that answers `endpoint`'s requests with `handler`, for [`layer`](#layer). + +### FetchTest.FailBody [#failbody] + +The body [`fail`](#fail) takes for endpoint `EP` and status `S`: a value of the `statusErrors` schemas for `S`, or of the `error` schema. + +- On a bound endpoint, `statusErrors` has the endpoint's and the client's schemas, but not their statuses, so the body may be a value of any of them. Its `error` is always set, `Schema.Unknown` by default, which takes anything. +- On a definition without `error`, a status without `statusErrors` takes any body, as the client's `defaultError` isn't known. + +### FetchTest.FailServices [#failservices] + +The services a [`fail`](#fail) handler for endpoint `EP` needs: those of encoding its `statusErrors` and `error` schemas. + +### FetchTest.Handler [#handler] + +One route of the fake backend, made by [`respond`](#respond) or [`fail`](#fail). Pass a list of them to [`layer`](#layer). + +- `R`: the services it needs to run, which the layer then needs. + +### FetchTest.HandlerServices [#handlerservices] + +The services handler `H` needs to run: `R` for a `Handler`. For a union of handlers, the union of their services, which is what [`layer`](#layer) needs. + +### FetchTest.LayerOptions [#layeroptions] + +Options for [`layer`](#layer). + +- `baseUrl`: where the routes start, such as `"https://api.test/v1"`. With it, a request matches a route only when its URL is the `baseUrl`, then the route's path. Without it, a route matches the end of a request's path, whatever comes before it, so the fake backend works under any client's `baseUrl`. + + + +### FetchTest.QueryParams [#queryparams] + +The query parameters of a request, as they were in the URL (decoded): a `string` per key, or a list of strings for a key that was repeated. + +### FetchTest.Reply [#reply-type] + +A response sent as it is, made by [`reply`](#reply). A [`respond`](#respond) handler returns one to answer with another status, such as `201` or `404`. + +### FetchTest.ReplyOptions [#replyoptions] + +Options for a [`reply`](#reply) or a [`fail`](#fail) handler. + + + +### FetchTest.RespondOptions [#respondoptions] + +Options for the responses of a [`respond`](#respond) handler that aren't a [`Reply`](#reply-type). + +- `status`: the status, from 200 to 599. Defaults to `200`, or to `204` when there's no body to send. +- `headers`: sent with the response, over its content type. + + + +### FetchTest.RespondRequest [#respondrequest] + +What a [`respond`](#respond) handler is called with, for one request to route `R`, whose endpoint has the `input` schema `I` and the query schema `QS`. + + + +### FetchTest.RespondResult [#respondresult] + +What a [`respond`](#respond) handler succeeds with, for an endpoint with the `output` schema `O` and the stream format `St`, or a [`Reply`](#reply-type): + +- without `St`: a value of `output`'s `Type`, encoded with `output` before it's sent. Without `output`, the value is sent by its runtime type (see [`reply`](#reply)). +- `"sse"`: a list of [`TestEvent`](#testevent)s, sent as Server-Sent Events. An `event` or `id` with a line break can't be sent, and the call dies. +- `"ndjson"`: a list of values of `output`'s `Type` (anything that has a JSON form without `output`), sent one per line. With `Fetch.text()`, a value with a line break, or a blank one, can't be sent as one line, and the call dies. + +### FetchTest.RespondServices [#respondservices] + +The services a [`respond`](#respond) handler for endpoint `EP` needs, besides its own: those of encoding `output`, and of decoding `input` and the query schema. + +### FetchTest.RouteParams [#routeparams] + +The path params a handler gets for route `R`: one key per `:param`, each a `string`, as it was in the URL (decoded). + +### FetchTest.TestEndpoint [#testendpoint] + +An endpoint the fake backend can answer for: one made by `Fetch.endpoint`, `client.endpoint` or `client.bind`. The fake backend reads its route and its schemas. + +### FetchTest.TestEvent [#testevent] + +One event a [`respond`](#respond) handler sends to an SSE endpoint (one with `stream: "sse"`): its `data`, of `output`'s `Type` (a `string` without `output`), and optionally its `event` name and `id`. + + + +## Recorded requests [#recorded-requests] + +Guide: [Check what was sent](/docs/testing/requests). + +### FetchTest.Recorder [#recorder] + +The service that keeps the requests the fake backend received, in the order it received them. [`layer`](#layer) provides it, with a new, empty record each time the layer is built. Read it with [`requests`](#requests). + +### FetchTest.requests [#requests] + +The requests the fake backend received so far, oldest first. + +### FetchTest.RequestBody [#requestbody] + +The body a handler gets for route `R`, whose endpoint has the `input` schema `I`: + +- `undefined` for a route whose method takes no body, such as `GET`; +- the decoded body, typed by `I`, with an `input` schema; +- `unknown` otherwise: the JSON value for a JSON body, the text for a text or form body, the bytes for other bytes, the `FormData` or stream as it was sent, and `undefined` without a body. + +### FetchTest.RequestQuery [#requestquery] + +The query a handler gets: decoded with the endpoint's query schema `QS` when it has one, as the call gave it, and the raw [`QueryParams`](#queryparams) otherwise. + +### FetchTest.SentRequest [#sentrequest] + +A request the fake backend received, as the [`Recorder`](#recorder) keeps it. + + diff --git a/site/content/docs/(latest)/reference/fetch.mdx b/site/content/docs/(latest)/reference/fetch.mdx new file mode 100644 index 0000000..4bc5bad --- /dev/null +++ b/site/content/docs/(latest)/reference/fetch.mdx @@ -0,0 +1,677 @@ +--- +title: "Fetch" +description: "Every member of the Fetch namespace: clients, calls, errors, plugins, endpoints, streams and pages." +--- + +{/* Written by scripts/reference-docs.mjs from the JSDoc. Run `pnpm run docs:reference` after changing it; don't edit this page. */} + +`@monarcode/effetch` exports one name, the `Fetch` namespace. Its members, grouped by the guide that covers them: + +```ts +import { Fetch } from "@monarcode/effetch"; +``` + +## Clients [#clients] + +Guide: [Declare a client](/docs/clients). + +### Fetch.isService [#isservice] + +Returns `true` if `u` is a class made by [`Service`](#service), or a class that extends one. `false` for anything else, including a key made with `Context.Service` and a [`Client`](#client). + +### Fetch.make [#make] + +Makes a [`Client`](#client). + +### Fetch.Service [#service] + +Declares a client as a service class: one class that is the client's service key, its layer and its config. + +### Fetch.Client [#client] + +A client made by [`make`](#make). Every call returns an Effect that needs no services, apart from those its schemas require (the call's or endpoint's own, and the client's `defaultError` and `statusErrors`), and that can fail with the plugins' errors and the `statusErrors` that apply, on top of Effetch's own. + +- `Ps`: the plugins the client was made with. +- `EB`: the client's `defaultError` schema. +- `SE`: the client's `statusErrors` map, or `undefined` without one. + + + +### Fetch.ClientConfig [#clientconfig] + +Configuration for [`make`](#make). + +- `baseUrl`: prepended to every path that isn't already an absolute `http://` or `https://` URL. A string, or an Effect (a `Config` works) that's run once, when the client is made. It can't contain a query string or a fragment: pass those with each call's `query` option. +- `headers`: sent with every request. A header passed to a call replaces the client's one of the same name. `content-type` and `content-length` are ignored here: they come from each request's body (set `content-type` on a call to override it). When a call has an `output` schema, Effetch sends an `Accept` header that matches it (`application/json`, or text for `Fetch.text()`), unless an `accept` header is set here or on the call. +- `defaultError`: the schema for non-2xx response bodies of calls that don't pass their own `error` option. A call's `error` replaces it. +- `statusErrors`: turns error responses into your own errors, by status, for every call (see [`StatusErrorMap`](#statuserrormap)). An endpoint's or a call's own `statusErrors` are tried first. +- `plugins`: hooks into every call (see [`Plugin`](#plugin-type)). `plugins[0]` is the outermost layer: its `onRequest` runs first and its `onResponse` last. Names must be unique. Pass the list inline: annotating it as `Plugin.Any[]` erases the plugins' types. + + + +### Fetch.ServiceClass [#serviceclass] + +A client as a service class: what [`Service`](#service) returns, to extend. + +### Fetch.ServiceClass.Any [#serviceclass-any] + +Any class made by [`Service`](#service), whatever its config. What [`isService`](#isservice) narrows to. + +## Calls [#calls] + +Guide: [Methods](/docs/calls). + +### Fetch.AnySchema [#anyschema] + +Any Effect schema accepted by the `output`, `error` and `input` options. + +### Fetch.Args [#args] + +The rest arguments after the path: the options object `T` is required when path `P` has parameters, optional otherwise. + +### Fetch.BaseOptions [#baseoptions] + +Options shared by every method. + +- `O`: the `output` schema, or `undefined` for the raw response. +- `EB`: the `error` schema for non-2xx bodies. +- `Ps`: the client's plugins, for the `plugins` override map. +- `Q`: the type of `query`, checked with [`QueryOf`](#queryof). Defaults to [`QueryInput`](#queryinput). +- `SE`: the call's `statusErrors` map, or `undefined` without one. +- `M`: the call's [`ResponseMode`](#responsemode), or `undefined` without one. + + + +### Fetch.BodyMethod [#bodymethod] + +The signature of `post`, `put`, `patch` and `del`: `body` allowed, typed by `input` when given. + +- `Ps`: the client's plugins. +- `DefaultEB`: the client's `defaultError` schema, used when a call has no `error`. +- `ClientSE`: the client's `statusErrors` map, or `undefined` without one. + +### Fetch.BodyOptions [#bodyoptions] + +The `body` and `input` options of methods that send a body. + + + +### Fetch.CallEffect [#calleffect] + +The Effect a call returns: it succeeds with [`Success`](#success), fails with [`CallError`](#callerror) and requires [`CallServices`](#callservices). + +- `O`: the `output` schema, or `undefined` for the raw response. +- `EB`: the `error` schema for non-2xx bodies. +- `I`: the `input` schema (`Schema.Unknown` or `undefined` when the call has none). +- `Ps`: the client's plugins. +- `SE`: the `statusErrors` maps of the call, the endpoint and the client, as a union. `undefined` (the default) when there are none. +- `M`: the [`ResponseMode`](#responsemode), or `undefined` (the default) for the decoded body alone. +- `QS`: an endpoint's `query` schema (see [`QuerySchema`](#queryschema)), or `undefined` (the default) without one. + +### Fetch.CallServices [#callservices] + +The services a call requires: those needed to decode `output`, `error` and the `statusErrors` maps' errors, and to encode `input` and an endpoint's `query`. + +- `SE`: the `statusErrors` maps of the call, the endpoint and the client, as a union. `undefined` (the default) when there are none. +- `QS`: the endpoint's `query` schema (see [`QuerySchema`](#queryschema)), or `undefined` (the default) without one. + +### Fetch.NoBodyMethod [#nobodymethod] + +The signature of `get`, `head` and `options`: no `body` or `input`. + +- `Ps`: the client's plugins. +- `DefaultEB`: the client's `defaultError` schema, used when a call has no `error`. +- `ClientSE`: the client's `statusErrors` map, or `undefined` without one. + +### Fetch.NoBodyRequestOptions [#nobodyrequestoptions] + +Options of methods that don't send a body: `get`, `head`, `options`. The type parameters are those of [`BaseOptions`](#baseoptions). + +### Fetch.ParamsOption [#paramsoption] + +The `params` option for path `P`: required (with exactly the path's parameter names) when the path has `:params`, forbidden otherwise. + +### Fetch.PathParamNames [#pathparamnames] + +The names of the path parameters in `P`, as a union of string literals. + +### Fetch.PathParams [#pathparams] + +The `params` object for path `P`: one required key per parameter name. + +### Fetch.PathParamValue [#pathparamvalue] + +A value accepted for a path parameter. It's converted with `String()` and then `encodeURIComponent`. + +### Fetch.QueryInput [#queryinput] + +The `query` option: an object whose entries become URL query parameters. Arrays repeat the key (`tags=a&tags=b`); `null` and `undefined` entries and array items are dropped. + +### Fetch.QueryOf [#queryof] + +The constraint on a `query` of type `Q`: each of `Q`'s own properties must be a [`QueryValue`](#queryvalue) or an array of them. + +### Fetch.QueryValue [#queryvalue] + +A single query value. Effetch drops `null` and `undefined` (Effect's own `UrlParams` would send `null` as the string `"null"`); other values are converted with `String()`. With Effect 4.1 or later, a value can also be `Redacted`: it's sent as its value, and stays redacted in Effect's own logs and traces. + +### Fetch.RequestMethod [#requestmethod] + +The signature of `request`: any HTTP method, `body` allowed, typed by `input` when given. + +- `Ps`: the client's plugins. +- `DefaultEB`: the client's `defaultError` schema, used when a call has no `error`. +- `ClientSE`: the client's `statusErrors` map, or `undefined` without one. + +### Fetch.RequestOptions [#requestoptions] + +Options of methods that send a body: `post`, `put`, `patch`, `del` and `request`. The type parameters are those of [`BaseOptions`](#baseoptions), and `I` is the `input` schema. + +## Responses [#responses] + +Guide: [Read the response](/docs/calls/responses). + +### Fetch.bytes [#bytes] + +Reads a 2xx body as bytes, a `Uint8Array`, for `output`. Use it for images, PDFs and other binary bodies. The array is typed `Uint8Array`, so in browsers, Node, Bun and Deno it can go straight into a `Blob`. React Native's `Blob` doesn't take arrays. + +### Fetch.text [#text] + +Reads a 2xx body as text, for `output`. Use it for plain-text tokens, CSV and other bodies that aren't JSON. + +- `Fetch.text()` gives the text as it was sent, as a `string`. An empty body is `""`. +- `Fetch.text(schema)` reads a single value, such as a count or a status: it trims the text, then decodes it with `schema`, whose encoded side is a string, such as `Schema.NumberFromString`. An empty body fails, as for JSON. + +### Fetch.BytesSchema [#bytesschema] + +The schema [`bytes`](#bytes) returns: a `Uint8Array` over an `ArrayBuffer`, read from the body's bytes. + +### Fetch.ResponseMode [#responsemode] + +What a call succeeds with, besides the decoded body: + +- `"decoded"` (the default): the decoded body, or the raw response without an `output` schema. +- `"decoded-and-response"`: a pair of the decoded body and the response, to read its status and headers too. Without an `output` schema, the first item is the response as well. + +### Fetch.Success [#success] + +What a call succeeds with: the `output` schema's type, or the raw `HttpClientResponse` without one. A conditional `output` gives the union. + +### Fetch.TextSchema [#textschema] + +A schema whose encoded side is a string, as [`text`](#text) takes: such as `Schema.String`, `Schema.NumberFromString` or a `Schema.Literals` of strings. + +## Uploads [#uploads] + +Guide: [Upload files](/docs/calls/uploads). + +### Fetch.multipart [#multipart] + +Sends a body as `multipart/form-data`, for `input`: the body is typed and checked by `schema`, as for JSON, then sent as `FormData`. Use it for file uploads. + +### Fetch.UploadFile [#uploadfile] + +A file to upload, for a field of a [`multipart`](#multipart) input schema. It takes the files each platform can send: + +- in browsers, Node, Bun and Deno, a `Blob` or `File`; +- in React Native, a [`NativeFile`](#nativefile), `{ uri, name, type }`, as its pickers give it. React Native's `FormData` reads the file from disk by `uri`, and can't send a `Blob`. + +### Fetch.MultipartFields [#multipartfields] + +What a [`multipart`](#multipart) input schema encodes a body to: an object of fields, each a [`MultipartValue`](#multipartvalue) or a list of them. + +### Fetch.MultipartSchema [#multipartschema] + +A schema [`multipart`](#multipart) takes: one whose encoded side is [`MultipartFields`](#multipartfields), such as a `Schema.Struct` of strings, numbers, booleans, dates, lists of them and [`UploadFile`](#uploadfile)s. + +### Fetch.MultipartValue [#multipartvalue] + +One value of a multipart field, as an `input` schema encodes it: a string, a number, a boolean, a bigint or a `Date` (sent as text), a file (`Blob`, `File` or [`NativeFile`](#nativefile)), or `null` or `undefined` (left out). + +### Fetch.NativeFile [#nativefile] + +A file picked in React Native: the object React Native's pickers give, and its `FormData` reads from disk by `uri`. + +- `uri`: where the file is, such as `file:///…` or `content://…`. +- `name`: the file name sent with it. A server only treats a part as a file when it has one, so it's required. +- `type`: its media type, such as `"image/jpeg"`. Without it, the part is sent as `application/octet-stream`, since Android rejects a file part without a type. + +### Fetch.UploadFileSchema [#uploadfileschema] + +The schema [`UploadFile`](#uploadfile) is: a `Blob` (a `File` is one) or a [`NativeFile`](#nativefile), encoded as it is. + +## Errors [#errors] + +Guide: [Call errors](/docs/errors). + +### Fetch.catchStatus [#catchstatus] + +Handles an `HttpError` with one of the given statuses, for one call: `f` gets the error, and the call continues with what `f` returns. Errors with other statuses, and every other error, pass through. + +- `status` is one status, such as `404`, or a list, such as `[401, 403]`. The handler's error has its `status` narrowed to them (see [`CaughtStatus`](#caughtstatus)). +- `HttpError` stays in the error type, since other statuses can still fail. `f`'s own errors are added. +- It works on any Effect whose errors include `HttpError`: calls, endpoints, and Effects built on them. + +### Fetch.DecodeError [#decodeerror] + +A 2xx response body didn't match the call's `output` schema, wasn't valid JSON, or couldn't be read. + +### Fetch.HttpError [#httperror] + +The server answered with a non-2xx status. + +### Fetch.HttpError.With [#httperror-with] + +An [`HttpError`](#httperror) whose `body` was decoded as `B`. `body` is `undefined` when the response didn't match the error schema. + +### Fetch.isFetchError [#isfetcherror] + +Returns `true` if `u` is a [`NetworkError`](#networkerror), [`HttpError`](#httperror) or [`DecodeError`](#decodeerror). + +### Fetch.NetworkError [#networkerror] + +The request never produced a response: DNS failure, connection refused, CORS rejection, the device is offline, and so on. + +### Fetch.optional [#optional] + +Turns a `404` into `Option.none()`, and a success into `Option.some`, for one call: the call succeeds with an `Option` of its value. Other errors, `HttpError`s with other statuses included, pass through. + +### Fetch.CallError [#callerror] + +What a call can fail with: `NetworkError`, `HttpError` (with `body` typed by the `error` schema), `DecodeError` when there's an `output` schema, the plugins' errors, and the errors of the `statusErrors` maps that apply (see [`StatusError`](#statuserror)). + +- `SE`: the `statusErrors` maps of the call, the endpoint and the client, as a union. `undefined` (the default) when there are none. + +### Fetch.CaughtStatus [#caughtstatus] + +The error [`catchStatus`](#catchstatus)'s handler gets: an `HttpError` whose `status` is narrowed to the statuses `S` it was given. Its `body` is `unknown`: to read it typed by the `error` schema, use `Effect.catchTag("HttpError", …)`. + +### Fetch.FetchError [#fetcherror] + +Every error the library itself can fail a call with. Plugins may add their own errors on top of these. + +### Fetch.StatusError [#statuserror] + +The errors a [`StatusErrorMap`](#statuserrormap) can fail a call with: the union of its schemas' types. `M` can be a union of maps (the call's, the endpoint's and the client's), and is `undefined` when there are none, which gives `never`. + +### Fetch.StatusErrorMap [#statuserrormap] + +The `statusErrors` option: turns error responses into your own errors. Each key is an HTTP status, and its value is the schema of the error that status means, or a list of schemas tried in order. The first schema that decodes the response's JSON body is what the call fails with, in place of an `HttpError`. + +### Fetch.StatusErrorSchema [#statuserrorschema] + +The schemas a [`StatusErrorMap`](#statuserrormap) lists, as a union, under its numeric keys only. `M` can be a union of maps, and `undefined` gives `never`. + +### Fetch.StatusErrorServices [#statuserrorservices] + +The services decoding a [`StatusErrorMap`](#statuserrormap)'s errors requires: the union of its schemas' `DecodingServices`. Like [`StatusError`](#statuserror), `M` can be a union of maps, and `undefined` gives `never`. + +## Plugins [#plugins] + +Guide: [Write a plugin](/docs/plugins/writing). + +### Fetch.plugin [#plugin] + +Defines a plugin. Returns its argument unchanged; it exists to infer `Name`, the errors, the services and the options type from the hooks. + +### Fetch.Plugin [#plugin-type] + +A plugin hooks into every call a client makes. + +- `onRequest` can change the request, or fail. Plugins run it in array order. It sees the full URL and the client's default headers. +- `onResponse` can change the response, or fail. It runs in reverse order and sees every response, non-2xx included: the library checks the status and decodes `output` only after the whole plugin chain. +- `onError` observes any failure of the call (after status check and decoding) and can't change the outcome. +- `onExit` observes the end of every call, success included, with its outcome, its response and how long it took (see [`PluginExitContext`](#pluginexitcontext)). It can't change the outcome either. +- `wrap` wraps the rest of the chain, for retries, timeouts and the like. It can add errors (`E`) but can't remove the ones from further in. + + + +### Fetch.Plugin.Any [#plugin-any] + +Any plugin. Use it to constrain a generic plugin-list parameter (`Ps extends ReadonlyArray`). + +### Fetch.Plugin.Definition [#plugin-definition] + +What [`plugin`](#plugin) accepts. Like [`Plugin`](#plugin-type), but each hook has its own error and service type parameters, so hooks that fail with different errors infer their union instead of conflicting. + +### Fetch.Plugin.Errors [#plugin-errors] + +The union of errors the plugins in `Ps` can add to a call. `unknown` if a plugin's types were erased (for example by [`Any`](#plugin-any)). + +### Fetch.Plugin.OnError [#plugin-onerror] + +The `onError` hook. `error` is a `FetchError`, another plugin's error, one of the call's `statusErrors`, or a defect's cause. It can't fail or change the call's outcome: if it dies, the defect is logged at Debug level and ignored. + +### Fetch.Plugin.OnExit [#plugin-onexit] + +The `onExit` hook: runs once per call, when it's over, with the call's `Exit`. On success that holds the call's result: the decoded `output`, or the response for a call without one, or, with `responseMode: "decoded-and-response"`, a pair of that and the response. Otherwise it holds the cause of its failure, defect or interruption. To tell whether the body was read, compare the result, or its first item, with `ctx.response`: a call returns the response itself only when it didn't decode it. It sees the final outcome, `statusErrors` and decoding included, which suits logging and metrics. + +### Fetch.Plugin.OnRequest [#plugin-onrequest] + +The `onRequest` hook: returns the request to send, possibly changed. + +### Fetch.Plugin.OnResponse [#plugin-onresponse] + +The `onResponse` hook: returns the response, possibly changed, or fails. Sees non-2xx responses too. + +### Fetch.Plugin.Options [#plugin-options] + +The options type of plugin `P`. + +### Fetch.Plugin.Override [#plugin-override] + +What one plugin accepts as a per-request override: `false` to skip it, or a partial of its options. Plugins without options accept only `false`. Keys set to `undefined` keep their default. + +### Fetch.Plugin.Overrides [#plugin-overrides] + +The `plugins` option of a call: an override per plugin name in `Ps`. Unknown names are compile errors, including when the client has no plugins. Plugins whose `name` isn't a string literal can't be overridden (they'd make every name valid). + +### Fetch.Plugin.Services [#plugin-services] + +The union of services the plugins in `Ps` require. `make` requires them once; calls on the client don't. `unknown` if a plugin's types were erased. + +### Fetch.Plugin.Upstream [#plugin-upstream] + +The client a plugin's `wrap` receives: the rest of the chain. + +### Fetch.Plugin.UpstreamError [#plugin-upstreamerror] + +Stands for the errors of everything inside a plugin's `wrap`: the network, the library's other errors and inner plugins' errors. It's opaque on purpose; a `wrap` can only pass it through. + +### Fetch.Plugin.UpstreamServices [#plugin-upstreamservices] + +Stands for the services required by everything inside a plugin's `wrap`. Opaque, like [`UpstreamError`](#plugin-upstreamerror). + +### Fetch.Plugin.Wrap [#plugin-wrap] + +The `wrap` hook: wraps the rest of the chain (`client`). Its error and service types are opaque placeholders, so a `wrap` can add errors and services but can't drop the ones from further in. `options` reads this call's merged options, and `route` this call's route (see [`PluginContext`](#plugincontext)). + +### Fetch.PluginContext [#plugincontext] + +What a plugin hook receives besides the request or response. + +- `request`: in `onRequest`, the request it receives. In `onResponse`, the request this plugin passed on (plugins after it may have changed it further; `response.request` is the one that was sent). In `onError` and `onExit`, the request as the call built it, before any plugin ran. +- `options`: the plugin's `defaults` merged with this call's override, `{ ...defaults, ...override }`, where `undefined` values in the override keep the default. `undefined` for a plugin without `defaults`. +- `route`: the call's method and path as written, before its params are filled in, such as `"GET /users/:id"`. It's the same for every call to that path, whether made with a method like `get` or an endpoint, so logs and metrics can be grouped by it. `undefined` for requests sent through `client.httpClient`. + + + +### Fetch.PluginExitContext [#pluginexitcontext] + +What a plugin's `onExit` hook receives besides the call's `Exit`: the fields of [`PluginContext`](#plugincontext), and + +- `response`: the response the plugin chain returned, whose status was checked and whose body was decoded. When a plugin failed after a response arrived, the last response the network sent (its body may not have been read). `undefined` when no response arrived: a network failure, a timeout, or a plugin that failed first. Its `request` is the one that was sent, after every plugin's `onRequest`. +- `durationMs`: how long the call took, in whole milliseconds measured with Effect's `Clock`, from when its request entered the plugin chain until the status was checked and the body decoded. Retries made by a plugin's `wrap` are included. + + + +## Endpoints and services [#endpoints-and-services] + +Guide: [Endpoints or methods](/docs/endpoints). + +### Fetch.endpoint [#endpoint] + +Defines an endpoint without a client: a route like `"GET /users/:id"` and the schemas and headers to call it with. You get back plain data, an [`UnboundEndpoint`](#unboundendpoint), that you can export from module level next to its schemas. `client.bind(definition)` turns it into an [`Endpoint`](#endpoint-type) of that client: the same one `client.endpoint(route, definition)` makes. + +- The route is checked as you type, as with `client.endpoint`. A route that isn't valid (which the types prevent) throws here, when the module loads. +- With an `input` schema, `body` is required on every call and typed by it. `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints take no `input`. +- Without `error`, the endpoint uses the `defaultError` of the client it's bound to. +- `statusErrors` (see [`StatusErrorMap`](#statuserrormap)) are tried before those of the client it's bound to. +- With a `query` schema (see [`QuerySchema`](#queryschema)), each call's `query` is typed and encoded by it, and required when the schema has required fields. +- With `stream: "sse"` or `stream: "ndjson"`, each call of the bound endpoint returns a `Stream` of the body's values. A `stream` that isn't one of those, or that comes with `responseMode` or a `Fetch.bytes()` output, throws here. +- Plugin overrides are given when binding: a definition doesn't know which plugins a client has. +- `definition.url(options)` builds the URL a call would go to, without the client's `baseUrl`. + +### Fetch.Endpoints [#endpoints] + +Declares a module's endpoints as a service class: one class that is the service key, its layer and its definitions. + +### Fetch.AnyUnboundEndpoint [#anyunboundendpoint] + +Any [`UnboundEndpoint`](#unboundendpoint), whatever its route and schemas. Use it to constrain a parameter that takes definitions. + +### Fetch.BindAllMethod [#bindallmethod] + +The signature of `client.bindAll`: binds a record of definitions at once, as `client.bind` binds each one. `Ps`, `DefaultEB` and `ClientSE` are the client's, as in [`BindMethod`](#bindmethod). + +### Fetch.BindMethod [#bindmethod] + +The signature of `client.bind`: turns an [`UnboundEndpoint`](#unboundendpoint) into an [`Endpoint`](#endpoint-type) of the client, the same one `client.endpoint` makes from the same route and definition. + +- `Ps`: the client's plugins. +- `DefaultEB`: the client's `defaultError` schema, used when the definition has no `error`. +- `ClientSE`: the client's `statusErrors` map, or `undefined` without one. + +### Fetch.BindOptions [#bindoptions] + +What `client.bind` takes besides the definition: headers and plugin overrides for every call of the bound endpoint. + +- `headers`: sent with every call, over the definition's headers. A call's own header of the same name wins. +- `plugins`: per-plugin overrides, as in a call's `plugins` option, checked against the client's plugins. A call's own override for a plugin wins, and when both give options, they're merged. + + + +### Fetch.BoundEndpoint [#boundendpoint] + +The endpoint a client makes from one entry of [`EndpointDefinitions`](#endpointdefinitions): what `client.bind` returns for that definition. `Ps`, `DefaultEB` and `ClientSE` are the client's, as in [`BindMethod`](#bindmethod). + +### Fetch.BoundEndpoints [#boundendpoints] + +The endpoints `client.bindAll` makes from a record of [`EndpointDefinitions`](#endpointdefinitions): one [`Endpoint`](#endpoint-type) for each entry, under the same name. + +### Fetch.Endpoint [#endpoint-type] + +An endpoint made by `client.endpoint` or `client.bind`: a function that sends its request with the options of one call, and returns the same Effect as the equivalent client method. With `stream`, it returns a `Stream` of the body's values instead, as `api.sse` and `api.ndjson` do. To page through a list endpoint, pass it to `Fetch.paginate`. + +### Fetch.EndpointArgs [#endpointargs] + +The arguments of an endpoint call: the options object `T` is required when route `R` has path params, the endpoint has an `input` schema, or its `query` schema `QS` has required fields, and optional otherwise. + +### Fetch.EndpointBody [#endpointbody] + +The `body` option of an endpoint call: not allowed on `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints, required and typed by the schema when the endpoint has an `input`, and optional otherwise (sent according to its runtime type, like a call's `body`). + +### Fetch.EndpointDefinition [#endpointdefinition] + +What an endpoint is defined with, besides its route. Everything is optional. + +- `output`: decodes the 2xx body, read as JSON, or as text or bytes with `Fetch.text()` and `Fetch.bytes()`. Without it, the endpoint succeeds with the raw `HttpClientResponse`. +- `error`: decodes non-2xx bodies into `HttpError.body`, replacing the client's `defaultError`. +- `statusErrors`: turns error responses into your own errors, by status (see [`StatusErrorMap`](#statuserrormap)). Tried before the client's. +- `input`: encodes `body` before it's sent as JSON, and makes `body` required on every call. Not allowed on `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints, which take no body. +- `headers`: sent with every call, over the client's headers. A call's own header of the same name wins. Unlike the client's headers, these can set `content-type`. +- `plugins`: per-plugin overrides for every call, as in a call's `plugins` option. A call's own override for a plugin wins, and when both give options, they're merged. +- `responseMode`: what every call succeeds with (see [`ResponseMode`](#responsemode)). A call's own `responseMode` wins. +- `query`: a schema for the query parameters (see [`QuerySchema`](#queryschema)). Each call's `query` is then typed by it, and encoded with it. +- `stream`: `"sse"` or `"ndjson"` makes every call return a `Stream` of the body's values (see [`StreamFormat`](#streamformat)). + + + +### Fetch.EndpointDefinitions [#endpointdefinitions] + +What `client.bindAll` and `Fetch.Endpoints` take: a record of definitions made with [`endpoint`](#endpoint), by the name each endpoint gets, each entry checked by [`EndpointEntry`](#endpointentry). `D` is the record's own type, and `Ps` the client's plugins. Names are strings: symbol keys are left out. + +### Fetch.EndpointEntry [#endpointentry] + +How `client.bindAll` and `Fetch.Endpoints` check one entry of a record of definitions, given the entry's own type `E` and the client's plugins `Ps`. An entry is a definition made with [`endpoint`](#endpoint), or a pair of a definition and the [`BindOptions`](#bindoptions) to bind it with. A pair's options are checked as `client.bind` checks them, so a misspelt option or plugin name is an error. + +### Fetch.EndpointMethod [#endpointmethod] + +The signature of `client.endpoint`: defines an [`Endpoint`](#endpoint-type) from a route and an [`EndpointDefinition`](#endpointdefinition). + +- `Ps`: the client's plugins. +- `DefaultEB`: the client's `defaultError` schema, used when the endpoint has no `error`. +- `ClientSE`: the client's `statusErrors` map, or `undefined` without one. + +### Fetch.EndpointOptions [#endpointoptions] + +The options of one endpoint call: `params` for the route's path (see [`ParamsOption`](#paramsoption)), `body` (see [`EndpointBody`](#endpointbody)), `query`, `headers`, `plugins` and `responseMode`. The schemas are fixed by the endpoint. + +- `Q`: the type of `query` without a query schema, checked with [`QueryOf`](#queryof). Defaults to [`QueryInput`](#queryinput). +- `M`: the call's [`ResponseMode`](#responsemode), which wins over the endpoint's, or `undefined` without one. +- `QS`: the endpoint's `query` schema, which types `query` (see [`EndpointQuery`](#endpointquery)), or `undefined` without one. + +### Fetch.EndpointQuery [#endpointquery] + +The `query` option of an endpoint call. With a `query` schema (see [`QuerySchema`](#queryschema)), it's typed by the schema's `Type`, and required when that has required fields. Without one, it's any [`QueryInput`](#queryinput), typed as `Q`. + +### Fetch.EndpointRoute [#endpointroute] + +The routes `endpoint` accepts: an uppercase HTTP method, one space, then a path that starts with `/` or an absolute `http://` or `https://` URL. + +### Fetch.EndpointsClass [#endpointsclass] + +A service class whose service is a record of endpoints: what [`Endpoints`](#endpoints) returns, to extend. + +### Fetch.EndpointUrlArgs [#endpointurlargs] + +The arguments of `endpoint.url`: its [`EndpointUrlOptions`](#endpointurloptions), which can be left out when nothing in them is required. + +### Fetch.EndpointUrlOptions [#endpointurloptions] + +What `endpoint.url` takes: `params` for the route's path (see [`ParamsOption`](#paramsoption)) and `query` (see [`EndpointQuery`](#endpointquery)), as a call takes them. + +### Fetch.QuerySchema [#queryschema] + +A schema for an endpoint's `query`: an object schema, usually a `Schema.Struct`, whose fields are the query parameters. A call's `query` is then typed by the schema's `Type`, and encoded with it before it's sent. A `Schema.Class` works too, and its calls take an instance. + +### Fetch.RouteMethod [#routemethod] + +The HTTP method of route `R` (`"GET /users/:id"` gives `"GET"`). + +### Fetch.RoutePath [#routepath] + +The path of route `R`, everything after the method and the space (`"GET /users/:id"` gives `"/users/:id"`). + +### Fetch.UnboundDefinition [#unbounddefinition] + +What [`endpoint`](#endpoint) defines an endpoint with, besides its route: an [`EndpointDefinition`](#endpointdefinition) without `plugins`. Everything is optional. + +- `output`: decodes the 2xx body, read as JSON, or as text or bytes with `Fetch.text()` and `Fetch.bytes()`. Without it, the endpoint succeeds with the raw `HttpClientResponse`. +- `error`: decodes non-2xx bodies into `HttpError.body`. Without it, the endpoint uses the `defaultError` of the client it's bound to. +- `statusErrors`: turns error responses into your own errors, by status (see [`StatusErrorMap`](#statuserrormap)). Tried before those of the client it's bound to. +- `input`: encodes `body` before it's sent as JSON, and makes `body` required on every call. Not allowed on `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints, which take no body. +- `headers`: sent with every call, over the client's headers. Headers given when binding, then a call's own, win over them. Unlike the client's headers, these can set `content-type`. +- `responseMode`: what every call succeeds with (see [`ResponseMode`](#responsemode)). A call's own `responseMode` wins. +- `query`: a schema for the query parameters (see [`QuerySchema`](#queryschema)). Each call's `query` is then typed by it, and encoded with it. +- `stream`: `"sse"` or `"ndjson"` makes every call return a `Stream` of the body's values (see [`StreamFormat`](#streamformat)). + +### Fetch.UnboundEndpoint [#unboundendpoint] + +An endpoint defined without a client, by [`endpoint`](#endpoint): its route, schemas and headers, as plain data. `client.bind` turns it into an [`Endpoint`](#endpoint-type) of that client, the same one `client.endpoint` makes from the same route and definition. + +### Fetch.ValidRoute [#validroute] + +The type of `endpoint`'s route argument: `R` itself when it's an [`EndpointRoute`](#endpointroute), otherwise the list of `" /"` starts. + +## Streaming [#streaming] + +Guide: [Streaming responses](/docs/streaming). + +### Fetch.SseEvent [#sseevent] + +One Server-Sent Event, as `api.sse` and SSE endpoints give it (see [`StreamElement`](#streamelement)). + +- `event`: the event's name, `"message"` when the server sends none. +- `id`: the last event ID the server sent, which carries over to the events after it, or `undefined`. +- `data`: the event's data, decoded with `output`: as JSON, or as text with `Fetch.text()`. Without `output`, the text as it was sent. + + + +### Fetch.StreamElement [#streamelement] + +What a stream in format `St` gives for each value, with the `output` schema `O`: + +- `"sse"`: an [`SseEvent`](#sseevent) whose `data` has `O`'s type, or is a `string` without `output`; +- `"ndjson"`: `O`'s type, or `unknown` (the parsed JSON) without `output`. + +### Fetch.StreamFormat [#streamformat] + +How a streamed response body is split into values: + +- `"sse"`: Server-Sent Events (`text/event-stream`), one value per event (see [`SseEvent`](#sseevent)). +- `"ndjson"`: newline-delimited JSON (`application/x-ndjson`), one value per line. + +### Fetch.StreamMethod [#streammethod] + +The signature of `api.sse` and `api.ndjson`: sends a request, and gives its response body as a `Stream` of values in format `St`, each a [`StreamElement`](#streamelement). It takes [`StreamOptions`](#streamoptions). + +- `St`: the [`StreamFormat`](#streamformat). +- `Ps`: the client's plugins. +- `DefaultEB`: the client's `defaultError` schema. +- `ClientSE`: the client's `statusErrors` map, or `undefined`. + +### Fetch.StreamOptions [#streamoptions] + +The options of `api.sse` and `api.ndjson`: those of a call, without `responseMode`, and with `method`. + +- `method`: the request's method. Defaults to `"GET"`. Streaming APIs that take a request body, such as those of language models, use `"POST"`. `GET`, `HEAD`, `OPTIONS` and `TRACE` take no `body` or `input`. +- `output`: decodes each value (see [`StreamElement`](#streamelement)). `Fetch.text()` gives each value's text; `Fetch.bytes()` can't be used. +- `params`, `query`, `headers`, `body`, `input`, `error`, `statusErrors` and `plugins`: as for any call. + +## Pagination [#pagination] + +Guide: [Pagination](/docs/pagination). + +### Fetch.paginate [#paginate] + +Pages through a list, as a `Stream` of pages: it calls `endpoint` (a [`PageEndpoint`](#pageendpoint)) for the first page, then for the next one while `next` gives a state, and stops after the page for which it gives `Option.none()`. See [`PaginateOptions`](#paginateoptions) for `start`, `request` and `next`. Each page is one value of the stream, so a page that is a list stays a list: `Stream.flattenIterable` gives its items instead. + +### Fetch.PageEndpoint [#pageendpoint] + +An endpoint [`paginate`](#paginate) can page through: one made by `client.endpoint` or `client.bind`, whose calls return an `Effect`. A definition made by `Fetch.endpoint` needs binding first, and a stream endpoint can't be paged. + +### Fetch.PageOf [#pageof] + +One page of endpoint `EP`: its `output`'s type, or the raw response without `output`. It's what [`paginate`](#paginate)'s stream gives, and what [`PaginateOptions`](#paginateoptions)' `next` gets. + +### Fetch.PageRequest [#pagerequest] + +The options of one page's call, as [`PaginateOptions`](#paginateoptions)' `request` returns them for endpoint `EP`: `params`, `body`, `query` and `headers`, typed as for any call of the endpoint. + +### Fetch.PageResponse [#pageresponse] + +What `next` gets as the response of a page of endpoint `EP`: the response when the endpoint's `responseMode` is `"decoded-and-response"`, for cursors in headers, and `undefined` otherwise. + +### Fetch.PaginateOptions [#paginateoptions] + +How [`paginate`](#paginate) goes from page to page, with a state `S`, such as a page number or a cursor. + +- `start`: the state of the first page. +- `request(state)`: the options of the call for that page. +- `next(page, state, response)`: the state of the next page, or `Option.none()` when this is the last one. `response` is the page's response when the endpoint's `responseMode` is `"decoded-and-response"` (see [`PageResponse`](#pageresponse)). + + diff --git a/site/content/docs/(latest)/reference/index.mdx b/site/content/docs/(latest)/reference/index.mdx index f463a3e..b83fe14 100644 --- a/site/content/docs/(latest)/reference/index.mdx +++ b/site/content/docs/(latest)/reference/index.mdx @@ -1,94 +1,41 @@ --- title: Entry points -description: Find which entry point exports what, and which page covers each export. +description: Find which entry point exports what, and the reference page that lists it. --- -This page lists what each of Effetch's entry points exports, and which page -of these docs covers it. For the known limits, see -[Limitations](/docs/reference/limitations). +This page lists Effetch's entry points and what each one exports. Each has a +reference page that lists every export, with the first paragraph of its docs +and a link to the guide that covers it. -Every export is documented, with an example, in the type declarations your -editor shows. +## The entry points -## @monarcode/effetch +Effetch has three entry points: -`@monarcode/effetch` exports the `Fetch` namespace. +| Import | What it exports | Reference | +| ---------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------- | +| `@monarcode/effetch` | The `Fetch` namespace: clients, calls, errors, plugins, endpoints, streams and pages | [Fetch](/docs/reference/fetch) | +| `@monarcode/effetch/plugins` | The built-in plugins: `bearer`, `retry`, `timeout`, `logger` and `consoleLogger` | [Plugins](/docs/reference/plugins) | +| `@monarcode/effetch/test` | The `FetchTest` namespace: a fake backend for tests | [FetchTest](/docs/reference/fetch-test) | -The exports, and the pages that cover them: +Two more subpaths export the same members without their namespace, for the +declaration files TypeScript writes. In your own code, import from the +entry points above, as [Installation](/docs/installation#import-effetch) +explains. -- `Service`, `ServiceClass` (and `ServiceClass.Any`), `isService`: - [declaring a client](/docs/clients). -- `make`, `ClientConfig`, `Client`: [setting up a client](/docs/clients) - and [making calls](/docs/calls). -- `endpoint`, `UnboundEndpoint`, `UnboundDefinition`, `AnyUnboundEndpoint`: - [defining endpoints](/docs/endpoints/defining). -- `Endpoints`, `EndpointsClass`: - [sharing endpoints as a service](/docs/endpoints/services). -- `BindMethod`, `BindOptions`, `BindAllMethod`, `EndpointDefinitions`, - `EndpointEntry`, `BoundEndpoint`, `BoundEndpoints`: - [other ways to bind endpoints](/docs/endpoints/calling). -- `Endpoint`, `EndpointMethod`, `EndpointDefinition`, `EndpointOptions`, - `EndpointBody`, `EndpointArgs`, `EndpointRoute`, `ValidRoute`, - `RouteMethod`, `RoutePath`: [endpoints](/docs/endpoints). -- `QuerySchema`, `EndpointQuery`: - [typed query parameters](/docs/endpoints/typed-query). -- `EndpointUrlOptions`, `EndpointUrlArgs`: - [building an endpoint's URL](/docs/endpoints/urls). -- `multipart`, `UploadFile`, `UploadFileSchema`, `NativeFile`, - `MultipartSchema`, `MultipartFields`, `MultipartValue`: - [upload files](/docs/calls/uploads). -- `text`, `bytes`, `TextSchema`, `BytesSchema`: - [read text or bytes](/docs/calls/responses#read-text-or-bytes). -- `NetworkError`, `HttpError` (and `HttpError.With`), `DecodeError`, - `FetchError`, `isFetchError`: [errors](/docs/errors). -- `StatusError`, `StatusErrorMap`, `StatusErrorSchema`, - `StatusErrorServices`: [errors by status](/docs/errors/status-errors). -- `catchStatus`, `optional`, `CaughtStatus`: - [catch a status](/docs/errors/catching#catch-a-status). -- `SseEvent`, `StreamElement`, `StreamFormat`, `StreamMethod`, - `StreamOptions`: [streaming responses](/docs/streaming). -- `paginate`, `PaginateOptions`, `PageEndpoint`, `PageRequest`, `PageOf`, - `PageResponse`: [pagination](/docs/pagination). -- `plugin`, `Plugin` (and the `Plugin.*` helper types), `PluginContext`, - `PluginExitContext`: - [writing plugins](/docs/plugins/writing). -- Option and result types, for wrapping the client in your own functions: - `RequestOptions`, `NoBodyRequestOptions`, `BaseOptions`, `BodyOptions`, - `ParamsOption`, `QueryInput`, `QueryOf`, `QueryValue`, `AnySchema`, - `Args`, `Success`, `ResponseMode`, `CallError`, `CallServices`, - `CallEffect`, - `NoBodyMethod`, `BodyMethod`, `RequestMethod`, `PathParamNames`, - `PathParams`, `PathParamValue`. `CallEffect` types a function that - returns a call; to take a call as an argument, accept any - `Effect.Effect`. +Every export is also documented, with an example, in the type declarations +your editor shows: hover a name, or go to its definition. -## @monarcode/effetch/plugins +## Types for your own functions -`@monarcode/effetch/plugins` exports the built-in [plugins](/docs/plugins). +To wrap the client in a function of your own, type it with the option and +result types under [Calls](/docs/reference/fetch#calls), such as +`Fetch.RequestOptions` and `Fetch.CallEffect`. `CallEffect` types a function +that returns a call. To take a call as an argument, accept any +`Effect.Effect`. -The exports: +## What's next -- `bearer`, `BearerOptions`, `BearerPlugin`, `TokenSource`, `TokenValue`, - `RefreshSource`. -- `logger`, `LoggerOptions`, `LoggerPlugin`. -- `consoleLogger`, `ConsoleLoggerOptions`, `ConsoleLoggerSettings`, - `ConsoleLoggerPlugin`, `ConsoleLoggerDetail`, `ConsoleLoggerRedact`, - `ConsoleLoggerCall`, `ConsoleLoggerColor`. -- `retry`, `RetryOptions`, `RetryPlugin`, `RetryBudgetOptions`, - `RetryBudgetPlugin`. -- `timeout`, `TimeoutOptions`, `TimeoutPlugin`, `TimeoutError`. - -## @monarcode/effetch/test - -`@monarcode/effetch/test` exports the `FetchTest` namespace, covered in -[testing](/docs/testing). - -The exports: - -- `layer`, `LayerOptions`, `Handler`, `HandlerServices`. -- `respond`, `RespondRequest`, `RespondResult`, `TestEvent`, `RespondOptions`, - `RespondServices`, `RouteParams`, `RequestBody`, `RequestQuery`, - `QueryParams`, `TestEndpoint`. -- `reply`, `Reply`, `ReplyOptions`. -- `fail`, `FailBody`, `FailServices`. -- `requests`, `Recorder`, `SentRequest`. +- [Compatibility](/docs/reference/compatibility): the Effect versions, + runtimes and TypeScript settings Effetch supports. +- [Limitations](/docs/reference/limitations): the known limits of paths, + plugins and streams. diff --git a/site/content/docs/(latest)/reference/meta.json b/site/content/docs/(latest)/reference/meta.json index 04424f0..193abd5 100644 --- a/site/content/docs/(latest)/reference/meta.json +++ b/site/content/docs/(latest)/reference/meta.json @@ -1,4 +1,11 @@ { "title": "Reference", - "pages": ["index", "limitations"] + "pages": [ + "index", + "fetch", + "plugins", + "fetch-test", + "compatibility", + "limitations" + ] } diff --git a/site/content/docs/(latest)/reference/plugins.mdx b/site/content/docs/(latest)/reference/plugins.mdx new file mode 100644 index 0000000..df776c9 --- /dev/null +++ b/site/content/docs/(latest)/reference/plugins.mdx @@ -0,0 +1,235 @@ +--- +title: "Plugins" +description: "Every export of @monarcode/effetch/plugins: the built-in plugins and their options." +--- + +{/* Written by scripts/reference-docs.mjs from the JSDoc. Run `pnpm run docs:reference` after changing it; don't edit this page. */} + +`@monarcode/effetch/plugins` exports the built-in plugins, their options and the types they return: + +```ts +import { + bearer, + consoleLogger, + logger, + retry, + timeout, + TimeoutError, +} from "@monarcode/effetch/plugins"; +``` + +## Bearer tokens [#bearer-tokens] + +Guide: [Refresh a token](/docs/plugins/token-refresh). + +### bearer [#bearer] + +Sends `Authorization: ` with every request. + +### BearerOptions [#beareroptions] + +Options for [`bearer`](#bearer). + +- `token`: where the token comes from (see [`TokenSource`](#tokensource)). It's resolved for every request, inside that request's fiber, and never cached, so a refreshed or cleared token takes effect on the next request. +- `scheme`: the word before the token. Defaults to `"Bearer"`. +- `refresh`: where a new token comes from when the server answers `401` to a request that `bearer` sent a token with (see [`RefreshSource`](#refreshsource)). The request is then sent once more, with the new token. Without `refresh`, a `401` is returned as it is. + + + +### BearerPlugin [#bearerplugin] + +The plugin made by [`bearer`](#bearer): it fails with `E` and needs `R`, the errors and services of the `token` and `refresh` Effects. Calls can only skip it (`plugins: { bearer: false }`). + +### RefreshSource [#refreshsource] + +Where [`bearer`](#bearer) gets a new token when the server answers `401`: + +- a function of the request that was refused, as it was sent, returning the new token or a promise of it; +- an Effect, whose error and services become the plugin's (and so the client's). + +### TokenSource [#tokensource] + +Where [`bearer`](#bearer) gets the token, for every request: + +- a string, for a token that never changes; +- a function of the request, returning the token or a promise of it; +- an Effect, whose error and services become the plugin's (and so the client's). + +### TokenValue [#tokenvalue] + +What a token source gives: the token, or `null`, `undefined` or `""` to send the request without an `Authorization` header. + +## Retries [#retries] + +Guide: [Retry-After and a time limit](/docs/plugins/retry-after). + +### retry [#retry] + +Retries a call that failed with a `NetworkError` or got a retryable status, for the configured methods only (idempotent ones by default, so a `POST` is never sent twice). + +### RetryBudgetOptions [#retrybudgetoptions] + +Options for [`retry`](#retry) with a time limit for the whole call: [`RetryOptions`](#retryoptions), plus `budget`. + + + +### RetryBudgetPlugin [#retrybudgetplugin] + +The plugin made by [`retry`](#retry) with a `budget`. It fails with `TimeoutError` when the budget runs out during an attempt. Calls can override `times` and `budget`, or skip it. + +### RetryOptions [#retryoptions] + +Options for [`retry`](#retry). + +- `times`: how many times to retry, after the first attempt. Defaults to `2`. Calls can override it. +- `schedule`: the delays between attempts. Defaults to an exponential backoff from 200ms, with jitter. `times` still caps the retries. +- `methods`: the methods that are retried. Defaults to the idempotent ones: `GET`, `HEAD`, `OPTIONS`, `PUT` and `DELETE`. +- `statuses`: the response statuses that are retried. Defaults to `408`, `429`, `500`, `502`, `503` and `504`. +- `retryAfter`: whether to wait as long as a retried response's `Retry-After` header asks, in place of the schedule's next delay. `true` caps the wait at 1 minute, and `{ max }` at `max`. Defaults to `false`. + + + +### RetryPlugin [#retryplugin] + +The plugin made by [`retry`](#retry). It adds no errors; calls can override `times` or skip it. + +## Time limits [#time-limits] + +Guide: [Choose a time limit](/docs/plugins#choose-a-time-limit). + +### timeout [#timeout] + +Fails the call with a [`TimeoutError`](#timeouterror), and aborts the request, when the response headers don't arrive within `duration`. + +### TimeoutError [#timeouterror] + +No response arrived within the [`timeout`](#timeout) plugin's duration. The request was aborted. + +- `url` is the request URL without its query string. +- `duration` is the limit that was exceeded, formatted (`"10s"`). + +### TimeoutOptions [#timeoutoptions] + +Options for [`timeout`](#timeout), and what a call can override: `plugins: { timeout: { duration } }`. + + + +### TimeoutPlugin [#timeoutplugin] + +The plugin made by [`timeout`](#timeout): it adds [`TimeoutError`](#timeouterror), and calls can override its `duration` or skip it. + +## Logging [#logging] + +Guide: [Built-in plugins](/docs/plugins#what-each-plugin-does). + +### logger [#logger] + +Logs one entry per call with Effect's logger: the method, the URL, the status and how long the response took, e.g. `GET https://api.example.com/todos 200 (35ms)`, or `… failed (35ms)` with the failure's cause. + +### LoggerOptions [#loggeroptions] + +Options for [`logger`](#logger). + +- `level`: the log level of every entry, `"Debug"` (the default) or `"Info"`. Effect's default logger hides Debug entries unless the minimum log level allows them. + + + +### LoggerPlugin [#loggerplugin] + +The plugin made by [`logger`](#logger). Calls can only skip it (`plugins: { logger: false }`). + +## Console logging [#console-logging] + +Guide: [Log to the console](/docs/plugins/console-logging). + +### consoleLogger [#consolelogger] + +Prints each call to the console while you develop: one line per call, opening a group with its URL, headers, bodies and error. + +### ConsoleLoggerCall [#consoleloggercall] + +The call `ConsoleLoggerOptions.filter` decides on. + +- `route`: the call's method and unfilled path, such as `"GET /users/:id"`. +- `request`: the request that was sent, after every plugin changed it. Without a response, it's the request as the call built it, before plugins ran. +- `response`: the response, or `undefined` when there was none. +- `exit`: the call's outcome. +- `durationMs`: how long the call took, in milliseconds. + + + +### ConsoleLoggerColor [#consoleloggercolor] + +How [`consoleLogger`](#consolelogger) colors its output. + +- `"auto"`: `"css"` where there's a `document` (browsers), else `false`. +- `"css"`: `%c` styles, for browser devtools and React Native DevTools. +- `"ansi"`: terminal escape codes, for Node, Bun and Deno. +- `false`: plain text. + +### ConsoleLoggerDetail [#consoleloggerdetail] + +How much [`consoleLogger`](#consolelogger) prints for each call. + +- `"summary"`: one line, such as `✗ POST /users/:id/roles 400 Bad Request 120 ms → InvalidRole`. +- `"headers"`: that line opens a group holding the full URL, the request and response headers, and the error. +- `"full"`: the request and response bodies too. + +### ConsoleLoggerOptions [#consoleloggeroptions] + +Options for [`consoleLogger`](#consolelogger). All are optional. + +- `enabled`: `false` makes the plugin do nothing, keeping its type, so it can stay in the plugin list in production. Defaults to `true`. +- `detail`: `"summary"`, `"headers"` or `"full"` (the default). See [`ConsoleLoggerDetail`](#consoleloggerdetail). +- `only`: `"all"` calls (the default), or `"errors"` for failed ones only. An interrupted call isn't a failed one. +- `collapsed`: whether groups start collapsed. Defaults to `true`, and to `false` in React Native: Metro's terminal drops `console.groupCollapsed` and everything logged inside it. Node, Bun and Deno print collapsed groups expanded. +- `slow`: calls that take at least this long are flagged with `⚠` and `(slow)`. Defaults to `false`, flagging none. +- `maxBodyLength`: body text longer than this many characters is cut. A JSON body within it is printed as an object, for devtools to expand; a longer one as its cut text. Defaults to `10_000`. +- `redact`: names to redact on top of the defaults, or `false` to redact nothing. See [`ConsoleLoggerRedact`](#consoleloggerredact). +- `filter`: prints only the calls it returns `true` for. +- `color`: see [`ConsoleLoggerColor`](#consoleloggercolor). Defaults to `"auto"`. + + + +### ConsoleLoggerPlugin [#consoleloggerplugin] + +The plugin made by [`consoleLogger`](#consolelogger). Calls can skip it (`plugins: { consoleLogger: false }`) or override its [`ConsoleLoggerSettings`](#consoleloggersettings). + +### ConsoleLoggerRedact [#consoleloggerredact] + +Names to redact on top of [`consoleLogger`](#consolelogger)'s defaults. Strings match a name ignoring case, `-` and `_`, so `"accessToken"` also matches `access_token` and `Access-Token`. A `RegExp` is tested against the name as it is. + + + +### ConsoleLoggerSettings [#consoleloggersettings] + +The options of [`consoleLogger`](#consolelogger) that calls can override, with `plugins: { consoleLogger: { ... } }`. See [`ConsoleLoggerOptions`](#consoleloggeroptions) for what each does. + + diff --git a/site/content/docs/(latest)/testing/requests.mdx b/site/content/docs/(latest)/testing/requests.mdx index 968181b..2a6e5e8 100644 --- a/site/content/docs/(latest)/testing/requests.mdx +++ b/site/content/docs/(latest)/testing/requests.mdx @@ -79,4 +79,5 @@ The fake backend picks a handler for each request by these rules: fail, or answer with another status. - [Use a hand-written HttpClient](/docs/testing/http-client): fake what the fake backend doesn't do, such as a network failure. -- [Entry points](/docs/reference): every export of `FetchTest`. +- [FetchTest](/docs/reference/fetch-test): every member of the `FetchTest` + namespace. diff --git a/site/package.json b/site/package.json index 6d2b034..6d54ebe 100644 --- a/site/package.json +++ b/site/package.json @@ -9,11 +9,15 @@ "preview": "vite preview" }, "dependencies": { + "@monarcode/effetch": "workspace:*", "@tanstack/react-router": "1.170.46", "@tanstack/react-start": "1.169.5", "@tanstack/start-static-server-functions": "1.167.44", + "@types/hast": "3.0.4", "fumadocs-core": "16.19.0", "fumadocs-mdx": "15.6.0", + "fumadocs-twoslash": "4.0.4", + "fumadocs-typescript": "5.6.0", "fumadocs-ui": "npm:@fumadocs/base-ui@16.19.0", "lucide-react": "1.72.0", "react": "19.3.1", diff --git a/site/src/components/mdx.tsx b/site/src/components/mdx.tsx index c2c61d5..f294033 100644 --- a/site/src/components/mdx.tsx +++ b/site/src/components/mdx.tsx @@ -1,18 +1,30 @@ +import * as Twoslash from "fumadocs-twoslash/ui"; import { Accordion, Accordions } from "fumadocs-ui/components/accordion"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; +import { TypeTable } from "fumadocs-ui/components/type-table"; import defaultMdxComponents from "fumadocs-ui/mdx"; import type { MDXComponents } from "mdx/types"; +import type { ComponentProps } from "react"; + +// Every name in an example is a hover target, hundreds a page, so they stay +// out of the tab order: the code reads the same without its hovers. +function PopupTrigger(props: ComponentProps) { + return ; +} export function getMDXComponents(components?: MDXComponents) { return { ...defaultMdxComponents, + ...Twoslash, + PopupTrigger, Accordion, Accordions, Step, Steps, Tab, Tabs, + TypeTable, ...components, } satisfies MDXComponents; } diff --git a/site/src/lib/mdx-options.ts b/site/src/lib/mdx-options.ts new file mode 100644 index 0000000..1d61ea2 --- /dev/null +++ b/site/src/lib/mdx-options.ts @@ -0,0 +1,184 @@ +import { sep } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { rehypeCodeDefaultOptions } from "fumadocs-core/mdx-plugins"; +import type { MDXPresetOptions } from "fumadocs-mdx/config"; +import { transformerTwoslash } from "fumadocs-twoslash"; +import { createGenerator, remarkAutoTypeTable } from "fumadocs-typescript"; +import type { Element, Root, RootContent } from "hast"; +import ts from "typescript"; + +/* + * How pages compile, for the build only: `vite.config.ts` hands these to + * Fumadocs MDX as its global options. Kept out of `docs.ts`, which the + * browser loads: the macro there drops only the `defineDocs` call, so its + * imports, TypeScript among them, would ship to every reader. + */ + +/** The repository's root: the package, its `dist` and `tsconfig.json`. */ +const root = fileURLToPath(new URL("../../../", import.meta.url)); +/** The site's own folder, which the type tables' paths start from. */ +const site = fileURLToPath(new URL("../../", import.meta.url)); + +/** + * The root `tsconfig.json`'s compiler options, which `check-docs` compiles + * the examples with, without `paths`: those point at `src`, and the hovers + * should show what readers get, the built `dist` with the namespace docs + * the build puts back. Twoslash runs from the root, so + * `@monarcode/effetch` resolves to `dist` through the package's `exports`. + */ +function exampleCompilerOptions() { + const file = `${root}tsconfig.json`; + const { config, error } = ts.readConfigFile(file, ts.sys.readFile); + if (error) + throw new Error(ts.flattenDiagnosticMessageText(error.messageText, "\n")); + const options = { ...config.compilerOptions }; + // The language service plugin is for editors. + delete options.paths; + delete options.plugins; + return options as Record; +} + +/** + * What to do with a type error in an example. `vite build` fails, as + * `check-docs` would, whatever `NODE_ENV` says. The dev server logs it and + * shows the example without hovers instead: a thrown error stops the server + * while a page is being written. + */ +function twoslashErrors(build: boolean) { + return (error: unknown, code: string) => { + if (build) throw error; + console.error(error); + return code; + }; +} + +/** + * A hover's docs: their first paragraph, with a list right after it, which + * finishes its sentence. + */ +function firstParagraph(docs: string) { + const [first = "", next = ""] = docs.split(/\n\s*\n/); + return /^\s*- /.test(next) ? `${first}\n\n${next}` : first; +} + +/** + * Formats a hover's type as fumadocs-twoslash's default does, except that a + * namespace keeps its `namespace Fetch` line. The default drops it, which + * leaves `Fetch` and `FetchTest` without a popup, and their docs unseen. + */ +function processHoverInfo(info: string) { + const content = info + .replace(/^\(([\w-]+)\)\s+/gm, "") + .replace(/\nimport .*$/, "") + .trim(); + if (/^namespace \w+$/.test(content)) return content; + const rest = content.replace(/^(interface|namespace) \w+$/gm, "").trim(); + if (/^[A-Z]\w*(?:<[^>]*>)?:/.test(rest)) return `type ${rest}`; + if (/^\w*\(/.test(rest)) return `function ${rest}`; + return rest; +} + +// Tags a hover leaves out: the page around it is the example. +const PAGE_TAGS = new Set(["example", "since"]); +// Twoslash's own opt-outs. +const OPT_OUT = /(?:^|\s)no-?twoslash(?:\s|$)/; +const LATEST = `${sep}(latest)${sep}`; + +/** + * Marks every `ts` block on a current page for Twoslash, so authors don't + * have to, unless its meta says `no-twoslash`. Pages of an older release + * line get no hovers: their examples would compile against the current + * `dist` and fail the build once the API changes. Runs before `rehypeCode`. + */ +function rehypeTwoslashMeta() { + return (tree: Root, file: { path?: string | undefined }) => { + if (!file.path?.includes(LATEST)) return; + visitCode(tree, (code) => { + const meta = String(code.data?.meta ?? ""); + if (OPT_OUT.test(meta)) return; + code.data = { ...code.data, meta: `${meta} twoslash`.trim() }; + }); + }; +} + +/** + * Calls `visit` with the `code` of each `ts` block, including those in MDX + * components such as ``, which aren't `element`s. + */ +function visitCode(node: Root | RootContent, visit: (code: Element) => void) { + if (!("children" in node)) return; + for (const child of node.children as RootContent[]) { + const code = child.type === "element" ? child.children[0] : undefined; + if ( + child.type === "element" && + child.tagName === "pre" && + code?.type === "element" && + code.tagName === "code" && + classes(code).includes("language-ts") + ) + visit(code); + else visitCode(child, visit); + } +} + +function classes(node: Element) { + const value = node.properties.className; + return Array.isArray(value) ? value.map(String) : []; +} + +/** The pages' MDX options; `build` is true for `vite build`. */ +export const mdxOptions = (build: boolean): MDXPresetOptions => ({ + rehypeCodeOptions: { + ...rehypeCodeDefaultOptions, + transformers: [ + ...(rehypeCodeDefaultOptions.transformers ?? []), + // Type hovers on every example. A type error fails the build. No + // cache: it's keyed by the block, so it would hide a change to the + // types. + transformerTwoslash({ + twoslashOptions: { + cwd: root, + compilerOptions: exampleCompilerOptions(), + }, + rendererRich: { processHoverInfo }, + onTwoslashError: twoslashErrors(build), + }), + // A hover shows a name's type and its docs' first paragraph, with + // the tags that say how to use it, such as `@default`. The export's + // own example and its version stay out: the page is the example, + // and every hover ships in the page. Runs before Twoslash renders + // its popups. + { + name: "hover-docs", + tokens() { + for (const node of this.meta.twoslash?.nodes ?? []) { + if (node.type !== "hover") continue; + if (node.docs) node.docs = firstParagraph(node.docs); + if (node.tags) + node.tags = node.tags.filter( + ([name]) => !PAGE_TAGS.has(name), + ); + } + }, + }, + ], + }, + // Before `rehypeCode`, which highlights what it leaves. + rehypePlugins: (plugins) => [rehypeTwoslashMeta, ...plugins], + remarkPlugins: [ + [ + remarkAutoTypeTable, + { + // No cache: it's keyed by the page, not the types, so it would + // keep showing an API that changed. + generator: createGenerator({ + tsconfigPath: `${site}tsconfig.json`, + }), + // A table's `path` starts from the site, where the workspace + // link `node_modules/@monarcode/effetch` points at the package. + options: { basePath: site }, + }, + ], + ], +}); diff --git a/site/src/styles/app.css b/site/src/styles/app.css index dbcc721..799f2ce 100644 --- a/site/src/styles/app.css +++ b/site/src/styles/app.css @@ -1,3 +1,4 @@ @import "tailwindcss"; @import "fumadocs-ui/css/neutral.css"; @import "fumadocs-ui/css/preset.css"; +@import "fumadocs-twoslash/twoslash.css"; diff --git a/site/tsconfig.json b/site/tsconfig.json index 4c5a5c2..bb61d10 100644 --- a/site/tsconfig.json +++ b/site/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "forceConsistentCasingInFileNames": true, "paths": { "@/*": ["./src/*"] }, - "noEmit": true + "noEmit": true, + "allowImportingTsExtensions": true } } diff --git a/site/vite.config.ts b/site/vite.config.ts index 0b0663d..f00c023 100644 --- a/site/vite.config.ts +++ b/site/vite.config.ts @@ -7,15 +7,20 @@ import { getSlugs } from "fumadocs-core/source"; import { fumadocsMdx } from "fumadocs-mdx/vite"; import { defineConfig } from "vite"; +import { mdxOptions } from "./src/lib/mdx-options.ts"; + // Every docs page, so the prerender doesn't depend on the sidebar linking to // each one. const docsPages: { path: string }[] = []; for await (const entry of glob("**/*.mdx", { cwd: "content/docs" })) docsPages.push({ path: ["/docs", ...getSlugs(entry)].join("/") }); -export default defineConfig({ +export default defineConfig(({ command }) => ({ plugins: [ - fumadocsMdx(), + // The pages' MDX options run here, in the build, never in the browser. + fumadocsMdx({ + globalOptions: { mdxOptions: mdxOptions(command === "build") }, + }), tailwindcss(), tanstackStart({ // Static files only: every page is prerendered to HTML at build time. @@ -33,4 +38,4 @@ export default defineConfig({ resolve: { tsconfigPaths: true, }, -}); +}));