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
128 changes: 64 additions & 64 deletions bun.lock

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,21 @@
"gen": "bun run --sequential gen:schemas gen:client format",
"test": "bun test",
"typecheck": "tsgo --noEmit",
"lint": "biome check ./src",
"lint": "biome check",
"format": "biome check --write --linter-enabled=false",
"build": "bunx --bun tsdown",
"prepublishOnly": "bun run build"
},
"dependencies": {
"minizod": "^0.0.3"
"minizod": "0.0.3"
},
"devDependencies": {
"@biomejs/biome": "2.4.12",
"@gameroman/config": "^0.1.0",
"@types/bun": "^1.3.11",
"@typescript/native-preview": "^7.0.0-dev.20260401.1",
"tsdown": "^0.21.7",
"zod": "^4.3.6"
"@biomejs/biome": "2.4.15",
"@gameroman/config": "0.1.0",
"@types/bun": "1.3.14",
"@typescript/native-preview": "7.0.0-dev.20260517.1",
"tsdown": "0.22.0",
"zod": "4.4.3"
},
"engines": {
"node": ">=24"
Expand Down
98 changes: 44 additions & 54 deletions scripts/gen-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
OperationParameterBase,
OperationQueryParameterSchema,
type QueryParamSchemaSchema,
recordToObject,
refToName,
type Schema,
SchemaSchema,
SchemaSchemaBoolean,
Expand Down Expand Up @@ -38,15 +40,17 @@ const OpenApiSchemaPaths = z.record(OpenApiSchemaPath, SchemaSchemaRef);

const OpenApiSchemaComponents = z.object();

const OpenApiServersSchema = z.tuple([
z.object({ url: z.literal("https://lichess.org") }),
z.object({ url: z.literal("https://lichess.dev") }),
z.object({ url: z.literal("http://localhost:{port}") }),
z.object({ url: z.literal("http://l.org") }),
]);

const OpenApiSchemaSchema = z.object({
openapi: z.literal("3.1.0"),
info: OpenApiSchemaInfo,
servers: z.tuple([
z.object({ url: z.literal("https://lichess.org") }),
z.object({ url: z.literal("https://lichess.dev") }),
z.object({ url: z.literal("http://localhost:{port}") }),
z.object({ url: z.literal("http://l.org") }),
]),
servers: OpenApiServersSchema,
tags: z.array(z.object({ name: z.string(), description: z.string() })),
paths: OpenApiSchemaPaths,
components: OpenApiSchemaComponents,
Expand Down Expand Up @@ -248,10 +252,30 @@ const ResponseStatus = z.string();

const OperationResponses = z.record(ResponseStatus, ResponseSchema);

const LichessServerSchema = z.union([
z.object({
url: z.literal([
"https://engine.lichess.ovh",
"https://explorer.lichess.org",
"https://tablebase.lichess.org",
]),
}),
z.object({
url: z.literal("http://localhost:{port}"),
variables: z.object({ port: z.object({ default: z.string() }) }),
}),
]);

const LichessServersSchema = z
.tuple([LichessServerSchema])
.rest(LichessServerSchema)
.transform((s) => ({ url: s[0].url, __id: "__servers" as const }));

const BaseTagSchemaOperation = z.object({
operationId: z.string(),
summary: z.string(),
description: z.string(),
servers: LichessServersSchema.optional(),
tags: z.array(z.string()),
security: SecuritySchema,
parameters: OperationParameters,
Expand Down Expand Up @@ -312,18 +336,7 @@ const TagSchemaSchemaPut = BaseTagSchemaOperation.extend({

const TagSchemaSchema = z
.object({
servers: z
.tuple([
z.object({
url: z.literal([
"https://engine.lichess.ovh",
"https://explorer.lichess.org",
"https://tablebase.lichess.org",
]),
}),
])
.transform((s) => ({ url: s[0].url, __id: "__servers" as const }))
.optional(),
servers: LichessServersSchema.optional(),
parameters: z
.array(OperationPathParameterSchema)
.transform((s) => ({ parameters: s, __id: "__parameters" as const }))
Expand Down Expand Up @@ -453,13 +466,13 @@ function schemaToTypescriptTypes(
case "$ref":
case "notverified:reftoprimitive": {
const ref = schema.$ref;
const name = ref.split("/").pop()!.replace(".yaml", "");
const name = refToName(ref);
const typescriptSchema = `schemas.${name}` as const;
return typescriptSchema;
}
case "notverified:reftoprimitive:nullable": {
const ref = schema.allOf[0].$ref;
const name = ref.split("/").pop()!.replace(".yaml", "");
const name = refToName(ref);
const typescriptSchema = `schemas.${name} | null` as const;
return typescriptSchema;
}
Expand All @@ -474,15 +487,7 @@ function schemaToTypescriptTypes(
: (`?: ${typescriptSchema}` as const);
objectRecord[k] = propStr;
}
const entries = Object.entries(objectRecord);
if (entries.length === 1) {
return `{ "${entries[0]![0]}" ${entries[0]![1]} }` as const;
}
return (
"{\n" +
entries.map(([k, v]) => ` "${k}" ${v},` as const).join("\n") +
"\n}"
);
return recordToObject(objectRecord, { colon: false });
}
case "boolean":
case "boolean-like": {
Expand Down Expand Up @@ -524,7 +529,7 @@ function schemaToTypescriptTypes(
}
case "array:notverified:reftoprimitive": {
const ref = schema.items.$ref;
const name = ref.split("/").pop()!.replace(".yaml", "");
const name = refToName(ref);
const typescriptSchema = `schemas.${name}` as const;
return `(${typescriptSchema})[]` as const;
}
Expand Down Expand Up @@ -552,32 +557,15 @@ function extractQueryParams(queryParams: OperationQueryParameter[]) {
? `: ${typescriptSchema}`
: `?: ${typescriptSchema}`;
}
const entries = Object.entries(params);
if (entries.length === 1) {
return `{ "${entries[0]![0]}" ${entries[0]![1]} }` as const;
}
return (
"{\n" +
entries.map(([k, v]) => ` "${k}" ${v},` as const).join("\n") +
"\n}"
);
return recordToObject(params, { colon: false });
}

function extractPathParams(pathParams: OperationPathParameter[]) {
const params: Record<string, string> = {};
for (const param of pathParams) {
const typescriptSchema = schemaToTypescriptTypes(param.schema);
params[param.name] = `: ${typescriptSchema}` as const;
}
const entries = Object.entries(params);
if (entries.length === 1) {
return `{ "${entries[0]![0]}" ${entries[0]![1]} }` as const;
params[param.name] = schemaToTypescriptTypes(param.schema);
}
return (
"{\n" +
entries.map(([k, v]) => ` "${k}" ${v},` as const).join("\n") +
"\n}"
);
return recordToObject(params);
}

function extractBodyTypes(bodySchema: Schema) {
Expand Down Expand Up @@ -665,10 +653,12 @@ function processOperation(
requestObjCode = `${requestPieces.join(", ")}`;
}

const baseUrl = options?.baseUrl || operation.servers?.url;

let baseUrlLine = "";
let baseUrlArg = "";
if (options?.baseUrl) {
baseUrlLine = ` const baseUrl = "${options.baseUrl}";\n`;
if (baseUrl) {
baseUrlLine = ` const baseUrl = "${baseUrl}";\n`;
baseUrlArg = ", baseUrl";
}

Expand All @@ -692,8 +682,8 @@ ${baseUrlLine}\

function processTag(tagSchema: TagSchema, rawApiPath: string) {
const methodsCode: string[] = [];
let sharedPathParams: OperationPathParameter[] | undefined = undefined;
let baseUrl: string | undefined = undefined;
let sharedPathParams: OperationPathParameter[] | undefined;
let baseUrl: string | undefined;

for (const operation of Object.values(tagSchema)) {
const processedOperation = processOperation(operation, rawApiPath, {
Expand Down
4 changes: 2 additions & 2 deletions scripts/gen-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import * as fs from "node:fs/promises";
import * as path from "node:path";
import { ZodError } from "zod";
import { prettifyError } from "zod/mini";
import { convertToZod, SchemaSchema } from "./shared";
import { convertToZod, refToName, SchemaSchema, StringYamlRef } from "./shared";

async function processFile(filePath: string) {
const normalizedFilePath = filePath.replaceAll("\\", "/");
const fileName = normalizedFilePath.split("/").pop()!.replace(".yaml", "");
const fileName = refToName(StringYamlRef.parse(normalizedFilePath));
const yamlStr = await Bun.file(normalizedFilePath).text();
const yamlContent = Bun.YAML.parse(yamlStr);
const parsedSchema = SchemaSchema.safeParse(yamlContent);
Expand Down
55 changes: 41 additions & 14 deletions scripts/shared.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as path from "node:path";
import * as z from "zod";

const SchemaUnparsed = z
Expand Down Expand Up @@ -29,6 +30,8 @@ const StringYamlRef = z
.templateLiteral([z.string(), ".yaml"])
.brand("StringYamlRef");

type StringYamlRef = z.infer<typeof StringYamlRef>;

const SchemaSchemaRef = BaseSchema.extend({
type: z.literal("object").optional(),
$ref: StringYamlRef,
Expand Down Expand Up @@ -240,6 +243,33 @@ function parseUnparsed(schema: Unparsed) {

type ConvertResult = { readonly zodSchema: string; readonly refs: string[] };

function refToName(ref: StringYamlRef) {
return path.basename(ref).replace(".yaml", "");
}

function recordToObject(
object: Record<string, string>,
options = { colon: true },
) {
const entries = Object.entries(object);

const colon = options.colon ? ":" : "";

if (entries.length <= 1) {
const firstEntry = entries[0];
if (firstEntry) {
return `{ "${firstEntry[0]}"${colon} ${firstEntry[1]} }`;
}
return "Record<string, never>";
}

const entriesKv = entries
.map(([k, v]) => ` "${k}"${colon} ${v},`)
.join("\n");

return `{\n${entriesKv}\n}`;
}

function convertToZod(schema: Schema, prefix: string = ""): ConvertResult {
if (schema.const !== undefined) {
return {
Expand All @@ -252,7 +282,7 @@ function convertToZod(schema: Schema, prefix: string = ""): ConvertResult {
switch (schema.__schema) {
case "$ref": {
const ref = schema.$ref;
const name = ref.split("/").pop()!.replace(".yaml", "");
const name = refToName(ref);
const prefixedName = `${prefix}${name}` as const;
return { zodSchema: prefixedName, refs: prefix ? [] : [name] } as const;
}
Expand All @@ -262,7 +292,9 @@ function convertToZod(schema: Schema, prefix: string = ""): ConvertResult {
);
const zodSchemas = subResults.map((r) => r.zodSchema);
const allRefs = new Set<string>();
subResults.forEach((r) => r.refs.forEach((ref) => allRefs.add(ref)));
subResults.forEach(
(r) => void r.refs.forEach((ref) => void allRefs.add(ref)),
);
return {
zodSchema: `z.union([${zodSchemas.join(", ")}])`,
refs: Array.from(allRefs),
Expand All @@ -286,10 +318,8 @@ function convertToZod(schema: Schema, prefix: string = ""): ConvertResult {
case "anyOf": {
const refNames: string[] = [];
const allRefs = new Set<string>();
for (const [_, refYaml] of Object.entries(
schema.discriminator.mapping,
)) {
const name = refYaml.split("/").pop()!.replace(".yaml", "");
for (const [_, ref] of Object.entries(schema.discriminator.mapping)) {
const name = refToName(ref);
refNames.push(prefix + name);
if (!prefix) allRefs.add(name);
}
Expand Down Expand Up @@ -387,20 +417,14 @@ function convertToZod(schema: Schema, prefix: string = ""): ConvertResult {
parseUnparsed(v),
prefix,
);
propRefs.forEach((r) => allRefs.add(r));
propRefs.forEach((r) => void allRefs.add(r));
let propStr = sch;
if (!required.has(k)) {
propStr = `z.optional(${propStr})`;
}
zodProps[k] = propStr;
}
const entries = Object.entries(zodProps);
const inner =
entries.length === 1
? `{ "${entries[0]![0]}": ${entries[0]![1]} }`
: "{\n" +
entries.map(([k, v]) => ` "${k}": ${v},`).join("\n") +
"\n}";
const inner = recordToObject(zodProps);
return {
zodSchema: `z.object(${inner})`,
refs: Array.from(allRefs),
Expand Down Expand Up @@ -471,6 +495,9 @@ export {
assertNever,
convertToZod,
QueryParamSchemaSchema,
recordToObject,
refToName,
SchemaSchema,
SchemaSchemaRef,
StringYamlRef,
};
8 changes: 5 additions & 3 deletions specs/lichess-api.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
openapi: "3.1.0"
info:
version: 2.0.139
version: 2.0.143
title: Lichess.org API reference
contact:
name: "Lichess.org API"
Expand Down Expand Up @@ -219,7 +219,8 @@ tags:

Runs <https://github.com/lichess-org/lila-openingexplorer>.

**The endpoint hostname is not lichess.org but explorer.lichess.org.**
> [!important]
> The hostname for these endpoints is `explorer.lichess.org` and not `lichess.org`.
- name: Puzzles
description: |
Fetch and solve [puzzles](https://lichess.org/training), view your puzzle history and dashboard.
Expand All @@ -241,7 +242,8 @@ tags:
description: |
Lookup positions from the [Lichess tablebase server](https://lichess.org/blog/W3WeMyQAACQAdfAL/7-piece-syzygy-tablebases-are-complete).

**The endpoint hostname is not lichess.org but tablebase.lichess.org.**
> [!important]
> The hostname for these endpoints is `tablebase.lichess.org` and not `lichess.org`.
- name: Teams
description: |
Access and manage Lichess teams and their members.
Expand Down
2 changes: 2 additions & 0 deletions specs/schemas/BroadcastGameEntry.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ properties:
description: The change in rating for the player as a result of this game
fideTC:
$ref: "./FideTimeControl.yaml"
ongoing:
type: boolean

required:
- round
Expand Down
2 changes: 2 additions & 0 deletions specs/schemas/BroadcastTour.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ properties:
description: "Full tournament description in markdown format, or in HTML if the html=1 query parameter is set."
teamTable:
type: boolean
showTeamScores:
type: boolean
url:
type: string
format: uri
Expand Down
Loading