diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..12615b6 --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,14 @@ +{ + "name": "flowapi", + "owner": { + "name": "Localix Lab" + }, + "description": "flowapi's agent plugin, installed from flowapi's own repository.", + "plugins": [ + { + "name": "flowapi", + "source": "./plugins/flowapi", + "description": "Types and SDKs from API descriptions with flowapi: the library's documentation for any agent, and a pipeline that writes a TypeScript SDK repository from an OpenAPI description, checked by a deterministic judge." + } + ] +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ccb4a3c..cf96e2a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,8 @@ concurrency: jobs: # scripts/check as it runs locally: formatting, the lints, the tests, the wasm build and the - # oracles (O3 for both targets, O5, O2, O8 for both SDKs, the ledger's report); then the npm + # oracles (O3 for both targets, O5, O2, O8 for both SDKs, the ledger's report) and the agent + # plugin's tests (plugins/flowapi); then the npm # package, built and held to the Rust command byte for byte. The benchmarks are not run here. check: runs-on: ubuntu-24.04 diff --git a/AGENTS.md b/AGENTS.md index 647fb48..b664c01 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,7 +68,7 @@ work here. license, `repo/texts.rs` the scripts, CI, release-please and the repository's `AGENTS.md`, `repo/mock.rs` the mock server's routes, `repo/suite.rs` a test per resource, `repo/readme.rs` `README.md` and `api.md`, `repo/example.rs` a schema's example value, `repo/lock.rs` - `.flowapi/lock.json` (the shape the `sdk-anything` plugin reads), `repo/plan.rs` what writing the + `.flowapi/lock.json` (the shape the agent plugin reads), `repo/plan.rs` what writing the repository changes on disk (`plan`: by the lock and what the host found at each path; every host runs it, none decides alone); `repo/files/` the texts printed as they are (scripts, `server.mjs`, the licenses); `sha256.rs` our own SHA-256. @@ -105,6 +105,16 @@ work here. TypeScript compiler they check with (`ts/`), and their results (`results/`, `REPORT.md`). - `bench/`: the benchmarks against the other generators, their budgets and results ([bench/README.md](bench/README.md)); `bench/competitors/` the other tools, pinned. +- `plugins/flowapi/`: the agent plugin `flowapi`, a Claude Code plugin and an Agent Plugins + 1.1.0 core package in one folder ([plugins/flowapi/AGENTS.md](plugins/flowapi/AGENTS.md) is + its guide): the `flowapi` skill (how to use flowapi), the `sdk` skill (`/flowapi:sdk`, an SDK + repository from a description, checked by its judge), the guard hook that keeps generated + files out of hand edits, and Node tests. Its version is the workspace's, held by its tests. + The `flowapi` skill's `references/` are copies of the README, `npm/README.md` and the commands' + help, written by `plugins/flowapi/scripts/docs.mjs`: an installed plugin cannot read outside + its folder, so after changing one of those, run the script (its test fails until you do). +- `.claude-plugin/marketplace.json`: this repository as a Claude Code marketplace, its one entry + `plugins/flowapi` (`claude plugin marketplace add localixai/flowapi`). ## Commands @@ -135,6 +145,9 @@ cargo test -p flowapi-sdk --test repo # the repositories kept i cargo test -p flowapi-cli --test generate_cli # generate's writing rules as the command runs them node crates/flowapi-sdk/tests/tsc.mjs # them type-checked after --sdk; after cargo build --release cargo run --release -p flowapi-cli -- -o types.ts +(cd plugins/flowapi && npm test) # the agent plugin; its e2e on target/release/flowapi +(cd plugins/flowapi && npm run docs) # the flowapi skill's references, after a docs change +claude plugin validate . --strict # the marketplace; in plugins/flowapi, the plugin bench/run.sh # the benchmarks, then held to bench/budgets.json ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index df966a1..66e59bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- The agent plugin `flowapi` (`plugins/flowapi`), installed from this repository as a + marketplace (`claude plugin marketplace add localixai/flowapi`, then + `claude plugin install flowapi@flowapi`). It is a Claude Code plugin and an Agent Plugins 1.1.0 + core package in one folder. The `flowapi` skill covers how to use flowapi, with its docs + copied as references. The `sdk` skill, `/flowapi:sdk`, writes an SDK repository from a + description with `flowapi-sdk.yml`, `generate` and a judge (determinism, typecheck, lint, + build, the built types, the package, the tests). `/flowapi:refine`, `update` and `release` + take it further, and a guard hook refuses hand edits of the files `.flowapi/lock.json` lists. + Its version is flowapi's. + ## 0.2.0 — 2026-11-26 - `flowapi generate --out [--check]` writes a TypeScript SDK's whole diff --git a/README.md b/README.md index e7330ba..bd899ad 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ npx @localix-ai/flowapi openapi.json -o types.ts ``` It has the commands for an SDK's config too (`summary`, `config draft|schema|check`, below), with -the Rust command's output byte for byte; `generate` is the Rust command's alone for now. +the Rust command's output byte for byte, and `generate` (below) the same files, lock included. The Rust command, built from a release tag: @@ -221,7 +221,7 @@ and a boundary RFC 2046 does not allow or a part holds (`boundary`). A header's operation, with a warning. The output imports nothing: the runtime is a few functions printed once. With `--sdk` the base URL and any authentication are still yours to add: the command does not print `servers`, `securitySchemes` or `security`. The SDK layer -(`crates/flowapi-sdk`, not yet behind a command) reads them, Swagger 2.0's `host`, `basePath` and +(`crates/flowapi-sdk`, the one `generate` writes a client with) reads them, Swagger 2.0's `host`, `basePath` and `schemes` included, and prints a table to put after this output: the servers with their variables, the security schemes, and each operation's method, path, own servers, security and how each response body is read. Every row of the specification's @@ -322,6 +322,30 @@ written and it exits 1; `src/lib/` and `examples/` are the user's, `CHANGELOG.md and a file the lock does not list is never touched. A file no longer generated is deleted unless changed. Every write is staged first, so a refusal leaves the folder as it was. +## Use it from an agent + +This repository is also a plugin marketplace. Its plugin, `flowapi`, gives a coding agent +flowapi's documentation and the SDK pipeline above: + +```sh +claude plugin marketplace add localixai/flowapi +claude plugin install flowapi@flowapi +``` + +In Claude Code 2.1.275 or later, one step does both: `/plugin install flowapi --marketplace localixai/flowapi`. + +- The `flowapi` skill says which output fits which need (types, `--sdk` functions, a whole SDK + repository) and carries this README's usage, the npm package's API and the commands' help. +- The `sdk` skill, `/flowapi:sdk [folder]`, makes an SDK repository: summary, a + drafted `flowapi-sdk.yml` the agent edits, `config check`, `generate`, then a judge + (determinism, typecheck, lint, build, the built types, the package, the tests against the mock + server), and around again until the judge passes. `/flowapi:refine`, `/flowapi:update` and + `/flowapi:release` take it further; a hook refuses hand edits of generated files. + +The same folder is an Agent Plugins 1.1.0 core package, so a core client loads the skills and +the hook too. Node 20 or newer must be on `PATH`. More in +[plugins/flowapi/README.md](plugins/flowapi/README.md). + ## How it works The core (`crates/flowapi`) reads the documents into a graph of types that belongs to no diff --git a/crates/flowapi-sdk/src/repo/lock.rs b/crates/flowapi-sdk/src/repo/lock.rs index 788cf69..e1cebca 100644 --- a/crates/flowapi-sdk/src/repo/lock.rs +++ b/crates/flowapi-sdk/src/repo/lock.rs @@ -1,5 +1,5 @@ -//! `.flowapi/lock.json`: the state of a generated repository, in the shape the `sdk-anything` -//! plugin reads (its `docs/lock.md`): the lock's format version, the flowapi that wrote it, the +//! `.flowapi/lock.json`: the state of a generated repository, in the shape the agent plugin +//! reads (`plugins/flowapi/docs/lock.md`): the lock's format version, the flowapi that wrote it, the //! hashes of the description and the config, the methods the config maps, every generated file //! with the SHA-256 of its bytes, and the names pinned when two would collide. Printed as stable //! JSON (keys in a fixed order, files sorted, two spaces), read back from JSON text. diff --git a/plugins/flowapi/.claude-plugin/plugin.json b/plugins/flowapi/.claude-plugin/plugin.json new file mode 100644 index 0000000..e491fa2 --- /dev/null +++ b/plugins/flowapi/.claude-plugin/plugin.json @@ -0,0 +1,21 @@ +{ + "name": "flowapi", + "displayName": "flowapi", + "version": "0.2.0", + "description": "Types and SDKs from API descriptions with flowapi: the library's documentation for any agent, and a pipeline that writes a TypeScript SDK repository from an OpenAPI description, checked by a deterministic judge.", + "author": { + "name": "Localix Lab" + }, + "homepage": "https://github.com/localixai/flowapi", + "repository": "https://github.com/localixai/flowapi", + "license": "MIT", + "keywords": [ + "openapi", + "json-schema", + "typescript", + "rust", + "sdk", + "codegen", + "agents" + ] +} diff --git a/plugins/flowapi/AGENTS.md b/plugins/flowapi/AGENTS.md new file mode 100644 index 0000000..e63c438 --- /dev/null +++ b/plugins/flowapi/AGENTS.md @@ -0,0 +1,72 @@ +# AGENTS.md: the flowapi plugin + +flowapi's plugin for coding agents, in flowapi's repository (`plugins/flowapi`), installed from +its marketplace (`.claude-plugin/marketplace.json` at the repository root). It carries flowapi's +documentation (the `flowapi` skill) and the SDK pipeline: an agent writes `flowapi-sdk.yml`, +flowapi (`bin/flowapi`: `npx -y @localix-ai/flowapi@`) generates a +TypeScript SDK repository from an OpenAPI description and that config, a deterministic judge +checks it, and the agent fixes the config until the judge passes. The repository's rules +(`../../AGENTS.md`) bind here too; this file adds the plugin's. + +## Layout + +| Path | What it is | +| --- | --- | +| `.claude-plugin/plugin.json`, `hooks/hooks.json` | The Claude Code form: the manifest and its hooks | +| `plugin.json`, `hooks.json` | The Agent Plugins 1.1.0 core form: the same plugin for a core client. A client that reads both loads the Claude Code form alone (Agent Plugins Extended §1.3.1) | +| `hooks/guard.mjs` | The guard, one script for both: no argument is Claude Code's PreToolUse on Edit, Write, MultiEdit, NotebookEdit, answering `hookSpecificOutput` with `permissionDecision: "deny"`; `core` reads the core's `file.modify` tool profile and answers `{ "decision": "deny", "reason" }` (core §7.3.6). Silence is no opinion: it never answers `allow`. Exit code 0 always | +| `lib/guard.mjs` | The guard's decision: `decide` (Claude Code's event), `decideCore` (the core's), the nearest `.flowapi/lock.json`, its `files`, the custom zones | +| `bin/judge.mjs` | The judge's command line: `judge.mjs [--steps] [--json] [--keep-going] [--generate] [--timeout]` | +| `lib/judge.mjs` | The judge's steps 0-6 and the report | +| `bin/flowapi`, `lib/flowapi-version` | flowapi at the one pinned version, through `npx`; `FLOWAPI_PLUGIN_FLOWAPI` runs another flowapi instead | +| `lib/run.mjs`, `lib/tree.mjs`, `lib/tools.mjs` | Running a command with a time limit; comparing two trees; the pinned tool versions (flowapi's read from `lib/flowapi-version`) and `FLOWAPI_PLUGIN_NPX` | +| `skills/flowapi/` | How to use flowapi. `references/*.md` are generated (below) | +| `skills/sdk/` | The SDK pipeline, `/flowapi:sdk`, and `references/config.md`, the config's catalogue. A skill, not a command: a command of the same name would hide it (Extended §4.6.1), and a core client loads skills but no commands | +| `commands/`, `agents/sdk-reviewer.md` | `/flowapi:refine`, `update`, `release`; the read-only reviewer. Claude Code's alone | +| `docs/lock.md` | The lock's shape the plugin relies on | +| `scripts/docs.mjs` | Writes `skills/flowapi/references/` from flowapi's docs; `--check` writes nothing and exits 1 when one differs | +| `test/` | Node tests (`npm test`): the guard in both forms and as a hook, the two packagings and the version, the references, the judge on a stand-in SDK, and the pipeline end to end on `test/fixtures/pets.json` with a real flowapi (skipped without one) | + +## The references are copies + +The `flowapi` skill's references are flowapi's own docs: the README's "Use" and "How it holds to +the specification", `npm/README.md`, and the commands' help (`crates/flowapi-cli/src/args.rs`, +`npm/src/cli.ts`). Those stay the source of truth. An installed plugin is a copy of this folder +alone and cannot read a file outside it (core §4.1), so the skill carries copies, each with a +first line naming its source. After a change to a source, run `node scripts/docs.mjs`; never edit +a reference by hand. `test/docs.test.mjs` fails when one differs from what the script writes. + +## Commands + +| Command | | +| --- | --- | +| `npm test` | Every test, fast and offline: `npx` is a stand-in (`FLOWAPI_PLUGIN_NPX`); the end-to-end test uses `FLOWAPI_PLUGIN_FLOWAPI` or the repository's `target/release/flowapi` and runs judge step 0 only | +| `npm run test:e2e` | The end-to-end test with judge steps 0-6 (`FLOWAPI_PLUGIN_E2E=1`: installs the SDK's TypeScript, fetches publint and attw) | +| `npm run docs` | Writes the `flowapi` skill's references; `node scripts/docs.mjs --check` checks them | +| `npm run validate` | `claude plugin validate . --strict`; at the repository root, the same validates the marketplace | +| `claude --plugin-dir plugins/flowapi` | The working tree in a real session | + +## Rules + +- **The agent never edits generated SDK files.** Everything listed in the lock's `files` outside + `src/lib/` and `examples/` is changed through `flowapi-sdk.yml` and `generate`. Every command, + skill and agent here says so, and the guard enforces it. +- **The guard fails open and stays cheap.** It reads the event and the lock, starts no process, + prints nothing but a denial, and exits 0 on any error: a broken lock must not block the person. +- **The judge is deterministic and never passes silently.** A missing script is `skip` with its + reason; the verdict is `pass` only when every step run passed. It installs nothing, publishes + nothing, and reaches the network only through `npx` fetching a pinned tool. +- **Tool versions are pinned** in `lib/tools.mjs`; the flowapi version comes from the lock. +- **Both forms stay equivalent.** The two manifests carry the same fields (the core one adds + `$schema`); an event added to `hooks/hooks.json` that the core defines is added to `hooks.json`; + skills use the Agent Skills fields alone, so both forms read them alike. `test/manifest.test.mjs` + and `test/hooks.test.mjs` hold this. +- **One version.** The plugin's version is flowapi's (`[workspace.package] version` in + `Cargo.toml`): both manifests, `package.json` and `lib/flowapi-version` change with it, and a + test fails when they differ. `bin/flowapi` then runs that release from npm, so a version is + raised here when its npm package is published. +- **No dependencies.** Node 20 or newer, ES modules (`.mjs`), the standard library only. +- **Every user-visible change** gets a line in `CHANGELOG.md` under `## Unreleased`, and in the + repository's `CHANGELOG.md`. +- No source file over 300 lines of working code. English only. No marketing words, and in the plugin's own + prose no other generator or company named (the references copy flowapi's docs as they are). Commit only when asked; never push unasked. diff --git a/plugins/flowapi/CHANGELOG.md b/plugins/flowapi/CHANGELOG.md new file mode 100644 index 0000000..47561ba --- /dev/null +++ b/plugins/flowapi/CHANGELOG.md @@ -0,0 +1,19 @@ +# Changelog + +## Unreleased + +- The plugin, on flowapi 0.2.0, as a Claude Code plugin and an Agent Plugins 1.1.0 core package + in one folder, installed from flowapi's repository (`flowapi@flowapi`). +- The `flowapi` skill: how to use flowapi, with flowapi's own docs as its references, copied by + `scripts/docs.mjs` and held to their sources by a test. +- The `sdk` skill (`/flowapi:sdk`): summary, draft, config, check, generate, install, judge; + the config's catalogue (`references/config.md`). `/flowapi:refine`, `update` and `release`; + the read-only `sdk-reviewer` agent. +- `bin/flowapi`, flowapi at the version in `lib/flowapi-version` through `npx`, or + `FLOWAPI_PLUGIN_FLOWAPI`. +- The guard hook, which refuses a hand edit of a file listed in `.flowapi/lock.json` (outside + `src/lib/` and `examples/`) and of the lock itself: in Claude Code on Edit, Write, MultiEdit + and NotebookEdit, in a core client on the `file.modify` tool profile. +- The judge, `bin/judge.mjs`, with steps 0-6 (determinism, typecheck, lint, build, dist types, + package, test) and a JSON report; the lock's shape in `docs/lock.md`; an end-to-end test of the + pipeline (`npm run test:e2e`). diff --git a/plugins/flowapi/LICENSE b/plugins/flowapi/LICENSE new file mode 100644 index 0000000..aaaf39a --- /dev/null +++ b/plugins/flowapi/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 LocalixAI and flowapi contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/flowapi/README.md b/plugins/flowapi/README.md new file mode 100644 index 0000000..3ec79d5 --- /dev/null +++ b/plugins/flowapi/README.md @@ -0,0 +1,73 @@ +# flowapi plugin + +flowapi's plugin for coding agents. It carries flowapi's documentation as a skill, so an agent +can make types and request functions from an OpenAPI or JSON Schema description without reading +the repository. It also carries a pipeline that makes a TypeScript SDK repository: the agent +writes one small file, `flowapi-sdk.yml`, with resource and method names, pagination, auth, +environments, and the operations left out and why. flowapi prints the whole repository from the +description and that file, a deterministic judge checks the result, and the agent changes the +config until the judge passes. It never edits generated files by hand. + +It is one package in two forms: a Claude Code plugin (`.claude-plugin/plugin.json`, +`hooks/hooks.json`) and an Agent Plugins 1.1.0 core package (`plugin.json`, `hooks.json`). The +skills and the guard are shared. The commands and the reviewer agent are Claude Code's alone. + +It runs flowapi 0.2.0 through `npx` (`bin/flowapi`), so nothing else needs installing. + +## Install + +```sh +claude plugin marketplace add localixai/flowapi +claude plugin install flowapi@flowapi +``` + +Node 20 or newer must be on `PATH`. + +## What it does + +- The `flowapi` skill: what flowapi does, which output fits which need (types, `--sdk` + functions, a whole SDK repository), the commands, diagnostics, and flowapi's own docs as its + references: the CLI's help, the README's usage, the npm package's API, and how the types follow + the specification. +- The `sdk` skill, `/flowapi:sdk [folder]`: summary, draft config, edits, check, + generate, install and judge, around again until the judge passes. +- `/flowapi:refine`, `/flowapi:update` and `/flowapi:release` improve the config, take a new + version of the description, and prepare a release. Publishing is left to you. The + `sdk-reviewer` agent reads a generated SDK's API from its user's side. +- The guard hook refuses an edit of a file listed in `.flowapi/lock.json`, unless it is under + `src/lib/` or `examples/`, where your own code lives. The refusal tells the agent to change + `flowapi-sdk.yml` instead. +- The judge checks a generated repository: + +```sh +node bin/judge.mjs ./my-sdk # a table +node bin/judge.mjs ./my-sdk --json # the report as JSON +``` + +| # | Step | What it checks | +| --- | --- | --- | +| 0 | determinism | two generations into empty folders are equal byte for byte | +| 1 | typecheck | `tsc --noEmit` | +| 2 | lint | the repository's `scripts/lint` | +| 3 | build | `scripts/build` | +| 4 | dist types | `tsc -p tsconfig.dist.json` over the built declarations | +| 5 | package | `publint --strict` and `attw --pack .` | +| 6 | test | `scripts/test`, against a mock server made from the description | + +It stops at the first failure (`--keep-going` runs the rest), shows the first 40 lines of what +failed, and reports a missing script as skipped, never as passed. `--steps 1,3` runs some steps; +`--generate ""` replaces the generate command, with `{out}` for the folder. The judge +installs nothing and publishes nothing; install the SDK's dependency first (`npm install`). + +`bin/flowapi` is flowapi at the version this plugin pins (`lib/flowapi-version`), through `npx`. +Every command and the judge's step 0 go through it. `FLOWAPI_PLUGIN_FLOWAPI` names another +flowapi command to use instead, such as a local build. + +## Files it relies on + +`.flowapi/lock.json` is written by flowapi: the hashes of the description, the config and +every generated file. Its shape is in [docs/lock.md](docs/lock.md). + +## License + +MIT. See [LICENSE](LICENSE). diff --git a/plugins/flowapi/agents/sdk-reviewer.md b/plugins/flowapi/agents/sdk-reviewer.md new file mode 100644 index 0000000..4074271 --- /dev/null +++ b/plugins/flowapi/agents/sdk-reviewer.md @@ -0,0 +1,26 @@ +--- +name: sdk-reviewer +description: Reviews a generated TypeScript SDK's API from its user's side, read-only - names, resource tree, pagination, errors, auth, the README's first example - against a checklist, and says which change to flowapi-sdk.yml would fix each finding. Use from /flowapi:refine, or before a release. +tools: Read, Grep, Glob +model: inherit +--- + +You read a generated SDK repository and its `flowapi-sdk.yml`; you edit nothing. Every fix you +propose is a change to `flowapi-sdk.yml`, never to a generated file. + +Check, and report each finding with the file and the config key that fixes it: + +1. **Names.** Resources and methods read as the API's own words; verbs are the usual ones (`list`, + `create`, `retrieve`, `update`, `delete`) unless the API means something else; no two names + differ only by case or underscores; a `GET` that returns one thing is not called `list`. + Read the names in `api.md`. +2. **The tree.** Nested resources follow the paths (`projects.members.list`), not the tags alone. +3. **Pagination.** Every list operation that pages has a scheme; the items path and the cursor + parameter match the response and the request. +4. **Errors and retries.** Operations that must not be retried have `retries: 0`. +5. **Auth and environments.** Every security scheme the spec uses is configured, with its + environment variable; the default environment is the production one. +6. **The README.** `headline_method` is the call a new user makes first. +7. **Coverage.** Every `skip` has a reason that a user would accept. + +Report at most 15 findings, the most important first, each in one or two lines. diff --git a/plugins/flowapi/bin/flowapi b/plugins/flowapi/bin/flowapi new file mode 100755 index 0000000..78a984d --- /dev/null +++ b/plugins/flowapi/bin/flowapi @@ -0,0 +1,14 @@ +#!/bin/sh +# flowapi at the version this plugin pins (lib/flowapi-version), through npx. Every command and the +# judge run flowapi through this file, so the agent and the judge use the same one. +# FLOWAPI_PLUGIN_FLOWAPI names another flowapi to run instead, as a command line (a Rust binary, or +# `node /npm/dist/cli.js`): for development and the tests. +set -eu +if [ -n "${FLOWAPI_PLUGIN_FLOWAPI:-}" ]; then + # Split on spaces on purpose: the value is a command and its first arguments. + # shellcheck disable=SC2086 + exec $FLOWAPI_PLUGIN_FLOWAPI "$@" +fi +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +version=$(tr -d ' \n' < "$root/lib/flowapi-version") +exec "${FLOWAPI_PLUGIN_NPX:-npx}" -y "@localix-ai/flowapi@$version" "$@" diff --git a/plugins/flowapi/bin/judge.mjs b/plugins/flowapi/bin/judge.mjs new file mode 100755 index 0000000..58b24a1 --- /dev/null +++ b/plugins/flowapi/bin/judge.mjs @@ -0,0 +1,104 @@ +#!/usr/bin/env node +// The judge's command line. Usage in HELP below; the steps are lib/judge.mjs. +// Exit code: 0 when every step run passed, 1 when one failed or was skipped, 2 on wrong usage. + +import { existsSync, statSync } from 'node:fs' +import { resolve } from 'node:path' +import { STEPS, judge } from '../lib/judge.mjs' + +const HELP = `usage: judge.mjs [--steps 0-6] [--json] [--keep-going] + [--generate ""] [--timeout ] + +Checks a TypeScript SDK repository generated from flowapi-sdk.yml: +${STEPS.map((s) => ` ${s.id} ${s.name}`).join('\n')} + + --steps which steps: "0-6" (the default), "1,3", "2-4,6" + --json the report as JSON on stdout + --keep-going run every step even after one failed + --generate the generate command for step 0, run in by the shell; {out} is the + empty folder to write into, {flowapi} the version from .flowapi/lock.json + (default: FLOWAPI_PLUGIN_FLOWAPI, else npx -y @localix-ai/flowapi@{flowapi}, then + generate flowapi-sdk.yml --out {out}) + --timeout the limit for each command, in seconds (default 600) +` + +function usage(message) { + process.stderr.write(`${message}\n\n${HELP}`) + process.exit(2) +} + +function parseSteps(text) { + const ids = new Set() + for (const part of text.split(',')) { + const match = /^\s*(\d+)\s*(?:-\s*(\d+)\s*)?$/.exec(part) + if (!match) throw new Error(`not a step list: ${text}`) + const from = Number(match[1]) + const to = match[2] === undefined ? from : Number(match[2]) + if (to < from) throw new Error(`not a step range: ${part.trim()}`) + for (let id = from; id <= to; id++) { + if (!STEPS.some((s) => s.id === id)) + throw new Error( + `no step ${id}: steps are 0-${STEPS.length - 1} (7-9 are not part of the judge yet)`, + ) + ids.add(id) + } + } + return [...ids].sort((a, b) => a - b) +} + +function parse(argv) { + const options = { ids: STEPS.map((s) => s.id), json: false, keepGoing: false } + let dir = null + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] + const value = () => (i + 1 < argv.length ? argv[++i] : usage(`${arg} needs a value`)) + if (arg === '-h' || arg === '--help') { + process.stdout.write(HELP) + process.exit(0) + } else if (arg === '--json') options.json = true + else if (arg === '--keep-going') options.keepGoing = true + else if (arg === '--steps') { + try { + options.ids = parseSteps(value()) + } catch (error) { + usage(error.message) + } + } else if (arg === '--generate') { + options.generate = value() + if (!options.generate.includes('{out}')) + usage('--generate must contain {out}, the folder to write into') + } else if (arg === '--timeout') { + const seconds = Number(value()) + if (!(seconds > 0)) usage('--timeout takes a number of seconds') + options.timeoutMs = seconds * 1000 + } else if (arg.startsWith('-')) usage(`unknown option ${arg}`) + else if (dir === null) dir = arg + else usage(`one only, got ${dir} and ${arg}`) + } + if (dir === null) usage(' is missing') + dir = resolve(dir) + if (!existsSync(dir) || !statSync(dir).isDirectory()) usage(`not a directory: ${dir}`) + return { dir, options } +} + +function table(report) { + const lines = [`judge: ${report.dir}`, ''] + const seconds = (ms) => `${(ms / 1000).toFixed(1)}s` + for (const s of report.steps) { + const note = s.reason ?? '' + lines.push( + `${String(s.step).padEnd(3)}${s.name.padEnd(13)}${s.status.padEnd(6)}${seconds(s.duration_ms).padStart(7)} ${note}`.trimEnd(), + ) + if (s.status === 'fail') { + if (s.command) lines.push(` $ ${s.command}`) + if (s.output) lines.push(...s.output.split('\n').map((line) => ` | ${line}`)) + } + } + lines.push('', `verdict: ${report.verdict}`) + return `${lines.join('\n')}\n` +} + +const { dir, options } = parse(process.argv.slice(2)) +const report = await judge(dir, options) +process.stdout.write(options.json ? `${JSON.stringify(report, null, 2)}\n` : table(report)) +process.exitCode = report.verdict === 'pass' ? 0 : 1 diff --git a/plugins/flowapi/commands/refine.md b/plugins/flowapi/commands/refine.md new file mode 100644 index 0000000..f0cdfaa --- /dev/null +++ b/plugins/flowapi/commands/refine.md @@ -0,0 +1,19 @@ +--- +description: Improve an SDK made with the flowapi plugin - names that read badly, operations left out, pagination missed - by changing flowapi-sdk.yml and generating again. +argument-hint: "[sdk folder] [what to improve]" +allowed-tools: Bash(${CLAUDE_PLUGIN_ROOT}/bin/flowapi:*) Bash(node ${CLAUDE_PLUGIN_ROOT}/bin/judge.mjs:*) Bash(npm install:*) +--- + +# Refine an SDK + +The SDK folder and what to improve are in `$ARGUMENTS`. `F` is `${CLAUDE_PLUGIN_ROOT}/bin/flowapi`. + +1. Read `flowapi-sdk.yml`, `api.md` and `README.md`. Run `F summary ` (by `--tag` when it is + large) to see what the description has that the config does not use. +2. Use the `sdk-reviewer` agent for a read of the API from its user's side when no specific + change was asked for. +3. Change `flowapi-sdk.yml` only: names, nesting, pagination, `skip`, `readme`. +4. `F config check flowapi-sdk.yml --json` until no error, `F generate flowapi-sdk.yml --out .`, + then `node ${CLAUDE_PLUGIN_ROOT}/bin/judge.mjs . --json` until it passes. +5. Report what changed in the API (from `git diff -- api.md` when the folder is a git repository) + and that a renamed or removed method breaks its callers. diff --git a/plugins/flowapi/commands/release.md b/plugins/flowapi/commands/release.md new file mode 100644 index 0000000..2466248 --- /dev/null +++ b/plugins/flowapi/commands/release.md @@ -0,0 +1,20 @@ +--- +description: Prepare an SDK made with the flowapi plugin for its first release - check the package, the judge, the license and the release files - without publishing anything. +argument-hint: "[sdk folder]" +allowed-tools: Bash(${CLAUDE_PLUGIN_ROOT}/bin/flowapi:*) Bash(node ${CLAUDE_PLUGIN_ROOT}/bin/judge.mjs:*) Bash(npm install:*) Bash(npm pack:*) +--- + +# Prepare a release + +The SDK folder is in `$ARGUMENTS`. This command never pushes, tags or publishes: it gets the +repository ready and tells the person what is left. + +1. `${CLAUDE_PLUGIN_ROOT}/bin/flowapi generate flowapi-sdk.yml --out . --check` exits 0: the files + are what the config generates. +2. The judge passes on steps 0-6. +3. `package.name`, `package.license` and `package.repository` in `flowapi-sdk.yml` are the + person's real choices, not the draft's guesses. Ask when they are not. +4. `npm pack --dry-run`: list what the package would hold and its size. +5. The repository holds `release-please-config.json` and `.release-please-manifest.json`. Say + what the person does next: put the folder in a git repository with a remote, turn on the + release workflow they want, and publish under their own npm account. diff --git a/plugins/flowapi/commands/update.md b/plugins/flowapi/commands/update.md new file mode 100644 index 0000000..4a33238 --- /dev/null +++ b/plugins/flowapi/commands/update.md @@ -0,0 +1,19 @@ +--- +description: Update an SDK made with the flowapi plugin to a new version of its OpenAPI description - regenerate, cover new operations, and report what changed. +argument-hint: " [sdk folder]" +allowed-tools: Bash(${CLAUDE_PLUGIN_ROOT}/bin/flowapi:*) Bash(node ${CLAUDE_PLUGIN_ROOT}/bin/judge.mjs:*) Bash(npm install:*) +--- + +# Update an SDK to a new description + +The new description and the SDK folder are in `$ARGUMENTS`. `F` is `${CLAUDE_PLUGIN_ROOT}/bin/flowapi`. + +1. Replace the description in the folder, or point `spec` in `flowapi-sdk.yml` at the new one. +2. `F config check flowapi-sdk.yml --json`. New operations are `config.coverage` errors: name each + under a resource, or `skip` it with a reason. A method whose operation is gone is an error too: + remove it from the config. +3. `F generate flowapi-sdk.yml --out .`, then the judge until it passes. +4. Report what changed for the SDK's users: methods added, removed or changed (from + `git diff -- api.md src/api.ts`). flowapi does not decide the version yet: say whether the + change looks breaking (a method removed or renamed, a parameter now required, a response field + gone) and leave the version to the person. diff --git a/plugins/flowapi/docs/lock.md b/plugins/flowapi/docs/lock.md new file mode 100644 index 0000000..c5883b6 --- /dev/null +++ b/plugins/flowapi/docs/lock.md @@ -0,0 +1,66 @@ +# `.flowapi/lock.json` + +The state of a generated SDK repository, written by `flowapi generate` alone +(`crates/flowapi-sdk/src/repo/lock.rs` in this repository). The plugin reads it in two places: the guard +(`lib/guard.mjs`), to know which files are generated, and the judge (`lib/judge.mjs`), for the +flowapi version that regenerates the repository. Nothing in the plugin writes it. + +This page is the shape the plugin relies on. flowapi's `generate` defines the file; when the two +disagree, flowapi is right and this page and the plugin are changed. + +## Where it is + +At `/.flowapi/lock.json`, next to `/flowapi-sdk.yml`. The repository's root is +the nearest directory above a file that holds `.flowapi/lock.json`; every path in the lock is +relative to it. + +## Fields + +```json +{ + "version": 1, + "flowapi": "0.2.0", + "spec_sha256": "3b1f…", + "config_sha256": "9a0c…", + "configured_endpoints": 42, + "files": { + "package.json": "5e88…", + "src/client.ts": "c1d2…", + "src/resources/projects.ts": "77ab…", + "examples/basic.ts": "0f3e…" + }, + "names": { + "GET /v1/projects/{project_id}/members": "projects.members.list" + } +} +``` + +| Field | Type | What it is | +| --- | --- | --- | +| `version` | integer | The lock's format version: `1` | +| `flowapi` | string | The exact flowapi version that wrote the repository; the judge regenerates with it | +| `spec_sha256` | string | SHA-256 (hex) of the OpenAPI description's bytes as read | +| `config_sha256` | string | SHA-256 (hex) of `flowapi-sdk.yml`'s bytes | +| `configured_endpoints` | integer | The number of operations the config maps to methods | +| `files` | object | Every file `generate` wrote: repo-relative path → SHA-256 (hex) of its bytes | +| `names` | object | Names pinned when two would collide: the operation (`"METHOD /path"` or `operationId`) → the name it keeps | + +Paths in `files` use `/` on every platform, never start with `/` or `./`, and never contain `..`. +`flowapi-sdk.yml` and the lock itself are not in `files`. + +## What the guard does with it + +On Claude Code's Edit, Write, MultiEdit and NotebookEdit, and on each path of an Agent Plugins core +client's `file.modify` operations (an edit, a write, a delete, and both ends of a move): + +- A target named `.flowapi/lock.json` is refused, wherever it is. +- A target under a directory that holds the lock, whose repo-relative path is a key of `files` and + is not under `src/lib/` or `examples/` (where the person's own code lives), is refused with the hint to + change `flowapi-sdk.yml` and generate again. +- Everything else goes through. A lock that cannot be read or is not JSON, or whose `files` is not + an object, refuses nothing: a broken lock must not block the person's work. + +On Windows and macOS the path is compared without case, as their file systems do. The guard reads +the paths the tool call names; a write through a shell command or a symbolic link is not seen. +`generate` covers those: a file whose bytes no longer match its hash in `files` is not overwritten +but reported as a conflict. diff --git a/plugins/flowapi/hooks.json b/plugins/flowapi/hooks.json new file mode 100644 index 0000000..b5e6ec1 --- /dev/null +++ b/plugins/flowapi/hooks.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.1.0/hooks.schema.json", + "hooks": { + "PreToolUse": [ + { + "command": "./hooks/guard.mjs", + "args": [ + "core" + ] + } + ] + } +} diff --git a/plugins/flowapi/hooks/guard.mjs b/plugins/flowapi/hooks/guard.mjs new file mode 100755 index 0000000..31706d9 --- /dev/null +++ b/plugins/flowapi/hooks/guard.mjs @@ -0,0 +1,36 @@ +#!/usr/bin/env node +// PreToolUse hook: the guard (lib/guard.mjs decides), for two clients. With no argument it is +// Claude Code's hook (hooks/hooks.json, matched to Edit, Write, MultiEdit and NotebookEdit): a +// denial is `hookSpecificOutput` with `permissionDecision: "deny"`. With the argument `core` it is +// the Agent Plugins core hook (hooks.json, every tool call, core 1.1.0 §7.3.6): it reads the +// `file.modify` tool profile and a denial is `{ "decision": "deny", "reason" }`. In both, silence +// (no output) is no opinion: it never answers `allow`, so the client's own permissions still apply. +// +// It runs before every edit, so it stays cheap: it reads the event and at most one lock per path, +// one file read per directory level, and starts no process. Any error lets the edit through with +// nothing printed; every answer is on stdout with exit code 0. + +import { decide, decideCore } from '../lib/guard.mjs' + +const core = process.argv[2] === 'core' +const chunks = [] +for await (const chunk of process.stdin) chunks.push(chunk) +let decision = null +try { + const event = JSON.parse(Buffer.concat(chunks).toString('utf8')) + decision = core ? decideCore(event) : decide(event) +} catch { + decision = null // fail open, and print nothing: the event may hold the person's file contents +} +if (decision) { + const answer = core + ? { decision: 'deny', reason: decision.reason } + : { + hookSpecificOutput: { + hookEventName: 'PreToolUse', + permissionDecision: 'deny', + permissionDecisionReason: decision.reason, + }, + } + process.stdout.write(`${JSON.stringify(answer)}\n`) +} diff --git a/plugins/flowapi/hooks/hooks.json b/plugins/flowapi/hooks/hooks.json new file mode 100644 index 0000000..a24625d --- /dev/null +++ b/plugins/flowapi/hooks/hooks.json @@ -0,0 +1,20 @@ +{ + "description": "flowapi: the guard. Refuses a hand edit of a file flowapi generated (listed in the nearest .flowapi/lock.json, outside src/lib/ and examples/) and of the lock itself. Silent everywhere else.", + "hooks": { + "PreToolUse": [ + { + "matcher": "Edit|Write|MultiEdit|NotebookEdit", + "hooks": [ + { + "type": "command", + "command": "node", + "args": [ + "${CLAUDE_PLUGIN_ROOT}/hooks/guard.mjs" + ], + "timeout": 10 + } + ] + } + ] + } +} diff --git a/plugins/flowapi/lib/flowapi-version b/plugins/flowapi/lib/flowapi-version new file mode 100644 index 0000000..0ea3a94 --- /dev/null +++ b/plugins/flowapi/lib/flowapi-version @@ -0,0 +1 @@ +0.2.0 diff --git a/plugins/flowapi/lib/guard.mjs b/plugins/flowapi/lib/guard.mjs new file mode 100644 index 0000000..8b32ed4 --- /dev/null +++ b/plugins/flowapi/lib/guard.mjs @@ -0,0 +1,109 @@ +// The guard's decision (hooks/guard.mjs is the hook around it). A file flowapi generated is +// changed through flowapi-sdk.yml and a new `generate`, never by hand, so an edit of one is +// refused with that hint. The generated files are the ones listed in the nearest +// .flowapi/lock.json above the target (docs/lock.md). +// +// Two clients ask, each with its own event: Claude Code names the file in its native tool input +// (`decide`), an Agent Plugins core client in the `file.modify` tool profile (`decideCore`, core +// 1.1.0 §7.3.6). Both end in the same decision for each path. +// +// It fails open: a missing, unreadable or broken lock, or an event it does not understand, and +// the edit goes through. `flowapi generate` still finds a hand edit later by its hash. + +import { readFileSync } from 'node:fs' +import nodePath from 'node:path' + +export const LOCK_DIR = '.flowapi' +export const LOCK_FILE = 'lock.json' +/** Where the person's own code lives: listed or not, these stay editable. */ +export const CUSTOM_ZONES = ['src/lib/', 'examples/'] +/** Claude Code's tools that write one file, named by `file_path` or `notebook_path`. */ +export const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']) + +const CHANGE_CONFIG = + 'change flowapi-sdk.yml and run generate again; your own code goes in src/lib/ or examples/.' + +/** + * The decision for one Claude Code PreToolUse event: `{ reason }` to deny, null to stay silent. + * `path`, `readFile` and `platform` are injected so tests can run the Windows rules on any machine. + */ +export function decide(event, options = {}) { + if (!event || !EDIT_TOOLS.has(event.tool_name)) return null + const input = event.tool_input ?? {} + return decidePaths([input.file_path ?? input.notebook_path], event.cwd, options) +} + +/** + * The decision for one core PreToolUse event. Only the `file.modify` profile names files in a + * portable way; every path an operation touches is checked: an edit, a write and a delete of a + * generated file, and a move from or onto one, are all refused. Without that profile: silent. + */ +export function decideCore(event, options = {}) { + const profile = event?.tool_profile + if (!profile || profile.name !== 'file.modify') return null + const operations = profile.input?.operations + if (!Array.isArray(operations)) return null + const paths = operations.flatMap((op) => (op?.kind === 'move' ? [op.from, op.to] : [op?.path])) + return decidePaths(paths, event.cwd, options) +} + +/** The first refusal among `paths`, each resolved against `cwd`; null when none is refused. */ +function decidePaths(paths, cwd, options) { + for (const target of paths) { + if (typeof target !== 'string' || target === '') continue + const decision = decidePath(target, cwd, options) + if (decision) return decision + } + return null +} + +function decidePath(target, cwd, options) { + const { path = nodePath, readFile = readFileSync, platform = process.platform } = options + const fold = platform === 'win32' || platform === 'darwin' // case-insensitive file systems + const same = (a, b) => (fold ? a.toLowerCase() === b.toLowerCase() : a === b) + const full = path.resolve(cwd || process.cwd(), target) + + const parent = path.dirname(full) + if (same(path.basename(full), LOCK_FILE) && same(path.basename(parent), LOCK_DIR)) { + return { + reason: `${LOCK_DIR}/${LOCK_FILE} is written by flowapi generate alone: ${CHANGE_CONFIG}`, + } + } + + let found = null + try { + found = nearestLock(parent, path, readFile) + } catch { + return null // a lock that cannot be read or parsed blocks nothing + } + if (!found) return null + const files = found.lock?.files + if (!files || typeof files !== 'object' || Array.isArray(files)) return null + + const rel = path.relative(found.root, full).split(path.sep).join('/') + if (rel === '' || rel.startsWith('../')) return null + const key = fold ? rel.toLowerCase() : rel + if (CUSTOM_ZONES.some((zone) => key.startsWith(fold ? zone.toLowerCase() : zone))) return null + const listed = Object.keys(files).some((name) => same(name, rel)) + if (!listed) return null + return { + reason: `${rel} is generated by flowapi from flowapi-sdk.yml (listed in ${LOCK_DIR}/${LOCK_FILE}); do not edit it by hand: ${CHANGE_CONFIG}`, + } +} + +/** + * The nearest directory at or above `dir` that holds the lock, with the lock parsed. + * Null when there is none; throws when one exists but cannot be read or parsed. + */ +export function nearestLock(dir, path = nodePath, readFile = readFileSync) { + for (let current = dir; ; current = path.dirname(current)) { + let text = null + try { + text = readFile(path.join(current, LOCK_DIR, LOCK_FILE), 'utf8') + } catch (error) { + if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') throw error + } + if (text !== null) return { root: current, lock: JSON.parse(text) } + if (path.dirname(current) === current) return null + } +} diff --git a/plugins/flowapi/lib/judge.mjs b/plugins/flowapi/lib/judge.mjs new file mode 100644 index 0000000..9ac7ba0 --- /dev/null +++ b/plugins/flowapi/lib/judge.mjs @@ -0,0 +1,206 @@ +// The judge: the checks a generated SDK repository passes before the agent may call it done +// (steps 0-6). Cheap ones first; it stops at the first failure unless +// asked to go on. A step whose script or file is missing is a skip with its reason, never a pass. +// It installs nothing and publishes nothing; the network is reached only by `npx` fetching a tool. + +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { head, run, shellQuote } from './run.mjs' +import { compareTrees } from './tree.mjs' +import { ATTW, FLOWAPI_VERSION, PUBLINT, defaultGenerate, npx } from './tools.mjs' + +export const STEPS = [ + { id: 0, name: 'determinism', check: determinism }, + { id: 1, name: 'typecheck', check: typecheck }, + { id: 2, name: 'lint', check: (ctx) => script(ctx, 'scripts/lint') }, + { id: 3, name: 'build', check: (ctx) => script(ctx, 'scripts/build') }, + { id: 4, name: 'dist types', check: distTypes }, + { id: 5, name: 'package', check: packageShape }, + { id: 6, name: 'test', check: (ctx) => script(ctx, 'scripts/test') }, +] + +/** + * Runs the steps `ids` on the repository `dir`. Options: `keepGoing`, `generate` (the command + * template), `timeoutMs` per command, `env`. Resolves to the report. + */ +export async function judge( + dir, + { ids, keepGoing = false, generate, timeoutMs, env = process.env } = {}, +) { + const ctx = { + dir, + generate: generate ?? defaultGenerate(env), + timeoutMs, + env: { ...env, CI: env.CI ?? '1' }, + } + const steps = [] + let failed = false + for (const step of STEPS.filter((s) => ids.includes(s.id))) { + if (failed && !keepGoing) { + steps.push({ + step: step.id, + name: step.name, + command: null, + status: 'skip', + reason: 'not run: an earlier step failed', + duration_ms: 0, + }) + continue + } + const started = Date.now() + const result = await step.check(ctx) + const entry = { + step: step.id, + name: step.name, + command: result.command ?? null, + status: result.status, + } + if (result.reason) entry.reason = result.reason + entry.duration_ms = Date.now() - started + if (result.output) entry.output = head(result.output) + steps.push(entry) + if (result.status === 'fail') failed = true + } + const verdict = failed ? 'fail' : steps.every((s) => s.status === 'pass') ? 'pass' : 'incomplete' + return { dir, verdict, steps } +} + +// Step 0: two generations into empty folders, compared byte for byte. +async function determinism(ctx) { + const command = ctx.generate + if (!existsSync(join(ctx.dir, 'flowapi-sdk.yml'))) { + return { + command, + status: 'fail', + reason: 'flowapi-sdk.yml is missing: the judge checks a repository generated from one', + } + } + const outs = [0, 1].map((i) => mkdtempSync(join(tmpdir(), `flowapi-plugin-gen${i}-`))) + try { + for (const out of outs) { + const line = command + .replaceAll('{out}', shellQuote(out)) + .replaceAll('{flowapi}', flowapiVersion(ctx.dir)) + const done = await run(line, [], { + cwd: ctx.dir, + env: ctx.env, + timeoutMs: ctx.timeoutMs, + shell: true, + }) + const failure = failureOf(done) + if (failure) + return { command, status: 'fail', reason: `generate: ${failure}`, output: done.output } + } + const { files, differences } = compareTrees(outs[0], outs[1]) + if (files === 0) + return { command, status: 'fail', reason: 'generate wrote no files into {out}' } + if (differences.length > 0) { + return { + command, + status: 'fail', + reason: `two runs differ in ${differences.length} of ${files} paths`, + output: differences.join('\n'), + } + } + return { command, status: 'pass', reason: `${files} files, equal in both runs` } + } finally { + for (const out of outs) rmSync(out, { recursive: true, force: true }) + } +} + +// Step 1: the sources and tests compile, with the repository's own TypeScript. +async function typecheck(ctx) { + const command = `npx --no -- tsc --noEmit` + if (!existsSync(join(ctx.dir, 'tsconfig.json'))) + return { command, status: 'fail', reason: 'tsconfig.json is missing' } + const missing = needsDependencies(ctx, command) + if (missing) return missing + return tool(ctx, command, ['--no', '--', 'tsc', '--noEmit']) +} + +// Step 4: the built declarations are valid on their own (skipLibCheck off in that config). +async function distTypes(ctx) { + const command = `npx --no -- tsc -p tsconfig.dist.json` + if (!existsSync(join(ctx.dir, 'tsconfig.dist.json'))) + return { command, status: 'skip', reason: 'tsconfig.dist.json is missing' } + const missing = needsDependencies(ctx, command) + if (missing) return missing + return tool(ctx, command, ['--no', '--', 'tsc', '-p', 'tsconfig.dist.json']) +} + +// Step 5: the package's exports and types for CommonJS and ESM, on the packed tarball. +async function packageShape(ctx) { + const commands = [ + [`npx -y ${PUBLINT} --strict`, ['-y', PUBLINT, '--strict']], + [`npx -y ${ATTW} --pack .`, ['-y', ATTW, '--pack', '.']], + ] + const command = commands.map(([line]) => line).join(' && ') + if (!existsSync(join(ctx.dir, 'package.json'))) + return { command, status: 'fail', reason: 'package.json is missing' } + for (const [line, args] of commands) { + const result = await tool(ctx, line, args) + if (result.status !== 'pass') return { ...result, command } + } + return { command, status: 'pass' } +} + +async function tool(ctx, command, args) { + const shell = process.platform === 'win32' // npx is a .cmd there + const done = await run(npx(ctx.env), args, { + cwd: ctx.dir, + env: ctx.env, + timeoutMs: ctx.timeoutMs, + shell, + }) + const failure = failureOf(done) + return failure + ? { command, status: 'fail', reason: failure, output: done.output } + : { command, status: 'pass' } +} + +// Steps 2, 3 and 6: the generated repository's own scripts. +async function script(ctx, rel) { + const command = rel + if (!existsSync(join(ctx.dir, rel))) + return { command, status: 'skip', reason: `${rel} is missing` } + const done = await run(join(ctx.dir, rel), [], { + cwd: ctx.dir, + env: ctx.env, + timeoutMs: ctx.timeoutMs, + }) + const failure = failureOf(done) + return failure + ? { command, status: 'fail', reason: failure, output: done.output } + : { command, status: 'pass' } +} + +function needsDependencies(ctx, command) { + if (existsSync(join(ctx.dir, 'node_modules'))) return null + return { + command, + status: 'fail', + reason: + 'node_modules is missing: install the dependencies first (scripts/bootstrap); the judge installs nothing', + } +} + +function failureOf(done) { + if (done.timedOut) return 'timed out' + if (done.code === null && !done.signal) return 'could not start' + if (done.signal) return `ended by ${done.signal}` + if (done.code !== 0) return `exit code ${done.code}` + return null +} + +/** The flowapi that wrote the repository, from its lock; the pinned one when there is none. */ +export function flowapiVersion(dir) { + try { + const lock = JSON.parse(readFileSync(join(dir, '.flowapi', 'lock.json'), 'utf8')) + if (typeof lock.flowapi === 'string' && /^[0-9A-Za-z.+-]+$/.test(lock.flowapi)) + return lock.flowapi + } catch { + // no lock yet, or a broken one: the pinned version + } + return FLOWAPI_VERSION +} diff --git a/plugins/flowapi/lib/run.mjs b/plugins/flowapi/lib/run.mjs new file mode 100644 index 0000000..496b9b9 --- /dev/null +++ b/plugins/flowapi/lib/run.mjs @@ -0,0 +1,81 @@ +// Running one command for the judge: stdout and stderr together in the order they came, a time +// limit that ends the whole process group, and the exit code. Never throws: a command that cannot +// start is reported like one that failed. + +import { spawn } from 'node:child_process' + +/** How much output is kept per command; the report shows only its first lines. */ +const KEEP_BYTES = 256 * 1024 + +/** + * Runs `file` with `args` in `cwd`; with `shell`, `file` is a whole command line for the system + * shell and `args` is empty. Resolves to `{ code, signal, timedOut, output }`. + */ +export function run( + file, + args, + { cwd, env = process.env, timeoutMs = 600_000, shell = false } = {}, +) { + return new Promise((resolve) => { + const chunks = [] + let kept = 0 + let timedOut = false + const keep = (chunk) => { + if (kept >= KEEP_BYTES) return + chunks.push(chunk.subarray(0, KEEP_BYTES - kept)) + kept += chunk.length + } + let child + try { + child = spawn(file, args, { + cwd, + env, + shell, + stdio: ['ignore', 'pipe', 'pipe'], + detached: process.platform !== 'win32', // its own group, so a time limit ends its children too + windowsHide: true, + }) + } catch (error) { + resolve({ code: null, signal: null, timedOut, output: `could not start: ${error.message}\n` }) + return + } + const timer = setTimeout(() => { + timedOut = true + stop(child) + }, timeoutMs) + child.stdout.on('data', keep) + child.stderr.on('data', keep) + let startError = null + child.on('error', (error) => { + startError = error + }) + child.on('close', (code, signal) => { + clearTimeout(timer) + let output = Buffer.concat(chunks).toString('utf8') + if (startError) output += `could not start: ${startError.message}\n` + resolve({ code: startError ? null : code, signal, timedOut, output }) + }) + }) +} + +function stop(child) { + try { + if (process.platform === 'win32') child.kill() + else process.kill(-child.pid, 'SIGKILL') + } catch { + // already gone + } +} + +/** The first `lines` lines of `text`, with a note of how many were left out. */ +export function head(text, lines = 40) { + const all = text.replace(/\s+$/, '').split('\n') + if (all.length <= lines) return all.join('\n') + return `${all.slice(0, lines).join('\n')}\n… ${all.length - lines} more lines` +} + +/** Quotes one argument for the system shell. */ +export function shellQuote(value) { + if (process.platform === 'win32') return `"${value.replace(/"/g, '""')}"` + return `'${value.replace(/'/g, `'\\''`)}'` +} diff --git a/plugins/flowapi/lib/tools.mjs b/plugins/flowapi/lib/tools.mjs new file mode 100644 index 0000000..37cc65b --- /dev/null +++ b/plugins/flowapi/lib/tools.mjs @@ -0,0 +1,33 @@ +// The tools the judge runs, at the versions it pins, and the one way to replace them in tests. + +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +/** The plugin's folder. */ +export const ROOT = fileURLToPath(new URL('..', import.meta.url)) + +/** + * The flowapi the plugin runs, from `lib/flowapi-version`, the one place it is written: `bin/flowapi` + * reads it too. The judge regenerates with the version a repository's lock names, else this one. + */ +export const FLOWAPI_VERSION = readFileSync(new URL('flowapi-version', import.meta.url), 'utf8').trim() +export const PUBLINT = 'publint@0.3.25' +export const ATTW = '@arethetypeswrong/cli@0.18.5' + +/** + * The `npx` the judge calls. `FLOWAPI_PLUGIN_NPX` names another program with the same arguments: + * the tests put a stand-in there, so no step reaches the network. + */ +export function npx(env = process.env) { + return env.FLOWAPI_PLUGIN_NPX || 'npx' +} + +/** + * The generate command when none is given: `{out}` is the folder, `{flowapi}` the version. + * `FLOWAPI_PLUGIN_FLOWAPI` replaces flowapi here as in `bin/flowapi`, so step 0 regenerates with the + * flowapi the agent used. + */ +export function defaultGenerate(env = process.env) { + const flowapi = env.FLOWAPI_PLUGIN_FLOWAPI || `${npx(env)} -y @localix-ai/flowapi@{flowapi}` + return `${flowapi} generate flowapi-sdk.yml --out {out}` +} diff --git a/plugins/flowapi/lib/tree.mjs b/plugins/flowapi/lib/tree.mjs new file mode 100644 index 0000000..3cd42ce --- /dev/null +++ b/plugins/flowapi/lib/tree.mjs @@ -0,0 +1,41 @@ +// Comparing two generated trees byte for byte: the judge's determinism step. + +import { lstatSync, readFileSync, readdirSync, readlinkSync } from 'node:fs' +import { join } from 'node:path' + +/** Every entry under `root` as `relative path → { kind, bytes | target }`, paths with `/`. */ +export function listTree(root) { + const entries = new Map() + const walk = (dir, prefix) => { + for (const name of readdirSync(dir).sort()) { + const full = join(dir, name) + const rel = prefix ? `${prefix}/${name}` : name + const stat = lstatSync(full) + if (stat.isDirectory()) walk(full, rel) + else if (stat.isSymbolicLink()) entries.set(rel, { kind: 'link', target: readlinkSync(full) }) + else entries.set(rel, { kind: 'file', bytes: readFileSync(full) }) + } + } + walk(root, '') + return entries +} + +/** The differences between two trees, one line each, sorted; empty when they are equal. */ +export function compareTrees(first, second) { + const a = listTree(first) + const b = listTree(second) + const differences = [] + for (const [rel, entry] of a) { + const other = b.get(rel) + if (!other) differences.push(`only in the first run: ${rel}`) + else if (!sameEntry(entry, other)) differences.push(`differs: ${rel}`) + } + for (const rel of b.keys()) if (!a.has(rel)) differences.push(`only in the second run: ${rel}`) + return { files: a.size, differences: differences.sort() } +} + +function sameEntry(x, y) { + if (x.kind !== y.kind) return false + if (x.kind === 'link') return x.target === y.target + return x.bytes.equals(y.bytes) +} diff --git a/plugins/flowapi/package.json b/plugins/flowapi/package.json new file mode 100644 index 0000000..35b91f8 --- /dev/null +++ b/plugins/flowapi/package.json @@ -0,0 +1,17 @@ +{ + "name": "flowapi-plugin", + "version": "0.2.0", + "private": true, + "description": "Types and SDKs from API descriptions with flowapi: the library's documentation for any agent, and a pipeline that writes a TypeScript SDK repository from an OpenAPI description, checked by a deterministic judge.", + "type": "module", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "scripts": { + "test": "node --test test/*.test.mjs", + "test:e2e": "FLOWAPI_PLUGIN_E2E=1 node --test test/e2e.test.mjs", + "docs": "node scripts/docs.mjs", + "validate": "claude plugin validate . --strict" + } +} diff --git a/plugins/flowapi/plugin.json b/plugins/flowapi/plugin.json new file mode 100644 index 0000000..1326500 --- /dev/null +++ b/plugins/flowapi/plugin.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.1.0/plugin.schema.json", + "name": "flowapi", + "displayName": "flowapi", + "version": "0.2.0", + "description": "Types and SDKs from API descriptions with flowapi: the library's documentation for any agent, and a pipeline that writes a TypeScript SDK repository from an OpenAPI description, checked by a deterministic judge.", + "author": { + "name": "Localix Lab" + }, + "homepage": "https://github.com/localixai/flowapi", + "repository": "https://github.com/localixai/flowapi", + "license": "MIT", + "keywords": [ + "openapi", + "json-schema", + "typescript", + "rust", + "sdk", + "codegen", + "agents" + ] +} diff --git a/plugins/flowapi/scripts/docs.mjs b/plugins/flowapi/scripts/docs.mjs new file mode 100755 index 0000000..c4b433c --- /dev/null +++ b/plugins/flowapi/scripts/docs.mjs @@ -0,0 +1,124 @@ +#!/usr/bin/env node +// The `flowapi` skill's references, copied from flowapi's own docs. The docs stay where they are +// (the README, the npm package's README, the commands' help) and are the source of truth; an +// installed plugin is a copy of this folder alone and cannot read a file outside it (Agent Plugins +// core 1.1.0 §4.1), so the skill carries copies. Each starts with one line naming its source. +// Relative links are made absolute on GitHub so they still work in the copy. +// +// node scripts/docs.mjs write skills/flowapi/references/*.md +// node scripts/docs.mjs --check write nothing; exit 1 and name each reference that differs + +import { readFileSync, readdirSync, writeFileSync } from 'node:fs' +import { join, posix } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** This plugin's folder, and the repository it sits in. */ +export const PLUGIN = fileURLToPath(new URL('..', import.meta.url)) +export const REPO = join(PLUGIN, '..', '..') +export const OUT = join(PLUGIN, 'skills', 'flowapi', 'references') +const BLOB = 'https://github.com/localixai/flowapi/blob/main/' + +/** Each reference: its file name and the parts it is made of, in order. */ +export const REFERENCES = [ + { name: 'use.md', parts: [{ kind: 'section', path: 'README.md', heading: '## Use' }] }, + { + name: 'conformance.md', + parts: [{ kind: 'section', path: 'README.md', heading: '## How it holds to the specification' }], + }, + { name: 'npm.md', parts: [{ kind: 'file', path: 'npm/README.md' }] }, + { + name: 'cli.md', + title: '# The `flowapi` command', + parts: [ + { kind: 'help', path: 'crates/flowapi-cli/src/args.rs', heading: '## The Rust command' }, + { kind: 'help', path: 'npm/src/cli.ts', heading: '## The npm command' }, + ], + }, +] + +/** Every reference's text, by file name. Throws when a source is not where it is expected. */ +export function render(repo = REPO) { + const out = new Map() + for (const ref of REFERENCES) { + const sources = ref.parts.map((part) => part.path) + const header = `` + const body = ref.parts.map((part) => renderPart(repo, part)) + const blocks = [header, ...(ref.title ? [ref.title] : []), ...body] + out.set(ref.name, `${blocks.join('\n\n')}\n`) + } + return out +} + +function renderPart(repo, part) { + const text = readFileSync(join(repo, part.path), 'utf8').replace(/\r\n/g, '\n') + if (part.kind === 'file') return absoluteLinks(text.trimEnd(), part.path) + if (part.kind === 'section') return absoluteLinks(section(text, part), part.path) + return `${part.heading}\n\n\`\`\`text\n${helpText(text, part.path)}\n\`\`\`` +} + +/** The section that starts at `heading`, up to the next heading of the same level. */ +function section(text, { path, heading }) { + const lines = text.split('\n') + const start = lines.indexOf(heading) + if (start < 0) throw new Error(`${path}: no line "${heading}"`) + const level = heading.indexOf(' ') + const prefix = `${'#'.repeat(level)} ` + let end = lines.findIndex((line, i) => i > start && line.startsWith(prefix)) + if (end < 0) end = lines.length + return lines.slice(start, end).join('\n').trimEnd() +} + +/** The help text a command prints: the Rust `HELP` string, or the TypeScript template literal. */ +function helpText(text, path) { + const rust = /const HELP: &str = "\\\n([\s\S]*?)";\n/.exec(text) + if (rust) { + if (rust[1].includes('\\')) throw new Error(`${path}: HELP holds an escape; read it by hand`) + return rust[1] + } + const ts = /const HELP = `([\s\S]*?)`\n/.exec(text) + if (!ts) throw new Error(`${path}: no HELP text`) + if (/\\[^`]|\$\{/.test(ts[1])) throw new Error(`${path}: HELP holds more than \\\` escapes`) + return ts[1].replaceAll('\\`', '`') +} + +/** Markdown links relative to `from` (and bare `#anchor`s) as absolute links on GitHub. */ +function absoluteLinks(text, from) { + return text.replace(/\]\(([^)\s]+)\)/g, (whole, target) => { + if (/^[a-z][a-z0-9+.-]*:/i.test(target)) return whole + if (target.startsWith('#')) return `](${BLOB}${from}${target})` + return `](${BLOB}${posix.normalize(posix.join(posix.dirname(from), target))})` + }) +} + +function main(argv) { + const check = argv.includes('--check') + const wanted = render() + const stale = [] + for (const [name, text] of wanted) { + const file = join(OUT, name) + let current = null + try { + current = readFileSync(file, 'utf8') + } catch { + current = null + } + if (current === text) continue + stale.push(name) + if (!check) writeFileSync(file, text) + } + const extra = readdirSync(OUT).filter((name) => !wanted.has(name)) + if (check) { + for (const name of stale) process.stderr.write(`stale: ${join('skills/flowapi/references', name)}\n`) + for (const name of extra) process.stderr.write(`not generated: ${join('skills/flowapi/references', name)}\n`) + if (stale.length + extra.length > 0) { + process.stderr.write('run `node scripts/docs.mjs` in plugins/flowapi and commit the result\n') + process.exitCode = 1 + } + } else { + for (const name of stale) process.stdout.write(`wrote ${join('skills/flowapi/references', name)}\n`) + for (const name of extra) process.stderr.write(`not generated, remove it: ${name}\n`) + if (extra.length > 0) process.exitCode = 1 + } +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) main(process.argv.slice(2)) diff --git a/plugins/flowapi/skills/flowapi/SKILL.md b/plugins/flowapi/skills/flowapi/SKILL.md new file mode 100644 index 0000000..b5804d5 --- /dev/null +++ b/plugins/flowapi/skills/flowapi/SKILL.md @@ -0,0 +1,54 @@ +--- +name: flowapi +description: How to use flowapi, which makes types from API descriptions - Swagger 2.0, OpenAPI 3.0 to 3.2 and JSON Schema into TypeScript or Rust (serde) types, optionally with request and response functions per operation (--sdk), from the command line or the npm API (@localix-ai/flowapi - generate, summary, configDraft, configCheck, configSchema). Use when asked for types or a client from an OpenAPI or JSON Schema description, to call flowapi or its npm package, or to read its diagnostics. +--- + +# flowapi + +flowapi reads an API description into a graph of types and prints it as TypeScript or as Rust +(serde). Every value a schema accepts, its type accepts: where a language has no type for a +keyword (`pattern`, `minimum`, `uniqueItems`), the type is wider and a comment above it says +`Not checked by this type: pattern.` It reads Swagger 2.0, OpenAPI 3.0, 3.1 and 3.2 and JSON +Schema (2020-12 unless `$schema` names another draft), in JSON or YAML, with every file a +relative `$ref` names. + +## Which way + +| The person needs | Use | +| --- | --- | +| Types only | `flowapi openapi.json -o types.ts` (`--target rust -o src/api.rs` for serde types) | +| Types and a function per operation that writes its request and one that reads its response, with no HTTP library | `--sdk` on the same command; Rust: `--target rust --sdk` | +| A whole SDK repository: client classes per resource, retries, pagination, a mock server, tests, package, CI | The `sdk` skill (`/flowapi:sdk [folder]` in Claude Code): `flowapi-sdk.yml`, then `flowapi generate` | +| Types from code (a build step, a browser, a bundler) | The npm API: `generate(text, { output })`, `generateFile(path)` from `@localix-ai/flowapi/node` | + +## Running it + +- From npm, no install: `npx -y @localix-ai/flowapi openapi.json -o types.ts`. Inside this + plugin, `${CLAUDE_PLUGIN_ROOT}/bin/flowapi` is that command at the version the plugin pins. +- The npm command prints TypeScript only. `--target rust` is the Rust command's: + `cargo install --locked --git https://github.com/localixai/flowapi --tag v flowapi-cli`. +- `flowapi --version` prints the version. Both commands print the same bytes for the same input. + +## Diagnostics + +Each is `error[]: ` or `warning[]: ...`, then `at ::`, +on standard error. An error writes no output and exits 1; warnings write the output and exit 0 +(`--quiet` hides them). From the npm API, `files` is empty when a diagnostic is an error, and each +diagnostic has `severity`, `code`, `message`, `uri`, `offset`, `line` and `column` +(`formatDiagnostic` prints it as the command does). Fix the description or the `$ref` the error +names; never edit the printed file, which says `Do not edit: generate again.` + +## References + +Read only the one the task needs: + +- [references/cli.md](references/cli.md): every flag and subcommand of both commands, their help + as printed. +- [references/use.md](references/use.md): what is printed, YAML, `$ref` resolution, the + TypeScript and Rust `--sdk` functions (parameters, bodies, multipart, responses, the errors they + refuse with), `summary` and `config`, and `generate`'s repository and lock. +- [references/npm.md](references/npm.md): the npm package's API (`generate`, `load`, + `summary`, `configDraft`, `configCheck`, `configSchema`, `repoFiles`, `repoPlan`), its two + WebAssembly modules and bundlers. +- [references/conformance.md](references/conformance.md): how the types are held to the + specification, and the one TypeScript limit to know. diff --git a/plugins/flowapi/skills/flowapi/references/cli.md b/plugins/flowapi/skills/flowapi/references/cli.md new file mode 100644 index 0000000..31f70e6 --- /dev/null +++ b/plugins/flowapi/skills/flowapi/references/cli.md @@ -0,0 +1,87 @@ + + +# The `flowapi` command + +## The Rust command + +```text +flowapi: types from an OpenAPI description or a JSON Schema + +Usage: flowapi [-o ] [--target ts|rust] [--sdk] [--quiet] + flowapi summary [--tag ] [--path ] [--max-bytes ] + flowapi config draft [-o ] + flowapi config schema + flowapi config check [--spec ] [--json] + flowapi generate --out [--check] + + -o, --output where to write the types (standard output by default) + -t, --target the language of the types: ts (the default) or rust (serde) + --sdk also a function per operation that writes its request and one that + reads its response, with no HTTP library and no I/O (Rust: serde and + serde_json only, as the types) + -q, --quiet print errors only, not warnings + -h, --help this help + -V, --version the version + +The description is Swagger 2.0, OpenAPI 3.0, 3.1 or 3.2, or a JSON Schema (2020-12 when it names no +$schema), in JSON or YAML (.yaml, .yml, or any text not opening with { or [). Files its +$refs name by a relative path are read too. + +For an SDK's config, flowapi-sdk.yml, which an agent writes: + summary the description in compact JSON: operations with their parameters, media + types and the pagination they look like they have; over --max-bytes (60000) + the tags alone, to be read on by --tag or --path + config draft a first config, every operation in a resource, as YAML + config schema the config's format, as JSON Schema + config check every issue of a config against its description (its `spec`, relative to the + config, or --spec): text, or JSON with --json; exits 1 on an error + generate the SDK's repository into --out: the client, package.json, scripts, tests + against a mock server, README.md, api.md, and .flowapi/lock.json, the hash of + each file written. A generated file changed by hand since (src/lib/ and + examples/ are yours) is a conflict: nothing is written and it exits 1. A file + no longer generated is deleted unless changed; one the lock does not list is + never touched. --check writes nothing and exits 1 when the output differs + +A description named `summary`, `config` or `generate` is read by its path: `flowapi ./summary`. +``` + +## The npm command + +```text +flowapi: types from an OpenAPI description or a JSON Schema + +Usage: flowapi [-o ] [--sdk] [--quiet] + flowapi summary [--tag ] [--path ] [--max-bytes ] + flowapi config draft [-o ] + flowapi config schema + flowapi config check [--spec ] [--json] + flowapi generate --out [--check] + + -o, --output where to write the types (standard output by default) + --sdk also a function per operation that writes its request and one that + reads its response, with no HTTP library and no I/O + -q, --quiet print errors only, not warnings + -h, --help this help + -V, --version the version + +The description is Swagger 2.0, OpenAPI 3.0, 3.1 or 3.2, or a JSON Schema (2020-12 when it names no +$schema), in JSON or YAML (.yaml, .yml, or any text not opening with { or [). Files its +$refs name by a relative path are read too. + +For an SDK's config, flowapi-sdk.yml, which an agent writes: + summary the description in compact JSON: operations with their parameters, media + types and the pagination they look like they have; over --max-bytes (60000) + the tags alone, to be read on by --tag or --path + config draft a first config, every operation in a resource, as YAML + config schema the config's format, as JSON Schema + config check every issue of a config against its description (its `spec`, relative to the + config, or --spec): text, or JSON with --json; exits 1 on an error + generate the SDK's repository into --out: the client, package.json, scripts, tests + against a mock server, README.md, api.md, and .flowapi/lock.json, the hash of + each file written. A generated file changed by hand since (src/lib/ and + examples/ are yours) is a conflict: nothing is written and it exits 1. A file + no longer generated is deleted unless changed; one the lock does not list is + never touched. --check writes nothing and exits 1 when the output differs + +A description named `summary`, `config` or `generate` is read by its path: `flowapi ./summary`. +``` diff --git a/plugins/flowapi/skills/flowapi/references/conformance.md b/plugins/flowapi/skills/flowapi/references/conformance.md new file mode 100644 index 0000000..eeb1ad7 --- /dev/null +++ b/plugins/flowapi/skills/flowapi/references/conformance.md @@ -0,0 +1,45 @@ + + +## How it holds to the specification + +For every schema in the official +[JSON-Schema-Test-Suite](https://github.com/json-schema-org/JSON-Schema-Test-Suite), flowapi prints +a type, and each test value is written as a literal of that type and handed to the TypeScript +compiler (`strict`, `exactOptionalPropertyTypes`). If the compiler refuses a valid value, the type +is wrong. If it refuses an invalid one, the type caught it. + +| Draft 2020-12 | Result | +| --- | --- | +| Valid values accepted (soundness) | **100.0%** (779 of 779) | +| Invalid values rejected (precision) | 69.0% (373 of 540) | +| Groups that failed to generate, or printed invalid TypeScript | 0 of 409 | + +From [conformance/results/suite.md](https://github.com/localixai/flowapi/blob/main/conformance/results/suite.md). The same measurement, each +schema wrapped as an OpenAPI 3.1 component and each tool run with its defaults +([conformance/results/compare.md](https://github.com/localixai/flowapi/blob/main/conformance/results/compare.md)): + +| Generator | Valid accepted | Invalid rejected | Failed to generate | Invalid TypeScript | +| --- | ---: | ---: | ---: | ---: | +| flowapi 0.1.0 | **100.0%** | **69.0%** | 0 | 0 | +| openapi-typescript 7.13.0 | 90.6% | 51.4% | 7 | 49 | +| @hey-api/openapi-ts 0.99.0 | 94.6% | 42.2% | 7 | 0 | + +TypeScript has no type for some keywords (`pattern`, `minimum`, `uniqueItems`). There the type +accepts more than the schema does, and a comment above it names the keywords it does not check. +Every keyword of every dialect is handled one of three ways: it becomes part of the type, it is +listed in that comment, or it is read as an annotation. The JSON reader is our own and passes +[JSONTestSuite](https://github.com/nst/JSONTestSuite). + +The suite has a few hundred schemas, so two more checks look past it. Thousands of random +schemas and values are generated from fixed seeds; our own validator, flowschema (which passes +the whole suite), says which values are valid, and every valid one must type-check against +flowapi's type ([conformance/results/props.md](https://github.com/localixai/flowapi/blob/main/conformance/results/props.md)). And every valid +example description the OAI keeps beside its schemas generates and type-checks +([conformance/results/oai.md](https://github.com/localixai/flowapi/blob/main/conformance/results/oai.md)). A requirements ledger lists every +MUST, SHOULD and MAY of OpenAPI 3.0.4, 3.1.2, 3.2.1 and JSON Schema 2020-12 that a types +generator answers to, each held by a test or named as something a type cannot state +([conformance/REPORT.md](https://github.com/localixai/flowapi/blob/main/conformance/REPORT.md)). + +One TypeScript limit shows in rare cases: an object literal with a key named like a member +every object inherits (`constructor`, `toString`) is checked against `Object`'s member when the +key is not declared, so `{ constructor: [0] }` can be refused by a type that allows it. diff --git a/plugins/flowapi/skills/flowapi/references/npm.md b/plugins/flowapi/skills/flowapi/references/npm.md new file mode 100644 index 0000000..5024c8c --- /dev/null +++ b/plugins/flowapi/skills/flowapi/references/npm.md @@ -0,0 +1,95 @@ + + +# @localix-ai/flowapi + +TypeScript types from OpenAPI 3.0, 3.1 and 3.2 and JSON Schema that follow the specification: +every value a schema accepts, its type accepts. This is flowapi's Rust generator compiled to +WebAssembly (about 208 KB gzipped), so it runs in Node 20+, Bun, Deno and browsers and has no +runtime dependency. Its output is the `flowapi` command's, byte for byte. What it promises, how +that is checked and how fast it is: [the main README](https://github.com/localixai/flowapi#readme). + +```sh +npx @localix-ai/flowapi openapi.json -o types.ts +``` + +```ts +import { generate } from '@localix-ai/flowapi' +import { generateFile } from '@localix-ai/flowapi/node' + +// The description's text, or [{ uri, text }, ...] with the documents its $refs reach. +const { files, diagnostics } = await generate(text, { output: 'types.ts' }) + +// From disk, with every file a relative $ref names (Node, Bun, Deno), JSON or YAML. +const result = await generateFile('openapi.yaml') +``` + +`files` is empty when a diagnostic is an error. Each diagnostic has its `severity`, `code`, +`message`, the document's `uri`, the byte `offset`, and the `line` and `column` the command +prints (`formatDiagnostic` prints it the same way). + +`load()` returns a generator whose `generate` and `references` are synchronous. The module is +`flowapi.wasm`, found beside the package's code with `new URL('./flowapi.wasm', import.meta.url)`, +which Vite, webpack and Parcel follow. With another bundler, serve +`@localix-ai/flowapi/flowapi.wasm` yourself and pass its URL, its bytes or a compiled +`WebAssembly.Module` to `load(source)` before the first call. + +YAML is read as the `flowapi` command reads it, by the same code: `.yaml` and `.yml` files, and +under any other name a text that does not open with `{` or `[`. A document's `uri` says which, so +give a YAML description as `{ uri: 'openapi.yaml', text }`: bare text is read as JSON, and +`references(text, uri)` takes the URI too. A diagnostic in a YAML document names its YAML line and +column, and a YAML text that JSON cannot hold is an error with the code `yaml.syntax`. The main +README says how YAML maps to JSON. + +## A config for a whole SDK + +The command has the Rust command's commands for an agent that writes an SDK's config, +`flowapi-sdk.yml`, and the SDK's repository from it, with the same arguments, output and exit +codes: + +```sh +npx -y @localix-ai/flowapi summary openapi.json --tag pets # the operations in compact JSON +npx -y @localix-ai/flowapi config draft openapi.json -o flowapi-sdk.yml # a first config +npx -y @localix-ai/flowapi config check flowapi-sdk.yml --json # every issue; 1 on an error +npx -y @localix-ai/flowapi config schema > flowapi-sdk.schema.json +npx -y @localix-ai/flowapi generate flowapi-sdk.yml --out sdk # the whole repository +npx -y @localix-ai/flowapi generate flowapi-sdk.yml --out sdk --check # 1 when it differs +``` + +`generate` writes the same files, byte for byte, and the same `.flowapi/lock.json` as the Rust +command, by the same rules: all or nothing (each file staged beside its target first); a +generated file changed by hand since is a conflict that writes nothing and exits 1, except under +`src/lib/` and `examples/`, which are yours and kept; a file the lock does not list is never +touched; one no longer generated is deleted unless changed, kept with a warning when it was; a +path out of `--out` or through a symbolic link is refused. Which of those applies is decided in +the module, by the code the Rust command runs; the package only reads the disk (SHA-256 by +`node:crypto`) and makes the changes. + +`summary` stays under `--max-bytes` (60000): over it, it gives the tags with their counts, to be +read one at a time with `--tag` or `--path`. `config check` reads the description the config's +`spec` names, relative to the config, or the one `--spec` names; it does not fetch a URL. + +The same from the API, over documents you read (`readDescription` reads them from disk): + +```ts +import { configCheck, configDraft, configSchema, summary } from '@localix-ai/flowapi' + +const { text } = await summary(documents, { tag: 'pets', maxBytes: 60_000 }) // null: not OpenAPI +const draft = await configDraft(documents, '../openapi.json') // `spec` as the config will name it +const found = await configCheck({ uri: 'flowapi-sdk.yml', text: yaml }, documents) +// found.ok, found.issues: [{ severity, code, pointer, line, column, message, hint? }], +// found.text and found.json: the issues as `config check` and `config check --json` print them. +const schema = await configSchema() +``` + +`generate`'s two halves are there too, with no disk: `repoFiles(config, documents, lock?)` gives +every file of the repository, its new lock and the paths to look at, and `repoPlan(...)`, given +what is at each of them, the changes to make, the conflicts and what the command prints. + +They are a second module, `flowapi-sdk.wasm` (about 413 KiB gzipped), compiled the first time +one of them is called; the types' `generate` never loads it. `loadSdk(source)` loads it as `load` loads the first +(serve `@localix-ai/flowapi/flowapi-sdk.wasm` with a bundler that does not copy it) and gives them +synchronous, with `configSpec(config)`: the `spec` a config names, for the host to read before +`configCheck`, and `repoFiles` and `repoPlan`. A config or a document that cannot be read gives no text and one diagnostic, as +`generate` does. + +MIT diff --git a/plugins/flowapi/skills/flowapi/references/use.md b/plugins/flowapi/skills/flowapi/references/use.md new file mode 100644 index 0000000..9fc34fd --- /dev/null +++ b/plugins/flowapi/skills/flowapi/references/use.md @@ -0,0 +1,247 @@ + + +## Use + +From npm, the same generator compiled to WebAssembly, reading JSON and YAML alike +([npm/README.md](https://github.com/localixai/flowapi/blob/main/npm/README.md) has its API): + +```sh +npx @localix-ai/flowapi openapi.json -o types.ts +``` + +It has the commands for an SDK's config too (`summary`, `config draft|schema|check`, below), with +the Rust command's output byte for byte, and `generate` (below) the same files, lock included. + +The Rust command, built from a release tag: + +```sh +cargo install --locked --git https://github.com/localixai/flowapi --tag v0.2.0 flowapi-cli +flowapi openapi.json -o types.ts +``` + +The crates are not on crates.io. A program takes them from the repository at a tag: + +```toml +[dependencies] +flowapi = { git = "https://github.com/localixai/flowapi", tag = "v0.2.0" } +flowapi-ts = { git = "https://github.com/localixai/flowapi", tag = "v0.2.0" } +``` + +In a checkout, `cargo run --release -p flowapi-cli -- openapi.json -o types.ts` does the same. + +```ts +// One type for each component schema and each operation, and Paths: +export type Pet = { + /** Unique within the store. */ + id: number; + kind: "cat" | "dog"; + tags?: [string, ...string[]]; + [key: `x-${string}`]: string; +}; +export type GetPet = { + parameters: { + path: { + id: number; + }; + }; + responses: { + "200": { + headers: { + "X-Rate-Limit": number; + }; + content: { + "application/json": Pet; + }; + }; + }; +}; +export type Paths = { + "/pets/{id}": { + get: GetPet; + }; +}; +``` + +If the schema lets an object hold other properties, its type has an index signature for them. +Swagger 2.0 descriptions are read too, into the same types as 3.x: `definitions` are the named +types, a `body` or `formData` parameter is the request body under each media type the +operation consumes, and a response's `schema` is its content under each type it produces. +A relative `$ref` resolves against the document's own URI: the path you give the command, or +the URI the library is given with each document; flowapi assumes no other base. +Files that a `$ref` names by relative path are read too, and so are YAML descriptions (`.yaml`, +`.yml`, or any file that does not open with `{` or `[`). YAML is read as JSON's data model under +YAML 1.2's core schema: a key that is not a string becomes its JSON text (`200:` is `"200"`) and +anchors are expanded. What JSON cannot hold is an error with the YAML line and column: `.inf` +and `.nan`, a mapping as a key, a repeated key, `<<` merge keys, a second document, or aliases +that would copy more than a million nodes (code `yaml.syntax`). The YAML reader is one crate +(`crates/flowapi-yaml`) the command and the npm package share, and it passes the YAML test suite +(`crates/flowapi-yaml/tests/yaml_suite.rs`). + +### An SDK, with no HTTP library + +`--sdk` adds two functions per operation after the types: `Request(input)` writes the request +and sends nothing, `Response(status, headers, body)` reads the answer you got back. Use any +HTTP client, or none in a test. + +```sh +cargo run --release -p flowapi-cli -- openapi.json --sdk -o api.ts +``` + +```ts +const r = getPetRequest({ path: { id: 7 }, query: { tags: ["a b", "c"] } }) +// { method: "GET", path: "/pets/7", query: "tags=a%20b&tags=c", headers: {} } +const res = await fetch(base + r.path + (r.query && "?" + r.query), r) +const body = new Uint8Array(await res.arrayBuffer()) +const out = getPetResponse(res.status, Object.fromEntries(res.headers), body) +if (out.response === "200") out.body // Pet, parsed from JSON + +const up = uploadPhotoRequest({ + path: { id: 7 }, + body: { contentType: "multipart/form-data", value: { photo: await flowapiBlob(file), tags: ["a", "b"] } }, +}) +// up.headers["content-type"]: "multipart/form-data; boundary=flowapi-<32 hex digits>" +// up.body: a Uint8Array, a part `photo` with the file's name and type, then `tags` twice +``` + +Parameters are written as their `style`, `explode` and `allowReserved` say (`simple`, `label`, +`matrix`, `form`, `spaceDelimited`, `pipeDelimited`, `deepObject` and 3.2's `cookie`; Swagger +2.0's `collectionFormat` read as those), percent-encoded per RFC 3986 everywhere but headers and +`style: cookie`, which pass as given; a parameter with `content` as its media type's text; cookies +into one `cookie` header. The body is `{ contentType, value }` of one of the operation's media +types: JSON, a form, text as given, or bytes (a `Uint8Array`, for a type neither JSON, text nor a +form, sent as they are). A `multipart/form-data` body is written from its members as the +Encoding Object's defaults say: a `Uint8Array` or a file a file part (`filename` its last path +segment, `blob` when it has none; `application/octet-stream` when it has no type), a string, +number or boolean a text part, an object JSON, an array's items one part each under its name, in +order (RFC 7578, 4.3); `undefined` is left out, `null` refused. A file is +`flowapiFile(bytes or text, name, type)`, or `await flowapiBlob(blobOrFile)`, the one step that +waits: `Request` takes bytes and stays synchronous. The description's `encoding` is not read +yet: give it as the body's `encoding` (`{ photo: { contentType, headers } }`); its `contentType` +replaces the default (a file's own type replaces it, and a list or a range needs one) and its +`headers` go into the part. The boundary is the content type's (`; boundary=`), else 128 random +bits from `globalThis.crypto`, drawn again while a part holds them and added to the request's +`content-type`; `body` is then bytes. 3.2's array of objects is written as its parts in order; +another multipart type is yours to write, as a string or bytes. A response is picked +by its status (the code, then `2XX`, then `default`) and its `Content-Type`, and its body, given as +text or as bytes, read by the type sent as the Rust SDK reads it: JSON parsed (a leading byte +order mark skipped), `text/*` a `string`, any other a `Uint8Array`, a media range any of those +its range allows. Bytes given for JSON or text are read as UTF-8; a string given for a binary type +is encoded as UTF-8, so give bytes (a string decoded from them has lost what was not UTF-8). +What the description does not name, and a JSON or text body that is not UTF-8 or not JSON, comes +back as `response: null` with the body as given. `flowapiReadsBytes(contentType)` (exported) +says which bodies are read as bytes, for a client that reads the others with `text()`. +`Request` throws a `FlowapiRequestError` (exported, with `location`, `parameter` and +`reason`) rather than write a request that would mean something else: a CR, LF or NUL in a header +or a `style: cookie` value (`control-character`), a path parameter that leaves its segment empty +or makes it `.` or `..` (`empty-segment`, `dot-segment`; `%2E` is a dot too), NaN or an infinity +anywhere in a parameter or a JSON or form body (`non-finite`: JSON has no such number, and +`JSON.stringify` would write `null`). In a multipart body (`parameter` the part's name) it also +refuses a CR, LF or NUL in a part's name, file name, type or header, `null` (`null`), a `"` or `\` +in a name or a file name (`quote`: RFC 7578 and WHATWG escape them differently), a file name that +is empty, `.` or `..` (`file-name`), a part header's name that is not a token or is +`Content-Disposition` (`header-name`), a list or a range as a part's type (`media-range`), a +Blob not read yet (`unread-blob`), an item of 3.2's array that is not an object (`unnamed-part`), +and a boundary RFC 2046 does not allow or a part holds (`boundary`). A header's name that is not a token is left out of the +operation, with a warning. The output imports nothing: the runtime is a few functions +printed once. With `--sdk` the base URL and any authentication are still yours to add: the +command does not print `servers`, `securitySchemes` or `security`. The SDK layer +(`crates/flowapi-sdk`, the one `generate` writes a client with) reads them, Swagger 2.0's `host`, `basePath` and +`schemes` included, and prints a table to put after this output: the servers with their +variables, the security schemes, and each operation's method, path, own servers, security and +how each response body is read. Every row of the specification's +Style Examples table, the pitfalls other generators fixed, and the SDKs of GitHub's, Stripe's and +Cloudflare's descriptions are run or type-checked +([conformance/results/sdk.md](https://github.com/localixai/flowapi/blob/main/conformance/results/sdk.md)); writing a request against +openapi-fetch's serializers: [bench/results/sdk.md](https://github.com/localixai/flowapi/blob/main/bench/results/sdk.md). + +For Rust, `--target rust --sdk` prints the same after the serde types: per operation an input +struct, `_request(&input)`, which returns an `sdk::Request` (method, path, query, headers, and +the body's content type and bytes) or an `sdk::RequestError` for what the TypeScript SDK refuses, +with the same `reason` codes (`Reason::code()`), and `_response(status, headers, body)`, which returns an +enum of the operation's responses or an `sdk::Error` holding the answer. No I/O, no async; the +runtime is a module printed once (`pub mod sdk`) and needs serde and serde_json, as the types do. + +```sh +cargo run --release -p flowapi-cli -- openapi.json --target rust --sdk -o src/api.rs +``` + +```rust +let r = api::get_pet_request(&api::GetPetInput { parameters: params })?; +// sdk::Request { method: "GET", path: "/pets/7", query: "tags=a%20b&tags=c", headers: [], body: None } +let res = client.get(format!("{base}{}?{}", r.path, r.query)).send()?; +let headers: Vec<(String, String)> = /* the answer's headers as text */; +match api::get_pet_response(res.status().as_u16(), &headers, &res.bytes()?)? { + api::GetPetResponse::Status200(pet) => { /* Pet, read by serde_json */ } + api::GetPetResponse::Default(status, body) => { /* any other status, and its bytes */ } +} +``` + +Each parameter is written by the same rules, through a serde `Serializer` that writes straight +into the request; members of a struct go in the order its schema names them, a map's +(`additionalProperties`) in key order. The body is an enum of the media types: JSON and form +bodies take their type, a multipart body or a media range its content type and bytes, any other +bytes; parameters of a content type (`; charset=utf-8`) are yours to add to `body`. A response +is an enum variant per status and media type: JSON read into its type (an empty or broken body is +an error, never a default; a leading byte order mark is skipped), `text/*` a `String`, other +bodies bytes; a range or `default` keeps the status. A JSON integer is the printed `Integer`: +exact from `i64::MIN` to `u64::MAX`, past that the whole `f64` serde_json reads it as. The same table, the cases and Rust's own (numbers as JavaScript writes them, integers +past 2^53 exact, enums as their strings) are compiled into one crate and run +([conformance/results/sdk-rust.md](https://github.com/localixai/flowapi/blob/main/conformance/results/sdk-rust.md)); generating the SDK of +GitHub's, Stripe's and Cloudflare's descriptions: +[conformance/results/sdk-rust-corpus.md](https://github.com/localixai/flowapi/blob/main/conformance/results/sdk-rust-corpus.md); writing a +request against progenitor's way: [bench/results/sdk-rust.md](https://github.com/localixai/flowapi/blob/main/bench/results/sdk-rust.md). + +### A config for a whole SDK + +For an agent that writes an SDK's config, `flowapi-sdk.yml` (its resources, a name for each +operation, pagination, environments, authentication), four commands read the description so the +agent does not have to: + +```sh +flowapi summary openapi.json --tag pets # the operations in compact JSON, with the pagination each looks like it has +flowapi config draft openapi.json -o flowapi-sdk.yml # a first config: every operation in a resource +flowapi config check flowapi-sdk.yml --json # every issue at once: code, JSON Pointer, YAML line, hint +flowapi config schema > flowapi-sdk.schema.json # the format as JSON Schema +``` + +`summary` stays under `--max-bytes` (60 KB): over it, it gives the tags with their counts, to be +read one at a time with `--tag` or `--path`. `config check` holds the config to its format (a +member it does not name is an error) and to the description: every operation is in a resource +or in `skip` with a reason, every reference names an operation (a typo names the closest), names +are compared as words (`list_all` and `listAll` are one name), a method's pagination fits its +operation's parameters and response schema, `auth` names the description's security schemes. +A draft passes the check, and the same description written in another order gives the same +draft. A description named `summary` or `config` is read by its path: `flowapi ./summary`. + +From a config that passes the check, the SDK layer prints the client itself in TypeScript +(`flowapi_sdk::client_files`): `src/api.ts` (the `--sdk` output and the +operations table), a class for each resource (`client.pets.photos.list(params, options)`), the +client class with its options, and the runtime in `src/core/`, which needs no dependency and +type-checks with `lib: ["es2022"]` alone. The runtime retries by status and `x-should-retry`, +waits what `retry-after-ms` or `Retry-After` ask (and refuses a wait past `maxRetryDelay`), times +each attempt out with its body read, removes its listener from the caller's `AbortSignal`, sends +the credentials of the first security alternative it can meet, masks them in its logs, refuses a +redirect to another origin unless allowed, reads lists by each pagination scheme with a guard +against a server that loops, and reads server-sent events and JSON lines whatever the chunks. A +call is awaited for its data; `asResponse()` and `withResponse()` give the raw response. + +`flowapi generate` writes the SDK's whole repository around that client: + +```sh +flowapi generate flowapi-sdk.yml --out . # the repository, and .flowapi/lock.json +flowapi generate flowapi-sdk.yml --out . --check # in CI: exits 1 when the output would differ +``` + +It is one package with no dependency at run time and `typescript` as its one development +dependency: built by `tsc` twice, ES modules and CommonJS, each with its types (`exports` sends +`import` and `require` each to its own); POSIX `scripts/` (`build`, `lint`, `test`, `check`, +`mock`); a mock server on `node:http` printed from the description, strict where a client goes +wrong (a path, a method, a required parameter, a body's media type) and answering each operation +with an example of its schema; a `node --test` file per resource calling every method against +it; `README.md` (its counts and examples written from the config, never typed), `api.md`, the +repository's `AGENTS.md`, the license (MIT or Apache-2.0), CI on Node 20, 22 and 24, and +release-please's config. `.flowapi/lock.json` holds the hash of every file written, of the +description and of the config. A generated file changed by hand since is a conflict: nothing is +written and it exits 1; `src/lib/` and `examples/` are the user's, `CHANGELOG.md` is written once, +and a file the lock does not list is never touched. A file no longer generated is deleted unless +changed. Every write is staged first, so a refusal leaves the folder as it was. diff --git a/plugins/flowapi/skills/sdk/SKILL.md b/plugins/flowapi/skills/sdk/SKILL.md new file mode 100644 index 0000000..360dfca --- /dev/null +++ b/plugins/flowapi/skills/sdk/SKILL.md @@ -0,0 +1,79 @@ +--- +name: sdk +description: Build a TypeScript SDK repository from an OpenAPI description with flowapi - write flowapi-sdk.yml, generate, and fix the config until the judge passes - and the rule that generated files change only through flowapi-sdk.yml. Use when asked to make, fix, update or release an SDK, when a file listed in .flowapi/lock.json needs a change, or when the person runs /flowapi:sdk [folder]. +allowed-tools: Bash(${CLAUDE_PLUGIN_ROOT}/bin/flowapi:*) Bash(node ${CLAUDE_PLUGIN_ROOT}/bin/judge.mjs:*) Bash(npm install:*) +--- + +# An SDK repository with flowapi + +flowapi writes every file of the SDK from two inputs: the API's description and +`flowapi-sdk.yml`. You write and fix the config; flowapi and the judge do the rest. + +`F` below is `${CLAUDE_PLUGIN_ROOT}/bin/flowapi`, flowapi at the version this plugin is tested +with; where that variable is not filled in, it is `bin/flowapi` at the root of this plugin, two +folders above this file. The judge is `node ${CLAUDE_PLUGIN_ROOT}/bin/judge.mjs`, beside it. + +When the person ran `/flowapi:sdk`, the arguments are the description (a path or a URL), then the +SDK's folder (`sdk` when not given). + +## The rule + +A file listed in `.flowapi/lock.json` is generated. Never edit, move or delete one: the guard hook +refuses it, and `generate` would call it a conflict. Change the config and generate again. Code of +the person's own goes in `src/lib/` and `examples/`, which flowapi never touches. + +## The pipeline + +1. **Folder.** Create the SDK folder. Copy the description into it, or keep its URL. The config + lives in the folder's root and every command runs from there. +2. **Read the API.** `F summary `: servers, security schemes, each operation with its + parameters, media types and the pagination its response looks like it has (with a reason and + how sure). Over 60 KB it prints the tags alone: read on with `--tag ` or + `--path `, one at a time. +3. **Draft.** `F config draft -o flowapi-sdk.yml`. Every operation lands in a resource, + with the default verbs and the pagination the responses look like. It already passes + `config check`; it is a start, not an answer. +4. **Decide.** What the draft cannot know ([references/config.md](references/config.md) lists + every key): + - Resource names: plural nouns from the domain (`pets`, `invoices`), nested where the paths + nest (`client.pets.photos.list()`), not the description's tags when those are teams or + products. + - Method names: `list`, `create`, `retrieve`, `update`, `delete` for the plain CRUD; a verb + for the rest (`cancel`, `archive`, `search`). A `GET` that is not a collection is not `list` + (`client.health.check()`, not `client.health.list()`). + - Pagination: keep a suggestion only when the response really pages; `pagination: false` on a + method turns a default off. + - `skip`: internal, deprecated or admin operations the SDK should not have, each with its + reason. Never skip an operation only because its name is hard. + - `package.name`, `package.client`, `package.license`, `auth..env_var`, `readme`. +5. **Check.** `F config check flowapi-sdk.yml --json`. Each issue has a `code`, a `pointer` into + the config, a `line` and a `hint`. Fix every error, read every warning, and check again until + `"errors":0`. +6. **Generate.** `F generate flowapi-sdk.yml --out .`. The summary line says what was written, + deleted and left unchanged. Exit 1 with a conflict means a generated file was changed by hand: + report the file and stop; never edit or delete it to get past this. `--check` writes nothing + and exits 1 when the output differs. +7. **Install.** `npm install --no-audit --no-fund` (TypeScript is the one dependency). +8. **Judge.** `node ${CLAUDE_PLUGIN_ROOT}/bin/judge.mjs . --json`. Steps: 0 determinism (generate + twice into empty folders), 1 typecheck, 2 lint, 3 build (ES modules and CommonJS), 4 the built + types, 5 the package (publint, attw), 6 the tests against a mock server made from the + description. A red step is fixed in `flowapi-sdk.yml`, then back to step 5. A red step no + config change can fix is a flowapi bug: report the step and its output. + +Done is the judge's verdict `pass` on steps 0-6. Report the steps with their times, the methods +by resource, what was skipped and why, and what the person decides next (the package name, the +license, publishing). Never edit a generated file, push, or publish. + +In Claude Code, `/flowapi:refine`, `/flowapi:update` and `/flowapi:release` take an SDK made this +way further; the `sdk-reviewer` agent reads its API from a user's side. + +## Issue codes seen often + +| Code | What to do | +| --- | --- | +| `config.coverage` | An operation is in no resource: name it under one, or add it to `skip` with a reason | +| `config.op.unknown` | `op` names no operation: the hint says the closest one | +| `config.schema.unknown` | A key the format does not have: the message lists the keys there | +| `config.generator.version` | The config pins another flowapi: set `generator.flowapi` to the version `F --version` prints | + +The text output names the same issues, one per paragraph, with `at ::`. diff --git a/plugins/flowapi/skills/sdk/references/config.md b/plugins/flowapi/skills/sdk/references/config.md new file mode 100644 index 0000000..ad88a44 --- /dev/null +++ b/plugins/flowapi/skills/sdk/references/config.md @@ -0,0 +1,85 @@ +# `flowapi-sdk.yml`: the catalogue + +Version 1 of the format, as `flowapi config schema` prints it; that schema is the authority. A key +not listed here is an error. + +## Top level + +| Key | Meaning | +| --- | --- | +| `version` | The format's version: `1` | +| `generator.flowapi` | The flowapi version the SDK is generated with (`0.2.0`, or `0.2.x` for any patch) | +| `spec` | The description: a path relative to the config, or a URL | +| `package.name` | The npm package's name (`@acme/sdk`) | +| `package.version` | The package's version, `0.1.0` unless given; the release tool raises it | +| `package.client` | The client class, in PascalCase (`Acme`) | +| `package.license` | An SPDX expression; MIT and Apache-2.0 get their text written | +| `package.repository` | The repository URL, for `package.json` | +| `environments.` | A base URL by name | +| `environments.default` | The environment used when the caller names none | +| `environments.env_var` | The variable that overrides the base URL (`ACME_BASE_URL`) | +| `auth..env_var` | The variable a scheme's credential is read from; `` is its name in the description | +| `defaults.retries` | Retries of a failed request (2) | +| `defaults.timeout` | Seconds a request may take, its body read (60) | +| `defaults.max_retry_delay` | The longest wait in seconds a server may ask for before a retry; longer is an error, not a sleep | +| `defaults.pagination` | The scheme of every method named `list` that names none | +| `pagination.` | A pagination scheme, by a name methods refer to | +| `resources..methods.` | A method: an `operationId`, `"METHOD /path"`, or an object below | +| `resources..resources` | Resources nested under it | +| `skip` | `[{ op, reason }]`: operations the SDK leaves out | +| `readme.headline_method` | The method the README shows first, as `resource.method` | +| `readme.pagination_method` | The method the README shows paging with | +| `readme.intro` | The README's opening paragraph | + +A method as an object: `op` (the operation), `pagination` (a scheme's name, or `false`), +`retries`, `stream: true` (the response is read as server-sent events or JSON lines). + +## Pagination schemes + +Each has `type`, `request` (parameter names) and `response` (paths in the body, `data.items`; the +body itself when `items` is not given). + +| `type` | `request` | `response` | +| --- | --- | --- | +| `cursor` | `cursor`, `limit` | `items`, `next` (the token), `has_more` | +| `last_item_id` | `cursor`, `limit` | `items`, `id` (the item member the next page starts after), `has_more` | +| `offset` | `offset`, `limit` | `items`, `total` | +| `page` | `page`, `per_page`; `start` (first page number) | `items`, `total_pages`, `has_more` | +| `link` | `limit` | `items`; `next` (a URL in the body) or `header` (`Link` with `rel="next"`) | +| `single` | none | `items`: one page, read as a list | + +## Example + +```yaml +version: 1 +generator: { flowapi: "0.2.0" } +spec: openapi.json +package: { name: "@acme/sdk", client: Acme, license: MIT } +environments: + production: https://api.acme.com + sandbox: https://sandbox.acme.com + default: production + env_var: ACME_BASE_URL +auth: + BearerAuth: { env_var: ACME_API_KEY } +pagination: + cursor: + type: cursor + request: { cursor: after, limit: limit } + response: { items: data, next: next_cursor } +resources: + projects: + methods: + list: { op: listProjects, pagination: cursor } + create: createProject + retrieve: getProject + archive: "POST /projects/{project_id}/archive" + resources: + members: + methods: + list: { op: listMembers, pagination: cursor } + remove: { op: removeMember, retries: 0 } +skip: + - { op: "GET /internal/health", reason: not public } +readme: { headline_method: projects.list } +``` diff --git a/plugins/flowapi/test/docs.test.mjs b/plugins/flowapi/test/docs.test.mjs new file mode 100644 index 0000000..844046b --- /dev/null +++ b/plugins/flowapi/test/docs.test.mjs @@ -0,0 +1,34 @@ +// The `flowapi` skill's references are what scripts/docs.mjs writes from flowapi's docs: a +// reference edited by hand, or a source changed without running the script, fails here. +import assert from 'node:assert/strict' +import { existsSync, readFileSync, readdirSync } from 'node:fs' +import { join } from 'node:path' +import { test } from 'node:test' +import { OUT, REPO, render } from '../scripts/docs.mjs' + +const inRepo = existsSync(join(REPO, 'Cargo.toml')) ? false : 'not inside the flowapi repository' + +test('every reference equals what the script writes, and nothing else is there', { skip: inRepo }, () => { + const wanted = render() + assert.deepEqual(readdirSync(OUT).sort(), [...wanted.keys()].sort()) + for (const [name, text] of wanted) { + assert.equal(readFileSync(join(OUT, name), 'utf8'), text, `${name} is stale: node scripts/docs.mjs`) + } +}) + +test('each reference names its source on its first line, and links stay absolute', { skip: inRepo }, () => { + for (const [name, text] of render()) { + assert.match(text.split('\n')[0], /^