Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

generate.ts

772 lines24.3 KB

1#!/usr/bin/env node
2​
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import {
13 FetchHttpClient,
14 HttpClient,
15 HttpClientRequest,
16 HttpClientResponse,
17} from "effect/unstable/http";
18import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
19​
20const UPSTREAM_REF = "07b695190f30a450e4921f71f77473e564395c59";
21const USER_AGENT = "effect-codex-app-server-generator";
22const GITHUB_API_BASE =
23 "https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
24​
25const GithubContentEntries = Schema.Array(
26 Schema.Struct({
27 name: Schema.String,
28 path: Schema.String,
29 download_url: Schema.NullOr(Schema.String),
30 type: Schema.String,
31 }),
32);
33type GithubContentEntry = (typeof GithubContentEntries.Type)[number];
34​
35const JsonSchemaDocument = Schema.StructWithRest(
36 Schema.Struct({
37 definitions: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),
38 }),
39 [Schema.Record(Schema.String, Schema.Json)],
40);
41const decodeGithubContentEntries = Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries));
42const decodeJsonSchemaDocument = Schema.decodeEffect(Schema.fromJsonString(JsonSchemaDocument));
43​
44interface GeneratedPaths {
45 readonly generatedDir: string;
46 readonly schemaOutputPath: string;
47 readonly metaOutputPath: string;
48 readonly namespacesOutputPath: string;
50​
51interface MethodEntry {
52 readonly method: string;
53 readonly paramsType?: string;
55​
56interface JsonSchemaFile {
57 readonly namespace?: string;
58 readonly exportName: string;
59 readonly fileName: string;
60 readonly downloadUrl: string;
61 readonly qualifiedName: string;
63​
64class GeneratorError extends Schema.TaggedErrorClass<GeneratorError>()("GeneratorError", {
65 detail: Schema.String,
66 cause: Schema.optional(Schema.Defect()),
67}) {
68 override get message() {
69 return this.detail;
70 }
72​
73const ManualSchemas: Record<string, Schema.Json> = {
74 GetAuthStatusParams: {
75 type: "object",
76 title: "GetAuthStatusParams",
77 properties: {
78 includeToken: {
79 anyOf: [{ type: "boolean" }, { type: "null" }],
80 },
81 refreshToken: {
82 anyOf: [{ type: "boolean" }, { type: "null" }],
83 },
84 },
85 },
86 GetConversationSummaryParams: {
87 title: "GetConversationSummaryParams",
88 oneOf: [
89 {
90 type: "object",
91 properties: {
92 rolloutPath: { type: "string" },
93 },
94 required: ["rolloutPath"],
95 },
96 {
97 type: "object",
98 properties: {
99 conversationId: { type: "string" },
100 },
101 required: ["conversationId"],
102 },
103 ],
104 },
105 GetConversationSummaryResponse: {
106 type: "object",
107 title: "GetConversationSummaryResponse",
108 properties: {
109 summary: {},
110 },
111 required: ["summary"],
112 },
113 GitDiffToRemoteParams: {
114 type: "object",
115 title: "GitDiffToRemoteParams",
116 properties: {
117 cwd: { type: "string" },
118 },
119 required: ["cwd"],
120 },
121 GitDiffToRemoteResponse: {
122 type: "object",
123 title: "GitDiffToRemoteResponse",
124 properties: {
125 sha: { type: "string" },
126 diff: { type: "string" },
127 },
128 required: ["sha", "diff"],
129 },
130 GetAuthStatusResponse: {
131 type: "object",
132 title: "GetAuthStatusResponse",
133 properties: {
134 authMethod: {
135 anyOf: [{}, { type: "null" }],
136 },
137 authToken: {
138 anyOf: [{ type: "string" }, { type: "null" }],
139 },
140 requiresOpenaiAuth: {
141 anyOf: [{ type: "boolean" }, { type: "null" }],
142 },
143 },
144 required: ["authMethod", "authToken", "requiresOpenaiAuth"],
145 },
146};
147​
148const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
149 const path = yield* Path.Path;
150 const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
151 return {
152 generatedDir,
153 schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
154 metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
155 namespacesOutputPath: path.join(generatedDir, "namespaces.gen.ts"),
156 } satisfies GeneratedPaths;
157});
158​
159const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
160 const fs = yield* FileSystem.FileSystem;
161 const { generatedDir } = yield* getGeneratedPaths();
162 yield* fs.makeDirectory(generatedDir, { recursive: true });
163});
164​
165const fetchText = Effect.fn("fetchText")(function* (url: string) {
166 return yield* HttpClientRequest.get(url).pipe(
167 HttpClientRequest.setHeader("user-agent", USER_AGENT),
168 HttpClient.execute,
169 Effect.flatMap(HttpClientResponse.filterStatusOk),
170 Effect.flatMap((okResponse) => okResponse.text),
171 Effect.mapError(
172 (cause) =>
173 new GeneratorError({
174 detail: `Failed to fetch ${url}`,
175 cause,
176 }),
177 ),
178 );
179});
180​
181const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
182 const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
183 return yield* decodeGithubContentEntries(raw);
184});
185​
186function collectSchemaEntries(
187 chunk: string,
188): ReadonlyArray<{ readonly name: string; readonly code: string }> {
189 const lines = chunk
190 .split("\n")
191 .map((line) => line.trim())
192 .filter((line) => line.length > 0 && !line.startsWith("//"));
193 const entries: Array<{ name: string; code: string }> = [];
194​
195 for (let index = 0; index < lines.length; index += 1) {
196 const typeLine = lines[index];
197 if (!typeLine?.startsWith("export type ")) {
198 continue;
199 }
200​
201 const constLine = lines[index + 1];
202 if (!constLine?.startsWith("export const ")) {
203 throw new Error(`Malformed generator output near: ${typeLine}`);
204 }
205​
206 const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
207 if (!match?.[1]) {
208 throw new Error(`Could not extract schema name from: ${typeLine}`);
209 }
210​
211 entries.push({
212 name: match[1],
213 code: `${typeLine}\n${constLine}`,
214 });
215 index += 1;
216 }
217​
218 return entries;
220​
221function normalizeNullableTypes(value: Schema.Json): Schema.Json {
222 if (Array.isArray(value)) {
223 return value.map(normalizeNullableTypes);
224 }
225 if (value === null || typeof value !== "object") {
226 return value;
227 }
228​
229 const normalizedEntries = Object.entries(value).map(([key, child]) => [
230 key,
231 normalizeNullableTypes(child),
232 ]);
233 const normalizedObject = Object.fromEntries(normalizedEntries) as Record<string, Schema.Json>;
234 const typeValue = normalizedObject.type;
235​
236 if (!Array.isArray(typeValue)) {
237 return normalizedObject;
238 }
239​
240 const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
241 if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
242 return normalizedObject;
243 }
244​
245 const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
246 if (nonNullTypes.length !== 1) {
247 return normalizedObject;
248 }
249 const nonNullType = nonNullTypes[0]!;
250​
251 const nextObject: Record<string, Schema.Json> = {};
252 for (const [key, child] of Object.entries(normalizedObject)) {
253 if (key !== "type") {
254 nextObject[key] = child;
255 }
256 }
257​
258 return {
259 anyOf: [
260 {
261 ...nextObject,
262 type: nonNullType,
263 },
264 { type: "null" },
265 ],
266 };
268​
269function stripNullDefaults(value: Schema.Json): Schema.Json {
270 if (Array.isArray(value)) {
271 return value.map(stripNullDefaults);
272 }
273 if (value === null || typeof value !== "object") {
274 return value;
275 }
276​
277 return Object.fromEntries(
278 Object.entries(value)
279 .filter(([key, child]) => !(key === "default" && child === null))
280 .map(([key, child]) => [key, stripNullDefaults(child)]),
281 ) as Schema.Json;
283​
284function toPascalCaseMethod(method: string) {
285 return method
286 .split("/")
287 .flatMap((segment) => segment.split(/(?=[A-Z])/))
288 .flatMap((segment) => segment.split(/[-_]/))
289 .filter(Boolean)
290 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
291 .join("");
293​
294function parseRequestEntries(fileContents: string): ReadonlyArray<MethodEntry> {
295 const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params:\s*([^,}]+)/g;
296 const entries: Array<MethodEntry> = [];
297 let match: RegExpExecArray | null;
298 while ((match = entryPattern.exec(fileContents)) !== null) {
299 entries.push({
300 method: match[1]!,
301 paramsType: match[2]!.trim(),
302 });
303 }
304 return entries;
306​
307function parseNotificationEntries(fileContents: string): ReadonlyArray<MethodEntry> {
308 const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g;
309 const entries: Array<MethodEntry> = [];
310 let match: RegExpExecArray | null;
311 while ((match = entryPattern.exec(fileContents)) !== null) {
312 entries.push({
313 method: match[1]!,
314 ...(match[2] ? { paramsType: match[2].trim() } : {}),
315 });
316 }
317 return entries;
319​
320function resolveSchemaTypeName(
321 rawTypeName: string,
322 generatedSchemaNames: ReadonlySet<string>,
323): string {
324 if (rawTypeName === "undefined") {
325 return "undefined";
326 }
327​
328 const candidates = [
329 rawTypeName,
330 `V2${rawTypeName}`,
331 `V1${rawTypeName}`,
332 `SerdeJson${rawTypeName}`,
333 ];
334 for (const candidate of candidates) {
335 if (generatedSchemaNames.has(candidate)) {
336 return candidate;
337 }
338 }
339​
340 throw new Error(`Unable to resolve schema type name: ${rawTypeName}`);
342​
343function resolveResponseTypeName(
344 method: string,
345 paramsType: string | undefined,
346 generatedSchemaNames: ReadonlySet<string>,
347): string {
348 const overrides: Record<string, string> = {
349 "account/logout": "LogoutAccountResponse",
350 "account/rateLimits/read": "GetAccountRateLimitsResponse",
351 "config/batchWrite": "ConfigWriteResponse",
352 "config/mcpServer/reload": "McpServerRefreshResponse",
353 "config/value/write": "ConfigWriteResponse",
354 "configRequirements/read": "ConfigRequirementsReadResponse",
355 };
356​
357 const override = overrides[method];
358 if (override) {
359 return resolveSchemaTypeName(override, generatedSchemaNames);
360 }
361​
362 if (paramsType && paramsType !== "undefined") {
363 const fromParams = paramsType.replace(/Params$/, "Response");
364 try {
365 return resolveSchemaTypeName(fromParams, generatedSchemaNames);
366 } catch {
367 // Fall through to method-based lookup.
368 }
369 }
370​
371 return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
373​
374function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
375 return [
376 `export const ${constantName} = {`,
377 ...entries.map(
378 (entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
379 ),
380 "} as const;",
381 "",
382 ].join("\n");
384​
385function renderTypeInterface(
386 interfaceName: string,
387 entries: ReadonlyArray<MethodEntry>,
388 typeName: (entry: MethodEntry) => string,
389) {
390 return [
391 `export interface ${interfaceName} {`,
392 ...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
393 "}",
394 "",
395 ].join("\n");
397​
398function renderSchemaMap(
399 constantName: string,
400 entries: ReadonlyArray<MethodEntry>,
401 typeName: (entry: MethodEntry) => string,
402) {
403 return [
404 `export const ${constantName} = {`,
405 ...entries.map((entry) => {
406 const schemaName = typeName(entry);
407 return ` ${JSON.stringify(entry.method)}: ${
408 schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
409 },`;
410 }),
411 "} as const;",
412 "",
413 ].join("\n");
415​
416function renderSchemaTypeReference(schemaName: string) {
417 return schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`;
419​
420function exportNameForPath(filePath: string): string {
421 const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
422 if (!relative.includes("/")) {
423 return relative;
424 }
425​
426 const [namespace, name] = relative.split("/", 2) as [string, string];
427 const namespacePrefix = namespace
428 .split(/[^A-Za-z0-9]+/)
429 .filter(Boolean)
430 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
431 .join("");
432 return `${namespacePrefix}${name}`;
434​
435function buildJsonSchemaFiles(
436 entries: ReadonlyArray<GithubContentEntry>,
437): ReadonlyArray<JsonSchemaFile> {
438 return entries
439 .filter(
440 (entry) =>
441 entry.type === "file" &&
442 entry.name.endsWith(".json") &&
443 entry.download_url !== null &&
444 !entry.name.startsWith("codex_app_server_protocol."),
445 )
446 .map((entry) => {
447 const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
448 const parts = relative.split("/");
449 if (parts.length > 1) {
450 return {
451 namespace: parts[0]!,
452 exportName: exportNameForPath(relative),
453 fileName: entry.name,
454 downloadUrl: entry.download_url!,
455 qualifiedName: relative.replace(/\.json$/, ""),
456 } satisfies JsonSchemaFile;
457 }
458 return {
459 exportName: exportNameForPath(relative),
460 fileName: entry.name,
461 downloadUrl: entry.download_url!,
462 qualifiedName: relative.replace(/\.json$/, ""),
463 } satisfies JsonSchemaFile;
464 });
466​
467function rewriteExternalRefs(
468 value: Schema.Json,
469 localDefinitionNames: ReadonlyMap<string, string>,
470 currentNamespace: string | undefined,
471 exportNameByQualifiedName: ReadonlyMap<string, string>,
472): Schema.Json {
473 if (Array.isArray(value)) {
474 return value.map((entry) =>
475 rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
476 );
477 }
478 if (value === null || typeof value !== "object") {
479 return value;
480 }
481​
482 return Object.fromEntries(
483 Object.entries(value).map(([key, child]) => {
484 if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
485 const definitionName = child.slice("#/definitions/".length);
486 const localRewrite = localDefinitionNames.get(definitionName);
487 if (localRewrite) {
488 return [key, `#/definitions/${localRewrite}`];
489 }
490​
491 const candidates = [
492 ...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
493 definitionName,
494 definitionName.replace(/^v[12]\//, ""),
495 definitionName.replace(/^serde_json\//, ""),
496 `v2/${definitionName}`,
497 `v1/${definitionName}`,
498 `serde_json/${definitionName}`,
499 ];
500​
501 const rewritten = candidates
502 .map((candidate) => exportNameByQualifiedName.get(candidate))
503 .find((candidate) => candidate !== undefined);
504​
505 if (!rewritten) {
506 throw new Error(`Missing rewritten definition for ref: ${child}`);
507 }
508​
509 return [key, `#/definitions/${rewritten}`];
510 }
511​
512 return [
513 key,
514 rewriteExternalRefs(
515 child,
516 localDefinitionNames,
517 currentNamespace,
518 exportNameByQualifiedName,
519 ),
520 ];
521 }),
522 ) as Schema.Json;
524​
525const generateFiles = Effect.fn("generateFiles")(function* () {
526 yield* ensureGeneratedDir();
527​
528 const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
529 fetchDirectoryEntries("schema/json"),
530 fetchDirectoryEntries("schema/json/v1"),
531 fetchDirectoryEntries("schema/json/v2"),
532 ]);
533​
534 const jsonSchemaFiles = [
535 ...buildJsonSchemaFiles(rootJsonEntries),
536 ...buildJsonSchemaFiles(v1JsonEntries),
537 ...buildJsonSchemaFiles(v2JsonEntries),
538 ].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
539​
540 const exportNameByQualifiedName = new Map(
541 jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
542 );
543 const aggregateSchemas: Record<string, Schema.Json> = {};
544​
545 for (const file of jsonSchemaFiles) {
546 const raw = yield* fetchText(file.downloadUrl);
547 const parsed = yield* decodeJsonSchemaDocument(raw);
548 const localDefinitionNames = new Map(
549 Object.keys(parsed.definitions ?? {}).map((definitionName) => [
550 definitionName,
551 `${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
552 ]),
553 );
554​
555 for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
556 aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults(
557 normalizeNullableTypes(
558 rewriteExternalRefs(
559 definitionSchema,
560 localDefinitionNames,
561 file.namespace,
562 exportNameByQualifiedName,
563 ),
564 ),
565 );
566 }
567​
568 const topLevelSchema: Record<string, Schema.Json> = {};
569 for (const [key, value] of Object.entries(parsed)) {
570 if (key !== "definitions") {
571 topLevelSchema[key] = value;
572 }
573 }
574​
575 aggregateSchemas[file.exportName] = stripNullDefaults(
576 normalizeNullableTypes(
577 rewriteExternalRefs(
578 topLevelSchema,
579 localDefinitionNames,
580 file.namespace,
581 exportNameByQualifiedName,
582 ),
583 ),
584 );
585 }
586​
587 for (const [name, schema] of Object.entries(ManualSchemas)) {
588 if (!(name in aggregateSchemas)) {
589 aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
590 }
591 }
592​
593 const generator = makeJsonSchemaGenerator();
594 for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
595 left.localeCompare(right),
596 )) {
597 generator.addSchema(name, schema as never);
598 }
599​
600 const generatedEntries = new Map<string, string>();
601 const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
602 if (output.length > 0) {
603 for (const entry of collectSchemaEntries(output)) {
604 if (!generatedEntries.has(entry.name)) {
605 generatedEntries.set(entry.name, entry.code);
606 }
607 }
608 }
609​
610 const generatedSchemaNames = new Set(generatedEntries.keys());
611 const clientRequestRaw = yield* fetchText(
612 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
613 );
614 const clientNotificationRaw = yield* fetchText(
615 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
616 );
617 const serverRequestRaw = yield* fetchText(
618 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
619 );
620 const serverNotificationRaw = yield* fetchText(
621 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
622 );
623​
624 const clientRequestEntries = parseRequestEntries(clientRequestRaw);
625 const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
626 const serverRequestEntries = parseRequestEntries(serverRequestRaw);
627 const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
628​
629 const prelude = [
630 "// This file is generated by the effect-codex-app-server package. Do not edit manually.",
631 `// Upstream protocol ref: ${UPSTREAM_REF}`,
632 "",
633 ];
634​
635 const schemaOutput = [
636 ...prelude,
637 'import * as Schema from "effect/Schema";',
638 "",
639 [...generatedEntries.values()].join("\n\n"),
640 "",
641 ].join("\n");
642​
643 const metaOutput = [
644 ...prelude,
645 'import * as CodexSchema from "./schema.gen.ts";',
646 "",
647 renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
648 renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
649 renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
650 renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
651 "export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
652 "export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
653 "export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
654 "export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
655 "",
656 renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
657 renderSchemaTypeReference(
658 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
659 ),
660 ),
661 renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
662 renderSchemaTypeReference(
663 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
664 ),
665 ),
666 renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
667 renderSchemaTypeReference(
668 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
669 ),
670 ),
671 renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
672 renderSchemaTypeReference(
673 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
674 ),
675 ),
676 renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
677 renderSchemaTypeReference(
678 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
679 ),
680 ),
681 renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
682 renderSchemaTypeReference(
683 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
684 ),
685 ),
686 renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
687 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
688 ),
689 renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
690 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
691 ),
692 renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
693 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
694 ),
695 renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
696 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
697 ),
698 renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
699 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
700 ),
701 renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
702 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
703 ),
704 ].join("\n");
705​
706 const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
707 for (const file of jsonSchemaFiles) {
708 if (!file.namespace) {
709 continue;
710 }
711 const current = namespaceGroups.get(file.namespace) ?? [];
712 current.push(file);
713 namespaceGroups.set(file.namespace, current);
714 }
715​
716 const namespacesOutput = [
717 ...prelude,
718 'import * as CodexSchema from "./schema.gen.ts";',
719 "",
720 ...[...namespaceGroups.entries()]
721 .toSorted(([left], [right]) => left.localeCompare(right))
722 .map(([namespace, files]) => {
723 const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
724 return [
725 `export const ${constantName} = {`,
726 ...files
727 .toSorted((left, right) => left.fileName.localeCompare(right.fileName))
728 .map(
729 (file) =>
730 ` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
731 ),
732 "} as const;",
733 "",
734 ].join("\n");
735 }),
736 ].join("\n");
737​
738 const fs = yield* FileSystem.FileSystem;
739 const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
740 yield* getGeneratedPaths();
741 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
742 yield* fs.writeFileString(metaOutputPath, metaOutput);
743 yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
744​
745 yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
746​
747 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
748 Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
749 Effect.flatMap((child) => child.exitCode),
750 Effect.tap((code) =>
751 code === 0
752 ? Effect.void
753 : Effect.fail(
754 new GeneratorError({
755 detail: `oxfmt failed with exit code ${code}`,
756 }),
757 ),
758 ),
759 );
760});
761​
762generateFiles().pipe(
763 Effect.scoped,
764 Effect.provide(
765 Layer.mergeAll(
766 Logger.layer([Logger.consolePretty()]),
767 NodeServices.layer,
768 FetchHttpClient.layer,
769 ),
770 ),
771 NodeRuntime.runMain,
772);