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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.5.3] - 2026-11-28

### Added

- Generate tree-shakeable OpenAPI adapter groups with `x-adapter-group`, including
each group's JSON validators and a direct client import.

## [0.5.2] - 2026-11-28

### Added
Expand Down
33 changes: 33 additions & 0 deletions docs/generate.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,36 @@ array buffers. Callbacks, webhooks, cookie parameters, response links, and
patterned `2XX` response keys are intentionally rejected with JSON-pointer
diagnostics because the current `@askrjs/fetch` descriptor contract has no
equivalent representation.

## Adapter groups

Set `x-adapter-group` on an operation to include it in a generated group
module. Group names use lowercase kebab case, start with a letter, and can
include digits, up to 252 characters total. Windows device names such as `con` and `com1` are reserved.
Use OpenAPI `tags` independently for documentation.

```yaml
paths:
/stats/kv:
get:
operationId: getKvStats
tags: [Stats, KV]
x-adapter-group: stats
responses:
"204":
description: No content
```

Import a group directly to bundle its endpoints and the runtime validators
they use.

```ts
import { createApiClient as createStatsClient } from "./generated/api/groups/stats";

const stats = createStatsClient({ baseUrl: "https://api.example.com" });
await stats.getKvStats();
```

The main generated entry still exports `api` and `createApiClient` with every
operation. Regenerate after renaming or removing groups to update the owned
output tree.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@askrjs/cli",
"version": "0.5.2",
"version": "0.5.3",
"description": "Unified CLI for the Askr platform",
"homepage": "https://github.com/askrjs/askr-cli#readme",
"bugs": {
Expand Down
237 changes: 181 additions & 56 deletions src/generate/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
references?: SchemaReferenceCollector,
): string {
if (schema.nullable === true) {
const { nullable, ...rest } = schema;

Check warning on line 49 in src/generate/generator.ts

View workflow job for this annotation

GitHub Actions / CI (ubuntu-latest)

eslint(no-unused-vars)

src/generate/generator.ts:49:13: Variable 'nullable' is declared but never used. Unused variables should start with a '_'.

Check warning on line 49 in src/generate/generator.ts

View workflow job for this annotation

GitHub Actions / CI (macos-latest)

eslint(no-unused-vars)

src/generate/generator.ts:49:13: Variable 'nullable' is declared but never used. Unused variables should start with a '_'.

Check warning on line 49 in src/generate/generator.ts

View workflow job for this annotation

GitHub Actions / CI (windows-latest)

eslint(no-unused-vars)

src/generate/generator.ts:49:13: Variable 'nullable' is declared but never used. Unused variables should start with a '_'.
return `(${schemaType(rest, at, direction, references)}) | null`;
}
if (schema.$ref) {
Expand Down Expand Up @@ -145,7 +145,7 @@
return reference(value.$ref, at, direction);
}
if (value.nullable === true) {
const { nullable, ...rest } = value;

Check warning on line 148 in src/generate/generator.ts

View workflow job for this annotation

GitHub Actions / CI (ubuntu-latest)

eslint(no-unused-vars)

src/generate/generator.ts:148:13: Variable 'nullable' is declared but never used. Unused variables should start with a '_'.

Check warning on line 148 in src/generate/generator.ts

View workflow job for this annotation

GitHub Actions / CI (macos-latest)

eslint(no-unused-vars)

src/generate/generator.ts:148:13: Variable 'nullable' is declared but never used. Unused variables should start with a '_'.

Check warning on line 148 in src/generate/generator.ts

View workflow job for this annotation

GitHub Actions / CI (windows-latest)

eslint(no-unused-vars)

src/generate/generator.ts:148:13: Variable 'nullable' is declared but never used. Unused variables should start with a '_'.
return `s.nullable(${render(rest, at)})`;
}
if (Array.isArray(value.type))
Expand Down Expand Up @@ -676,6 +676,12 @@
return Promise.all(value.map((item) => this.expand(item, uri, document, stack)));
if (!value || typeof value !== "object") return value;
const object = value as Json;
// Operation extensions are data. A reference-shaped group value must still
// reach the generator's scalar validation at the operation pointer.
const expandField = (key: string, child: unknown, operationId = object.operationId) =>
key === "x-adapter-group" && typeof operationId === "string"
? child
: this.expand(child, uri, document, stack);
if (typeof object.$ref === "string") {
const resolved = await this.resolveRef(object.$ref, uri, document, stack);
const siblingEntries = Object.entries(object).filter(([key]) => key !== "$ref");
Expand All @@ -685,12 +691,11 @@
? { ...(resolved as Json) }
: {};
for (const [key, child] of siblingEntries)
result[key] = await this.expand(child, uri, document, stack);
result[key] = await expandField(key, child, object.operationId ?? result.operationId);
return result;
}
const result: Json = {};
for (const [key, child] of Object.entries(object))
result[key] = await this.expand(child, uri, document, stack);
for (const [key, child] of Object.entries(object)) result[key] = await expandField(key, child);
return result;
}

Expand Down Expand Up @@ -785,7 +790,43 @@
const source = await readSource(uri, resolved);
return new OpenApiBundler(source.document, source.uri, resolved).bundle();
}
export function generateFiles(document: Json): Record<(typeof OWNED)[number], string> {
function endpointModule() {
return {
schemaReferences: new Set<string>(),
operationReferences: new Set<string>(),
validators: new Map<string, string>(),
imports: new Set<string>(),
usesValidators: false,
endpoints: [] as { id: string; expression: string }[],
};
}

type EndpointModule = ReturnType<typeof endpointModule>;

function renderEndpointDefinitions(module: EndpointModule, parent: string) {
const typeImports = [
["schemas", module.schemaReferences],
["operations", module.operationReferences],
] as const;
const imports = typeImports
.filter(([, names]) => names.size)
.map(
([file, names]) =>
`import type { ${[...names].sort().join(", ")} } from "${parent}/${file}";\n`,
);
const validators = [...module.validators].map(
([name, expression]) =>
`const validate${name}: import("@askrjs/schema").Schema<${name}> = ${expression} as import("@askrjs/schema").Schema<${name}>;`,
);
const schemaImport = module.usesValidators
? 'import { schema as s } from "@askrjs/schema";\n'
: "";
return `${imports.join("")}\n${schemaImport}${validators.join("\n")}\n`;
}

export function generateFiles(
document: Json,
): Record<(typeof OWNED)[number] | `groups/${string}.ts`, string> {
const version = String(document.openapi ?? "");
if (!/^3\.(0|1)\.\d+$/.test(version))
fail(`Unsupported OpenAPI version ${version || "missing"}`, "#/openapi");
Expand Down Expand Up @@ -826,50 +867,64 @@
);
}
const operationSchemaReferences = new Set<string>();
const apiSchemaReferences = new Set<string>();
const apiOperationReferences = new Set<string>();
const contentSchemaReferences: SchemaReferenceCollector = {
requestNames,
add(name) {
operationSchemaReferences.add(name);
apiSchemaReferences.add(name);
},
};
let usesValidators = false;
const validators = new Map<string, string>();
const emitValidator: ValidatorEmitter = (value, at, direction) => {
usesValidators = true;
return validatorExpression(value, at, direction, (ref, location, usage) => {
const original = pointerPart(ref.split("/").at(-1)!);
const base = pascal(original);
const name = usage === "request" ? (requestNames.get(base) ?? base) : base;
if (!Object.hasOwn(schemas, original)) fail("Unknown component reference", location);
apiSchemaReferences.add(name);
if (!validators.has(name)) {
validators.set(name, "");
validators.set(
name,
emitValidator(schemas[original], pointer("components", "schemas", original), usage),
);
}
return `s.raw<${name}>({}, value => validate${name}.safeParse(value))`;
});
};
const ungrouped = endpointModule();
const groups = new Map<string, EndpointModule>();
const orderedEndpoints: { id: string; group?: string; expression: string }[] = [];
const operationTypes: string[] = [];
const descriptors: string[] = [];
const imports = new Set<string>();
const seen = new Set<string>();
for (const path of Object.keys(document.paths ?? {}).sort())
for (const method of METHODS) {
const operation = document.paths[path]?.[method];
if (!operation) continue;
imports.add(method === "delete" ? "del" : method);
const at = pointer("paths", path, method);
const id = operation.operationId;
if (!id || !identifier.test(id))
fail("A unique JavaScript-identifier operationId is required", `${at}/operationId`, id);
if (seen.has(id)) fail("Duplicate operationId", `${at}/operationId`, id);
seen.add(id);
const group: unknown = operation["x-adapter-group"];
let module = ungrouped;
if (group !== undefined) {
if (
typeof group !== "string" ||
group.length > 252 ||
!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?![\s\S])/.test(group) ||
/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(group)
) {
throw new GenerationError(
`${id}: x-adapter-group must be a lowercase kebab-case name of at most 252 characters and cannot be a Windows device name at ${at}/x-adapter-group`,
);
}
module = groups.get(group) ?? endpointModule();
groups.set(group, module);
}
const { imports, validators, schemaReferences, operationReferences } = module;
imports.add(method === "delete" ? "del" : method);
const contentSchemaReferences: SchemaReferenceCollector = {
requestNames,
add(name) {
operationSchemaReferences.add(name);
schemaReferences.add(name);
},
};
const emitValidator: ValidatorEmitter = (value, at, direction) => {
module.usesValidators = true;
return validatorExpression(value, at, direction, (ref, location, usage) => {
const original = pointerPart(ref.split("/").at(-1)!);
const base = pascal(original);
const name = usage === "request" ? (requestNames.get(base) ?? base) : base;
if (!Object.hasOwn(schemas, original)) fail("Unknown component reference", location);
schemaReferences.add(name);
if (!validators.has(name)) {
validators.set(name, "");
validators.set(
name,
emitValidator(schemas[original], pointer("components", "schemas", original), usage),
);
}
return `s.raw<${name}>({}, value => validate${name}.safeParse(value))`;
});
};
if (operation.callbacks) fail("Callbacks are unsupported", `${at}/callbacks`, id);
const parametersByIdentity = new Map<string, Json>();
for (const parameter of [
Expand Down Expand Up @@ -915,7 +970,7 @@
const list = byLocation[location]!.sort((a, b) => a.name.localeCompare(b.name));
if (!list.length) return undefined;
const name = `${prefix}${pascal(location)}`;
apiOperationReferences.add(name);
operationReferences.add(name);
operationTypes.push(
`export type ${name} = {\n${list.map((p) => ` ${JSON.stringify(p.name)}${p.required || location === "path" ? "" : "?"}: ${schemaType(p.schema ?? {}, `${at}/parameters`, "request", { requestNames, add: (name) => operationSchemaReferences.add(name) })};`).join("\n")}\n};`,
);
Expand Down Expand Up @@ -986,26 +1041,92 @@
}
if (operation.security ?? document.security)
chain.push(`security(${JSON.stringify(operation.security ?? document.security)})`);
descriptors.push(` ${id}: ${chain.join("\n .")},`);
const expression = chain.join("\n .");
if (group !== undefined) module.endpoints.push({ id, expression });
orderedEndpoints.push({ id, group, expression });
}
const files = {
const metadata = JSON.stringify(
{
servers: (document.servers ?? []).map((server: Json) => server.url),
securitySchemes: document.components?.securitySchemes ?? {},
},
null,
2,
);
const fetchImports = (module: EndpointModule) =>
`import { ${["defineApi", "createClient", ...[...module.imports].sort()].join(", ")} } from "@askrjs/fetch";\nimport type { ClientOptions } from "@askrjs/fetch";\n`;
const clientFactory =
"export const createApiClient = (options?: ClientOptions) => createClient(api, options);\n";
const groupAliases = new Map([...groups.keys()].map((name, index) => [name, `group${index}`]));
const groupImports = [...groupAliases]
.map(([name, alias]) => `import { builders as ${alias} } from "./groups/${name}";\n`)
.join("");
const descriptors = orderedEndpoints.map(({ id, group, expression }) =>
groups.size
? ` [${JSON.stringify(id)}]: ${group === undefined ? expression : `${groupAliases.get(group)}.${id}()`},`
: ` ${id}: ${expression},`,
);
const files: ReturnType<typeof generateFiles> = {
"schemas.ts": `${schemaLines.join("\n\n")}\n`,
"operations.ts": `${operationSchemaReferences.size ? `import type { ${[...operationSchemaReferences].sort().join(", ")} } from "./schemas";\n\n` : ""}${operationTypes.join("\n\n")}\n`,
"api.ts": `import { ${["defineApi", "createClient", ...[...imports].sort()].join(", ")} } from "@askrjs/fetch";\nimport type { ClientOptions } from "@askrjs/fetch";\n${apiSchemaReferences.size ? `import type { ${[...apiSchemaReferences].sort().join(", ")} } from "./schemas";\n` : ""}${apiOperationReferences.size ? `import type { ${[...apiOperationReferences].sort().join(", ")} } from "./operations";\n` : ""}\n${usesValidators ? 'import { schema as s } from "@askrjs/schema";\n' : ""}${[...validators].map(([name, expression]) => `const validate${name}: import("@askrjs/schema").Schema<${name}> = ${expression} as import("@askrjs/schema").Schema<${name}>;`).join("\n")}\nexport const api = defineApi({\n${descriptors.join("\n")}\n}, ${JSON.stringify({ servers: (document.servers ?? []).map((s: Json) => s.url), securitySchemes: document.components?.securitySchemes ?? {} }, null, 2)});\n\nexport const createApiClient = (options?: ClientOptions) => createClient(api, options);\n`,
"api.ts": `${fetchImports(ungrouped)}${groupImports}${renderEndpointDefinitions(ungrouped, ".")}export const api = defineApi({\n${descriptors.join("\n")}\n}, ${metadata});\n\n${clientFactory}`,
"index.ts": `export * from "./schemas";\nexport * from "./operations";\nexport { api, createApiClient } from "./api";\n`,
".askr-generated.json": "",
} satisfies Record<(typeof OWNED)[number], string>;
files[".askr-generated.json"] = `${JSON.stringify({ version: 1, files: [...OWNED] }, null, 2)}\n`;
};
const groupFiles = [...groups.keys()].sort().map((name) => {
const module = groups.get(name)!;
const path = `groups/${name}.ts` as const;
const builders = module.endpoints.map(
({ id, expression }) => ` [${JSON.stringify(id)}]: () => ${expression},`,
);
const endpoints = module.endpoints.map(
({ id }) => ` [${JSON.stringify(id)}]: builders.${id}(),`,
);
files[path] =
`${fetchImports(module)}${renderEndpointDefinitions(module, "..")}export const builders = {\n${builders.join("\n")}\n};\n\nexport const createApiClient = (options?: ClientOptions) => createClient(defineApi({\n${endpoints.join("\n")}\n}, ${metadata}), options);\n`;
return path;
});
files[".askr-generated.json"] =
`${JSON.stringify({ version: 1, files: [...OWNED, ...groupFiles] }, null, 2)}\n`;
return files;
}
async function existingFiles(directory: string) {
async function outputEntries(directory: string) {
try {
return (await readdir(directory)).sort();
return await readdir(directory, { withFileTypes: true });
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
throw error;
}
}

async function checkGenerated(
output: string,
files: Record<string, string>,
directories: ReadonlySet<string>,
prefix = "",
): Promise<void> {
const entries = await outputEntries(join(output, prefix));
const found = new Set(entries.map((entry) => prefix + entry.name));
if (!prefix && !entries.length)
throw new GenerationError(`Generated directory is missing: ${output}`);
const mismatch = (path: string, reason: string): never => {
throw new GenerationError(`Generated file ownership differs in ${output}: ${reason} ${path}`);
};
for (const path of [...Object.keys(files), ...directories]) {
if (path.startsWith(prefix) && !path.slice(prefix.length).includes("/") && !found.has(path))
mismatch(path, "missing");
}
for (const entry of entries) {
const path = prefix + entry.name;
if (entry.isDirectory() && directories.has(path)) {
await checkGenerated(output, files, directories, path + "/");
} else {
if (!entry.isFile() || !Object.hasOwn(files, path)) mismatch(path, "unexpected");
if ((await readFile(join(output, path), "utf8")) !== files[path])
throw new GenerationError(`Generated file is stale: ${path}`);
}
}
}
export async function writeGenerated(
directory: string,
files: Record<string, string>,
Expand All @@ -1031,21 +1152,25 @@
`Generated output must be a directory without a symbolic link: ${JSON.stringify(output)}`,
);
}
const entries = await existingFiles(output);
if (check) {
if (!entries.length) throw new GenerationError(`Generated directory is missing: ${output}`);
const expected = Object.keys(files).sort();
if (JSON.stringify(entries) !== JSON.stringify(expected))
throw new GenerationError(`Generated file ownership differs in ${output}`);
for (const name of expected)
if ((await readFile(join(output, name), "utf8")) !== files[name])
throw new GenerationError(`Generated file is stale: ${name}`);
return;
const directories = new Set<string>();
for (const name of Object.keys(files)) {
const parts = name.split("/");
if (
name.includes("\\") ||
name.includes(":") ||
parts.some((part) => !part || part === "." || part === "..")
)
throw new GenerationError(`Invalid generated file path: ${JSON.stringify(name)}`);
for (let depth = 1; depth < parts.length; depth++)
directories.add(parts.slice(0, depth).join("/"));
}
if (entries.length && !entries.includes(".askr-generated.json"))
if (check) return checkGenerated(output, files, directories);
const entries = await outputEntries(output);
if (entries.length && !entries.some((entry) => entry.name === ".askr-generated.json"))
throw new GenerationError(`Refusing to overwrite non-generated directory: ${output}`);
const stage = await createSiblingStage(output, "askr-generated");
try {
for (const directory of directories) await mkdir(join(stage, directory), { recursive: true });
for (const [name, content] of Object.entries(files))
await writeFile(join(stage, name), content);
await swapStagedDirectoryLocked(stage, output);
Expand Down Expand Up @@ -1078,6 +1203,6 @@
}
const document = await loadOpenApi(input, loadOptions);
const files = generateFiles(document);
await mkdir(dirname(resolve(output)), { recursive: true });
if (!check) await mkdir(dirname(resolve(output)), { recursive: true });
await writeGenerated(output, files, check);
}
Loading
Loading