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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,30 @@ Every entry says what changed as a caller sees it, why, and what to watch for
never a contract. Braze's collection gives 95 operations from 99 requests (four documented twice). See
[the reference](docs/REFERENCE.md). Watch for: a POST that only reads keeps the write effect its method gives, so
the CLI corrects it with an override.
- **A WordPress list pages by its header.** The page style takes `start` (the first page's number) and `pagesHeader`
(a response header with the number of pages), and `items: ""` when the answer itself is the list.
`wpJsonToOpenApi` returns `overrides` that give every collection read this style, from 1, by `X-WP-TotalPages`;
pass them to `generate`. Before, a WordPress read had no paging, so `api … --all` refused it. Watch for: an executor
that reads `pagination` must handle the two new fields; cli-core does from its next release.
- **A permanent delete gets its own key: `permissions.forceFlags`.** WordPress's `force=true` deletes for good, while a
delete without it moves the item to the trash. `forceFlags: ["force"]` gives such a delete `<group>.delete.force`
besides `<group>.delete`, applying when the flag is `true`, so a CLI can ask before a permanent delete and still
allow the trash. See [the generator's options](docs/standards/kit-surface.md).
- **A publish key covers a date change: `valueKeys[].also`.** WordPress publishes a scheduled post whose `date` moves
into the past, with no `status` in the call. `also: ["date", "date_gmt"]` makes setting either need the key, unless
the call itself sets `status` to a value outside `values` (`draft`, `pending` or `private`). The manifest carries it
as the key's `body` fields with `unless`. Watch for: an executor that does not read `unless` asks for the key on a
draft's date change too, which is safe.
- **A sign-in stays under its site's path: `hostFetch`'s `credentialScope`.** Sites under a path share a host
(`host/blog`, a WordPress multisite in subfolders), and the origin check let a redirect carry the sign-in to
`host/other`. With `credentialScope: "https://host/blog/wp-json"`, a signed request outside it is refused before it
is sent, and a redirect out of it drops `authorization`, `cookie` and `proxy-authorization`. A path with an encoded
slash (`%2F`, `%5C`) counts as outside, as a server that decodes it before routing could leave the scope.

### Changed — may break callers

- **`wpJsonToOpenApi` refuses the `batch/v1` namespace.** A batch call carries requests to other routes in its body,
past the keys those routes need, so a CLI never offers it. A CLI that listed it stops generating.

## 0.119.0 — 18.11.2026

Expand Down
11 changes: 8 additions & 3 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,16 @@ positive byte budget, then decodes strict UTF-8 JSON. It bounds declared length
bytes, cancels on rejection/interruption and releases its own reader. It never fetches or interprets
HTTP status, provider fields or credentials. A caller still owns those policies and its deadline.

`hostFetch({ hosts, fetch?, timeoutMs?, redirects? })` is the `fetch` a CLI sends HTTP through
`hostFetch({ hosts, fetch?, timeoutMs?, redirects?, credentialScope? })` is the `fetch` a CLI sends HTTP through
([WC-CMD-32](standards/commands.md#wc-cmd-32--declare-every-host-the-cli-contacts-and-reach-them-only-through-hostfetch)).
It returns a `FetchLike` that refuses, before anything is sent, a URL whose host is not in `hosts`
(`configuration_error`, reason `network.host-undeclared`, the message naming the host and `hosts`), and any scheme
but http and https. It follows redirects itself, at most `redirects` (5), so every hop is checked; a 303, or a 301
or 302 after a POST, goes on as a GET without the body; a hop to another origin drops `authorization`, `cookie` and
`proxy-authorization`. A caller's `redirect: "manual"` or `"error"` is passed on. `timeoutMs` (30 s,
`proxy-authorization`. A site under a path shares its host with others (`host/blog`, a WordPress multisite in
subfolders): `credentialScope` (`https://host/blog/wp-json`) then limits the sign-in to that origin and path. A request
outside it that carries one of those headers is refused before it is sent (`configuration_error`), and a hop out of it
drops them. A caller's `redirect: "manual"` or `"error"` is passed on. `timeoutMs` (30 s,
`HOST_FETCH_TIMEOUT_MS`) bounds the whole exchange, body included, beside the caller's own `signal`; a timeout is
`timeout` and a failed connection `network_error`. `hostCovered(hostname, hosts)` and `hostProblems(hosts)` are the
matching and the check it uses: `*.acme.example` covers `api.acme.example`, never `acme.example`.
Expand Down Expand Up @@ -289,7 +292,9 @@ template's `theme//slug`, a plugin's `dir/file`) fits no path segment and is lef
namespaces not offered; a route
that is still a pattern, a second route on one path or an argument with no type stops generation, unless `exclude`
names the route with a reason. WordPress answers a list without its page count in the body, so `pagination: true`
finds no paging for it.
finds no paging for it; the result's `overrides`, passed to `generate`, give each collection read the page style from 1
with the count in `X-WP-TotalPages`. The `batch/v1` namespace is refused: one batch call runs other routes' writes
past the keys they need.

**A Postman collection becomes OpenAPI.** `postmanToOpenApi(collection, { variables, exclude, version })` takes a
parsed collection, v2.0 or v2.1, and returns an OpenAPI 3.1 document for `adaptOpenApi` with its `omissions`. Commit
Expand Down
15 changes: 12 additions & 3 deletions docs/standards/kit-surface.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ From the source the generator reads:
empty or not in kebab case stops generation; map that operation in `commands`. `segments` renames a path segment
or, with `""`, leaves it out: `{ "0-3": "deals", crm: "", objects: "" }`. Without `names` the command is the operation
id in kebab case, as before.
- **`permissions`**: `{ group, deletingFlags, shares, valueKeys }`. `group` is a name (`files`) or a function of the operation, for
- **`permissions`**: `{ group, deletingFlags, forceFlags, shares, valueKeys }`. `group` is a name (`files`) or a function of the operation, for
example the first word of its `command` (set only with `names`). Each key lands in the manifest as the operation's `permissions`.
- `<group>.delete` for every destructive operation (Yandex Disk's `DELETE /trash/resources` empties the whole
trash), and for every operation that takes a flag in `deletingFlags`, as a top-level body field (Notion's
Expand All @@ -122,7 +122,14 @@ From the source the generator reads:
`posts.publish` and `pages.publish`. The key applies when the call sends one of those values, in the body or the
query; where the field's default is one of them (a WordPress template), leaving it out publishes too, and the key
always applies. A read that filters by the value gets no key, nor a field of that name without such an enum (a
comment's `status`); a rule no write matches stops generation.
comment's `status`); a rule no write matches stops generation. `also` names fields that make the same change
another way: WordPress publishes a scheduled post whose `date` moves into the past, so with
`also: ["date", "date_gmt"]` setting either needs the key too, unless the call itself sets `field` to another value
its enum lists (for WordPress `draft`, `pending`, `private`). A call that leaves `field` out needs the key: the
stored value is unknown without a read. An `also` field no guarded write takes stops generation.
- `<group>.delete.force` beside `<group>.delete` on every delete that takes a flag in `forceFlags`: WordPress's
`force=true` deletes for good, where a delete without it moves to the trash. The key applies when the flag is
`true`. A flag no delete takes stops generation.

Which flags delete is the CLI's call: read the service's documentation, and count an undocumented flag as a delete.
A flag counts on every method, a GET included: Yandex Disk's upload link is a GET whose `overwrite` replaces a file.
Expand All @@ -134,7 +141,9 @@ From the source the generator reads:
string, so a `start` date is not taken for an offset. Answer fields are dotted paths. Only reads page: a POST
search pages once `readingPosts` or an override makes it a read. An override's
`pagination` sets it where detection misses or misreads, and `pagination: null` says the read does not page; a
parameter the operation does not take stops generation.
parameter the operation does not take stops generation. A page style may say where the first page is (`start: 1`)
and name a response header with the number of pages (`pagesHeader: "x-wp-totalpages"`), with `items: ""` when the
answer itself is the list: WordPress's, which `wpJsonToOpenApi` gives in its `overrides`.
- **`auth`**: `{ securitySchemes, security, reason }` replaces the source's sign-in, the operations' own requirements
included. Yandex Disk's Swagger 1.2 has no scheme, and its header is `Authorization: OAuth <token>`:
`{ oauth: { type: "http", scheme: "OAuth" } }`. HubSpot's spec has no private app token. An operation keeps its own
Expand Down
14 changes: 10 additions & 4 deletions src/codegen/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,12 +197,17 @@ export const coverageGenerator =
const guarded = model.operations.flatMap((operation) =>
(operation.permissions ?? []).map((permission) => ({ id: operation.id, permission })),
)
const when = ({ body, query, values }: OperationPermission) =>
[
...(body ?? []).map((flag) => `body \`${flag}\` is true`),
...(query ?? []).map((flag) => `query \`${flag}\` is true`),
const when = ({ body, query, values, unless }: OperationPermission) => {
const set = [
...Object.entries(values ?? {}).map(([field, listed]) => `\`${field}\` is ${listed.join(" or ")}`),
...(body ?? []).map((flag) => `body \`${flag}\` is ${unless ? "set" : "true"}`),
...(query ?? []).map((flag) => `query \`${flag}\` is ${unless ? "set" : "true"}`),
].join(" or ")
const except = Object.entries(unless ?? {}).map(
([field, listed]) => `the call sets \`${field}\` to ${listed.join(" or ")}`,
)
return except.length > 0 ? `${set}, unless ${except.join(" or ")}` : set
}
const content = [
`# ${options.title}`,
"",
Expand Down Expand Up @@ -241,6 +246,7 @@ export const coverageGenerator =
page.items ? `items \`${page.items}\`` : undefined,
"hasMore" in page && page.hasMore ? `more \`${page.hasMore}\`` : undefined,
"total" in page && page.total ? `total \`${page.total}\`` : undefined,
"pagesHeader" in page && page.pagesHeader ? `pages header \`${page.pagesHeader}\`` : undefined,
].filter(Boolean)
return `| \`${id}\` | ${page.style} | ${request.join(", ") || "—"} | ${answer.join(", ")} | ${cell(paginationSource)} |`
}),
Expand Down
18 changes: 17 additions & 1 deletion src/codegen/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,18 @@ export type Pagination =
limit?: PageParameter
}
| { style: "offset"; offset: PageParameter; limit?: PageParameter; items: string; total?: string }
| { style: "page"; page: PageParameter; limit?: PageParameter; items: string; total?: string }
| {
style: "page"
page: PageParameter
limit?: PageParameter
/** `""` when the answer itself is the list, as WordPress's. */
items: string
total?: string
/** The first page's number, where the source says it (WordPress counts from 1): `--all` then needs none given. */
start?: number
/** A response header holding the number of pages, as WordPress's `X-WP-TotalPages`: that page is the last. */
pagesHeader?: string
}
/** The answer holds the next page's whole URL. */
| { style: "link"; next: string; items?: string }

Expand All @@ -190,6 +201,11 @@ export interface OperationPermission {
* Both places count, as a service that merges them (WordPress) publishes from either.
*/
values?: Readonly<Record<string, readonly string[]>>
/**
* The key does not apply when the call itself sets a field to one of these: `{ status: ["draft", "pending", "private"] }` keeps
* a draft's date change free. A call that leaves the field out still needs the key, as the stored value is unknown.
*/
unless?: Readonly<Record<string, readonly string[]>>
}

/** The scheme names an operation needs, each with its OAuth scopes; one requirement of the list is enough. */
Expand Down
3 changes: 2 additions & 1 deletion src/codegen/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ const SCHEME_TYPES = new Set<SecurityScheme["type"]>(["apiKey", "http", "oauth2"
const FLOWS = ["implicit", "password", "clientCredentials", "authorizationCode"] as const

/** A spec without a single operationId (Attio's) still has calls: `get /v2/objects/{object}` → `getV2ObjectsByObject`. */
const derivedId = (method: string, path: string): string =>
/** The id `adaptOpenApi` gives an operation without an `operationId`: `getWpV2PostsById`. */
export const derivedId = (method: string, path: string): string =>
method +
path
.split("/")
Expand Down
81 changes: 73 additions & 8 deletions src/codegen/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,14 @@ export const applyPagination = (
if (operation.effect !== "read") problems.push(`${at} on an operation that is not a read`)
const request = requestParameters(operation, schemas)
const answer = answerPaths(operation, schemas)
const { style: _, ...fields } = override.pagination as Record<string, unknown>
const { style, start, pagesHeader, ...fields } = override.pagination as Record<string, unknown>
if (start !== undefined && (style !== "page" || !Number.isInteger(start) || (start as number) < 0))
problems.push(`${at}: start must be a whole number from 0, on the page style`)
if (pagesHeader !== undefined && (style !== "page" || typeof pagesHeader !== "string" || pagesHeader === ""))
problems.push(`${at}: pagesHeader must name a header, on the page style`)
for (const [field, value] of Object.entries(fields)) {
// `items: ""`: the answer itself is the list.
if (field === "items" && value === "") continue
if (typeof value === "string") {
// An answer without a schema has nothing to check the path against.
if (answer.size > 0 && !answer.has(value))
Expand Down Expand Up @@ -207,8 +213,17 @@ export interface PermissionRule {
* `enum`, so a field of the same name that means something else (a comment's `status`) gets no key, nor does a read
* that filters by the value. Where the field's default is one of `values` (a WordPress template), leaving it out
* publishes too, and the key always applies.
*
* `also` names fields that make the same change through another door: WordPress publishes a scheduled post whose
* `date` moves into the past. Setting one applies the key too, unless the call itself sets `field` to a value
* outside `values` (a draft's new date); a call that leaves `field` out cannot say what is stored, so it needs the key.
*/
valueKeys?: readonly { key: string; field: string; values: readonly string[] }[]
valueKeys?: readonly { key: string; field: string; values: readonly string[]; also?: readonly string[] }[]
/**
* Flags that make a delete permanent instead of a move to the trash: WordPress's `force`. A delete that takes one
* also needs `<group>.delete.force` when the flag is `true`; without it the trash is `<group>.delete` alone.
*/
forceFlags?: readonly string[]
}

/** The top-level properties a body may carry, through references, inheritance, unions and subtypes. */
Expand Down Expand Up @@ -280,16 +295,38 @@ export const applyPermissionRule = (model: ApiModel, rule: PermissionRule): ApiM
}
const valueKeys = rule.valueKeys ?? []
// A field whose default is one of the values publishes when the call leaves it out: the key then always applies.
const takes = (operation: ApiOperation, names: readonly string[]) => ({
body: names.filter((name) => fieldsOf(operation).has(name)),
query: names.filter((name) =>
operation.parameters.some((parameter) => parameter.in === "query" && parameter.name === name),
),
})
const flagged = ({ body, query }: { body: string[]; query: string[] }) => ({
...(body.length > 0 ? { body } : {}),
...(query.length > 0 ? { query } : {}),
})
const valued = (operation: ApiOperation): OperationPermission[] =>
operation.effect === "read"
? []
: valueKeys.flatMap(({ key, field, values }) => {
: valueKeys.flatMap(({ key, field, values, also = [] }) => {
const { enums, defaults } = valuesOf(operation, field)
const named = values.filter((value) => enums.includes(value))
if (named.length === 0) return []
return defaults.some((value) => values.includes(value as string))
? [{ key }]
: [{ key, values: { [field]: named } }]
if (defaults.some((value) => values.includes(value as string))) return [{ key }]
const others = takes(operation, also)
const unless = [...new Set(enums.filter((value): value is string => typeof value === "string"))].filter(
(value) => !values.includes(value),
)
return [
{
key,
values: { [field]: named },
...flagged(others),
...(others.body.length + others.query.length > 0 && unless.length > 0
? { unless: { [field]: unless } }
: {}),
},
]
})
const idle = valueKeys.filter(
({ key }) => !model.operations.some((operation) => valued(operation).some((one) => one.key === key)),
Expand All @@ -298,6 +335,18 @@ export const applyPermissionRule = (model: ApiModel, rule: PermissionRule): ApiM
throw new CodegenError(
idle.map(({ field, values }) => `valueKeys: no write lists ${values.join(" or ")} in the enum of "${field}"`),
)
// A misspelt `also` would leave the other door open without a word.
const idleAlso = valueKeys.flatMap(({ key, also = [] }) =>
also
.filter(
(name) =>
!model.operations.some((operation) =>
valued(operation).some((one) => one.key === key && (one.body?.includes(name) || one.query?.includes(name))),
),
)
.map((name) => `valueKeys: also "${name}" is in no write that "${key}" guards`),
)
if (idleAlso.length > 0) throw new CodegenError(idleAlso)
const unused = flags.filter(
(flag) =>
!model.operations.some(
Expand All @@ -308,14 +357,30 @@ export const applyPermissionRule = (model: ApiModel, rule: PermissionRule): ApiM
)
if (unused.length > 0)
throw new CodegenError(unused.map((flag) => `deletingFlags: "${flag}" is in no request body or query`))
const forceFlags = rule.forceFlags ?? []
const forcing = (operation: ApiOperation) => takes(operation, forceFlags)
const idleForce = forceFlags.filter(
(flag) =>
!model.operations.some((operation) => {
if (operation.effect !== "destructive") return false
const { body, query } = forcing(operation)
return body.includes(flag) || query.includes(flag)
}),
)
if (idleForce.length > 0)
throw new CodegenError(idleForce.map((flag) => `forceFlags: "${flag}" is in no delete's request body or query`))
return {
...model,
operations: model.operations.map((operation) => {
const group = typeof rule.group === "string" ? rule.group : rule.group(operation)
const permissions: OperationPermission[] = []
if (rule.shares?.includes(operation.id)) permissions.push({ key: `${group}.share` })
if (operation.effect === "destructive") permissions.push({ key: `${group}.delete` })
else {
if (operation.effect === "destructive") {
permissions.push({ key: `${group}.delete` })
const force = forcing(operation)
if (force.body.length + force.query.length > 0)
permissions.push({ key: `${group}.delete.force`, ...flagged(force) })
} else {
const body = flags.filter((flag) => fieldsOf(operation).has(flag))
const query = flags.filter((flag) =>
operation.parameters.some((parameter) => parameter.in === "query" && parameter.name === flag),
Expand Down
Loading
Loading