Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .oxfmtrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"coverage",
".smoke",
".tanstack",
"routeTree.gen.ts"
"routeTree.gen.ts",
"site/versions"
],
"sortImports": {
"customGroups": [
Expand Down
3 changes: 2 additions & 1 deletion .oxlintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"**/coverage/**",
"**/.smoke/**",
"**/.tanstack/**",
"**/routeTree.gen.ts"
"**/routeTree.gen.ts",
"site/versions/**"
],
"rules": {
"no-unused-vars": "off",
Expand Down
9 changes: 9 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,15 @@ to static files. It's a package in the pnpm workspace and isn't published.
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.
- Older release lines in `site/content/docs/<line>/` are snapshots of
released docs, with that release's types in `site/versions/<line>/`.
Don't edit them, and don't update them when the API changes: the docs
check and Twoslash skip them. `pnpm run docs:snapshot <line>` writes one;
its header comment says when and how.
- Each page is also served as Markdown (`/docs/<page>.md`), and
`/llms.txt` and `/llms-full.txt` list the current line's pages. Link
between pages with root-relative paths, which the Markdown turns into
full URLs.
- `pnpm run check` doesn't build the site. After changing `site/`, run
`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
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ All notable changes to `@monarcode/effetch`, newest first.
types. A [Compatibility](https://effetch.pages.dev/docs/reference/compatibility)
page lists the supported Effect versions, runtimes and TypeScript
settings.
- Each page of the site is also served as Markdown, from the page's
"Copy Markdown" button and its view options, and
[llms.txt](https://effetch.pages.dev/llms.txt) and
[llms-full.txt](https://effetch.pages.dev/llms-full.txt) list the pages
for LLMs.

### Changed

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ pnpm run check
| `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. |
| `pnpm run docs:snapshot` | Freezes an older release line's docs into the site, such as `pnpm run docs:snapshot 0.1` when `0.2` starts. |

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
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
"typecheck": "tsc --noEmit",
"check:docs": "node scripts/check-docs.mjs",
"docs:reference": "node scripts/reference-docs.mjs",
"docs:snapshot": "node scripts/snapshot-docs.mjs",
"test": "vitest run",
"test:watch": "vitest",
"check:package": "publint --strict && attw --pack . --profile esm-only",
Expand Down
17 changes: 11 additions & 6 deletions scripts/reference-docs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ ${importLine}
entry,
...entry.members,
])) {
body += `\n### ${entry.name} [#${entry.id}]\n\n${summaryOf(entry.declaration, page, checker, targets)}\n`;
body += `\n### ${entry.name} [#${entry.id}]\n\n${summaryOf(entry, page, checker, targets)}\n`;
if (entry.table) {
const declared = entry.source
.replace(/^src\//, "")
Expand All @@ -327,10 +327,14 @@ ${importLine}
}

/**
* 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.
* An entry's first paragraph, and the list after it, such as a type's
* values or a function's behavior. An entry with a type table keeps the list
* only when the paragraph leads into it ("…, and"), since the table lists the
* properties. A link to an export on the reference becomes a link to its
* entry; others become code.
*/
function summaryOf(node, page, checker, targets) {
function summaryOf(entry, page, checker, targets) {
const node = entry.declaration;
const doc = ts.getJSDocCommentsAndTags(node).filter(ts.isJSDoc).at(-1);
const comment = doc?.comment;
let text = "";
Expand All @@ -347,8 +351,9 @@ function summaryOf(node, page, checker, targets) {
}
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]);
const unfinished = !/[.!?]\s*$/.test(blocks[0] ?? "");
if ((unfinished || !entry.table) && /^\s*- /.test(blocks[1] ?? ""))
kept.push(blocks[1]);
return kept.map(toMarkdown).join("\n\n");
}

Expand Down
233 changes: 233 additions & 0 deletions scripts/snapshot-docs.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
#!/usr/bin/env node
// Freezes a release line's docs into the site, so readers can still open
// them once the next line is current.
//
// node scripts/snapshot-docs.mjs 0.1
//
// Run it while preparing the first release of a new line (for `0.2.0-rc.0`,
// snapshot `0.1`), and again after a later patch to that line. It takes the
// pages from the line's newest release tag, not from `main`, which already
// documents the new line, and that release's types from npm, so the
// snapshot's type tables show the line's own API.
//
// Options:
// --tag v0.1.3 take the pages from this tag instead of the newest one
// --worktree take the pages from the working tree, to try the script
// before the line has a release (with --types)
// --types 0.1.3 take the types from this published version instead of
// the tag's

import { execFileSync } from "node:child_process";
import {
cpSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

const root = fileURLToPath(new URL("../", import.meta.url));
const docs = join(root, "site", "content", "docs");
const LATEST = "(latest)";
const PAGES = `site/content/docs/${LATEST}`;

const { values, positionals } = parseArgs({
allowPositionals: true,
options: {
tag: { type: "string" },
worktree: { type: "boolean", default: false },
types: { type: "string" },
},
});
const [line] = positionals;
if (!line || !/^\d+\.\d+$/.test(line))
fail("Usage: node scripts/snapshot-docs.mjs <line>, such as 0.1");
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
const current = pkg.version.split(".").slice(0, 2).join(".");
if (line === current && !values.worktree)
fail(
`${line} is the current line (package.json is ${pkg.version}). Snapshot a line once the next one has started.`,
);

if (
values.tag !== undefined &&
!new RegExp(`^v${line.replace(".", "\\.")}\\.\\d+(-[\\w.]+)?$`).test(
values.tag,
)
)
fail(`--tag must be a v${line}.* release tag, such as v${line}.0`);
const tag = values.worktree ? undefined : (values.tag ?? newestTag(line));
const typesVersion = values.types ?? tag?.slice(1);
if (!typesVersion) fail("--worktree needs --types <published version>");

const scratch = mkdtempSync(join(tmpdir(), "snapshot-docs-"));
try {
// Everything is built in the scratch folder first, so a failure, such as
// npm being offline, leaves the existing snapshot as it was.
const pages = join(scratch, "pages");
const types = join(scratch, "types");
copyPages(pages);
copyTypes(types);
const count = rewritePages(pages);
// Titled by the release it was taken from, such as 0.1.3.
setTitle(join(pages, "meta.json"), typesVersion);

// Formatted like the rest of the pages, so `check` passes on the result.
// The scratch folder is outside the repository, so name the config.
execFileSync(
join(root, "node_modules", ".bin", "oxfmt"),
["--config", join(root, ".oxfmtrc.json"), "--write", pages],
{
cwd: root,
stdio: "inherit",
},
);

// Swapped in only once both are ready.
const target = join(docs, line);
const typesTarget = join(root, "site", "versions", line, "types");
rmSync(target, { recursive: true, force: true });
rmSync(typesTarget, { recursive: true, force: true });
cpSync(pages, target, { recursive: true });
cpSync(types, typesTarget, { recursive: true });
console.log(
`✓ ${line}: ${count} pages from ${tag ?? "the working tree"}, types from ${pkg.name}@${typesVersion}`,
);
} catch (error) {
console.error(`✗ ${error instanceof Error ? error.message : error}`);
process.exitCode = 1;
} finally {
rmSync(scratch, { recursive: true, force: true });
}

function fail(message) {
console.error(`✗ ${message}`);
process.exit(1);
}

/**
* The line's newest release tag, by semver precedence: a release beats its
* own prereleases, and `rc.1` beats `rc.0` and `alpha.8`.
*/
function newestTag(line) {
const tags = execFileSync("git", ["tag", "--list", `v${line}.*`], {
cwd: root,
encoding: "utf8",
})
.split("\n")
.filter((name) => /^v\d+\.\d+\.\d+(-[\w.]+)?$/.test(name));
if (tags.length === 0) fail(`no v${line}.* tag: has ${line} been released?`);
return tags.sort(compareVersions).at(-1);
}

function compareVersions(a, b) {
const [coreA, preA] = splitVersion(a);
const [coreB, preB] = splitVersion(b);
const patch = Number(coreA.split(".")[2]) - Number(coreB.split(".")[2]);
if (patch !== 0) return patch;
if (preA === undefined || preB === undefined)
return (preA === undefined ? 1 : 0) - (preB === undefined ? 1 : 0);
const partsA = preA.split(".");
const partsB = preB.split(".");
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const x = partsA[i];
const y = partsB[i];
// A shorter prerelease comes first: `rc` before `rc.0`.
if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
const numeric = /^\d+$/.test(x) && /^\d+$/.test(y);
const order = numeric
? Number(x) - Number(y)
: x < y
? -1
: x > y
? 1
: 0;
if (order !== 0) return order;
}
return 0;
}

function splitVersion(tag) {
const dash = tag.indexOf("-");
return dash === -1
? [tag.slice(1)]
: [tag.slice(1, dash), tag.slice(dash + 1)];
}

function copyPages(target) {
if (!tag) {
cpSync(join(docs, LATEST), target, { recursive: true });
return;
}
const listed = execFileSync("git", ["ls-tree", "-d", tag, "--", PAGES], {
cwd: root,
encoding: "utf8",
});
if (!listed.trim()) throw new Error(`${tag} has no ${PAGES}`);
const archive = execFileSync(
"git",
["archive", "--format=tar", tag, PAGES],
{ cwd: root, maxBuffer: 1 << 28 },
);
const extracted = join(scratch, "archive");
mkdirSync(extracted, { recursive: true });
execFileSync("tar", ["-x", "-C", extracted], { input: archive });
cpSync(join(extracted, PAGES), target, { recursive: true });
}

/** The published `.d.ts` files of the line's release, from npm. */
function copyTypes(types) {
const file = execFileSync(
"npm",
[
"pack",
`${pkg.name}@${typesVersion}`,
"--pack-destination",
scratch,
// A cache of its own, so it doesn't depend on the machine's.
"--cache",
join(scratch, "npm-cache"),
"--silent",
],
{ cwd: scratch, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] },
).trim();
execFileSync("tar", ["-xzf", join(scratch, file), "-C", scratch]);
cpSync(join(scratch, "package", "dist"), types, {
recursive: true,
filter: (path) => !/\.(js|map)$/.test(path),
});
}

/**
* Points the snapshot at itself: links into the docs, and type tables at its
* own types. Its examples get no Twoslash hovers: the site adds them to
* `(latest)` pages only, as theirs would come from the current package.
*/
function rewritePages(target) {
let count = 0;
for (const name of readdirSync(target, { recursive: true })) {
if (!name.endsWith(".mdx")) continue;
const path = join(target, name);
const text = readFileSync(path, "utf8")
.replace(/\]\(\/docs(?=[/#)])/g, `](/docs/${line}`)
.replace(/href="\/docs(?=[/#"])/g, `href="/docs/${line}`)
.replace(
/path="node_modules\/@monarcode\/effetch\/dist\//g,
`path="versions/${line}/types/`,
);
writeFileSync(path, text);
count++;
}
return count;
}

function setTitle(path, title) {
const meta = JSON.parse(readFileSync(path, "utf8"));
writeFileSync(path, `${JSON.stringify({ ...meta, title }, null, "\t")}\n`);
}
5 changes: 0 additions & 5 deletions site/content/docs/(latest)/reference/fetch-test.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,6 @@ The services handler `H` needs to run: `R` for a `Handler<R>`. For a union of ha

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`.

<auto-type-table
path="node_modules/@monarcode/effetch/dist/test/FetchTest.d.ts"
name="LayerOptions"
Expand All @@ -89,9 +87,6 @@ Options for a [`reply`](#reply) or a [`fail`](#fail) handler.

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.

<auto-type-table
path="node_modules/@monarcode/effetch/dist/test/FetchTest.d.ts"
name="RespondOptions"
Expand Down
Loading
Loading