Open History to see the last commit
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 = "b39f943a634a6e7ba86c3d6e8cf6d5f35e612566";
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;
49}
50
51interface MethodEntry {
52 readonly method: string;
53 readonly paramsType?: string;
54}
55
56interface JsonSchemaFile {
57 readonly namespace?: string;
58 readonly exportName: string;
59 readonly fileName: string;
60 readonly downloadUrl: string;
61 readonly qualifiedName: string;
62}
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 }
71}
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;
219}
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 };
267}
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;
282}
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("");
292}
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;
305}
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;
318}
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}`);
341}
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 "account/usage/read": "GetAccountTokenUsageResponse",
352 "config/batchWrite": "ConfigWriteResponse",
353 "config/mcpServer/reload": "McpServerRefreshResponse",
354 "config/value/write": "ConfigWriteResponse",
355 "configRequirements/read": "ConfigRequirementsReadResponse",
356 };
357
358 const override = overrides[method];
359 if (override) {
360 return resolveSchemaTypeName(override, generatedSchemaNames);
361 }
362
363 if (paramsType && paramsType !== "undefined") {
364 const fromParams = paramsType.replace(/Params$/, "Response");
365 try {
366 return resolveSchemaTypeName(fromParams, generatedSchemaNames);
367 } catch {
368 // Fall through to method-based lookup.
369 }
370 }
371
372 return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
373}
374
375function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
376 return [
377 `export const ${constantName} = {`,
378 ...entries.map(
379 (entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
380 ),
381 "} as const;",
382 "",
383 ].join("\n");
384}
385
386function renderTypeInterface(
387 interfaceName: string,
388 entries: ReadonlyArray<MethodEntry>,
389 typeName: (entry: MethodEntry) => string,
390) {
391 return [
392 `export interface ${interfaceName} {`,
393 ...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
394 "}",
395 "",
396 ].join("\n");
397}
398
399function renderSchemaMap(
400 constantName: string,
401 entries: ReadonlyArray<MethodEntry>,
402 typeName: (entry: MethodEntry) => string,
403) {
404 return [
405 `export const ${constantName} = {`,
406 ...entries.map((entry) => {
407 const schemaName = typeName(entry);
408 return ` ${JSON.stringify(entry.method)}: ${
409 schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
410 },`;
411 }),
412 "} as const;",
413 "",
414 ].join("\n");
415}
416
417function renderSchemaTypeReference(schemaName: string) {
418 return schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`;
419}
420
421function exportNameForPath(filePath: string): string {
422 const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
423 if (!relative.includes("/")) {
424 return relative;
425 }
426
427 const [namespace, name] = relative.split("/", 2) as [string, string];
428 const namespacePrefix = namespace
429 .split(/[^A-Za-z0-9]+/)
430 .filter(Boolean)
431 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
432 .join("");
433 return `${namespacePrefix}${name}`;
434}
435
436function buildJsonSchemaFiles(
437 entries: ReadonlyArray<GithubContentEntry>,
438): ReadonlyArray<JsonSchemaFile> {
439 return entries
440 .filter(
441 (entry) =>
442 entry.type === "file" &&
443 entry.name.endsWith(".json") &&
444 entry.download_url !== null &&
445 !entry.name.startsWith("codex_app_server_protocol."),
446 )
447 .map((entry) => {
448 const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
449 const parts = relative.split("/");
450 if (parts.length > 1) {
451 return {
452 namespace: parts[0]!,
453 exportName: exportNameForPath(relative),
454 fileName: entry.name,
455 downloadUrl: entry.download_url!,
456 qualifiedName: relative.replace(/\.json$/, ""),
457 } satisfies JsonSchemaFile;
458 }
459 return {
460 exportName: exportNameForPath(relative),
461 fileName: entry.name,
462 downloadUrl: entry.download_url!,
463 qualifiedName: relative.replace(/\.json$/, ""),
464 } satisfies JsonSchemaFile;
465 });
466}
467
468function rewriteExternalRefs(
469 value: Schema.Json,
470 localDefinitionNames: ReadonlyMap<string, string>,
471 currentNamespace: string | undefined,
472 exportNameByQualifiedName: ReadonlyMap<string, string>,
473): Schema.Json {
474 if (Array.isArray(value)) {
475 return value.map((entry) =>
476 rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
477 );
478 }
479 if (value === null || typeof value !== "object") {
480 return value;
481 }
482
483 return Object.fromEntries(
484 Object.entries(value).map(([key, child]) => {
485 if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
486 const definitionName = child.slice("#/definitions/".length);
487 const localRewrite = localDefinitionNames.get(definitionName);
488 if (localRewrite) {
489 return [key, `#/definitions/${localRewrite}`];
490 }
491
492 const candidates = [
493 ...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
494 definitionName,
495 definitionName.replace(/^v[12]\//, ""),
496 definitionName.replace(/^serde_json\//, ""),
497 `v2/${definitionName}`,
498 `v1/${definitionName}`,
499 `serde_json/${definitionName}`,
500 ];
501
502 const rewritten = candidates
503 .map((candidate) => exportNameByQualifiedName.get(candidate))
504 .find((candidate) => candidate !== undefined);
505
506 if (!rewritten) {
507 throw new Error(`Missing rewritten definition for ref: ${child}`);
508 }
509
510 return [key, `#/definitions/${rewritten}`];
511 }
512
513 return [
514 key,
515 rewriteExternalRefs(
516 child,
517 localDefinitionNames,
518 currentNamespace,
519 exportNameByQualifiedName,
520 ),
521 ];
522 }),
523 ) as Schema.Json;
524}
525
526const generateFiles = Effect.fn("generateFiles")(function* () {
527 yield* ensureGeneratedDir();
528
529 const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
530 fetchDirectoryEntries("schema/json"),
531 fetchDirectoryEntries("schema/json/v1"),
532 fetchDirectoryEntries("schema/json/v2"),
533 ]);
534
535 const jsonSchemaFiles = [
536 ...buildJsonSchemaFiles(rootJsonEntries),
537 ...buildJsonSchemaFiles(v1JsonEntries),
538 ...buildJsonSchemaFiles(v2JsonEntries),
539 ].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
540
541 const exportNameByQualifiedName = new Map(
542 jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
543 );
544 const aggregateSchemas: Record<string, Schema.Json> = {};
545
546 for (const file of jsonSchemaFiles) {
547 const raw = yield* fetchText(file.downloadUrl);
548 const parsed = yield* decodeJsonSchemaDocument(raw);
549 const localDefinitionNames = new Map(
550 Object.keys(parsed.definitions ?? {}).map((definitionName) => [
551 definitionName,
552 `${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
553 ]),
554 );
555
556 for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
557 aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults(
558 normalizeNullableTypes(
559 rewriteExternalRefs(
560 definitionSchema,
561 localDefinitionNames,
562 file.namespace,
563 exportNameByQualifiedName,
564 ),
565 ),
566 );
567 }
568
569 const topLevelSchema: Record<string, Schema.Json> = {};
570 for (const [key, value] of Object.entries(parsed)) {
571 if (key !== "definitions") {
572 topLevelSchema[key] = value;
573 }
574 }
575
576 aggregateSchemas[file.exportName] = stripNullDefaults(
577 normalizeNullableTypes(
578 rewriteExternalRefs(
579 topLevelSchema,
580 localDefinitionNames,
581 file.namespace,
582 exportNameByQualifiedName,
583 ),
584 ),
585 );
586 }
587
588 for (const [name, schema] of Object.entries(ManualSchemas)) {
589 if (!(name in aggregateSchemas)) {
590 aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
591 }
592 }
593
594 const generator = makeJsonSchemaGenerator();
595 for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
596 left.localeCompare(right),
597 )) {
598 generator.addSchema(name, schema as never);
599 }
600
601 const generatedEntries = new Map<string, string>();
602 const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
603 if (output.length > 0) {
604 for (const entry of collectSchemaEntries(output)) {
605 if (!generatedEntries.has(entry.name)) {
606 generatedEntries.set(entry.name, entry.code);
607 }
608 }
609 }
610
611 const generatedSchemaNames = new Set(generatedEntries.keys());
612 const clientRequestRaw = yield* fetchText(
613 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
614 );
615 const clientNotificationRaw = yield* fetchText(
616 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
617 );
618 const serverRequestRaw = yield* fetchText(
619 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
620 );
621 const serverNotificationRaw = yield* fetchText(
622 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
623 );
624
625 const clientRequestEntries = parseRequestEntries(clientRequestRaw);
626 const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
627 const serverRequestEntries = parseRequestEntries(serverRequestRaw);
628 const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
629
630 const prelude = [
631 "// This file is generated by the effect-codex-app-server package. Do not edit manually.",
632 `// Upstream protocol ref: ${UPSTREAM_REF}`,
633 "",
634 ];
635
636 const schemaOutput = [
637 ...prelude,
638 'import * as Schema from "effect/Schema";',
639 "",
640 [...generatedEntries.values()].join("\n\n"),
641 "",
642 ].join("\n");
643
644 const metaOutput = [
645 ...prelude,
646 'import * as CodexSchema from "./schema.gen.ts";',
647 "",
648 renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
649 renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
650 renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
651 renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
652 "export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
653 "export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
654 "export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
655 "export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
656 "",
657 renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
658 renderSchemaTypeReference(
659 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
660 ),
661 ),
662 renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
663 renderSchemaTypeReference(
664 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
665 ),
666 ),
667 renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
668 renderSchemaTypeReference(
669 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
670 ),
671 ),
672 renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
673 renderSchemaTypeReference(
674 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
675 ),
676 ),
677 renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
678 renderSchemaTypeReference(
679 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
680 ),
681 ),
682 renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
683 renderSchemaTypeReference(
684 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
685 ),
686 ),
687 renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
688 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
689 ),
690 renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
691 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
692 ),
693 renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
694 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
695 ),
696 renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
697 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
698 ),
699 renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
700 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
701 ),
702 renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
703 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
704 ),
705 ].join("\n");
706
707 const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
708 for (const file of jsonSchemaFiles) {
709 if (!file.namespace) {
710 continue;
711 }
712 const current = namespaceGroups.get(file.namespace) ?? [];
713 current.push(file);
714 namespaceGroups.set(file.namespace, current);
715 }
716
717 const namespacesOutput = [
718 ...prelude,
719 'import * as CodexSchema from "./schema.gen.ts";',
720 "",
721 ...[...namespaceGroups.entries()]
722 .toSorted(([left], [right]) => left.localeCompare(right))
723 .map(([namespace, files]) => {
724 const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
725 return [
726 `export const ${constantName} = {`,
727 ...files
728 .toSorted((left, right) => left.fileName.localeCompare(right.fileName))
729 .map(
730 (file) =>
731 ` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
732 ),
733 "} as const;",
734 "",
735 ].join("\n");
736 }),
737 ].join("\n");
738
739 const fs = yield* FileSystem.FileSystem;
740 const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
741 yield* getGeneratedPaths();
742 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
743 yield* fs.writeFileString(metaOutputPath, metaOutput);
744 yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
745
746 yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
747
748 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
749 Effect.flatMap((spawner) =>
750 spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
751 ),
752 Effect.flatMap((child) => child.exitCode),
753 Effect.tap((code) =>
754 code === 0
755 ? Effect.void
756 : Effect.fail(
757 new GeneratorError({
758 detail: `vp fmt failed with exit code ${code}`,
759 }),
760 ),
761 ),
762 );
763});
764
765generateFiles().pipe(
766 Effect.scoped,
767 Effect.provide(
768 Layer.mergeAll(
769 Logger.layer([Logger.consolePretty()]),
770 NodeServices.layer,
771 FetchHttpClient.layer,
772 ),
773 ),
774 NodeRuntime.runMain,
775);